fix(antigravity): swarm review fixes

- remove the real delegating operations (bare operation ids) from a swarm turn's bridge catalog
- write the swarm request record in the comment's transaction; verify author, actor, task and company
- keep a swarm request out of another run's first turn; keep its marker through wake coalescing
- carry every swarm refusal to the user as a typed provider failure
- keep a pending /swarm request across a reload; refuse /swarm in the new-task composer and with per-message model choices
- fix the runner-e2e swarm case types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-23 23:36:17 -06:00
1 parent 26bddb09f1
commit 81c246104d
20 files changed
+270 -32

No files matched your search

@@ -1320,7 +1320,9 @@ describe("issue comment reopen routes", () => {
.post("/api/issues/11111111-1111-4111-8111-111111111111/comments")
.send({ body: "two helpers write a.txt and b.txt", nativeCommand: "swarm" });
expect(res.status).toBe(201);
expect(mockSwarm.record).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ commentId: "comment-1", userId: "local-board" }));
// Written in the same transaction as the comment, so neither can exist without the other.
expect(mockSwarm.record).toHaveBeenCalledWith(mockTx, expect.objectContaining({ commentId: "comment-1", userId: "local-board" }));
expect(mockIssueService.addComment).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.anything(), expect.anything(), mockTx);
await waitForWakeup(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
"22222222-2222-4222-8222-222222222222",
expect.objectContaining({ contextSnapshot: expect.objectContaining({ antigravitySwarmCommentId: "comment-1" }) }),
+14 -7
View File
@@ -19816,6 +19816,12 @@ export function issueRoutes(
},
tx,
);
// The swarm request commits with its comment or not at all.
if (swarmRequested && actor.actorType === "user") {
await recordAntigravitySwarmRequest(tx as unknown as Db, {
companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: insertedComment.id, userId: actor.actorId,
});
}
const updated =
actor.actorType === "user" && currentIssue.status !== "done"
? await svc.update(
@@ -19921,9 +19927,15 @@ export function issueRoutes(
dbOrTx,
);
const needsFastResponse = actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status);
comment = needsFastResponse ? await db.transaction(async tx => {
comment = needsFastResponse || swarmRequested ? await db.transaction(async tx => {
const saved = await add(tx as unknown as Db);
if (actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status)) {
// The swarm request commits with its comment or not at all.
if (swarmRequested && actor.actorType === "user") {
await recordAntigravitySwarmRequest(tx as unknown as Db, {
companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: saved.id, userId: actor.actorId,
});
}
if (needsFastResponse && actor.actorType === "user" && currentIssue.assigneeAgentId && !["done", "cancelled", "backlog"].includes(currentIssue.status)) {
await enqueueFastResponse(tx as unknown as Db, { companyId: currentIssue.companyId, issueId: currentIssue.id, agentId: currentIssue.assigneeAgentId,
responsibleUserId: actor.actorId, sourceCommentId: saved.id, sourceKey: `comment:${saved.id}`, acceptedAt: new Date(saved.createdAt) });
fastResponseEnqueued = true;
@@ -20060,11 +20072,6 @@ export function issueRoutes(
comment,
currentIssue.assigneeAgentId,
);
if (swarmRequested && req.actor.type === "board" && req.actor.userId) {
await recordAntigravitySwarmRequest(db, {
companyId: currentIssue.companyId, issueId: currentIssue.id, commentId: comment.id, userId: req.actor.userId,
});
}
const swarmWakeContext = swarmRequested ? { antigravitySwarmCommentId: comment.id } : {};
await revalidateActiveSourceRecoveryAfterCommittedWrite({
@@ -0,0 +1,98 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { activityLog, agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
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";
const support = await getEmbeddedPostgresTestSupport();
const USER = "swarm-user";
describe.skipIf(!support.supported)("trusted /swarm run selection (database)", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-antigravity-swarm-");
db = createDb(database.connectionString);
await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: true });
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
async function seed(options: { author?: "user" | "agent"; record?: "match" | "none" | "other-actor" | "other-comment" } = {}) {
const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: `S${randomUUID().slice(0, 4)}` }).returning();
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning();
const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Swarm", status: "todo", assigneeAgentId: agent!.id }).returning();
const [comment] = await db.insert(issueComments).values({ companyId: company!.id, issueId: issue!.id,
...(options.author === "agent" ? { authorType: "agent", authorAgentId: agent!.id } : { authorType: "user", authorUserId: USER }), body: "two helpers" }).returning();
const record = options.record ?? "match";
if (record !== "none") {
await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id,
commentId: record === "other-comment" ? randomUUID() : comment!.id, userId: record === "other-actor" ? "someone-else" : USER });
}
return { company: company!, agent: agent!, issue: issue!, comment: comment! };
}
const resolve = (f: Awaited<ReturnType<typeof seed>>, overrides: Partial<Parameters<typeof resolveAntigravitySwarmRun>[1]> = {}) =>
resolveAntigravitySwarmRun(db, { companyId: f.company.id, issueId: f.issue.id, runId: randomUUID(), agent: f.agent,
context: { antigravitySwarmCommentId: f.comment.id }, remote: false, planning: false, ...overrides });
it("selects the swarm for the user's recorded request and logs that it started", async () => {
const f = await seed();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "running", runtimeMode: "native",
runtimeModeResolvedAt: new Date(), nativeIssueId: f.issue.id, responsibleUserId: USER, startedAt: new Date(), contextSnapshot: { issueId: f.issue.id } }).returning();
expect(await resolve(f, { runId: run!.id })).toBe(true);
const started = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issue.id), eq(activityLog.action, "issue.antigravity_swarm_started")));
expect(started).toHaveLength(1);
expect(String((started[0]!.details as Record<string, unknown>).summary)).toMatch(/does not sandbox the helpers/);
});
it.each([
["no recorded request", { record: "none" as const }],
["a record by another actor", { record: "other-actor" as const }],
["a record for another comment", { record: "other-comment" as const }],
["an agent-authored comment", { author: "agent" as const }],
])("never selects the swarm for %s", async (_name, options) => {
expect(await resolve(await seed(options))).toBe(false);
});
it("never selects the swarm for a comment an agent wrote on a user's behalf", async () => {
const f = await seed();
await db.update(issueComments).set({ authorAgentId: f.agent.id }).where(eq(issueComments.id, f.comment.id));
expect(await resolve(f)).toBe(false);
});
it("never selects the swarm for another task's comment, even with a record on this task", async () => {
const f = await seed();
const [otherIssue] = await db.insert(issues).values({ companyId: f.company.id, title: "Other", status: "todo", assigneeAgentId: f.agent.id }).returning();
const [otherComment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: otherIssue!.id, authorType: "user", authorUserId: USER, body: "x" }).returning();
await recordAntigravitySwarmRequest(db, { companyId: f.company.id, issueId: f.issue.id, commentId: otherComment!.id, userId: USER });
expect(await resolve(f, { context: { antigravitySwarmCommentId: otherComment!.id } })).toBe(false);
});
it("ignores a wake without the marker, and a marker from another task or company", async () => {
const f = await seed();
expect(await resolve(f, { context: { commentId: f.comment.id, wakeCommentId: f.comment.id } })).toBe(false);
const other = await seed();
expect(await resolve(f, { context: { antigravitySwarmCommentId: other.comment.id } })).toBe(false);
expect(await resolve(other, { companyId: f.company.id })).toBe(false);
});
it.each([
["a remote environment", { remote: true }, /this computer/],
["Plan mode", { planning: true }, /Plan mode/],
])("refuses in plain language in %s instead of running an ordinary request", async (_name, overrides, message) => {
await expect(resolve(await seed(), overrides)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(message) });
});
it("refuses when the flag is off", async () => {
const f = await seed();
await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: false });
try {
await expect(resolve(f)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/not turned on/) });
} finally {
await instanceSettingsService(db).updateExperimental({ enableAntigravitySwarm: true });
}
expect((await db.select().from(activityLog).where(eq(activityLog.action, ANTIGRAVITY_SWARM_REQUESTED_ACTION))).length).toBeGreaterThan(0);
});
});
+3 -2
View File
@@ -1,4 +1,4 @@
import { and, eq, sql } from "drizzle-orm";
import { and, eq, isNotNull, isNull, sql } from "drizzle-orm";
import { activityLog, agents, issueComments, type Db } from "@paperclipai/db";
import { logActivity } from "./activity-log.js";
import { instanceSettingsService } from "./instance-settings.js";
@@ -96,7 +96,8 @@ export async function resolveAntigravitySwarmRun(db: Db, input: {
const commentId = requestedAntigravitySwarmCommentId(input.context);
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)))
.innerJoin(issueComments, and(eq(issueComments.id, commentId), eq(issueComments.issueId, input.issueId), eq(issueComments.companyId, input.companyId),
isNotNull(issueComments.authorUserId), isNull(issueComments.authorAgentId)))
.where(and(eq(activityLog.companyId, input.companyId), eq(activityLog.action, ANTIGRAVITY_SWARM_REQUESTED_ACTION),
eq(activityLog.entityId, input.issueId), eq(activityLog.actorType, "user"), eq(activityLog.actorId, issueComments.authorUserId),
sql`${activityLog.details}->>'commentId' = ${commentId}`))
@@ -1635,3 +1635,12 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => {
expect(deps.executeRun).not.toHaveBeenCalled();
});
});
describe("a /swarm request survives wake coalescing", () => {
const swarm = { issueId: "issue-1", wakeReason: "issue_commented", wakeCommentId: "c-swarm", antigravitySwarmCommentId: "c-swarm" };
const ordinary = { issueId: "issue-1", wakeReason: "issue_commented", wakeCommentId: "c-later" };
it("keeps the swarm marker whichever comment arrived first, so the merged run selects its own swarm", () => {
expect(mergeCoalescedContextSnapshot(swarm, ordinary)).toMatchObject({ antigravitySwarmCommentId: "c-swarm" });
expect(mergeCoalescedContextSnapshot(ordinary, swarm)).toMatchObject({ antigravitySwarmCommentId: "c-swarm" });
});
});
@@ -10,7 +10,7 @@ import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
import { undeliveredLegacyUserCommentIds } from "../explicit-native-continuation.js";
import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js";
import {
claimFirstTurnQueuedInput, firstTurnClaimedCommentIds, firstTurnTakesAllQueuedComments, runAcceptsFirstTurnQueuedInput,
claimFirstTurnQueuedInput, deferredWakeJoinsFirstTurn, firstTurnClaimedCommentIds, firstTurnTakesAllQueuedComments, runAcceptsFirstTurnQueuedInput,
} from "./first-turn-queued-input.js";
const support = await getEmbeddedPostgresTestSupport();
@@ -187,3 +187,17 @@ describe.skipIf(!support.supported)("first-turn queued input", () => {
commentIds: [withFile] })]).toEqual([]);
});
});
describe("a /swarm request never joins another run's first turn", () => {
const user = "user-1";
const commentId = "6f1c1b0e-5a52-4b0a-9a51-0d6c9c3b2f11";
const wake = (context: Record<string, unknown>) => ({
agentId: "agent-1", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: user, reason: "issue_commented",
payload: { issueId: "issue-1", commentId, mutation: "comment", _paperclipWakeContext: { wakeReason: "issue_commented", commentId, wakeCommentId: commentId, wakeCommentIds: [commentId], ...context } },
});
it("keeps the swarm request for its own run selection", () => {
const run = { agentId: "agent-1", responsibleUserId: user };
expect(deferredWakeJoinsFirstTurn(wake({}), run)).toBe(true);
expect(deferredWakeJoinsFirstTurn(wake({ antigravitySwarmCommentId: commentId }), run)).toBe(false);
});
});
@@ -109,6 +109,8 @@ export function deferredWakeJoinsFirstTurn(
reason !== null && COMMENT_WAKE_REASONS.has(reason) &&
!payload.interactionId && !context.interactionId && !context.interactionStatus &&
!payload.queuedCommentInterrupt && context.resumeIntent !== true &&
// A /swarm request selects its own run (a different provider route).
context.antigravitySwarmCommentId === undefined &&
!deferredWakeIsChatRequest(payload) &&
queuedCommentIdsFromWakePayload(payload).length > 0;
}