mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
fix(antigravity): one stored fact per swarm selection; bounded automatic attempts
Run selection records the verified swarm request on the run it selects, in one transaction that locks the task, so a swarm that succeeded on any selection path is never run again. Automatic wakes attempt a request at most three times and refuse plainly after a Stop; a fresh /swarm or Retry still runs it. A second concurrent selection for the same request is refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
045af9ed08
commit
4095ad1f8b
2 files changed
+96
-20
No files matched your search
@@ -85,6 +85,7 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
|
||||
nativeIssueId: f.issue.id, responsibleUserId: USER, contextSnapshot: { issueId: f.issue.id, retryOfRunId: source!.id } }).returning();
|
||||
// A recovery wake carries only the retry link (wakeReason issue_recovery_action_restored), not the marker.
|
||||
expect(await resolve(f, { runId: retry!.id, context: { issueId: f.issue.id, retryOfRunId: source!.id, wakeReason: "issue_recovery_action_restored" } })).toBe(true);
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, retry!.id));
|
||||
const [second] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: f.issue.id, responsibleUserId: USER, contextSnapshot: { issueId: f.issue.id, retryOfRunId: retry!.id } }).returning();
|
||||
expect(await resolve(f, { runId: second!.id, context: { issueId: f.issue.id, retryOfRunId: retry!.id } })).toBe(true);
|
||||
@@ -122,6 +123,59 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
|
||||
expect(await resolve(g, { context: { issueId: g.issue.id, wakeReason: "issue_commented" } })).toBe(false);
|
||||
});
|
||||
|
||||
const setStatus = (id: string, status: string) => db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, id));
|
||||
const automatic = (f: Awaited<ReturnType<typeof seed>>, runId: string, wakeReason = "issue_assigned") =>
|
||||
resolve(f, { runId, context: { issueId: f.issue.id, wakeReason } });
|
||||
|
||||
it("records the request on the run it selects, so a fallback-selected swarm that succeeded is not run again", async () => {
|
||||
const f = await seed();
|
||||
const first = await insertRun(f, {});
|
||||
expect(await automatic(f, first.id)).toBe(true);
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first.id)))[0]!.contextSnapshot).toMatchObject({ antigravitySwarmCommentId: f.comment.id });
|
||||
await setStatus(first.id, "succeeded");
|
||||
expect(await automatic(f, (await insertRun(f, {})).id, "issue_blocker_stalled")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not run a swarm again after a retried swarm succeeded", async () => {
|
||||
const f = await seed();
|
||||
const failed = await insertRun(f, {});
|
||||
expect(await resolve(f, { runId: failed.id })).toBe(true);
|
||||
await setStatus(failed.id, "failed");
|
||||
const retry = await insertRun(f, { retryOfRunId: failed.id });
|
||||
expect(await resolve(f, { runId: retry.id, context: { issueId: f.issue.id, wakeReason: "issue_recovery_action_restored" } })).toBe(true);
|
||||
await setStatus(retry.id, "succeeded");
|
||||
expect(await automatic(f, (await insertRun(f, {})).id, "issue_continuation_needed")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a failed swarm pending, and refuses plainly after three failed attempts", async () => {
|
||||
const f = await seed();
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const run = await insertRun(f, {});
|
||||
expect(await automatic(f, run.id)).toBe(true);
|
||||
await setStatus(run.id, "failed");
|
||||
}
|
||||
await expect(automatic(f, (await insertRun(f, {})).id)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/three attempts/) });
|
||||
});
|
||||
|
||||
it("starts exactly one swarm for one request when two wakes arrive together", async () => {
|
||||
const f = await seed();
|
||||
const [a, b] = [await insertRun(f, {}), await insertRun(f, {})];
|
||||
const results = await Promise.allSettled([automatic(f, a.id), automatic(f, b.id)]);
|
||||
expect(results.filter(result => result.status === "fulfilled" && result.value === true)).toHaveLength(1);
|
||||
expect(results.filter(result => result.status === "rejected")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("after Stop, automatic wakes refuse plainly and a manual Retry runs the swarm again", async () => {
|
||||
const f = await seed();
|
||||
const stopped = await insertRun(f, {});
|
||||
expect(await automatic(f, stopped.id)).toBe(true);
|
||||
await setStatus(stopped.id, "cancelled");
|
||||
await expect(automatic(f, (await insertRun(f, {})).id, "issue_blocker_stalled")).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
|
||||
// resumeTaskRetry's wake: reason task_retry, context { issueId, triggeredBy, actorId, responsibleUserId }, no marker or retry link.
|
||||
const retry = await insertRun(f, {});
|
||||
expect(await resolve(f, { runId: retry.id, context: { issueId: f.issue.id, triggeredBy: "board", actorId: USER, responsibleUserId: USER, wakeReason: "task_retry" } })).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a remote environment", { remote: true }, /this computer/],
|
||||
["Plan mode", { planning: true }, /Plan mode/],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { and, desc, eq, isNotNull, isNull, sql } from "drizzle-orm";
|
||||
import { activityLog, agents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db";
|
||||
import { and, desc, eq, isNotNull, isNull, ne, sql } from "drizzle-orm";
|
||||
import { activityLog, agents, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { PaperclipRunnerProviderProfileError } from "./native-runtime/provider-profile.js";
|
||||
@@ -20,6 +20,8 @@ import { PaperclipRunnerProviderProfileError } from "./native-runtime/provider-p
|
||||
*/
|
||||
export const ANTIGRAVITY_SWARM_COMMAND = "swarm" as const;
|
||||
export const ANTIGRAVITY_SWARM_UNAVAILABLE = "antigravity_swarm_unavailable";
|
||||
/** Automatic wakes (recovery, sweeps) attempt one swarm request at most this often; the user can always ask again. */
|
||||
export const ANTIGRAVITY_SWARM_AUTOMATIC_ATTEMPTS = 3;
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const record = (value: unknown): Json =>
|
||||
@@ -101,11 +103,7 @@ async function pendingSwarmCommentId(db: Db, companyId: string, issueId: string)
|
||||
.where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId),
|
||||
isNotNull(issueComments.authorUserId), isNull(issueComments.authorAgentId)))
|
||||
.orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1);
|
||||
if (!latest) return null;
|
||||
const [fulfilled] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "succeeded"),
|
||||
sql`${heartbeatRuns.contextSnapshot}->>'antigravitySwarmCommentId' = ${latest.id}`)).limit(1);
|
||||
return fulfilled ? null : latest.id;
|
||||
return latest?.id ?? null;
|
||||
}
|
||||
|
||||
export async function recordAntigravitySwarmRequest(db: Db, input: { companyId: string; issueId: string; commentId: string; userId: string }): Promise<void> {
|
||||
@@ -130,9 +128,9 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
|
||||
remote: boolean;
|
||||
planning: boolean;
|
||||
}): Promise<boolean> {
|
||||
const commentId = requestedAntigravitySwarmCommentId(input.context)
|
||||
?? await inheritedSwarmCommentId(db, input.companyId, input.issueId, input.runId, input.context)
|
||||
?? await pendingSwarmCommentId(db, input.companyId, input.issueId);
|
||||
const marked = requestedAntigravitySwarmCommentId(input.context);
|
||||
const explicit = marked ?? await inheritedSwarmCommentId(db, input.companyId, input.issueId, input.runId, input.context);
|
||||
const commentId = explicit ?? await pendingSwarmCommentId(db, input.companyId, input.issueId);
|
||||
if (!commentId) return false;
|
||||
const [requested] = await db.select({ id: activityLog.id }).from(activityLog)
|
||||
.innerJoin(issueComments, and(eq(issueComments.id, commentId), eq(issueComments.issueId, input.issueId), eq(issueComments.companyId, input.companyId),
|
||||
@@ -142,15 +140,39 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
|
||||
sql`${activityLog.details}->>'commentId' = ${commentId}`))
|
||||
.limit(1);
|
||||
if (!requested) return false;
|
||||
const refusal = antigravitySwarmRefusal({ enabled: await swarmEnabled(db), agent: input.agent, remote: input.remote, planning: input.planning });
|
||||
if (refusal) throw new PaperclipRunnerProviderProfileError(ANTIGRAVITY_SWARM_UNAVAILABLE, refusal);
|
||||
await logActivity(db, {
|
||||
companyId: input.companyId, actorType: "system", actorId: "paperclip", agentId: input.agent.id, runId: input.runId,
|
||||
issueId: input.issueId, action: "issue.antigravity_swarm_started", entityType: "issue", entityId: input.issueId,
|
||||
details: {
|
||||
commentId,
|
||||
summary: "Started a Google Antigravity swarm with helpers. Helper actions are approved automatically by Antigravity's auto mode. Paperclip does not sandbox the helpers on this computer and cannot see their shell commands, which can write outside the task folder (for example in temp directories). Usage is one total for the coordinator and its helpers.",
|
||||
},
|
||||
// The user asked for this run: a fresh /swarm comment, or Retry. Everything
|
||||
// else (recovery, sweeps, continuations) is automatic and bounded below.
|
||||
const manual = marked !== null || record(input.context).wakeReason === "task_retry";
|
||||
const refuse = (message: string): never => { throw new PaperclipRunnerProviderProfileError(ANTIGRAVITY_SWARM_UNAVAILABLE, message); };
|
||||
return db.transaction(async (tx) => {
|
||||
// One selection at a time per task, so one request starts one swarm.
|
||||
await tx.select({ id: issues.id }).from(issues)
|
||||
.where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))).for("update");
|
||||
const attempts = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, input.companyId), ne(heartbeatRuns.id, input.runId),
|
||||
sql`${heartbeatRuns.contextSnapshot}->>'antigravitySwarmCommentId' = ${commentId}`));
|
||||
if (attempts.some(run => run.status === "succeeded")) return false;
|
||||
if (attempts.some(run => ["queued", "running"].includes(run.status))) refuse("A swarm for this request is already running.");
|
||||
if (!manual && attempts.some(run => run.status === "cancelled")) {
|
||||
refuse("The swarm for this request was stopped. Send /swarm again, or use Retry, to start it again.");
|
||||
}
|
||||
if (!manual && attempts.filter(run => ["failed", "timed_out"].includes(run.status)).length >= ANTIGRAVITY_SWARM_AUTOMATIC_ATTEMPTS) {
|
||||
refuse("The swarm did not finish after three attempts, so Paperclip stopped retrying it. Send /swarm again to start a new one.");
|
||||
}
|
||||
const refusal = antigravitySwarmRefusal({ enabled: await swarmEnabled(tx as unknown as Db), agent: input.agent, remote: input.remote, planning: input.planning });
|
||||
if (refusal) refuse(refusal);
|
||||
// The one stored fact every later decision reads: this run serves this request.
|
||||
await tx.update(heartbeatRuns)
|
||||
.set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ antigravitySwarmCommentId: commentId })}::jsonb` })
|
||||
.where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)));
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId: input.companyId, actorType: "system", actorId: "paperclip", agentId: input.agent.id, runId: input.runId,
|
||||
issueId: input.issueId, action: "issue.antigravity_swarm_started", entityType: "issue", entityId: input.issueId,
|
||||
details: {
|
||||
commentId,
|
||||
summary: "Started a Google Antigravity swarm with helpers. Helper actions are approved automatically by Antigravity's auto mode. Paperclip does not sandbox the helpers on this computer and cannot see their shell commands, which can write outside the task folder (for example in temp directories). Usage is one total for the coordinator and its helpers.",
|
||||
},
|
||||
});
|
||||
return true;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user