diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index f2080171fa2..2b507f39973 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -70,14 +70,58 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( 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 () => { + it("never borrows 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("treats a recovery or retry of a swarm run as the same swarm request, never as ordinary work", async () => { + const f = await seed(); + const [source] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "failed", runtimeMode: "native", + nativeIssueId: f.issue.id, responsibleUserId: USER, contextSnapshot: { issueId: f.issue.id, antigravitySwarmCommentId: f.comment.id } }).returning(); + const [retry] = 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: 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); + 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); + // A retry chain from another task never borrows its swarm request. + const other = await seed({ record: "none" }); + expect(await resolve(other, { context: { retryOfRunId: source!.id } })).toBe(false); + }); + + async function insertRun(f: Awaited>, values: Record) { + const [run] = 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 }, ...values } as never).returning(); + return run!; + } + + it("inherits the swarm request through a retry link stored only on the run row", async () => { + const f = await seed(); + const source = await insertRun(f, { status: "failed", contextSnapshot: { issueId: f.issue.id, antigravitySwarmCommentId: f.comment.id } }); + const retry = await insertRun(f, { retryOfRunId: source.id }); + expect(await resolve(f, { runId: retry.id, context: { issueId: f.issue.id, wakeReason: "issue_recovery_action_restored" } })).toBe(true); + }); + + it.each(["issue_blocker_stalled", "issue_assigned", "issue_continuation_needed"])( + "runs a %s wake as the swarm while the user's latest message is an unfulfilled swarm request", async wakeReason => { + const f = await seed(); + const run = await insertRun(f, {}); + expect(await resolve(f, { runId: run.id, context: { issueId: f.issue.id, wakeReason } })).toBe(true); + }); + + it("runs ordinary work once the swarm succeeded, or after a newer ordinary message", async () => { + const f = await seed(); + await insertRun(f, { status: "succeeded", contextSnapshot: { issueId: f.issue.id, antigravitySwarmCommentId: f.comment.id } }); + expect(await resolve(f, { context: { issueId: f.issue.id, wakeReason: "issue_assigned" } })).toBe(false); + const g = await seed(); + await db.insert(issueComments).values({ companyId: g.company.id, issueId: g.issue.id, authorType: "user", authorUserId: USER, body: "thanks", createdAt: new Date(Date.now() + 1000) }); + expect(await resolve(g, { context: { issueId: g.issue.id, wakeReason: "issue_commented" } })).toBe(false); + }); + it.each([ ["a remote environment", { remote: true }, /this computer/], ["Plan mode", { planning: true }, /Plan mode/], diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index c9982b453c2..f5cefa4e638 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -1,5 +1,5 @@ -import { and, eq, isNotNull, isNull, sql } from "drizzle-orm"; -import { activityLog, agents, issueComments, type Db } from "@paperclipai/db"; +import { and, desc, eq, isNotNull, isNull, sql } from "drizzle-orm"; +import { activityLog, agents, heartbeatRuns, issueComments, 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"; @@ -71,6 +71,43 @@ export async function antigravitySwarmCommentRefusal(db: Db, issue: { companyId: * the user's swarm. Throws a plain-language failure when the swarm was asked * for but cannot run here, so the run is not silently an ordinary request. */ +/** + * Every run that re-creates a swarm request is that swarm, never ordinary work: + * - a retry or automatic recovery inherits it through its retry link (the run + * column, or the context copy), following a bounded chain on the same task; + * - any other wake on the task (blocker-stalled and stranded-work sweeps, + * continuations, restart recovery) runs it while the user's latest message is + * a swarm request that no successful swarm run has fulfilled. + * The record check in resolveAntigravitySwarmRun still applies to the result. + */ +async function inheritedSwarmCommentId(db: Db, companyId: string, issueId: string, runId: string, context: unknown): Promise { + const [current] = await db.select({ retryOfRunId: heartbeatRuns.retryOfRunId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + let retryOf: unknown = current?.retryOfRunId ?? record(context).retryOfRunId; + for (let hop = 0; hop < 8 && typeof retryOf === "string" && /^[0-9a-f-]{36}$/i.test(retryOf); hop++) { + const [source] = await db.select({ contextSnapshot: heartbeatRuns.contextSnapshot, retryOfRunId: heartbeatRuns.retryOfRunId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, retryOf), eq(heartbeatRuns.companyId, companyId), + sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`)); + if (!source) return null; + const inherited = requestedAntigravitySwarmCommentId(source.contextSnapshot); + if (inherited) return inherited; + retryOf = source.retryOfRunId ?? record(source.contextSnapshot).retryOfRunId; + } + return null; +} + +async function pendingSwarmCommentId(db: Db, companyId: string, issueId: string): Promise { + const [latest] = await db.select({ id: issueComments.id }).from(issueComments) + .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; +} + export async function recordAntigravitySwarmRequest(db: Db, input: { companyId: string; issueId: string; commentId: string; userId: string }): Promise { await logActivity(db, { companyId: input.companyId, actorType: "user", actorId: input.userId, issueId: input.issueId, @@ -93,7 +130,9 @@ export async function resolveAntigravitySwarmRun(db: Db, input: { remote: boolean; planning: boolean; }): Promise { - const commentId = requestedAntigravitySwarmCommentId(input.context); + const commentId = requestedAntigravitySwarmCommentId(input.context) + ?? await inheritedSwarmCommentId(db, input.companyId, input.issueId, input.runId, input.context) + ?? 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),