diff --git a/.changeset/assistant-continue-coordinator.md b/.changeset/assistant-continue-coordinator.md new file mode 100644 index 000000000..c6ece25d4 --- /dev/null +++ b/.changeset/assistant-continue-coordinator.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Coordinate recorded Assistant continuation with durable retries and dormant child sessions. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index e19cc1881..9781a058c 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -94,3 +94,11 @@ Resume reuses an operation UUID after an uncertain response and reveals Assistan only if the same account, navigation and foreground intent still own the result. Newer bus state owns Terminal status. A restored Assistant stays paused until an explicit message; existing live execution keeps its current state. + +Continue coordinates one durable operation from a specific retained record into +a new Studio child with a dormant Terminal. It freezes current child context, +accepts it through the existing source owner, and verifies one native no-reply +seed before permitting Attach. Retries consult the original allocation identity +and receipt before reading a newer source record. Completed retries only verify +saved preparation and preserve an already-running child's lease and execution. +End and authority changes fence each asynchronous step and final attachment. diff --git a/packages/harness/src/core/assistant-continuation.test.ts b/packages/harness/src/core/assistant-continuation.test.ts new file mode 100644 index 000000000..b51719324 --- /dev/null +++ b/packages/harness/src/core/assistant-continuation.test.ts @@ -0,0 +1,520 @@ +import { createHash } from "node:crypto"; +import { mkdtemp, mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { AssistantContinuation } from "./assistant-continuation.js"; +import { AssistantContinuationStore } from "./assistant-continuation-store.js"; +import { AssistantSessionStore } from "./assistant-session-store.js"; +import { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js"; +import { projectAssistantRecord } from "./assistant-record.js"; +import { FileAssistantSourceStore } from "./assistant-source-store.js"; +import { createAssistantContextDelivery } from "./studio-assistant-delivery.js"; +import { createAssistantContextCandidate } from "./assistant-sources.js"; +import { assertAssistantRuntimeReady } from "./assistant-runtime-readiness.js"; +import { sourceContext } from "./test-fixtures/assistant-context.js"; +import type { HostedOpenCode } from "./opencode-host.js"; +import type { HarnessSession } from "../shared/types.js"; +import type { AssistantContinuationNative } from "./assistant-continuation-native.js"; + +const op = "11111111-1111-4111-8111-111111111111"; +const digest = (value: string) => + createHash("sha256").update(value).digest("hex"); +const request = { + expectedRevision: 1, + expectedRecordRevision: 7, + operationId: op, +}; +const gate = () => { + let release!: () => void; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, release }; +}; +let root: string; +let cleanup: () => void; +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "assistant-continue-integration-")); + cleanup = () => {}; +}); +afterEach(async () => { + cleanup(); + await rm(root, { recursive: true, force: true }); +}); + +async function fixture() { + const store = new AssistantContinuationStore(root), + associations = new AssistantSessionStore(root); + const binding = { + harnessSessionId: "parent", + contextAuthorityScope: digest("context/parent"), + cwd: root, + conversationId: "ses_parent", + }; + await associations.associate( + binding, + digest("native/parent"), + async () => binding.conversationId, + ); + await associations.transition("parent", 0, { + lifecycle: "ended", + execution: "paused", + }); + const source = { + id: "parent", + cwd: root, + harness: "claude-code", + status: "exited", + title: "Source", + agentMapIdentity: { + sessionId: "parent", + projectId: "project", + userId: "user", + }, + boundWorkflowPath: null, + agentSessionId: "terminal-original", + } as unknown as HarnessSession; + const rows = new Map([[source.id, source]]); + let authorized = true, + loseSeed = false; + const authorize = vi.fn(async (id: string) => + authorized + ? associations.association({ + harnessSessionId: id, + cwd: root, + contextAuthorityScope: digest(`context/${id}`), + }) + : null, + ); + const records = { + read: vi.fn(async () => + projectAssistantRecord( + [ + { + info: { + id: "msg_user", + sessionID: "ses_parent", + role: "user", + time: { created: 1 }, + }, + parts: [ + { + id: "prt_text", + sessionID: "ses_parent", + messageID: "msg_user", + type: "text", + text: "Preserve the completed draft.", + }, + ], + }, + ], + binding, + 7, + ), + ), + }; + const allocationInputs = new Map(); + const sessions = { + get: (id: string) => rows.get(id), + allocateDormant: vi.fn(async (_sourceId, input) => { + const encoded = JSON.stringify(input), + saved = allocationInputs.get(input.childSessionId); + if (saved && saved !== encoded) + throw new Error("allocation identity changed"); + allocationInputs.set(input.childSessionId, encoded); + const existing = rows.get(input.childSessionId); + if (existing) return existing; + const child = { + ...source, + id: input.childSessionId, + title: "Child", + agentSessionId: null, + terminalState: "not-started", + agentMapIdentity: { + ...source.agentMapIdentity!, + sessionId: input.childSessionId, + }, + } as HarnessSession; + rows.set(child.id, child); + return child; + }), + }; + const hosts = new Map(), + controllers = new Map(); + const host = { + current: (id: string) => hosts.get(id) ?? null, + ensure: vi.fn(async (id: string): Promise => { + const previous = hosts.get(id); + if (previous) return previous; + const controller = new AbortController(), + stateRoot = join(root, "opencode", digest(`native/${id}`)); + await mkdir(stateRoot, { recursive: true, mode: 0o700 }); + const hosted: HostedOpenCode = { + harnessSessionId: id, + cwd: root, + stateRoot, + contextAuthorityScope: digest(`context/${id}`), + model: { providerID: "sapiom", modelID: "fixture" }, + signal: controller.signal, + isCurrent: () => + authorized && !controller.signal.aborted && hosts.get(id) === hosted, + server: { + pid: 123, + exited: new Promise(() => {}), + close: async () => {}, + fetch: vi.fn(), + fetchJson: vi.fn(), + }, + }; + hosts.set(id, hosted); + controllers.set(hosted, controller); + return hosted; + }), + assertCurrent: vi.fn(async (hosted: HostedOpenCode) => { + if (!hosted.isCurrent()) throw new Error("authority changed"); + }), + retireExact: async (hosted: HostedOpenCode) => { + controllers.get(hosted)?.abort(); + if (hosts.get(hosted.harnessSessionId) === hosted) + hosts.delete(hosted.harnessSessionId); + }, + retireWithResult: async (id: string) => { + const hosted = hosts.get(id); + if (hosted) await host.retireExact(hosted); + return { state: hosted ? ("confirmed" as const) : ("absent" as const) }; + }, + observe: vi.fn(), + beginShutdown: () => { + for (const controller of controllers.values()) controller.abort(); + hosts.clear(); + }, + }; + cleanup = host.beginShutdown; + const lifecycle = new AssistantLifecycleCoordinator({ + store: associations, + host, + canAttach: (id) => store.canAttach(id), + associations: { + ensure: async (hosted) => { + const saved = await authorize(hosted.harnessSessionId); + if (!saved) throw new Error("no saved association"); + return saved.conversationId; + }, + }, + }); + const creations = new Set(), + seeds = new Set(); + const native: Pick = { + conversation: vi.fn(async (_hosted, receipt, advance) => { + if (receipt.phase === "allocated") { + await advance({ phase: "creating" }); + creations.add(receipt.childStudioId); + } + if (!creations.has(receipt.childStudioId)) + throw new Error("native creation uncertain"); + return `ses_${receipt.childStudioId.replaceAll("-", "")}`; + }), + seed: vi.fn(async (_hosted, receipt, _system, advance) => { + if (receipt.phase === "accepting") { + await advance({ phase: "seeding" }); + seeds.add(receipt.seedMessageId); + if (loseSeed) { + loseSeed = false; + throw new Error("lost seed acknowledgement"); + } + } + if (!seeds.has(receipt.seedMessageId)) + throw new Error("seed unavailable"); + }), + }; + const resolveCandidate = vi.fn(async (hosted, receipt) => { + const context = sourceContext(); + context.session = { + ...context.session, + id: hosted.harnessSessionId, + cwd: hosted.cwd, + }; + context.guidance.push({ + id: "recorded-continuation", + kind: "continuation", + required: true, + source: `studio:${receipt.sourceBinding.harnessSessionId}`, + revision: receipt.brief.sha256, + status: "available", + text: receipt.brief.text, + }); + return createAssistantContextCandidate( + context, + hosted.contextAuthorityScope, + ); + }); + const delivery = createAssistantContextDelivery({ + resolveContext: vi.fn(async () => { + throw new Error("ordinary context resolver must not run"); + }), + storeFor: (hosted) => + new FileAssistantSourceStore( + hosted.stateRoot, + hosted.contextAuthorityScope, + ), + assertCurrent: host.assertCurrent, + prepareRuntime: async (_hosted, retained) => + assertAssistantRuntimeReady(retained), + }); + const originalAccept = delivery.acceptFrozen; + const accept = vi.spyOn(delivery, "acceptFrozen"), + compose = vi.spyOn(delivery, "compose"); + const assertAvailable = vi.fn(async () => {}); + const options = { + store, + associations, + lifecycle, + records, + sessions, + authorize, + native, + delivery, + resolveCandidate, + assertAvailable, + }; + const service = () => new AssistantContinuation(options); + const instance = service(); + return { + store, + associations, + binding, + source, + rows, + hosts, + host, + lifecycle, + records, + sessions, + native, + creations, + seeds, + resolveCandidate, + delivery, + originalAccept, + accept, + compose, + assertAvailable, + service, + run: () => instance.continue("parent", request), + receipt: () => store.read(binding, op), + revoke: () => { + authorized = false; + }, + loseSeed: () => { + loseSeed = true; + }, + }; +} + +it("creates one child with dormant Terminal and new accepted scope, retains the source, and returns paused", async () => { + const f = await fixture(); + const original = JSON.stringify(f.source); + const first = f.run(); + expect(f.run()).toBe(first); + const result = await first; + expect(result.session.id).not.toBe("parent"); + expect(result.session).toMatchObject({ + terminalState: "not-started", + agentSessionId: null, + }); + expect(result.attachment.lifecycle).toMatchObject({ + lifecycle: "open", + execution: "paused", + }); + expect(result.receipt).toMatchObject({ + phase: "prepared", + sourceRecordRevision: 7, + sourceLifecycleRevision: 1, + }); + expect(result.receipt.acceptedRef?.authorityScope).not.toBe( + f.binding.contextAuthorityScope, + ); + expect(result.receipt.childBinding?.conversationId).not.toBe("ses_parent"); + expect(JSON.stringify(f.source)).toBe(original); + expect(f.creations.size).toBe(1); + expect(f.seeds.size).toBe(1); + expect(f.accept).toHaveBeenCalledOnce(); + expect(f.host.observe).toHaveBeenCalledOnce(); +}); + +it("reconciles a prepared operation after service restart without new context, allocation or native mutations", async () => { + const f = await fixture(); + const first = await f.run(); + const running = f.hosts.get(first.session.id)!; + await f.lifecycle.enable(running); + const revision = (await f.lifecycle.describe(first.session.id)).revision; + f.records.read.mockRejectedValue(new Error("latest record unavailable")); + f.resolveCandidate.mockRejectedValue(new Error("current guidance changed")); + const repeated = await f.service().continue("parent", request); + expect(repeated.session.id).toBe(first.session.id); + expect(repeated.attachment.lease).toBe(first.attachment.lease); + expect(repeated.attachment.lifecycle).toMatchObject({ + revision, + execution: "enabled", + }); + expect(f.hosts.get(first.session.id)).toBe(running); + expect(f.sessions.allocateDormant).toHaveBeenCalledTimes(2); + expect(f.accept).toHaveBeenCalledOnce(); + expect(f.resolveCandidate).toHaveBeenCalledOnce(); + expect(f.creations.size).toBe(1); + expect(f.seeds.size).toBe(1); +}); + +it("rejects a result when End wins after the child attachment was granted", async () => { + const f = await fixture(), + attach = f.lifecycle.attach.bind(f.lifecycle); + vi.spyOn(f.lifecycle, "attach").mockImplementationOnce(async (...args) => { + const attached = await attach(...args); + const ending = f.lifecycle.beginEnd(args[0]); + await ending.persistence; + await f.lifecycle.finishEnd(ending.fence); + return attached; + }); + await expect(f.run()).rejects.toThrow(); + expect((await f.receipt())?.phase).toBe("prepared"); +}); + +it("reconciles lost acceptance acknowledgement with the exact frozen candidate and acceptance ID", async () => { + const f = await fixture(); + const original = f.originalAccept; + f.accept.mockImplementationOnce(async (...args) => { + await original(...args); + throw new Error("lost acceptance ack"); + }); + await expect(f.run()).rejects.toThrow("lost acceptance ack"); + const pending = (await f.receipt())!; + expect(pending).toMatchObject({ phase: "accepting", acceptedRef: null }); + f.resolveCandidate.mockRejectedValue(new Error("new guidance unavailable")); + const result = await f.service().continue("parent", request); + expect(result.receipt.acceptedRef?.acceptanceId).toBe(pending.acceptanceId); + expect(f.accept.mock.calls.map((args) => args[3])).toEqual([ + pending.acceptanceId, + pending.acceptanceId, + ]); + expect(f.resolveCandidate).toHaveBeenCalledOnce(); + expect(f.creations.size).toBe(1); +}); + +it("reconciles a lost seed result using the existing accepted reference and child", async () => { + const f = await fixture(); + f.loseSeed(); + await expect(f.run()).rejects.toThrow("lost seed acknowledgement"); + const pending = (await f.receipt())!; + expect(pending.phase).toBe("seeding"); + f.records.read.mockRejectedValue(new Error("record changed")); + const result = await f.service().continue("parent", request); + expect(result.session.id).toBe(pending.childStudioId); + expect(result.receipt.acceptedRef).toEqual(pending.acceptedRef); + expect(f.accept).toHaveBeenCalledOnce(); + expect(f.seeds.size).toBe(1); +}); + +it("cannot repair lost committed material from a prepared receipt", async () => { + const f = await fixture(); + const result = await f.run(); + const hosted = f.hosts.get(result.session.id)!; + const objectPath = join( + hosted.stateRoot, + "assistant-context", + "v1", + hosted.contextAuthorityScope, + "objects", + result.receipt.brief.sha256, + ); + await rm(objectPath); + await expect(f.service().continue("parent", request)).rejects.toMatchObject({ + failure: { code: "context_unavailable" }, + }); + expect(f.accept).toHaveBeenCalledOnce(); + expect(f.seeds.size).toBe(1); +}); + +it("fails before allocating for inactive context delivery or missing required record", async () => { + const f = await fixture(); + f.assertAvailable.mockRejectedValueOnce(new Error("context inactive")); + await expect(f.run()).rejects.toThrow("context inactive"); + expect(f.records.read).not.toHaveBeenCalled(); + f.records.read.mockResolvedValueOnce(null as never); + await expect(f.run()).rejects.toThrow(); + expect(f.sessions.allocateDormant).not.toHaveBeenCalled(); + expect(f.host.ensure).not.toHaveBeenCalled(); +}); + +it("End during held child context preparation fences late acceptance and seeding", async () => { + const f = await fixture(); + const held = gate(), + original = f.resolveCandidate.getMockImplementation()!; + f.resolveCandidate.mockImplementationOnce(async (...args) => { + await held.promise; + return original(...args); + }); + const running = f.run(); + const failed = expect(running).rejects.toThrow(); + await vi.waitFor(() => expect(f.resolveCandidate).toHaveBeenCalled()); + const pending = (await f.receipt())!; + const end = f.lifecycle.beginEnd(pending.childStudioId); + await Promise.all([end.native, end.persistence]); + await f.lifecycle.finishEnd(end.fence); + await failed; + held.release(); + await Promise.resolve(); + expect(f.accept).not.toHaveBeenCalled(); + expect(f.seeds.size).toBe(0); + expect(await f.associations.lifecycle(pending.childStudioId)).toMatchObject({ + lifecycle: "ended", + }); + await expect(f.service().continue("parent", request)).rejects.toThrow(); +}); + +it("source End cancels pending preparation without changing the frozen source", async () => { + const f = await fixture(); + const held = gate(), + original = f.resolveCandidate.getMockImplementation()!; + f.resolveCandidate.mockImplementationOnce(async (...args) => { + await held.promise; + return original(...args); + }); + const running = f.run(); + const failed = expect(running).rejects.toThrow(); + await vi.waitFor(() => expect(f.resolveCandidate).toHaveBeenCalled()); + const pending = (await f.receipt())!, + end = f.lifecycle.beginEnd("parent"); + await Promise.all([end.native, end.persistence]); + await f.lifecycle.finishEnd(end.fence); + await failed; + held.release(); + expect(f.accept).not.toHaveBeenCalled(); + expect((await f.receipt())!.brief).toEqual(pending.brief); +}); + +it("a different source revision cannot adopt an existing operation", async () => { + const f = await fixture(); + await f.run(); + await expect( + f.service().continue("parent", { ...request, expectedRecordRevision: 8 }), + ).rejects.toThrow("continuation changed"); + expect(f.creations.size).toBe(1); +}); + +it("revalidates the allocator digest after source and child move to another project at the same cwd", async () => { + const f = await fixture(); + const first = await f.run(); + Object.assign(f.source.agentMapIdentity!, { projectId: "changed-project" }); + Object.assign(first.session.agentMapIdentity!, { + projectId: "changed-project", + }); + f.host.ensure.mockClear(); + vi.mocked(f.native.seed).mockClear(); + await expect(f.service().continue("parent", request)).rejects.toThrow( + "allocation identity changed", + ); + expect(f.host.ensure).not.toHaveBeenCalled(); + expect(f.native.seed).not.toHaveBeenCalled(); + expect(f.creations.size).toBe(1); +}); diff --git a/packages/harness/src/core/assistant-continuation.ts b/packages/harness/src/core/assistant-continuation.ts new file mode 100644 index 000000000..e3ec3f472 --- /dev/null +++ b/packages/harness/src/core/assistant-continuation.ts @@ -0,0 +1,415 @@ +import { basename } from "node:path"; +import { setTimeout, clearTimeout } from "node:timers"; +import { + encodeAssistantContext, + type AcceptedAssistantContext, +} from "@sapiom/opencode"; +import { openCodeTransportFailure } from "../shared/opencode-errors.js"; +import type { AssistantRecordBinding } from "../shared/assistant-record.js"; +import type { HarnessSession } from "../shared/types.js"; +import { + awaitAssistantInspection, + type AssistantAttachment, + type AssistantLifecycleCoordinator, +} from "./assistant-lifecycle.js"; +import { + AssistantContinuationConflictError, + freezeContinuationCandidate, + thawContinuationCandidate, + type AssistantContinuationReceipt, + type AssistantContinuationStore, +} from "./assistant-continuation-store.js"; +import type { AssistantContinuationNative } from "./assistant-continuation-native.js"; +import type { + AssistantAssociation, + AssistantSessionStore, +} from "./assistant-session-store.js"; +import type { AssistantRecordStore } from "./assistant-record-store.js"; +import { + OpenCodeAccessError, + OpenCodeTransportError, + type HostedOpenCode, +} from "./opencode-host.js"; +import type { SessionManager } from "./session-manager.js"; +import type { AssistantContextDelivery } from "./studio-assistant-delivery.js"; +import { + acceptedAssistantRecord, + type AssistantContextCandidate, +} from "./assistant-sources.js"; + +export interface AssistantContinueRequest { + expectedRevision: number; + expectedRecordRevision: number; + operationId: string; +} +export interface PreparedAssistantContinuation { + session: HarnessSession; + attachment: AssistantAttachment; + /** Private receipt: the route must explicitly project public provenance. */ + receipt: AssistantContinuationReceipt; +} +interface Options { + store: AssistantContinuationStore; + records: Pick; + sessions: Pick; + associations: Pick; + lifecycle: Pick< + AssistantLifecycleCoordinator, + | "describe" + | "snapshot" + | "subscribe" + | "prepareContinuation" + | "inspect" + | "attach" + | "use" + >; + native: Pick; + delivery: AssistantContextDelivery; + authorize: (id: string) => Promise; + resolveCandidate: ( + hosted: HostedOpenCode, + receipt: AssistantContinuationReceipt, + signal: AbortSignal, + ) => Promise; + /** Context runtime activation belongs to the existing delivery/runtime owner. */ + assertAvailable: () => Promise; + timeoutMs?: number; +} +const reference = ({ + context: _context, + instructionSet: _set, + ...ref +}: AcceptedAssistantContext) => ref; +const recordBinding = ({ + harnessSessionId, + contextAuthorityScope, + conversationId, + cwd, +}: AssistantAssociation): AssistantRecordBinding => ({ + harnessSessionId, + contextAuthorityScope, + conversationId, + cwd, +}); +const changed = () => + new OpenCodeTransportError(openCodeTransportFailure("lifecycle_changed")); +const same = (a: unknown, b: unknown) => + JSON.stringify(a) === JSON.stringify(b); + +/** One child and one frozen preparation per operation; no ordinary prompt/recovery dispatch. */ +export class AssistantContinuation { + private readonly pending = new Map< + string, + { request: string; promise: Promise } + >(); + constructor(private readonly options: Options) {} + + continue( + id: string, + request: AssistantContinueRequest, + ): Promise { + const key = `${id}/${request.operationId}`, + encoded = JSON.stringify(request); + const pending = this.pending.get(key); + if (pending) + return pending.request === encoded + ? pending.promise + : Promise.reject(new AssistantContinuationConflictError()); + const promise = this.run(id, { ...request }); + const entry = { request: encoded, promise }; + this.pending.set(key, entry); + void promise + .finally(() => { + if (this.pending.get(key) === entry) this.pending.delete(key); + }) + .catch(() => {}); + return promise; + } + + private async run( + id: string, + request: AssistantContinueRequest, + ): Promise { + const controller = new AbortController(), + signal = controller.signal; + const timer = setTimeout( + () => controller.abort(changed()), + this.options.timeoutMs ?? 45_000, + ); + let receipt: AssistantContinuationReceipt | null = null; + let release: (() => Promise) | undefined; + const unsubscribe = this.options.lifecycle.subscribe(() => { + if (receipt?.phase === "prepared") return; + const state = this.options.lifecycle + .snapshot() + .find((row) => row.harnessSessionId === id); + if ( + state && + (state.revision !== request.expectedRevision || + state.lifecycle === "ending") + ) + controller.abort(changed()); + }); + try { + await awaitAssistantInspection(this.options.assertAvailable(), signal); + const source = await awaitAssistantInspection( + this.options.authorize(id), + signal, + ); + if (!source || source.harnessSessionId !== id) + throw new OpenCodeAccessError("Assistant source unavailable"); + const binding = recordBinding(source); + const sourceSession = this.options.sessions.get(id); + if (!sourceSession?.agentMapIdentity) + throw new OpenCodeAccessError("Assistant project unavailable"); + const sourceFacts = { + cwd: sourceSession.cwd, + projectId: sourceSession.agentMapIdentity.projectId, + userId: sourceSession.agentMapIdentity.userId, + }; + const harness = sourceSession.harness; + const checkChild = (child: HarnessSession) => { + if ( + child.harness !== harness || + !same(sourceFacts, { + cwd: child.cwd, + projectId: child.agentMapIdentity?.projectId, + userId: child.agentMapIdentity?.userId, + }) || + child.agentMapIdentity?.sessionId !== child.id + ) + throw new OpenCodeAccessError("Assistant child project changed"); + }; + const check = async () => { + signal.throwIfAborted(); + if ( + !same( + source, + await awaitAssistantInspection(this.options.authorize(id), signal), + ) + ) + throw new OpenCodeAccessError("Assistant source changed"); + const state = await awaitAssistantInspection( + this.options.lifecycle.describe(id), + signal, + ); + signal.throwIfAborted(); + if ( + receipt?.phase !== "prepared" && + (state.revision !== request.expectedRevision || + state.lifecycle === "ending") + ) + throw changed(); + const current = this.options.sessions.get(id); + if ( + !current || + current.harness !== harness || + !same(sourceFacts, { + cwd: current.cwd, + projectId: current.agentMapIdentity?.projectId, + userId: current.agentMapIdentity?.userId, + }) + ) + throw new OpenCodeAccessError("Assistant project changed"); + const child = + receipt && this.options.sessions.get(receipt.childStudioId); + if (child) checkChild(child); + }; + const locking = this.options.store.operationLock( + binding, + request.operationId, + ); + // A timed-out waiter must release a lock it acquires after returning. + void locking.then( + (late) => { + if (signal.aborted && !release) void late().catch(() => {}); + }, + () => {}, + ); + release = await awaitAssistantInspection(locking, signal); + receipt = await this.options.store.read(binding, request.operationId); + await check(); + receipt = await this.options.store.reserve( + binding, + request.expectedRecordRevision, + request.expectedRevision, + request.operationId, + () => this.options.records.read(binding), + signal, + ); + await check(); + // The allocator owns the original project/user/harness digest. Consult it + // on every retry, including prepared receipts after a same-cwd rebind. + await this.options.sessions.allocateDormant(id, { + childSessionId: receipt.childStudioId, + harness, + expectedSource: sourceFacts, + }); + await check(); + if (receipt.phase === "reserved") { + receipt = await this.options.store.update( + receipt, + { phase: "allocated" }, + signal, + ); + } + const child = this.options.sessions.get(receipt.childStudioId); + if (!child) + throw new OpenCodeAccessError("Prepared Studio child unavailable"); + checkChild(child); + const childLifecycle = await this.options.lifecycle.describe(child.id); + if (childLifecycle.lifecycle !== "open") throw changed(); + if (receipt.phase !== "prepared" && childLifecycle.revision !== 0) + throw changed(); + // A completed receipt is verified through a read-only operation. It must + // never reacquire mutating preparation while its child is running. + const prepare = + receipt.phase === "prepared" + ? this.options.lifecycle.inspect.bind(this.options.lifecycle) + : this.options.lifecycle.prepareContinuation.bind( + this.options.lifecycle, + ); + const prepared = await prepare( + child.id, + childLifecycle.revision, + async (hosted, preparationSignal) => { + const operationSignal = AbortSignal.any([ + signal, + preparationSignal, + hosted.signal, + ]); + const advance = async ( + patch: Parameters[1], + ) => { + await check(); + operationSignal.throwIfAborted(); + receipt = await this.options.store.update( + receipt!, + patch, + operationSignal, + ); + await check(); + operationSignal.throwIfAborted(); + return receipt; + }; + if (["allocated", "creating"].includes(receipt!.phase)) { + const conversationId = await this.options.native.conversation( + hosted, + receipt!, + advance, + operationSignal, + ); + await check(); + operationSignal.throwIfAborted(); + const association = await this.options.associations.associate( + hosted, + basename(hosted.stateRoot), + async () => conversationId, + operationSignal, + ); + if (!association || association.conversationId !== conversationId) + throw new AssistantContinuationConflictError(); + await advance({ + phase: "associated", + childBinding: recordBinding(association), + }); + } + const associated = await awaitAssistantInspection( + this.options.authorize(child.id), + operationSignal, + ); + if ( + !associated || + !same(recordBinding(associated), receipt!.childBinding) || + associated.nativeScope !== basename(hosted.stateRoot) || + associated.contextAuthorityScope !== hosted.contextAuthorityScope || + associated.cwd !== hosted.cwd + ) + throw new OpenCodeAccessError("Assistant child binding changed"); + if (receipt!.phase === "associated") { + const candidate = await awaitAssistantInspection( + this.options.resolveCandidate(hosted, receipt!, operationSignal), + operationSignal, + ); + await advance({ + phase: "accepting", + frozenCandidate: freezeContinuationCandidate( + candidate, + receipt!.childBinding!, + receipt!.acceptanceId, + ), + }); + } + const candidate = thawContinuationCandidate( + receipt!.frozenCandidate!, + receipt!.childBinding!, + receipt!.acceptanceId, + ); + let accepted = acceptedAssistantRecord( + candidate, + hosted.contextAuthorityScope, + associated.conversationId, + receipt!.acceptanceId, + ); + if (!receipt!.acceptedRef) { + accepted = await this.options.delivery.acceptFrozen( + hosted, + associated.conversationId, + candidate, + receipt!.acceptanceId, + operationSignal, + ); + await advance({ acceptedRef: reference(accepted) }); + } + if ( + encodeAssistantContext(reference(accepted)) !== + encodeAssistantContext(receipt!.acceptedRef) + ) + throw new AssistantContinuationConflictError(); + // compose reads the exact accepted-source owner; receipt material is never a recovery fallback. + const { system } = await this.options.delivery.compose( + hosted, + associated.conversationId, + accepted, + { attemptToken: receipt!.attemptToken }, + operationSignal, + ); + await check(); + operationSignal.throwIfAborted(); + await this.options.native.seed( + hosted, + receipt!, + system, + advance, + operationSignal, + ); + if (receipt!.phase !== "prepared") + await advance({ phase: "prepared" }); + await check(); + operationSignal.throwIfAborted(); + return receipt!; + }, + signal, + ); + await check(); + const attachment = await this.options.lifecycle.attach( + child.id, + childLifecycle.revision, + ); + await check(); + await this.options.lifecycle.use(child.id, attachment.lease); + const session = this.options.sessions.get(child.id); + if ( + !session || + attachment.conversationId !== prepared.childBinding?.conversationId + ) + throw new AssistantContinuationConflictError(); + checkChild(session); + return { session, attachment, receipt: prepared }; + } finally { + clearTimeout(timer); + unsubscribe(); + if (release) await release(); + } + } +} diff --git a/packages/harness/src/core/assistant-lifecycle.test.ts b/packages/harness/src/core/assistant-lifecycle.test.ts index fb4b4cd42..1a1d8e7aa 100644 --- a/packages/harness/src/core/assistant-lifecycle.test.ts +++ b/packages/harness/src/core/assistant-lifecycle.test.ts @@ -505,6 +505,20 @@ it("failed Continue preparation retires only its provisional host and releases t expect(await store.lifecycle("studio-a")).toBeNull(); }); +it("mutating Continue preparation rejects live leases while read-only reconciliation preserves them", async () => { + const attachment = await coordinator.attach("studio-a", 0); + const hosted = current!; + await coordinator.enable(hosted); + const revision = (await coordinator.describe("studio-a")).revision; + const prepare = vi.fn(); + await expect(coordinator.prepareContinuation("studio-a", revision, prepare)).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + expect(prepare).not.toHaveBeenCalled(); + expect(await coordinator.inspect("studio-a", revision, async (runtime) => runtime)).toBe(hosted); + expect(await coordinator.use("studio-a", attachment.lease)).toMatchObject({ hosted }); + expect((await coordinator.describe("studio-a")).execution).toBe("enabled"); + expect(retire).not.toHaveBeenCalled(); +}); + it("Continue requires an open exact revision and discards a late result after durable change", async () => { await store.transition("studio-a", 0, { lifecycle: "ended", execution: "paused" }); await expect(coordinator.prepareContinuation("studio-a", 1, vi.fn())).rejects.toThrow(); diff --git a/packages/harness/src/core/assistant-lifecycle.ts b/packages/harness/src/core/assistant-lifecycle.ts index 5ac7aad98..ee9e48a5b 100644 --- a/packages/harness/src/core/assistant-lifecycle.ts +++ b/packages/harness/src/core/assistant-lifecycle.ts @@ -598,6 +598,9 @@ export class AssistantLifecycleCoordinator { try { await revision(); hosted = this.options.host.current(id) ?? undefined; + // Continue may mutate native preparation only before a child has a live + // lease. Prepared-operation retries use the read-only inspection path. + if (retain && this.leases.has(id)) throw failure("lifecycle_changed"); provisional = !hosted; if (!hosted) { started = true;