diff --git a/docs/api/issues.md b/docs/api/issues.md index 54fca5809d1..bfbc5318d31 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -241,6 +241,30 @@ POST /api/issues/{issueId}/comments Agent @-mentions are context only and do not trigger heartbeats. Normal comment feedback can still wake the current assignee. Use explicit assignment or a review request to ask another agent to act. +#### Start a Google Antigravity swarm + +``` +POST /api/issues/{issueId}/comments +{ "body": "/swarm write the tests for the parser", "nativeCommand": "swarm" } +``` + +The optional `nativeCommand` field accepts only `"swarm"`. It asks the task's Google Antigravity assignee to run the comment as a swarm with helpers. The swarm's only instruction is the comment text, without a leading `/swarm`. Comment text alone is never read as a command: without `nativeCommand`, `/swarm` is ordinary text. + +Only a signed-in board user can send `nativeCommand`. Any other caller, such as an agent, gets `403` with `Only a signed-in user can start a swarm`. + +The endpoint refuses these requests with `422` and `{ "error": "", "code": "antigravity_swarm_unavailable" }`. It saves no comment and wakes no agent. Checks run in this order: + +| When | `error` | +| --- | --- | +| The task is a chat | `Swarm works in task comments, not in chats.` | +| The instance setting is off | `Swarm is not turned on for this Paperclip. An instance admin can turn on "Google Antigravity swarm" in Settings, Experimental.` | +| The assignee is not a Google Antigravity agent | `Swarm works only for tasks assigned to a Google Antigravity agent.` | +| The task is in Plan mode | `Swarm is not available while the task is in Plan mode: helpers change files. Approve the plan first, then send /swarm.` | +| Nothing follows `/swarm` | `This swarm has no request to run. Send /swarm followed by what the swarm should do.` | +| More than 16,000 characters follow `/swarm` | `This swarm request is too long. Keep what follows /swarm under 16,000 characters.` | + +A later `/swarm` on the same task replaces an earlier request that has not completed. The earlier request never runs, neither as a swarm nor as ordinary work. Other comments sent in the meantime reach the agent in an ordinary turn, never inside the swarm's request. + ### Discard a Queued Comment ``` diff --git a/server/src/services/antigravity-swarm-refusal.ts b/server/src/services/antigravity-swarm-refusal.ts index f64018ef0c9..e29aa66d1a1 100644 --- a/server/src/services/antigravity-swarm-refusal.ts +++ b/server/src/services/antigravity-swarm-refusal.ts @@ -5,3 +5,13 @@ * it automatically, because every automatic attempt would refuse the same way. */ export const ANTIGRAVITY_SWARM_UNAVAILABLE = "antigravity_swarm_unavailable"; + +/** The activity a signed-in user's /swarm request records (the request's only proof). */ +export const ANTIGRAVITY_SWARM_REQUESTED_ACTION = "issue.antigravity_swarm_requested"; + +/** A Google Antigravity agent: the only kind of agent that runs a /swarm. */ +export function isAntigravityAgent(agent: { adapterType: string; adapterConfig: unknown } | null): boolean { + const config = agent?.adapterConfig !== null && typeof agent?.adapterConfig === "object" && !Array.isArray(agent.adapterConfig) + ? agent.adapterConfig as Record : {}; + return agent?.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity"; +} diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index cf7517c7b85..444abb9ee3d 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -8,6 +8,7 @@ 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"; +import { saveUndeliveredUserComments } from "./work-intent-outbox.js"; const support = await getEmbeddedPostgresTestSupport(); const USER = "swarm-user"; @@ -316,6 +317,69 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( expect(await automatic(f, (await insertRun(f, {})).id)).toEqual({ commentId: later!.id, request: "three helpers write c.txt" }); }); + /** + * One wake can carry several user comments (coalescing merges them, newest + * wake context last). The rule, in comment order: the newest recorded /swarm + * runs as the swarm with its own text; an older recorded /swarm is replaced + * (never run, neither as a swarm nor as ordinary work, and counted handled); + * every ordinary comment waits for an ordinary run and never rides in the swarm. + */ + it.each([ + { name: "swarm then ordinary", order: ["S1", "O"], runs: "S1", requeued: ["O"], replaced: [] }, + { name: "ordinary then swarm", order: ["O", "S1"], runs: "S1", requeued: ["O"], replaced: [] }, + { name: "swarm then swarm", order: ["S1", "S2"], runs: "S2", requeued: [], replaced: ["S1"] }, + { name: "swarm, ordinary, swarm", order: ["S1", "O", "S2"], runs: "S2", requeued: ["O"], replaced: ["S1"] }, + ])("a wake carrying $name runs $runs as the swarm, re-queues $requeued and replaces $replaced", async ({ order, runs, requeued, replaced }) => { + const f = await seed({ record: "none" }); + await db.delete(issueComments).where(eq(issueComments.id, f.comment.id)); + const base = Date.now() - 60_000; + const ids: Record = {}; + for (const [index, label] of order.entries()) { + const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, authorType: "user", + authorUserId: USER, body: label.startsWith("S") ? `/swarm request ${label}` : `ordinary ${label}`, + createdAt: new Date(base + index * 1000) }).returning(); + ids[label] = comment!.id; + if (label.startsWith("S")) await recordAntigravitySwarmRequest(db, { companyId: f.company.id, issueId: f.issue.id, commentId: comment!.id, userId: USER }); + } + const wakeContext = order.map(label => ({ issueId: f.issue.id, wakeReason: "issue_commented", wakeCommentId: ids[label], + wakeCommentIds: [ids[label]], ...(label.startsWith("S") ? { antigravitySwarmCommentId: ids[label] } : {}) })) + .reduce>((merged, wake) => mergeCoalescedContextSnapshot(merged, wake), {}); + const run = await insertRun(f, { startedAt: new Date(Date.now() + 1000), contextSnapshot: wakeContext }); + // The swarm runs the newest request with only that request's text. + expect(await resolve(f, { runId: run.id, context: wakeContext })).toEqual({ commentId: ids[runs], request: `request ${runs}` }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]!.contextSnapshot) + .toMatchObject({ antigravitySwarmCommentId: ids[runs] }); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 2000) }).where(eq(heartbeatRuns.id, run.id)); + // Handled: the swarm's own request and every request it replaced. Ordinary comments are still owed. + const all = Object.values(ids); + expect(new Set(await deliveredQueuedCommentIds(db, { companyId: f.company.id, issueId: f.issue.id, agentId: f.agent.id, commentIds: all }))) + .toEqual(new Set([runs, ...replaced].map(label => ids[label]))); + // Only the ordinary comments wait in an ordinary receipt; a replaced request is never re-queued. + 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(requeued.length ? [requeued.map(label => ids[label])] : []); + for (const wake of waiting) { + expect((wake.payload as Record>)._paperclipWakeContext).not.toHaveProperty("antigravitySwarmCommentId"); + } + // The next run is ordinary work: no swarm is pending, and a replaced request never starts one. + expect(await automatic(f, (await insertRun(f, {})).id, "issue_commented")).toBeNull(); + for (const label of replaced) { + await expect(resolve(f, { runId: (await insertRun(f, {})).id, context: { issueId: f.issue.id, antigravitySwarmCommentId: ids[label] } })) + .rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/newer \/swarm/) }); + } + }); + + it("keeps a recorded /swarm request's marker when an undelivered-comment backstop re-queues it", 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: "and update the readme", createdAt: new Date(Date.now() + 1000) }).returning(); + await saveUndeliveredUserComments(db, { companyId: f.company.id, issueId: f.issue.id, agentId: f.agent.id, + commentIds: [f.comment.id, ordinary!.id], allowedStatuses: ["todo"] }); + const [receipt] = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.company.id), + eq(agentWakeupRequests.status, "deferred_issue_execution"))); + expect((receipt!.payload as Record)._paperclipWakeContext).toMatchObject({ antigravitySwarmCommentId: f.comment.id }); + }); + 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 2eddf86d010..32d4c7b7a86 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -4,6 +4,7 @@ import { activityLog, agentWakeupRequests, agents, heartbeatRuns, issueComments, import { logActivity } from "./activity-log.js"; import { instanceSettingsService } from "./instance-settings.js"; import { PaperclipRunnerProviderProfileError } from "./native-runtime/provider-profile.js"; +import { recordedSwarmRequestSql } from "./queued-comment-delivery.js"; import { saveUndeliveredUserComments } from "./work-intent-outbox.js"; import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from "../lib/queued-comment-context.js"; @@ -22,8 +23,8 @@ import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from * never run as an ordinary request. */ export const ANTIGRAVITY_SWARM_COMMAND = "swarm" as const; -export { ANTIGRAVITY_SWARM_UNAVAILABLE } from "./antigravity-swarm-refusal.js"; -import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "./antigravity-swarm-refusal.js"; +export { ANTIGRAVITY_SWARM_REQUESTED_ACTION, ANTIGRAVITY_SWARM_UNAVAILABLE, isAntigravityAgent } from "./antigravity-swarm-refusal.js"; +import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, ANTIGRAVITY_SWARM_UNAVAILABLE, isAntigravityAgent } from "./antigravity-swarm-refusal.js"; /** 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; @@ -31,10 +32,6 @@ type Json = Record; const record = (value: unknown): Json => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; -export function isAntigravityAgent(agent: { adapterType: string; adapterConfig: unknown } | null): boolean { - const config = record(agent?.adapterConfig); - return agent?.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity"; -} export function antigravitySwarmRefusal(input: { enabled: boolean; @@ -57,8 +54,6 @@ export function requestedAntigravitySwarmCommentId(context: unknown): string | n return typeof value === "string" && /^[0-9a-f-]{36}$/i.test(value) ? value : null; } -export const ANTIGRAVITY_SWARM_REQUESTED_ACTION = "issue.antigravity_swarm_requested"; - /** The swarm's instruction from a recorded request comment: its text, without a leading /swarm it may still carry. */ export function antigravitySwarmRequestFromComment(body: string): string { return (parseLeadingUserCommand(body, ["swarm"])?.argument ?? body).trim(); @@ -160,12 +155,35 @@ export async function resolveAntigravitySwarmRun(db: Db, input: { sql`${activityLog.details}->>'commentId' = ${commentId}`)) .limit(1); if (!requested) return null; - // The swarm's only instruction is this recorded comment's own text. - const request = antigravitySwarmRequestFromComment(requested.body); const refuse = (message: string): never => { throw new PaperclipRunnerProviderProfileError(ANTIGRAVITY_SWARM_UNAVAILABLE, message); }; + // A later user /swarm replaces an earlier one (queued-comment-delivery.ts + // counts the earlier one handled). When the newest request rode into this + // wake, this run is that swarm; otherwise this request was replaced and + // never runs, neither as a swarm nor as ordinary work. + const wakeIds = await wakeCommentIds(db, input); + const recordedInWake = await recordedSwarmRequestIds(db, input.companyId, input.issueId, wakeIds); + const newest = await newestSwarmRequest(db, input.companyId, input.issueId); + let selected = { commentId, body: requested.body }; + if (newest && newest.id !== commentId) { + if (!wakeIds.includes(newest.id)) { + await queueCommentsTheSwarmDoesNotSend(db, { ...input, commentId }); + refuse("A newer /swarm request on this task replaced this one, so this one did not run."); + } + selected = { commentId: newest.id, body: newest.body }; + } + const replacedCommentIds = recordedInWake.filter(id => id !== selected.commentId); + // The swarm's only instruction is this recorded comment's own text. + const request = antigravitySwarmRequestFromComment(selected.body); // A requested swarm with nothing (or too much) to run is refused, never run as ordinary work. const requestRefusal = antigravitySwarmRequestRefusal(request); if (requestRefusal) refuse(requestRefusal); + return selectSwarm(db, { ...input, commentId: selected.commentId, request, replacedCommentIds, refuse }); +} + +async function selectSwarm(db: Db, input: Parameters[1] & { + commentId: string; request: string; replacedCommentIds: string[]; refuse: (message: string) => never; +}): Promise { + const { commentId, request, refuse } = input; 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) @@ -208,7 +226,9 @@ export async function resolveAntigravitySwarmRun(db: Db, input: { 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.", + ...(input.replacedCommentIds.length ? { replacedCommentIds: input.replacedCommentIds } : {}), + summary: (input.replacedCommentIds.length ? "Your latest /swarm request replaced the earlier one, which did not run. " : "") + + "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 { commentId, request }; @@ -247,12 +267,7 @@ async function userRetryStartedRun(db: Db, input: { companyId: string; agentId: async function queueCommentsTheSwarmDoesNotSend(db: Db, input: { companyId: string; issueId: string; runId: string; agent: { id: string }; context: unknown; commentId: string; }): Promise { - 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))]; + const others = (await wakeCommentIds(db, input)).filter(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), @@ -265,6 +280,31 @@ async function queueCommentsTheSwarmDoesNotSend(db: Db, input: { commentIds: owed, allowedStatuses: ["backlog", "todo", "in_progress", "in_review", "blocked"] }); } +/** The user comment ids this run's wake carries (its stored context and the wake's own), in order. */ +async function wakeCommentIds(db: Db, input: { companyId: string; runId: string; context: unknown }): Promise { + 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]); + return [...new Set(merged.filter((id): id is string => typeof id === "string" && /^[0-9a-f-]{36}$/i.test(id)))]; +} + +async function recordedSwarmRequestIds(db: Db, companyId: string, issueId: string, commentIds: string[]): Promise { + if (commentIds.length === 0) return []; + const rows = await db.select({ id: issueComments.id }).from(issueComments).where(and(eq(issueComments.companyId, companyId), + eq(issueComments.issueId, issueId), inArray(issueComments.id, commentIds), recordedSwarmRequestSql(companyId, sql`${issueComments}`))); + return commentIds.filter(id => rows.some(row => row.id === id)); +} + +/** The task's newest live recorded /swarm request: the one a later request has not replaced. */ +async function newestSwarmRequest(db: Db, companyId: string, issueId: string): Promise<{ id: string; body: string } | null> { + const [newest] = await db.select({ id: issueComments.id, body: issueComments.body }).from(issueComments) + .where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), isNull(issueComments.deletedAt), + recordedSwarmRequestSql(companyId, sql`${issueComments}`))) + .orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1); + return newest ?? null; +} + export interface AntigravitySwarmSelection { commentId: string; /** The recorded request comment's own text: the swarm's only instruction. */ diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index d9cbb2c62ea..8752c3e4dd7 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -1,5 +1,6 @@ import { and, eq, inArray, sql, type SQL } from "drizzle-orm"; -import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db"; +import { activityLog, heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db"; +import { ANTIGRAVITY_SWARM_REQUESTED_ACTION } from "./antigravity-swarm-refusal.js"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; /** The wake reason an inbound chat message records (see chat inbound wakeups). */ @@ -44,7 +45,8 @@ export async function deliveredQueuedCommentIds(tx: Pick, input: { or jsonb_path_exists(delivered_run.context_snapshot, '$.paperclipWake.messages[*] ? (@.id == $id)', jsonb_build_object('id', ${issueComments.id}::text))))) or ${firstTurnDeliveredSql(companyId, issueId, input.agentId)} - or ${historyReadDeliveredSql(companyId, issueId, input.agentId)})`, + or ${historyReadDeliveredSql(companyId, issueId, input.agentId)} + or ${replacedSwarmRequestSql(companyId)})`, )); return new Set(rows.map(row => row.id)); } @@ -59,6 +61,35 @@ function swarmRunDeliversOnlyItsRequest(run: SQL) { or ${run}.context_snapshot->>'antigravitySwarmCommentId' = ${issueComments.id}::text)`; } +/** + * SQL: the comment row `comment` (an `issue_comments` reference or alias) is a + * signed-in user's recorded /swarm request on its task: the user wrote it and + * the server recorded the request for that user (services/antigravity-swarm.ts). + */ +export function recordedSwarmRequestSql(companyId: string, comment: SQL) { + return sql`(${comment}.author_user_id is not null and ${comment}.author_agent_id is null + and exists (select 1 from ${activityLog} swarm_record + where swarm_record.company_id = ${companyId} and swarm_record.action = ${ANTIGRAVITY_SWARM_REQUESTED_ACTION} + and swarm_record.entity_id = ${comment}.issue_id::text and swarm_record.actor_type = 'user' + and swarm_record.actor_id = ${comment}.author_user_id + and swarm_record.details->>'commentId' = ${comment}.id::text))`; +} + +/** + * A later user /swarm replaces an earlier one: once a newer recorded request + * exists on the task, the earlier request is handled. It never runs, neither + * as a swarm nor as ordinary work, and no backstop replays it. + */ +function replacedSwarmRequestSql(companyId: string) { + const newer = sql.raw("newer_swarm_request"); + return sql`(${recordedSwarmRequestSql(companyId, sql`${issueComments}`)} + and exists (select 1 from ${issueComments} ${newer} + where ${newer}.company_id = ${companyId} and ${newer}.issue_id = ${issueComments.issueId} + and ${newer}.deleted_at is null + and (${newer}.created_at, ${newer}.id) > (${issueComments.createdAt}, ${issueComments.id}) + and ${recordedSwarmRequestSql(companyId, newer)}))`; +} + export const TASK_HISTORY_READ_EVENT = "task_history.read"; export async function recordTaskHistoryRead(db: Db, input: { diff --git a/server/src/services/work-intent-outbox.ts b/server/src/services/work-intent-outbox.ts index a1eb2edbc71..a143337a717 100644 --- a/server/src/services/work-intent-outbox.ts +++ b/server/src/services/work-intent-outbox.ts @@ -1,8 +1,9 @@ -import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; -import { agentWakeupRequests, budgetPolicies, issueComments, issues, type Db } from "@paperclipai/db"; +import { and, desc, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; +import { agents, agentWakeupRequests, budgetPolicies, issueComments, issues, type Db } from "@paperclipai/db"; +import { isAntigravityAgent } from "./antigravity-swarm-refusal.js"; import { notifyDeferredExecutionEligibility, notifyDeferredExecutionWork, notifyDeferredWakesForIssue } from "./deferred-execution-notifications.js"; import { withQueuedCommentIdsInWakePayload } from "./issue-queued-comment-queue.js"; -import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js"; +import { deliveredQueuedCommentIds, recordedSwarmRequestSql } from "./queued-comment-delivery.js"; import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; import { notifyRunDispatch } from "./run-dispatch-notifications.js"; import { persistActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; @@ -161,6 +162,17 @@ export async function saveUndeliveredUserComments(db: Db, input: { const resumingAgentId = live.find(row => row.id === latest)?.authorAgentId ?? null; const agentResume = resumingAgentId !== null && remaining.every(id => live.find(row => row.id === id)?.authorAgentId); const resumeIntent = agentResume ? { resumeIntent: true, followUpRequested: true } : {}; + // A recorded /swarm request keeps its marker, so the receipt's run selects + // that swarm (services/antigravity-swarm.ts) instead of sending it as + // ordinary text. A request a later /swarm replaced already counts delivered. + // A task reassigned to another kind of agent gets the comment as text. + const [assignee] = await tx.select({ adapterType: agents.adapterType, adapterConfig: agents.adapterConfig }).from(agents) + .where(and(eq(agents.companyId, input.companyId), eq(agents.id, input.agentId))); + const [swarmRequest] = !isAntigravityAgent(assignee ?? null) ? [] : await tx.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, input.issueId), + inArray(issueComments.id, remaining), recordedSwarmRequestSql(input.companyId, sql`${issueComments}`))) + .orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1); + const swarmMarker = swarmRequest ? { antigravitySwarmCommentId: swarmRequest.id } : {}; await notifyDeferredExecutionWork(tx, { companyId: input.companyId }); await notifyDeferredWakesForIssue(tx, { companyId: input.companyId, issueId: input.issueId }); const [saved] = await tx.insert(agentWakeupRequests).values({ @@ -173,7 +185,7 @@ export async function saveUndeliveredUserComments(db: Db, input: { ...resumeIntent, ...(input.executionWait ? { executionWait: input.executionWait } : {}), [DEFERRED_WAKE_CONTEXT_KEY]: { issueId: input.issueId, taskId: input.issueId, wakeReason: "issue_commented", - source: "issue.comment", wakeCommentIds: remaining, wakeCommentId: latest, ...resumeIntent } }, remaining), + source: "issue.comment", wakeCommentIds: remaining, wakeCommentId: latest, ...resumeIntent, ...swarmMarker } }, remaining), }).returning({ id: agentWakeupRequests.id }); if (saved && issue.status === "done" && input.reopenAgentClosedDone) { const { issueService } = await import("./issues.js");