fix(antigravity): keep merged comments queued and a stopped swarm stopped

Review follow-ups:
- A swarm run sends only its recorded /swarm request, so it now counts
  as delivering only that comment. Other user comments merged into its
  wake (older or newer) are saved as their own waiting request and a
  following ordinary run delivers them.
- A Retry counts for a swarm only when it started that run and was made
  after the last attempt and the latest Stop. A click joined to a swarm
  that was still running no longer restarts it after the user stops it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 13:43:43 -06:00
1 parent a11d23a7e9
commit 83d933743f
3 files changed
+158 -20

No files matched your search

@@ -5,6 +5,9 @@ import { activityLog, agentWakeupRequests, agents, companies, createDb, EMBEDDED
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, recordAntigravitySwarmRequest, resolveAntigravitySwarmRun } from "./antigravity-swarm.js";
import { instanceSettingsService } from "./instance-settings.js";
import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js";
import { queuedCommentIdsFromWakePayload } from "../lib/queued-comment-context.js";
import { mergeCoalescedContextSnapshot } from "./heartbeat/run-preparation.js";
const support = await getEmbeddedPostgresTestSupport();
const USER = "swarm-user";
@@ -124,10 +127,12 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
});
/** The wake Retry records for the user (task-retry.ts); `initiatedBy` marks an automatic retry on their behalf. */
const userRetry = async (f: Awaited<ReturnType<typeof seed>>, intent: Record<string, unknown> = {}) => {
/** `runId` is the run the click started, or the busy run it joined (status coalesced). */
const userRetry = async (f: Awaited<ReturnType<typeof seed>>, intent: Record<string, unknown> = {},
link: { runId?: string; status?: string; reason?: string } = {}) => {
await new Promise(resolve => setTimeout(resolve, 5));
await db.insert(agentWakeupRequests).values({ companyId: f.company.id, agentId: f.agent.id, source: "on_demand", triggerDetail: "manual",
reason: "task_retry", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: USER,
reason: link.reason ?? "task_retry", status: link.status ?? "queued", runId: link.runId ?? null, requestedByActorType: "user", requestedByActorId: USER,
payload: { issueId: f.issue.id, taskRetry: { schema: "paperclip.task-retry.v1", actorId: USER, ...intent } } });
};
const setStatus = (id: string, status: string) => db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, id));
@@ -184,14 +189,40 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
// Nor is a recovery run whose copied context still carries the request marker.
await expect(resolve(f, { runId: (await insertRun(f, {})).id })).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
// Nor an automatic retry on the user's behalf.
await userRetry(f, { initiatedBy: "provider_limit_reset" });
const onBehalf = await insertRun(f, {});
await userRetry(f, { initiatedBy: "provider_limit_reset" }, { runId: onBehalf.id });
await expect(resolve(f, { runId: onBehalf.id, context: retryContext })).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
// Nor the user's Retry that started another run.
await userRetry(f, {}, { runId: onBehalf.id });
await expect(resolve(f, { runId: (await insertRun(f, {})).id, context: retryContext })).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
// The user's own Retry (resumeTaskRetry: reason task_retry, no marker or retry link) runs it again.
await userRetry(f);
// The user's own Retry runs it again in the run it started, also once promotion renamed the wake's reason.
const retry = await insertRun(f, {});
await userRetry(f, {}, { runId: retry.id, reason: "issue_execution_promoted" });
expect(await resolve(f, { runId: retry.id, context: retryContext })).toMatchObject({ request: expect.any(String) });
});
it("never restarts a stopped swarm for a Retry clicked while that swarm was still running", async () => {
const f = await seed();
const swarm = await insertRun(f, {});
expect(await automatic(f, swarm.id)).toMatchObject({ request: expect.any(String) });
// Retry while busy joins the running swarm (task-retry.ts records it coalesced onto that run).
await userRetry(f, {}, { runId: swarm.id, status: "coalesced" });
await new Promise(resolve => setTimeout(resolve, 5));
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(eq(heartbeatRuns.id, swarm.id));
await expect(automatic(f, (await insertRun(f, {})).id, "issue_blocker_stalled")).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
});
it("needs a Retry made after the Stop, even when an earlier click starts the next run", async () => {
const f = await seed();
const first = await insertRun(f, {});
expect(await automatic(f, first.id)).toMatchObject({ request: expect.any(String) });
const next = await insertRun(f, { status: "queued" });
await userRetry(f, {}, { runId: next.id });
await new Promise(resolve => setTimeout(resolve, 5));
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(eq(heartbeatRuns.id, first.id));
await expect(resolve(f, { runId: next.id })).rejects.toMatchObject({ message: expect.stringMatching(/stopped/) });
});
it("caps automatic attempts even when a recovery copies the request marker or names a retry", async () => {
const f = await seed();
for (let attempt = 0; attempt < 3; attempt++) {
@@ -201,8 +232,58 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
}
await expect(resolve(f, { runId: (await insertRun(f, {})).id })).rejects.toMatchObject({ message: expect.stringMatching(/three attempts/) });
await expect(automatic(f, (await insertRun(f, {})).id, "task_retry")).rejects.toMatchObject({ message: expect.stringMatching(/three attempts/) });
await userRetry(f);
expect(await automatic(f, (await insertRun(f, {})).id, "task_retry")).toMatchObject({ request: expect.any(String) });
const retried = await insertRun(f, {});
await userRetry(f, {}, { runId: retried.id });
expect(await automatic(f, retried.id, "task_retry")).toMatchObject({ request: expect.any(String) });
});
it("leaves an ordinary comment merged into the swarm's wake queued for its own ordinary run", async () => {
const f = await seed();
const [ordinary] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, authorType: "user",
authorUserId: USER, body: "actually, use b.txt instead" }).returning();
const wakeContext = { issueId: f.issue.id, wakeReason: "issue_commented", antigravitySwarmCommentId: f.comment.id,
wakeCommentIds: [f.comment.id, ordinary!.id], wakeCommentId: ordinary!.id };
const run = await insertRun(f, { startedAt: new Date(Date.now() + 1000), contextSnapshot: wakeContext });
expect(await resolve(f, { runId: run.id, context: wakeContext })).toEqual({ commentId: f.comment.id, request: "two helpers" });
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 2000) }).where(eq(heartbeatRuns.id, run.id));
// The swarm received only its request: the ordinary comment is not delivered by it.
const delivered = await deliveredQueuedCommentIds(db, { companyId: f.company.id, issueId: f.issue.id, agentId: f.agent.id,
commentIds: [f.comment.id, ordinary!.id] });
expect([...delivered]).toEqual([f.comment.id]);
// It waits in its own receipt, which a following ordinary run delivers.
const waiting = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.company.id),
eq(agentWakeupRequests.status, "deferred_issue_execution")));
expect(waiting.map(wake => queuedCommentIdsFromWakePayload(wake.payload))).toEqual([[ordinary!.id]]);
// A retry of the swarm that copies the merged context does not queue the comment twice.
const retry = await insertRun(f, { retryOfRunId: run.id, contextSnapshot: wakeContext });
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, run.id));
await resolve(f, { runId: retry.id, context: wakeContext });
expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.company.id),
eq(agentWakeupRequests.status, "deferred_issue_execution")))).toHaveLength(1);
});
it("runs the swarm and re-queues an older ordinary comment that coalescing merged into its wake", async () => {
const f = await seed();
const [ordinary] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, authorType: "user",
authorUserId: USER, body: "also rename the folder", createdAt: new Date(Date.now() - 60_000) }).returning();
const wakeContext = mergeCoalescedContextSnapshot(
{ issueId: f.issue.id, wakeReason: "issue_commented", wakeCommentId: ordinary!.id, wakeCommentIds: [ordinary!.id] },
{ issueId: f.issue.id, wakeReason: "issue_commented", wakeCommentId: f.comment.id, wakeCommentIds: [f.comment.id], antigravitySwarmCommentId: f.comment.id });
const run = await insertRun(f, { startedAt: new Date(Date.now() + 1000), contextSnapshot: wakeContext });
expect(await resolve(f, { runId: run.id, context: wakeContext })).toEqual({ commentId: f.comment.id, request: "two helpers" });
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 2000) }).where(eq(heartbeatRuns.id, run.id));
expect([...await deliveredQueuedCommentIds(db, { companyId: f.company.id, issueId: f.issue.id, agentId: f.agent.id,
commentIds: [f.comment.id, ordinary!.id] })]).toEqual([f.comment.id]);
const waiting = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.company.id),
eq(agentWakeupRequests.status, "deferred_issue_execution")));
expect(waiting.map(wake => queuedCommentIdsFromWakePayload(wake.payload))).toEqual([[ordinary!.id]]);
// The following ordinary run is not a swarm, and it delivers the comment.
const followUp = await insertRun(f, { startedAt: new Date(Date.now() + 3000),
contextSnapshot: { issueId: f.issue.id, wakeReason: "issue_commented", wakeCommentIds: [ordinary!.id] } });
expect(await automatic(f, followUp.id, "issue_commented")).toBeNull();
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 4000) }).where(eq(heartbeatRuns.id, followUp.id));
expect(await deliveredQueuedCommentIds(db, { companyId: f.company.id, issueId: f.issue.id, agentId: f.agent.id,
commentIds: [ordinary!.id] })).toEqual(new Set([ordinary!.id]));
});
it("lets a task reassigned to another kind of agent run ordinary work instead of refusing every run", async () => {
+59 -13
View File
@@ -1,9 +1,11 @@
import { and, desc, eq, gt, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm";
import { and, desc, eq, gt, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
import { parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared";
import { activityLog, agentWakeupRequests, 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";
import { saveUndeliveredUserComments } from "./work-intent-outbox.js";
import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from "../lib/queued-comment-context.js";
/**
* Google Antigravity's native `/swarm`, started only by a signed-in user.
@@ -168,20 +170,26 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
// 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, createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns)
const attempts = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, createdAt: heartbeatRuns.createdAt,
finishedAt: heartbeatRuns.finishedAt, updatedAt: heartbeatRuns.updatedAt }).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 null;
if (attempts.some(run => ["queued", "running"].includes(run.status))) refuse("A swarm for this request is already running.");
// The user asked for this attempt: it is the request's first run (the
// fresh /swarm comment), or the user pressed Retry after the last attempt.
// Run context and wake reasons are not proof (recoveries copy context, and
// an agent can name any wake reason), so Retry is read from the user's own
// retry request. Everything else (recovery, sweeps, continuations,
// automatic retries) is automatic and bounded below.
const lastAttemptAt = attempts.reduce<Date | null>((latest, run) => !latest || run.createdAt > latest ? run.createdAt : latest, null);
const manual = lastAttemptAt === null || await userRetriedSince(tx as unknown as Db, {
companyId: input.companyId, agentId: input.agent.id, issueId: input.issueId, since: lastAttemptAt });
// fresh /swarm comment), or this run is the one the user's Retry started,
// clicked after the last attempt began and after any Stop. Run context and
// wake reasons are not proof (recoveries copy context, and an agent can
// name any wake reason), so Retry is read from the user's own retry
// request. A click that joined an attempt already running belongs to that
// attempt. Everything else (recovery, sweeps, continuations, automatic
// retries) is automatic and bounded below.
const latestOf = (dates: Date[]) => dates.reduce<Date | null>((latest, at) => !latest || at > latest ? at : latest, null);
const lastAttemptAt = latestOf(attempts.map(run => run.createdAt));
const stoppedAt = latestOf(attempts.filter(run => run.status === "cancelled").map(run => run.finishedAt ?? run.updatedAt));
const manual = lastAttemptAt === null || await userRetryStartedRun(tx as unknown as Db, {
companyId: input.companyId, agentId: input.agent.id, issueId: input.issueId, runId: input.runId,
since: stoppedAt && stoppedAt > lastAttemptAt ? stoppedAt : lastAttemptAt });
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.");
}
@@ -190,6 +198,7 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
}
const refusal = antigravitySwarmRefusal({ enabled: await swarmEnabled(tx as unknown as Db), agent: input.agent, remote: input.remote, planning: input.planning });
if (refusal) refuse(refusal);
await queueCommentsTheSwarmDoesNotSend(tx as unknown as Db, { ...input, commentId });
// 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` })
@@ -206,19 +215,56 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
});
}
/** A Retry the signed-in user asked for on this task and agent after `since` (automatic retries excluded). */
async function userRetriedSince(db: Db, input: { companyId: string; agentId: string; issueId: string; since: Date }): Promise<boolean> {
/**
* A Retry the signed-in user asked for on this task and agent after `since`
* that started this run: its request is this run's wake, or is linked to this
* run (automatic retries excluded). Promotion renames a deferred Retry's wake
* reason, so a Retry is also known by its own retry intent.
*/
async function userRetryStartedRun(db: Db, input: { companyId: string; agentId: string; issueId: string; runId: string; since: Date }): Promise<boolean> {
const [retry] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, input.agentId),
inArray(agentWakeupRequests.reason, ["task_retry", "retry_failed_run"]),
or(inArray(agentWakeupRequests.reason, ["task_retry", "retry_failed_run"]),
sql`${agentWakeupRequests.payload}->'taskRetry'->>'schema' = 'paperclip.task-retry.v1'`),
eq(agentWakeupRequests.requestedByActorType, "user"), isNotNull(agentWakeupRequests.requestedByActorId),
gt(agentWakeupRequests.requestedAt, input.since),
sql`coalesce(${agentWakeupRequests.payload}->>'issueId', ${agentWakeupRequests.payload}->>'taskId') = ${input.issueId}`,
sql`${agentWakeupRequests.payload}->'taskRetry'->>'initiatedBy' is null`,
or(eq(agentWakeupRequests.runId, input.runId), sql`exists (select 1 from ${heartbeatRuns} started
where started.company_id = ${input.companyId} and started.id = ${input.runId}
and started.wakeup_request_id = ${agentWakeupRequests.id})`),
)).limit(1);
return Boolean(retry);
}
/**
* The swarm sends the provider only its request comment. Other user comments
* merged into this run's wake (queued-comment-delivery.ts does not count them
* delivered by a swarm run) are saved as their own receipt, so a following
* ordinary run delivers them. A comment another receipt already carries is not
* saved twice (a retry of the swarm copies the merged context).
*/
async function queueCommentsTheSwarmDoesNotSend(db: Db, input: {
companyId: string; issueId: string; runId: string; agent: { id: string }; context: unknown; commentId: string;
}): Promise<void> {
const [run] = await db.select({ contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)));
const merged = [run?.contextSnapshot, input.context].flatMap(value => [...queuedCommentIdsFromRunContext(value),
record(value).wakeCommentId, record(value).commentId]);
const others = [...new Set(merged.filter((id): id is string => typeof id === "string" && /^[0-9a-f-]{36}$/i.test(id)
&& id !== input.commentId))];
if (others.length === 0) return;
const receipts = await db.select({ payload: agentWakeupRequests.payload }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, input.agent.id),
eq(agentWakeupRequests.status, "deferred_issue_execution"),
sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`));
const waiting = new Set(receipts.flatMap(receipt => queuedCommentIdsFromWakePayload(receipt.payload)));
const owed = others.filter(id => !waiting.has(id));
if (owed.length === 0) return;
await saveUndeliveredUserComments(db, { companyId: input.companyId, issueId: input.issueId, agentId: input.agent.id,
commentIds: owed, allowedStatuses: ["backlog", "todo", "in_progress", "in_review", "blocked"] });
}
export interface AntigravitySwarmSelection {
commentId: string;
/** The recorded request comment's own text: the swarm's only instruction. */
@@ -37,6 +37,7 @@ export async function deliveredQueuedCommentIds(tx: Pick<Db, "select">, input: {
and (delivered_run.native_issue_id = ${issueId} or delivered_run.context_snapshot->>'issueId' = ${issueId})
and delivered_run.started_at > ${issueComments.createdAt}
and delivered_run.started_at >= ${issueComments.updatedAt}
and ${swarmRunDeliversOnlyItsRequest(sql`delivered_run`)}
and (coalesce(delivered_run.context_snapshot->'wakeCommentIds', '[]'::jsonb) ? ${issueComments.id}::text
or (delivered_run.retry_of_run_id is not null and jsonb_path_exists(delivered_run.context_snapshot, '$.executionContinuation.messages[*] ? (@.id == $id)',
jsonb_build_object('id', ${issueComments.id}::text))
@@ -48,6 +49,16 @@ export async function deliveredQueuedCommentIds(tx: Pick<Db, "select">, input: {
return new Set(rows.map(row => row.id));
}
/**
* A trusted /swarm run (services/antigravity-swarm.ts) sends the provider only
* its recorded request comment. Other comments merged into its wake stay
* undelivered and wait for an ordinary run.
*/
function swarmRunDeliversOnlyItsRequest(run: SQL) {
return sql`(${run}.context_snapshot->>'antigravitySwarmCommentId' is null
or ${run}.context_snapshot->>'antigravitySwarmCommentId' = ${issueComments.id}::text)`;
}
export const TASK_HISTORY_READ_EVENT = "task_history.read";
export async function recordTaskHistoryRead(db: Db, input: {