diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 3d98f79f8fb8a..79e200a254890 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ChatFileAttachment, + CheckpointId, MessageId, NodeId, ProjectId, @@ -31,6 +32,7 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; import * as TestClock from "effect/testing/TestClock"; @@ -3116,3 +3118,461 @@ describe("AntigravityAdapterV2 update_steps checklist", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 teardown and native background work", () => { + it.live( + "skips destructive session/close on scope teardown even when close capability is advertised", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-teardown-log-" }); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-agy-teardown-ws-", + }); + const requestLog = path.join(logs, "requests.ndjson"); + let closeSessionCalls = 0; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + const instanceId = ProviderInstanceId.make("antigravity-skip-close-test"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AGENT_VERSION: "1.5.14", + T3_ACP_REQUEST_LOG_PATH: requestLog, + }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + start: () => + runtime.start().pipe( + Effect.map((started) => ({ + ...started, + initializeResult: { + ...started.initializeResult, + agentCapabilities: { + ...started.initializeResult.agentCapabilities, + sessionCapabilities: { + ...started.initializeResult.agentCapabilities?.sessionCapabilities, + close: {}, + }, + }, + }, + })), + ), + closeSession: () => + Effect.sync(() => { + closeSessionCalls += 1; + }).pipe(Effect.andThen(runtime.closeSession())), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const threadId = ThreadId.make("thread-antigravity-skip-close"); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + + const sessionScope = yield* Scope.make(); + const session = yield* adapter + .openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-skip-close"), + modelSelection, + runtimePolicy, + }) + .pipe(Effect.provideService(Scope.Scope, sessionScope)); + yield* session.ensureThread({ threadId, modelSelection, runtimePolicy }); + yield* Scope.close(sessionScope, Exit.void); + + assert.equal(closeSessionCalls, 0); + const methods = (yield* fileSystem.readFileString(requestLog)) + .trim() + .split("\n") + .map((line) => (JSON.parse(line) as { method?: string }).method); + assert.include(methods, "session/new"); + assert.notInclude(methods, "session/close"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "reports live swarm workers to hasPendingBackgroundWork while letting parked mentions allow session replacement", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-prof-" }); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-ws-" }); + const instanceId = ProviderInstanceId.make("antigravity-swarm-pending-test"); + let spawnCount = 0; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + profileDirectory: profile, + makeRuntime: (input) => { + spawnCount += 1; + return makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AGENT_VERSION: "1.5.14", + }, + }, + }).pipe(Effect.provideService(SecureRandom.SecureRandom, crypto)); + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const threadId = ThreadId.make("thread-antigravity-swarm-pending"); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-swarm-pending"), + modelSelection, + runtimePolicy, + }); + const initialThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const rootSessionId = initialThread.nativeThreadRef?.nativeId; + assert.isNotNull(rootSessionId ?? null); + if (!rootSessionId) { + throw new Error("Expected Antigravity initial thread to have a nativeId"); + } + const writeSwarm = (members: Record, targetSessionId = rootSessionId) => { + const swarmFile = path.join( + profile, + "antigravity-acp", + "brain", + targetSessionId, + ".system_generated", + "swarm", + "members.json", + ); + return fileSystem + .makeDirectory(path.dirname(swarmFile), { recursive: true }) + .pipe( + Effect.andThen(fileSystem.writeFileString(swarmFile, JSON.stringify({ members }))), + ); + }; + + assert.isDefined(session.hasPendingBackgroundWork); + assert.isFalse(yield* session.hasPendingBackgroundWork!); + + // Working worker blocks idle release, forceNewNativeThread replacement, and rollbackThread. + yield* writeSwarm({ + worker: { + conversation_id: "11111111-1111-1111-1111-111111111111", + role: "worker", + phase: "RUNNING", + wake_mode: "working", + killed: false, + }, + }); + assert.isTrue(yield* session.hasPendingBackgroundWork!); + const blockedError = yield* session + .ensureThread({ threadId, modelSelection, runtimePolicy, forceNewNativeThread: true }) + .pipe(Effect.flip); + assert.instanceOf(blockedError.cause, ProviderAdapter.ProviderAdapterProtocolError); + assert.include( + (blockedError.cause as ProviderAdapter.ProviderAdapterProtocolError).detail, + "Cannot replace ACP session", + ); + const blockedRollbackError = yield* session + .rollbackThread({ + providerThread: initialThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("cp-0"), + appRunOrdinal: 0, + }, + providerThreadTurns: [], + }) + .pipe(Effect.flip); + assert.instanceOf(blockedRollbackError.cause, ProviderAdapter.ProviderAdapterProtocolError); + assert.include( + (blockedRollbackError.cause as ProviderAdapter.ProviderAdapterProtocolError).detail, + "Cannot roll back ACP provider thread", + ); + assert.equal(spawnCount, 1); + + // Waiting worker (wake_mode: "mentions") still pins idle release, but allows session replacement and rollback. + yield* writeSwarm({ + worker: { + conversation_id: "11111111-1111-1111-1111-111111111111", + role: "worker", + phase: "RUNNING", + wake_mode: "mentions", + last_read_seq: 2, + last_nudged_seq: 2, + killed: false, + }, + }); + assert.isTrue(yield* session.hasPendingBackgroundWork!); + const replacedThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + forceNewNativeThread: true, + }); + assert.equal(spawnCount, 2); + assert.equal(replacedThread.nativeThreadRef?.nativeId, "mock-session-1"); + + yield* writeSwarm( + { + worker: { + conversation_id: "11111111-1111-1111-1111-111111111111", + role: "worker", + phase: "RUNNING", + wake_mode: "mentions", + last_read_seq: 2, + last_nudged_seq: 2, + killed: false, + }, + }, + "mock-session-1", + ); + assert.isTrue(yield* session.hasPendingBackgroundWork!); + const rolledBack = yield* session.rollbackThread({ + providerThread: replacedThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("cp-0"), + appRunOrdinal: 0, + }, + providerThreadTurns: [], + }); + assert.equal(spawnCount, 3); + assert.equal(rolledBack.providerThread.nativeThreadRef?.nativeId, "mock-session-1"); + + // Once the active worker is killed, pending work is false. + yield* writeSwarm( + { + worker: { + conversation_id: "11111111-1111-1111-1111-111111111111", + role: "worker", + phase: "KILLED", + wake_mode: "mentions", + killed: true, + }, + }, + "mock-session-1", + ); + assert.isFalse(yield* session.hasPendingBackgroundWork!); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "aborts forceNewNativeThread and rollbackThread replacement at commit when active background work starts during startup", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const profile = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-agy-replace-race-prof-", + }); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-agy-replace-race-ws-", + }); + const instanceId = ProviderInstanceId.make("antigravity-replace-race-test"); + let spawnCount = 0; + let rootSessionId: string | undefined; + let initialScopeFinalized = false; + const finalizedReplacementSpawns: Array = []; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + + const writeSwarmWorker = (targetSessionId: string) => { + const swarmFile = path.join( + profile, + "antigravity-acp", + "brain", + targetSessionId, + ".system_generated", + "swarm", + "members.json", + ); + return fileSystem.makeDirectory(path.dirname(swarmFile), { recursive: true }).pipe( + Effect.andThen( + fileSystem.writeFileString( + swarmFile, + JSON.stringify({ + members: { + worker: { + conversation_id: "11111111-1111-1111-1111-111111111111", + role: "worker", + phase: "RUNNING", + wake_mode: "working", + killed: false, + }, + }, + }), + ), + ), + ); + }; + + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + profileDirectory: profile, + makeRuntime: (input) => + Effect.gen(function* () { + spawnCount += 1; + const currentSpawn = spawnCount; + const runtimeScope = yield* Effect.scope; + yield* Scope.addFinalizer( + runtimeScope, + Effect.sync(() => { + if (currentSpawn === 1) { + initialScopeFinalized = true; + } else { + finalizedReplacementSpawns.push(currentSpawn); + } + }), + ); + const runtime = yield* makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AGENT_VERSION: "1.5.14", + }, + }, + }).pipe(Effect.provideService(SecureRandom.SecureRandom, crypto)); + return currentSpawn === 2 || currentSpawn === 3 + ? ({ + ...runtime, + start: () => + Effect.gen(function* () { + if (rootSessionId === undefined) { + throw new Error( + "Expected initial rootSessionId before replacement start", + ); + } + yield* writeSwarmWorker(rootSessionId).pipe(Effect.orDie); + return yield* runtime.start(); + }), + } satisfies RuntimeService) + : runtime; + }), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const threadId = ThreadId.make("thread-antigravity-replace-race"); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-replace-race"), + modelSelection, + runtimePolicy, + }); + const initialThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + rootSessionId = initialThread.nativeThreadRef?.nativeId ?? undefined; + assert.isDefined(rootSessionId); + + const abortedError = yield* session + .ensureThread({ threadId, modelSelection, runtimePolicy, forceNewNativeThread: true }) + .pipe(Effect.flip); + assert.instanceOf(abortedError.cause, ProviderAdapter.ProviderAdapterProtocolError); + assert.include( + (abortedError.cause as ProviderAdapter.ProviderAdapterProtocolError).detail, + "Cannot replace ACP session", + ); + assert.equal(spawnCount, 2); + assert.include(finalizedReplacementSpawns, 2); + assert.isFalse(initialScopeFinalized); + assert.isTrue(yield* session.hasPendingBackgroundWork!); + + // Clear swarm so rollback pre-check passes, then race active work into rollback replacement startup. + yield* fileSystem.remove( + path.join( + profile, + "antigravity-acp", + "brain", + rootSessionId!, + ".system_generated", + "swarm", + ), + { recursive: true }, + ); + assert.isFalse(yield* session.hasPendingBackgroundWork!); + + const abortedRollbackError = yield* session + .rollbackThread({ + providerThread: initialThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("cp-0"), + appRunOrdinal: 0, + }, + providerThreadTurns: [], + }) + .pipe(Effect.flip); + assert.instanceOf(abortedRollbackError.cause, ProviderAdapter.ProviderAdapterProtocolError); + assert.include( + (abortedRollbackError.cause as ProviderAdapter.ProviderAdapterProtocolError).detail, + "Cannot roll back ACP provider thread", + ); + assert.equal(spawnCount, 3); + assert.include(finalizedReplacementSpawns, 3); + assert.isFalse(initialScopeFinalized); + assert.isTrue(yield* session.hasPendingBackgroundWork!); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 9534a50829fa1..aec7685e34fd6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -34,6 +34,7 @@ import { antigravitySubagentLaunches, describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, + readAntigravityHasPendingBackgroundWork, readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; @@ -247,6 +248,9 @@ export function makeAntigravityAcpAdapterFlavor( deferFinalizeForBackgroundWork: true, wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, + // Antigravity treats session/close as ForceStopCascadeTree and writes a fake user force-cancel + // inbox notice; closing the process via SIGTERM shuts it down without destroying cascade state. + skipCloseSessionOnTeardown: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, // agy sometimes loses the terminal update or wake for a background command, which would // hold the turn in Working forever. 30 minutes still leaves long commands room. @@ -320,6 +324,12 @@ export function makeAntigravityAcpAdapterFlavor( profileDirectory, sessionId, }), + hasPendingBackgroundWork: ({ sessionId, purpose }) => + readAntigravityHasPendingBackgroundWork({ + profileDirectory, + sessionId, + purpose, + }), }), }; } diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index e0336da84ac64..11e844c8667aa 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -1,8 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off -- fixtures name transcript files by URL. +import * as NodeFS from "node:fs"; import * as NodeURL from "node:url"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { expect, it } from "@effect/vitest"; +import { expect, it, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -13,6 +14,7 @@ import { describeAntigravitySubagentLaunches, readAntigravityChildrenAtWork, readAntigravityChildWork, + readAntigravityHasPendingBackgroundWork, readAntigravityPendingReply, } from "./AntigravityChildWork.ts"; import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts"; @@ -682,4 +684,309 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { expect(yield* pending()).toBe(false); }), ); + + it.effect( + "detects active and waiting swarms, detached subagents, and wakes while ignoring pre-stop records", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-bg-work-" }); + const write = (conversationId: string, segments: ReadonlyArray, value: unknown) => { + const file = path.join( + profile, + "antigravity-acp", + "brain", + conversationId, + ".system_generated", + ...segments, + ); + return fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen( + fs.writeFileString(file, typeof value === "string" ? value : JSON.stringify(value)), + ), + ); + }; + const hasPending = (purpose?: "idle_release" | "session_replace") => + readAntigravityHasPendingBackgroundWork({ + profileDirectory: profile, + sessionId: ROOT, + ...(purpose === undefined ? {} : { purpose }), + }); + const workerA = "11111111-1111-1111-1111-111111111111"; + const workerB = "22222222-2222-2222-2222-222222222222"; + const detachedId = "33333333-3333-3333-3333-333333333333"; + + // Clean empty profile stays releasable. + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + // Coordinator-only or killed swarm returns false. + yield* write(ROOT, ["swarm", "members.json"], { + members: { + coordinator: { + conversation_id: ROOT, + role: "coordinator", + phase: "RUNNING", + wake_mode: "mentions", + killed: false, + }, + "worker-dead": { + conversation_id: workerB, + role: "worker", + phase: "KILLED", + wake_mode: "mentions", + killed: true, + }, + }, + }); + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + // Waiting swarm worker (wake_mode: "mentions") pins idle_release without blocking session_replace. + yield* write(ROOT, ["swarm", "members.json"], { + members: { + coordinator: { + conversation_id: ROOT, + role: "coordinator", + phase: "RUNNING", + wake_mode: "mentions", + killed: false, + }, + "worker-waiting": { + conversation_id: workerA, + role: "worker", + phase: "RUNNING", + wake_mode: "mentions", + last_read_seq: 4, + last_nudged_seq: 4, + killed: false, + }, + }, + }); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(false); + + // Actively working swarm worker (wake_mode: "working") returns true for both purposes. + yield* write(ROOT, ["swarm", "members.json"], { + members: { + "worker-active": { + conversation_id: workerA, + role: "worker", + phase: "RUNNING", + wake_mode: "working", + killed: false, + }, + }, + }); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + + // A worker predating a system stop notice does not pin the session. + yield* write(workerA, ["messages", "brief-old.json"], { + sender: ROOT, + timestamp: "2026-11-23T01:00:00Z", + content: "brief", + }); + yield* write(ROOT, ["messages", "stop-1.json"], { + id: "stop-1", + sender: "system", + priority: "MESSAGE_PRIORITY_LOW", + timestamp: "2026-11-23T01:10:00Z", + content: + "[Notice] All your subagents and background tasks have been stopped due to server restart.", + }); + yield* write(ROOT, ["messages", "read.json"], { "stop-1": true }); + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + // A worker woken after a force-cancellation notice is live again. + yield* write(ROOT, ["messages", "stop-2.json"], { + id: "stop-2", + sender: "system", + priority: "MESSAGE_PRIORITY_LOW", + timestamp: "2026-11-23T01:20:00Z", + content: + "[Notice] All your subagents and background tasks have been stopped due to user force cancellation.", + }); + yield* write(ROOT, ["messages", "read.json"], { "stop-1": true, "stop-2": true }); + yield* write(workerA, ["messages", "wake-new.json"], { + sender: ROOT, + timestamp: "2026-11-23T01:25:00Z", + content: "resume work", + }); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + + // Remove swarm file and test detached invoke_subagent lifecycle against the stop notice. + yield* fs.remove( + path.join(profile, "antigravity-acp", "brain", ROOT, ".system_generated", "swarm"), + { recursive: true }, + ); + yield* write(ROOT, ["subagents", `${detachedId}.json`], { + conversationId: detachedId, + state: "SUBAGENT_STATE_ALIVE", + }); + // Predates stop-2 -> ignored. + yield* write(detachedId, ["messages", "launch-old.json"], { + sender: ROOT, + timestamp: "2026-11-23T01:15:00Z", + content: "old prompt", + }); + expect(yield* hasPending("idle_release")).toBe(false); + + // Revived after stop-2 -> pending until child reports. + yield* write(detachedId, ["messages", "launch-new.json"], { + sender: ROOT, + timestamp: "2026-11-23T01:25:00Z", + content: "new prompt", + }); + expect(yield* hasPending("idle_release")).toBe(true); + + // Child reported -> no longer pending. + yield* write(ROOT, ["messages", "report-1.json"], { + id: "report-1", + sender: detachedId, + priority: "MESSAGE_PRIORITY_LOW", + timestamp: "2026-11-23T01:26:00Z", + content: "done", + }); + yield* write(ROOT, ["messages", "read.json"], { + "stop-1": true, + "stop-2": true, + "report-1": true, + }); + expect(yield* hasPending("idle_release")).toBe(false); + + // Parent sent a follow-up prompt after the child reported -> active again. + yield* write(detachedId, ["messages", "followup.json"], { + sender: ROOT, + timestamp: "2026-11-23T01:27:00Z", + content: "follow up", + }); + expect(yield* hasPending("idle_release")).toBe(true); + + // Killed detached child -> false. + yield* write(ROOT, ["subagents", `${detachedId}.json`], { + conversationId: detachedId, + state: "SUBAGENT_STATE_KILLED", + }); + expect(yield* hasPending("idle_release")).toBe(false); + + // Unread high-priority wake holds the session open even with no children. + yield* write(ROOT, ["messages", "wake-unread.json"], { + id: "wake-unread", + sender: `${ROOT}/task-1`, + priority: "MESSAGE_PRIORITY_HIGH", + timestamp: "2026-11-23T01:28:00Z", + }); + expect(yield* hasPending("idle_release")).toBe(true); + + // Corrupt read.json is treated as unknown for lifecycle checks while keeping pendingReply fail-closed. + yield* write(ROOT, ["messages", "read.json"], "{truncated"); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + expect( + yield* readAntigravityPendingReply({ profileDirectory: profile, sessionId: ROOT }), + ).toBe(false); + + // Mark wake read, then verify a corrupt parent message neither masks a working swarm nor + // reports "no work" on its own. + yield* write(ROOT, ["messages", "read.json"], { + "stop-1": true, + "stop-2": true, + "report-1": true, + "wake-unread": true, + }); + yield* write(ROOT, ["messages", "corrupt.json"], "{truncated"); + yield* write(ROOT, ["swarm", "members.json"], { + members: { + "worker-working": { + conversation_id: workerA, + role: "worker", + phase: "RUNNING", + wake_mode: "working", + killed: false, + }, + }, + }); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + + // Remove swarm: unreadable parent inbox still conservatively returns true until removed. + yield* fs.remove( + path.join(profile, "antigravity-acp", "brain", ROOT, ".system_generated", "swarm"), + { recursive: true }, + ); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + + yield* fs.remove( + path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + "messages", + "corrupt.json", + ), + ); + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + // Decoded non-waking final transcript step stays releasable; partial tail preserves unknown. + yield* write( + ROOT, + ["logs", "transcript.jsonl"], + `${JSON.stringify({ step_index: 0, type: "PLANNER_RESPONSE", status: "DONE", content: "ok" })}\n`, + ); + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + yield* write( + ROOT, + ["logs", "transcript.jsonl"], + `${JSON.stringify({ step_index: 0, type: "PLANNER_RESPONSE", status: "DONE", content: "ok" })}\n{"type":"SYSTEM_MESSAGE"`, + ); + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + expect( + yield* readAntigravityPendingReply({ profileDirectory: profile, sessionId: ROOT }), + ).toBe(false); + + yield* write(ROOT, ["logs", "transcript.jsonl"], ""); + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + + // Transient lstat I/O failure on messages/ is preserved conservatively instead of treated as empty. + const messagesDir = path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + "messages", + ); + const realLstat = NodeFS.promises.lstat.bind(NodeFS.promises); + const lstatSpy = vi.spyOn(NodeFS.promises, "lstat").mockImplementation((async ( + targetPath, + options, + ) => { + if (String(targetPath) === messagesDir) { + throw Object.assign(new Error("EIO"), { code: "EIO" }); + } + return realLstat(targetPath, options); + }) as typeof NodeFS.promises.lstat); + yield* Effect.gen(function* () { + expect(yield* hasPending("idle_release")).toBe(true); + expect(yield* hasPending("session_replace")).toBe(true); + }).pipe(Effect.ensuring(Effect.sync(() => lstatSpy.mockRestore()))); + + expect(yield* hasPending("idle_release")).toBe(false); + expect(yield* hasPending("session_replace")).toBe(false); + }), + ); }); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index aa0932cf0f41a..84f56900c601f 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -13,7 +13,12 @@ import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; -import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; +import { + antigravityManagedPath, + antigravityProfileRoot, + inspectAntigravityManagedPath, + inspectAntigravityProfileRoot, +} from "./AntigravityProfilePaths.ts"; import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts"; // Field numbers from the runtime's trajectory protos (exa.cortex_pb). @@ -668,63 +673,105 @@ const decodeInboxPriorityMessage = Schema.decodeUnknownOption( ), ); -async function hasUnreadWakingInboxMessage( +type BackgroundWorkCheckState = "yes" | "no" | "unknown"; + +function nodeErrorCode(cause: unknown): string | undefined { + return typeof cause === "object" && + cause !== null && + "code" in cause && + typeof cause.code === "string" + ? cause.code + : undefined; +} + +async function inspectUnreadWakingInboxMessage( profileRoot: string, sessionId: string, -): Promise { +): Promise { const directory = ["antigravity-acp", "brain", sessionId, ".system_generated", "messages"]; - const inbox = await antigravityManagedPath(profileRoot, directory, "directory"); - if (inbox === undefined) return false; + const inbox = await inspectAntigravityManagedPath(profileRoot, directory, "directory"); + if (inbox.status === "missing" || inbox.status === "invalid") return "no"; + if (inbox.status === "error") return "unknown"; const entries = await NodeFSP.readdir(inbox.path).catch(() => undefined); - if (entries === undefined) return false; + if (entries === undefined) return "unknown"; const messageNames = entries.filter((name) => name.endsWith(".json") && name !== "read.json"); - if (messageNames.length === 0 || messageNames.length > MAX_MESSAGE_FILES) return false; + if (messageNames.length === 0) return "no"; + if (messageNames.length > MAX_MESSAGE_FILES) return "unknown"; let readReceipts: Readonly> = {}; if (entries.includes("read.json")) { - const receiptFile = await antigravityManagedPath( + const receiptFile = await inspectAntigravityManagedPath( profileRoot, [...directory, "read.json"], "file", ); - if (receiptFile === undefined || receiptFile.info.size > MAX_STEP_BYTES) return false; - const rawReceipts = await NodeFSP.readFile(receiptFile.path, "utf8").catch(() => undefined); - if (rawReceipts === undefined) return false; - const decodedReceipts = decodeReadReceipts(rawReceipts); - if (Option.isNone(decodedReceipts)) return false; - readReceipts = decodedReceipts.value; + if (receiptFile.status !== "missing") { + if (receiptFile.status !== "ok" || receiptFile.info.size > MAX_STEP_BYTES) return "unknown"; + const rawReceipts = await NodeFSP.readFile(receiptFile.path, "utf8").catch(() => undefined); + if (rawReceipts === undefined) return "unknown"; + const decodedReceipts = decodeReadReceipts(rawReceipts); + if (Option.isNone(decodedReceipts)) return "unknown"; + readReceipts = decodedReceipts.value; + } } + let unknown = false; for (const name of messageNames) { const fileId = name.slice(0, -5); if (readReceipts[fileId] === true) continue; - const file = await antigravityManagedPath(profileRoot, [...directory, name], "file"); - if (file === undefined || file.info.size > MAX_STEP_BYTES) continue; + const file = await inspectAntigravityManagedPath(profileRoot, [...directory, name], "file"); + if (file.status === "missing") continue; + if (file.status !== "ok" || file.info.size > MAX_STEP_BYTES) { + unknown = true; + continue; + } const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); - if (raw === undefined) continue; + if (raw === undefined) { + unknown = true; + continue; + } const decoded = decodeInboxPriorityMessage(raw); - if (Option.isNone(decoded)) continue; + if (Option.isNone(decoded)) { + unknown = true; + continue; + } if (decoded.value.id !== undefined && readReceipts[decoded.value.id] === true) continue; - if (decoded.value.priority === HIGH_PRIORITY_MESSAGE) return true; + if (decoded.value.priority === HIGH_PRIORITY_MESSAGE) return "yes"; } - return false; + return unknown ? "unknown" : "no"; } -async function readLastTranscriptLine( +async function inspectLastTranscriptLine( profileRoot: string, sessionId: string, -): Promise | undefined> { - const transcript = await antigravityManagedPath( +): Promise< + | { readonly status: "absent" } + | { readonly status: "invalid" } + | { readonly status: "unknown" } + | { readonly status: "ok"; readonly line: Schema.Schema.Type } +> { + const transcript = await inspectAntigravityManagedPath( profileRoot, ["antigravity-acp", "brain", sessionId, ".system_generated", "logs", "transcript.jsonl"], "file", ); - if (transcript === undefined) return undefined; - const handle = await NodeFSP.open( - transcript.path, - NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), - ); + if (transcript.status === "missing") return { status: "absent" }; + if (transcript.status === "invalid") return { status: "invalid" }; + if (transcript.status === "error") return { status: "unknown" }; + let handle: NodeFSP.FileHandle; + try { + handle = await NodeFSP.open( + transcript.path, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + } catch (cause) { + const code = nodeErrorCode(cause); + if (code === "ENOENT") return { status: "absent" }; + if (code === "ELOOP") return { status: "invalid" }; + return { status: "unknown" }; + } try { const stat = await handle.stat(); - if (!stat.isFile() || stat.size === 0) return undefined; + if (!stat.isFile()) return { status: "invalid" }; + if (stat.size === 0) return { status: "absent" }; for (const byteCap of [PENDING_REPLY_TAIL_BYTES, TRANSCRIPT_BYTE_CAP]) { const start = Math.max(0, stat.size - byteCap); const buffer = Buffer.alloc(stat.size - start); @@ -734,19 +781,131 @@ async function readLastTranscriptLine( end -= 1; } if (end === 0) { - if (start === 0) return undefined; + if (start === 0) return { status: "absent" }; continue; } const trimmed = buffer.subarray(0, end); const lastNewline = trimmed.lastIndexOf(0x0a); if (lastNewline === -1 && start > 0) continue; const line = trimmed.toString("utf8", lastNewline + 1); - return Option.getOrUndefined(decodeTranscriptLine(line)); + const decoded = decodeTranscriptLine(line); + return Option.isSome(decoded) ? { status: "ok", line: decoded.value } : { status: "unknown" }; } - return undefined; + return { status: "unknown" }; + } catch { + return { status: "unknown" }; } finally { - await handle.close(); + await handle.close().catch(() => undefined); + } +} + +const SYSTEM_STOP_NOTICE_PREFIX = + "All your subagents and background tasks have been stopped due to "; + +const decodeInboxMessageSummary = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + sender: Schema.String, + timestamp: Schema.optional(Schema.String), + content: Schema.optional(Schema.String), + }), + ), +); + +const decodeSwarmMembers = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + members: Schema.optional( + Schema.Record( + Schema.String, + Schema.Struct({ + conversation_id: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + desired_state: Schema.optional(Schema.String), + phase: Schema.optional(Schema.String), + wake_mode: Schema.optional(Schema.String), + killed: Schema.optional(Schema.Boolean), + last_read_seq: Schema.optional(Schema.Number), + last_nudged_seq: Schema.optional(Schema.Number), + }), + ), + ), + }), + ), +); + +interface InboxMessageSummary { + readonly sender: string; + readonly timestampMs: number | undefined; + readonly content: string | undefined; +} + +interface InboxMessagesResult { + readonly messages: ReadonlyArray; + readonly incomplete: boolean; +} + +const parseTimestampMs = (timestamp: string | undefined): number | undefined => { + if (timestamp === undefined) return undefined; + const ms = Date.parse(timestamp); + return Number.isFinite(ms) ? ms : undefined; +}; + +async function readMessageSummaries( + profileRoot: string, + conversationId: string, +): Promise { + const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"]; + const inbox = await inspectAntigravityManagedPath(profileRoot, directory, "directory"); + if (inbox.status === "missing" || inbox.status === "invalid") { + return { messages: [], incomplete: false }; + } + if (inbox.status === "error") return { messages: [], incomplete: true }; + const entries = await NodeFSP.readdir(inbox.path).catch(() => undefined); + if (entries === undefined) return { messages: [], incomplete: true }; + const names = entries.filter((name) => name.endsWith(".json") && name !== "read.json"); + if (names.length > MAX_MESSAGE_FILES) return { messages: [], incomplete: true }; + const messages: Array = []; + let incomplete = false; + for (const name of names) { + const file = await inspectAntigravityManagedPath(profileRoot, [...directory, name], "file"); + if (file.status === "missing") continue; + if (file.status !== "ok" || file.info.size > MAX_STEP_BYTES) { + incomplete = true; + continue; + } + const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); + if (raw === undefined) { + incomplete = true; + continue; + } + const decoded = decodeInboxMessageSummary(raw); + if (Option.isNone(decoded)) { + incomplete = true; + continue; + } + messages.push({ + sender: decoded.value.sender, + timestampMs: parseTimestampMs(decoded.value.timestamp), + content: decoded.value.content, + }); } + return { messages, incomplete }; +} + +async function inspectUnansweredWakingTranscriptStep( + profileRoot: string, + sessionId: string, +): Promise { + const lastStep = await inspectLastTranscriptLine(profileRoot, sessionId); + if (lastStep.status === "absent" || lastStep.status === "invalid") return "no"; + if (lastStep.status === "unknown") return "unknown"; + if (lastStep.line.type !== "SYSTEM_MESSAGE") return "no"; + return lastStep.line.content === undefined || + lastStep.line.content.includes(`priority=${HIGH_PRIORITY_MESSAGE}`) || + !lastStep.line.content.includes(`priority=${LOW_PRIORITY_MESSAGE}`) + ? "yes" + : "no"; } /** @@ -760,14 +919,10 @@ export const readAntigravityPendingReply = Effect.fn("readAntigravityPendingRepl const read = async (): Promise => { const profileRoot = await antigravityProfileRoot(input.profileDirectory); if (profileRoot === undefined) return false; - if (await hasUnreadWakingInboxMessage(profileRoot, input.sessionId)) return true; - const lastStep = await readLastTranscriptLine(profileRoot, input.sessionId); - if (lastStep === undefined || lastStep.type !== "SYSTEM_MESSAGE") return false; - return ( - lastStep.content === undefined || - lastStep.content.includes(`priority=${HIGH_PRIORITY_MESSAGE}`) || - !lastStep.content.includes(`priority=${LOW_PRIORITY_MESSAGE}`) - ); + if ((await inspectUnreadWakingInboxMessage(profileRoot, input.sessionId)) === "yes") { + return true; + } + return (await inspectUnansweredWakingTranscriptStep(profileRoot, input.sessionId)) === "yes"; }; return yield* Effect.tryPromise({ try: read, @@ -776,6 +931,188 @@ export const readAntigravityPendingReply = Effect.fn("readAntigravityPendingRepl }, ); +/** + * True when Antigravity owns background work for this session that would be lost if the process + * were torn down: unread high-priority wakes, unanswered waking steps, live swarm members in + * `swarm/members.json`, or active/revived detached subagents in `subagents/*.json`. + * Ignores persisted child records predating the latest system stop notice. + */ +export const readAntigravityHasPendingBackgroundWork = Effect.fn( + "readAntigravityHasPendingBackgroundWork", +)(function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; + readonly purpose?: "idle_release" | "session_replace"; +}) { + if (!NATIVE_ID.test(input.sessionId)) return false; + const read = async (): Promise => { + const profileRootResult = await inspectAntigravityProfileRoot(input.profileDirectory); + if (profileRootResult.status === "missing") return false; + if (profileRootResult.status === "error") return true; + const profileRoot = profileRootResult.path; + let unknownState = false; + const inboxWakeState = await inspectUnreadWakingInboxMessage(profileRoot, input.sessionId); + if (inboxWakeState === "yes") return true; + if (inboxWakeState === "unknown") unknownState = true; + const transcriptState = await inspectUnansweredWakingTranscriptStep( + profileRoot, + input.sessionId, + ); + if (transcriptState === "yes") return true; + if (transcriptState === "unknown") unknownState = true; + + const parentInbox = await readMessageSummaries(profileRoot, input.sessionId); + if (parentInbox.incomplete) { + unknownState = true; + } + let latestSystemStopMs: number | undefined; + const reportedSenders = new Set(); + const latestReportMsBySender = new Map(); + for (const msg of parentInbox.messages) { + reportedSenders.add(msg.sender); + if (msg.timestampMs !== undefined) { + const previousReportMs = latestReportMsBySender.get(msg.sender); + if (previousReportMs === undefined || msg.timestampMs > previousReportMs) { + latestReportMsBySender.set(msg.sender, msg.timestampMs); + } + if (msg.sender === "system" && msg.content?.includes(SYSTEM_STOP_NOTICE_PREFIX) === true) { + if (latestSystemStopMs === undefined || msg.timestampMs > latestSystemStopMs) { + latestSystemStopMs = msg.timestampMs; + } + } + } + } + + const swarmLookup = await inspectAntigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", input.sessionId, ".system_generated", "swarm", "members.json"], + "file", + ); + if (swarmLookup.status === "error") { + unknownState = true; + } + const swarmFile = swarmLookup.status === "ok" ? swarmLookup : undefined; + const rawSwarm = + swarmFile !== undefined && swarmFile.info.size <= MAX_STEP_BYTES + ? await NodeFSP.readFile(swarmFile.path, "utf8").catch(() => undefined) + : undefined; + const swarm = + rawSwarm === undefined ? undefined : Option.getOrUndefined(decodeSwarmMembers(rawSwarm)); + if (swarmFile !== undefined && swarm === undefined) { + unknownState = true; + } + const swarmChildIds = new Set(); + for (const member of Object.values(swarm?.members ?? {})) { + if (member.conversation_id !== undefined) { + swarmChildIds.add(member.conversation_id); + } + } + for (const [name, member] of Object.entries(swarm?.members ?? {})) { + if (name === "coordinator" || member.role === "coordinator") continue; + if ( + member.killed === true || + member.phase === "KILLED" || + member.phase === "STOPPED" || + member.desired_state === "KILLED" || + member.desired_state === "STOPPED" + ) { + continue; + } + if (latestSystemStopMs !== undefined) { + if (member.conversation_id === undefined || !NATIVE_ID.test(member.conversation_id)) { + continue; + } + const childInbox = await readMessageSummaries(profileRoot, member.conversation_id); + if (childInbox.incomplete) { + unknownState = true; + continue; + } + let latestChildMsgMs: number | undefined; + for (const msg of childInbox.messages) { + if ( + msg.timestampMs !== undefined && + (latestChildMsgMs === undefined || msg.timestampMs > latestChildMsgMs) + ) { + latestChildMsgMs = msg.timestampMs; + } + } + if (latestChildMsgMs === undefined || latestChildMsgMs <= latestSystemStopMs) { + continue; + } + } + const isActivelyWorking = + member.wake_mode === "working" || + member.phase === "STARTING" || + (member.last_nudged_seq !== undefined && + member.last_read_seq !== undefined && + member.last_nudged_seq > member.last_read_seq); + if (isActivelyWorking || input.purpose !== "session_replace") { + return true; + } + } + + const subagentsLookup = await inspectAntigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", input.sessionId, ".system_generated", "subagents"], + "directory", + ); + if (subagentsLookup.status === "error") { + unknownState = true; + } else if (subagentsLookup.status === "ok") { + const childIds = await listDetachedChildIds(profileRoot, input.sessionId); + if (childIds === undefined) { + unknownState = true; + } else { + for (const childId of childIds) { + if (swarmChildIds.has(childId)) continue; + const subagent = await readDetachedSubagent(profileRoot, input.sessionId, childId); + if (subagent === undefined) { + unknownState = true; + continue; + } + if (subagent.state === "SUBAGENT_STATE_KILLED") continue; + const childInbox = await readMessageSummaries(profileRoot, childId); + if (childInbox.incomplete) { + unknownState = true; + continue; + } + let latestPromptFromParentMs: number | undefined; + for (const msg of childInbox.messages) { + if ( + msg.sender === input.sessionId && + msg.timestampMs !== undefined && + (latestPromptFromParentMs === undefined || msg.timestampMs > latestPromptFromParentMs) + ) { + latestPromptFromParentMs = msg.timestampMs; + } + } + if ( + latestSystemStopMs !== undefined && + (latestPromptFromParentMs === undefined || + latestPromptFromParentMs <= latestSystemStopMs) + ) { + continue; + } + if (!reportedSenders.has(childId)) return true; + const latestReportMs = latestReportMsBySender.get(childId); + if ( + latestPromptFromParentMs !== undefined && + (latestReportMs === undefined || latestPromptFromParentMs > latestReportMs) + ) { + return true; + } + } + } + } + + return unknownState; + }; + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }).pipe(Effect.orElseSucceed(() => true)); +}); + /** * agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them: * a child is done, or waits for guidance, once its message is in the parent's inbox or its record diff --git a/apps/server/src/provider/acp/AntigravityProfilePaths.ts b/apps/server/src/provider/acp/AntigravityProfilePaths.ts index eb5ef1fcac292..ef55bc71168c6 100644 --- a/apps/server/src/provider/acp/AntigravityProfilePaths.ts +++ b/apps/server/src/provider/acp/AntigravityProfilePaths.ts @@ -1,37 +1,92 @@ // @effect-diagnostics nodeBuiltinImport:off -- lstat proves no managed component is a link. -import type * as NodeFS from "node:fs"; -import * as NodeFSP from "node:fs/promises"; +import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; +function errorCode(cause: unknown): string | undefined { + return typeof cause === "object" && + cause !== null && + "code" in cause && + typeof cause.code === "string" + ? cause.code + : undefined; +} + /** - * Proves a native runtime entry is at its literal path below the canonical profile: every - * component exists with the expected type and none is a link. A link could point at another - * child's transcript or another session's database under the same profile. + * Inspects a native runtime entry below the canonical profile, distinguishing genuinely absent + * paths (`missing`), symlinks/wrong entry types/escaped paths (`invalid`), and transient or + * permission lookup failures (`error`). */ -export async function antigravityManagedPath( +export async function inspectAntigravityManagedPath( profileRoot: string, segments: ReadonlyArray, kind: "file" | "directory", -): Promise<{ readonly path: string; readonly info: NodeFS.Stats } | undefined> { +): Promise< + | { readonly status: "ok"; readonly path: string; readonly info: NodeFS.Stats } + | { readonly status: "missing" } + | { readonly status: "invalid" } + | { readonly status: "error"; readonly cause: unknown } +> { let current = profileRoot; let info: NodeFS.Stats | undefined; for (const [index, segment] of segments.entries()) { current = NodePath.join(current, segment); - info = await NodeFSP.lstat(current).catch(() => undefined); + try { + info = await NodeFS.promises.lstat(current); + } catch (cause) { + const code = errorCode(cause); + if (code === "ENOENT") return { status: "missing" }; + if (code === "ENOTDIR") return { status: "invalid" }; + return { status: "error", cause }; + } const expectFile = kind === "file" && index === segments.length - 1; - if ( - info === undefined || - info.isSymbolicLink() || - (expectFile ? !info.isFile() : !info.isDirectory()) - ) { - return undefined; + if (info.isSymbolicLink() || (expectFile ? !info.isFile() : !info.isDirectory())) { + return { status: "invalid" }; } } - if (info === undefined) return undefined; - return (await NodeFSP.realpath(current).catch(() => undefined)) === current - ? { path: current, info } - : undefined; + if (info === undefined) return { status: "invalid" }; + let canonical: string; + try { + canonical = await NodeFS.promises.realpath(current); + } catch (cause) { + const code = errorCode(cause); + if (code === "ENOENT") return { status: "missing" }; + if (code === "ENOTDIR") return { status: "invalid" }; + return { status: "error", cause }; + } + return canonical === current ? { status: "ok", path: current, info } : { status: "invalid" }; +} + +/** + * Proves a native runtime entry is at its literal path below the canonical profile: every + * component exists with the expected type and none is a link. A link could point at another + * child's transcript or another session's database under the same profile. + */ +export async function antigravityManagedPath( + profileRoot: string, + segments: ReadonlyArray, + kind: "file" | "directory", +): Promise<{ readonly path: string; readonly info: NodeFS.Stats } | undefined> { + const result = await inspectAntigravityManagedPath(profileRoot, segments, kind); + return result.status === "ok" ? { path: result.path, info: result.info } : undefined; +} + +export async function inspectAntigravityProfileRoot( + profileDirectory: string, +): Promise< + | { readonly status: "ok"; readonly path: string } + | { readonly status: "missing" } + | { readonly status: "error"; readonly cause: unknown } +> { + try { + return { status: "ok", path: await NodeFS.promises.realpath(profileDirectory) }; + } catch (cause) { + const code = errorCode(cause); + if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing" }; + return { status: "error", cause }; + } } -export const antigravityProfileRoot = (profileDirectory: string) => - NodeFSP.realpath(profileDirectory).catch(() => undefined); +export const antigravityProfileRoot = async (profileDirectory: string) => { + const result = await inspectAntigravityProfileRoot(profileDirectory); + return result.status === "ok" ? result.path : undefined; +}; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d4d8b0b54505b..839725a7508d3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -707,6 +707,21 @@ export interface AcpAdapterV2Flavor { * through `ACP_OPEN_REPLY_QUIET_LIMIT` instead of closing early. */ readonly hasPendingReply?: (sessionId: string) => Effect.Effect; + /** + * True when the agent owns background work outside ACP's wire state (such as native + * subagents, swarms, or queued wakes). `purpose: "idle_release"` also covers live + * waiting workers whose process state would be lost on idle teardown, while + * `"session_replace"` checks only actively executing work so rollbacks stay possible. + */ + readonly hasPendingBackgroundWork?: (input: { + readonly sessionId: string; + readonly purpose: "idle_release" | "session_replace"; + }) => Effect.Effect; + /** + * Skip `session/close` during scope teardown when the agent treats it as a destructive + * force-cancel rather than a graceful detach. + */ + readonly skipCloseSessionOnTeardown?: boolean; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -7989,6 +8004,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( commitSessionState: ( replacement: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) => Effect.Effect, + beforeCommit?: Effect.Effect< + void, + EffectAcpErrors.AcpError | ProviderAdapter.ProviderAdapterProtocolError + >, ) { const previousScope = runtimeScope; const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); @@ -8073,6 +8092,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.uninterruptible( Effect.gen(function* () { yield* awaitAdmittedNativeResponses; + if (beforeCommit !== undefined) { + yield* beforeCommit.pipe( + Effect.tapError(() => + quarantineNativeTransportAtGeneration(replacementGeneration), + ), + ); + } yield* wireAcpRuntimeHandlers( replacementExit.value.replacementRuntime, replacementGeneration, @@ -8161,6 +8187,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: ThreadId | null, candidate: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { + itemIdentityVersion = 2; rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, candidate.sessionId); @@ -10273,7 +10300,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const transportHadOutstandingResponses = yield* closeNativeTransport; const sessionCapabilities = started.initializeResult.agentCapabilities?.sessionCapabilities; - if (sessionCapabilities?.close != null) { + if (sessionCapabilities?.close != null && flavor.skipCloseSessionOnTeardown !== true) { yield* runtimeTransitionPermit.withPermitsIfAvailable(1)( Effect.gen(function* () { const teardownState = yield* Ref.get(runtimeTeardownState); @@ -10303,8 +10330,65 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // A replacement agent can negotiate capabilities the initial agent did not have. const canReportBackgroundWork = - continuationRequests !== undefined && - (flavor.followAgentWorkState === true || Boolean(flavor.enablePostSettleContinuation)); + flavor.hasPendingBackgroundWork !== undefined || + flavor.hasPendingReply !== undefined || + (continuationRequests !== undefined && + (flavor.followAgentWorkState === true || Boolean(flavor.enablePostSettleContinuation))); + const checkPendingBackgroundWork = Effect.fn("AcpAdapterV2.checkPendingBackgroundWork")( + function* (purpose: "idle_release" | "session_replace") { + const rootSessionId = yield* Ref.get(activeSessionId); + if (postSettleContinuationEnabled || followsAgentWorkState) { + if ( + followsAgentWorkState && + rootSessionId !== null && + hasWorkingDescendant(rootSessionId) + ) + return true; + if ( + followsAgentWorkState && + (agentWork?.state === "running" || + agentWork?.state === "requires_action" || + agentRequests.size > 0) + ) + return true; + if ((yield* Ref.get(wakeBuffer)).length > 0) return true; + if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; + if (yield* Ref.get(continuationRequested)) return true; + if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; + const active = yield* Ref.get(activeTurn); + if ( + active !== null && + [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) + ) { + return true; + } + const carryover = yield* Ref.get(carryoverSubagents); + if ( + carryover !== null && + carryover.subagents.some(acpSubagentHasPendingBackgroundWork) + ) { + return true; + } + } + if (rootSessionId !== null) { + if (flavor.hasPendingBackgroundWork !== undefined) { + if ( + yield* flavor.hasPendingBackgroundWork({ + sessionId: rootSessionId, + purpose, + }) + ) { + return true; + } + } else if (flavor.hasPendingReply !== undefined) { + if (yield* flavor.hasPendingReply(rootSessionId)) { + return true; + } + } + } + return false; + }, + ); const sessionRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: options.instanceId, driver, @@ -10326,42 +10410,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), ...(canReportBackgroundWork ? { - hasPendingBackgroundWork: Effect.gen(function* () { - if (!postSettleContinuationEnabled && !followsAgentWorkState) return false; - const rootSessionId = yield* Ref.get(activeSessionId); - if ( - followsAgentWorkState && - rootSessionId !== null && - hasWorkingDescendant(rootSessionId) - ) - return true; - if ( - followsAgentWorkState && - (agentWork?.state === "running" || - agentWork?.state === "requires_action" || - agentRequests.size > 0) - ) - return true; - if ((yield* Ref.get(wakeBuffer)).length > 0) return true; - if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; - if (yield* Ref.get(continuationRequested)) return true; - if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; - const active = yield* Ref.get(activeTurn); - if ( - active !== null && - [...active.subagents.values()].some(acpSubagentHasPendingBackgroundWork) - ) { - return true; - } - const carryover = yield* Ref.get(carryoverSubagents); - if ( - carryover !== null && - carryover.subagents.some(acpSubagentHasPendingBackgroundWork) - ) { - return true; - } - return false; - }), + hasPendingBackgroundWork: checkPendingBackgroundWork("idle_release"), } : {}), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( @@ -10369,26 +10418,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return yield* runtimeTransitionPermit.withPermit( Effect.gen(function* () { if (threadInput.forceNewNativeThread) { - const currentTurn = yield* Ref.get(activeTurn); - const pendingWork = yield* ( - sessionRuntime.hasPendingBackgroundWork ?? Effect.succeed(false) - ); - if (currentTurn !== null || pendingWork) - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: - "Cannot replace ACP session while a turn or background work is active", - }); + const assertCanReplaceSession = Effect.gen(function* () { + const currentTurn = yield* Ref.get(activeTurn); + const pendingWork = canReportBackgroundWork + ? yield* checkPendingBackgroundWork("session_replace") + : false; + if (currentTurn !== null || pendingWork) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: + "Cannot replace ACP session while a turn or background work is active", + }); + } + }); + yield* assertCanReplaceSession; yield* awaitRuntimeTeardown(); - const previousItemIdentityVersion = itemIdentityVersion; - itemIdentityVersion = 2; + const previousPendingTerminalEnvironment = pendingTerminalEnvironment; prepareTerminalEnvironment(yield* readMcpContext(threadInput.threadId)); - yield* startReplacementAcpRuntime(threadInput.threadId, (candidate) => - commitReplacementSession(threadInput.threadId, candidate), + yield* startReplacementAcpRuntime( + threadInput.threadId, + (candidate) => commitReplacementSession(threadInput.threadId, candidate), + assertCanReplaceSession, ).pipe( Effect.tapError(() => Effect.sync(() => { - itemIdentityVersion = previousItemIdentityVersion; + pendingTerminalEnvironment = previousPendingTerminalEnvironment; }), ), ); @@ -11102,15 +11156,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeTransitionPermit .withPermit( Effect.gen(function* () { - const currentTurn = yield* Ref.get(activeTurn); - if (currentTurn !== null) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Cannot roll back ACP provider thread ${rollbackInput.providerThread.id} while turn ${currentTurn.providerTurnId} is active`, - }); - } + let blockedByGuard = false; + const assertCanRollbackSession = Effect.gen(function* () { + const currentTurn = yield* Ref.get(activeTurn); + if (currentTurn !== null) { + blockedByGuard = true; + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Cannot roll back ACP provider thread ${rollbackInput.providerThread.id} while turn ${currentTurn.providerTurnId} is active`, + }); + } + const pendingWork = canReportBackgroundWork + ? yield* checkPendingBackgroundWork("session_replace") + : false; + if (pendingWork) { + blockedByGuard = true; + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Cannot roll back ACP provider thread ${rollbackInput.providerThread.id} while background work is active`, + }); + } + }); + yield* assertCanRollbackSession; yield* awaitRuntimeTeardown(); - itemIdentityVersion = 2; + const previousPendingTerminalEnvironment = pendingTerminalEnvironment; prepareTerminalEnvironment( yield* readMcpContext(rollbackInput.providerThread.appThreadId), ); @@ -11118,7 +11187,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rollbackInput.providerThread.appThreadId, (candidate) => commitReplacementSession(rollbackInput.providerThread.appThreadId, candidate), - ).pipe(Effect.retry({ times: 1 })); + assertCanRollbackSession, + ).pipe( + Effect.retry({ times: 1, while: () => !blockedByGuard }), + Effect.tapError(() => + Effect.sync(() => { + pendingTerminalEnvironment = previousPendingTerminalEnvironment; + }), + ), + ); const now = yield* DateTime.now; return { providerThread: {