From 7e7e10021d689e82766337002b1dd95c80cc9888 Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 21:30:36 +0000 Subject: [PATCH] feat(harness): fence paused continuation preparation --- .changeset/paused-continuation-admission.md | 5 ++ .../harness/docs/assistant-continuation.md | 8 +++ .../src/core/assistant-lifecycle.test.ts | 71 +++++++++++++++++++ .../harness/src/core/assistant-lifecycle.ts | 35 +++++++-- .../src/core/assistant-source-store.test.ts | 18 +++++ .../src/core/assistant-source-store.ts | 17 +++++ 6 files changed, 149 insertions(+), 5 deletions(-) create mode 100644 .changeset/paused-continuation-admission.md diff --git a/.changeset/paused-continuation-admission.md b/.changeset/paused-continuation-admission.md new file mode 100644 index 000000000..1986c5672 --- /dev/null +++ b/.changeset/paused-continuation-admission.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Reserve exclusive paused Assistant continuation preparation and reject retries that lose committed accepted material. diff --git a/packages/harness/docs/assistant-continuation.md b/packages/harness/docs/assistant-continuation.md index c790d371f..40a372f45 100644 --- a/packages/harness/docs/assistant-continuation.md +++ b/packages/harness/docs/assistant-continuation.md @@ -29,3 +29,11 @@ separate revision lock. A private child lookup is durable before allocation; ordinary attachment is blocked until the linked receipt is verified prepared. Missing or corrupt linked receipts fail closed. An existing receipt is read before newer source history, so retries use the same frozen record and child. + +Trusted continuation preparation shares the lifecycle admission slot with +inspection, Attach and Resume. It requires an open matching revision, retains +its exact host only after successful checks, and grants no runtime lease. +End preempts preparation; ordinary attachment follows verified preparation. +If a previous acceptance already committed, a retry validates its original +manifest and material before any writes. Pending receipt input cannot repair +lost committed material, including after a lost acceptance acknowledgement. diff --git a/packages/harness/src/core/assistant-lifecycle.test.ts b/packages/harness/src/core/assistant-lifecycle.test.ts index cafc900c7..fb4b4cd42 100644 --- a/packages/harness/src/core/assistant-lifecycle.test.ts +++ b/packages/harness/src/core/assistant-lifecycle.test.ts @@ -468,3 +468,74 @@ it("pending Continue children cannot attach and End fences a late admission resu expect(ensure).not.toHaveBeenCalled(); expect(associate).not.toHaveBeenCalled(); }); + +it("Continue exclusively prepares a gated child and keeps its exact runtime without a lease", async () => { + canAttach.mockResolvedValue(false); + const held = gate(), prepare = vi.fn(async () => { await held.promise; return "seeded"; }); + const preparing = coordinator.prepareContinuation("studio-a", 0, prepare); + await vi.waitFor(() => expect(prepare).toHaveBeenCalledOnce()); + const provisional = current; + await expect(coordinator.inspect("studio-a", 0, vi.fn())).rejects.toThrow(); + await expect(coordinator.attach("studio-a", 0)).rejects.toThrow(); + await expect(coordinator.prepareContinuation("studio-a", 0, vi.fn())).rejects.toThrow(); + held.release(); + expect(await preparing).toBe("seeded"); + expect(canAttach).not.toHaveBeenCalled(); + expect(current).toBe(provisional); + expect(await store.lifecycle("studio-a")).toBeNull(); + expect(associate).not.toHaveBeenCalled(); + expect(observe).not.toHaveBeenCalled(); + expect(retire).not.toHaveBeenCalled(); + await expect(coordinator.use("studio-a", "not-a-lease")).rejects.toThrow(); + canAttach.mockResolvedValue(true); + const attached = await coordinator.attach("studio-a", 0); + expect(current).toBe(provisional); + expect(attached.lifecycle).toMatchObject({ revision: 1, execution: "paused" }); + expect(observe).toHaveBeenCalledOnce(); +}); + +it("failed Continue preparation retires only its provisional host and releases the slot", async () => { + await expect(coordinator.prepareContinuation("studio-a", 0, async () => { + throw new Error("seed unavailable"); + })).rejects.toThrow("seed unavailable"); + expect(current).toBeNull(); + expect(retire).toHaveBeenCalledOnce(); + expect(await coordinator.prepareContinuation("studio-a", 0, async () => "retried")).toBe("retried"); + expect(current).not.toBeNull(); + expect(await store.lifecycle("studio-a")).toBeNull(); +}); + +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(); + await expect(coordinator.prepareContinuation("studio-a", 0, vi.fn())).rejects.toThrow(); + expect(ensure).not.toHaveBeenCalled(); + await store.transition("studio-a", 1, { lifecycle: "open", execution: "paused" }); + await expect(coordinator.prepareContinuation("studio-a", 2, async () => { + await store.transition("studio-a", 2, { lifecycle: "ending", execution: "paused" }); + return "late"; + })).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + expect(current).toBeNull(); + expect(observe).not.toHaveBeenCalled(); +}); + +it("End preempts hung Continue preparation and its late result cannot retire a replacement", async () => { + const held = gate(), prepare = vi.fn(async () => { await held.promise; return "old"; }); + const preparing = coordinator.prepareContinuation("studio-a", 0, prepare); + const rejected = expect(preparing).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + await vi.waitFor(() => expect(prepare).toHaveBeenCalledOnce()); + const old = current!; + const ending = coordinator.beginEnd("studio-a"); + expect(old.signal.aborted).toBe(true); + await rejected; + await ending.persistence; + const ended = await coordinator.finishEnd(ending.fence); + const opened = await store.transition("studio-a", ended.revision, { lifecycle: "open", execution: "paused" }); + await coordinator.prepareContinuation("studio-a", opened.revision, async () => "new"); + const replacement = current!; + held.release(); + await Promise.resolve(); + expect(current).toBe(replacement); + expect(replacement.signal.aborted).toBe(false); + expect(observe).not.toHaveBeenCalled(); +}); diff --git a/packages/harness/src/core/assistant-lifecycle.ts b/packages/harness/src/core/assistant-lifecycle.ts index 39108cb0a..f21a9b9f2 100644 --- a/packages/harness/src/core/assistant-lifecycle.ts +++ b/packages/harness/src/core/assistant-lifecycle.ts @@ -240,14 +240,35 @@ export class AssistantLifecycleCoordinator { return { conversationId, lease, lifecycle: { ...lifecycle } }; } - /** Exclusive temporary ownership, shared with Attach and future Resume. Never + /** Exclusive temporary ownership, shared with Attach, Continue and Resume. Never * creates an association or grants execution. Callback results stay private; * the caller revalidates its saved binding after provisional cleanup. */ - async inspect( + inspect( id: string, expectedRevision: number, read: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, callerSignal?: AbortSignal, + ): Promise { + return this.prepareRuntime(id, expectedRevision, read, false, callerSignal); + } + + /** Trusted Continue preparation owns an open child before its receipt permits + * Attach. Keep the exact runtime on success, but grant no lease or execution. */ + prepareContinuation( + id: string, + expectedRevision: number, + prepare: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, + callerSignal?: AbortSignal, + ): Promise { + return this.prepareRuntime(id, expectedRevision, prepare, true, callerSignal); + } + + private async prepareRuntime( + id: string, + expectedRevision: number, + read: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, + retain: boolean, + callerSignal?: AbortSignal, ): Promise { if ( this.closed || @@ -276,7 +297,11 @@ export class AssistantLifecycleCoordinator { check(); const state = await awaitAssistantInspection(this.describe(id), signal); check(); - if (state.revision !== expectedRevision || state.lifecycle === "ending") + if ( + state.revision !== expectedRevision || + state.lifecycle === "ending" || + (retain && state.lifecycle !== "open") + ) throw failure("lifecycle_changed"); }; let hosted: HostedOpenCode | undefined; @@ -322,7 +347,7 @@ export class AssistantLifecycleCoordinator { return result; } finally { try { - if (provisional && started) { + if (provisional && started && !(complete && retain)) { if ( this.inspections.get(id) === controller && this.generation(id) === fence.generation @@ -334,7 +359,7 @@ export class AssistantLifecycleCoordinator { void this.options.host.retireExact(hosted).catch(() => {}); } } - if (complete) await revision(); + if (complete && !retain) await revision(); } finally { clearTimeout(timer); if (this.inspections.get(id) === controller) diff --git a/packages/harness/src/core/assistant-source-store.test.ts b/packages/harness/src/core/assistant-source-store.test.ts index 092885086..f69cc73d8 100644 --- a/packages/harness/src/core/assistant-source-store.test.ts +++ b/packages/harness/src/core/assistant-source-store.test.ts @@ -63,6 +63,24 @@ afterEach(async () => { await fs.rm(directory, { recursive: true, force: true }); }); +it("does not repair a committed acceptance's missing material from retried pending input", async () => { + const fixture = await retain(); + const source = fixture.accepted.instructionSet.sources.find( + (item) => item.status === "available", + )!; + if (source.status !== "available") + throw new Error("fixture source unavailable"); + const objectPath = join(root(), "objects", source.contentHash); + await fs.rm(objectPath); + await expect( + retain(new FileAssistantSourceStore(directory, sourceScope), fixture), + ).rejects.toBeInstanceOf(AssistantContextError); + await expect(fs.stat(objectPath)).rejects.toMatchObject({ code: "ENOENT" }); + expect(JSON.parse(await fs.readFile(manifest(), "utf8"))).toEqual( + fixture.accepted, + ); +}); + describe("durable accepted Assistant sources", () => { it("reads exact retained text after restart and detaches returned data", async () => { const fixture = await retain(); diff --git a/packages/harness/src/core/assistant-source-store.ts b/packages/harness/src/core/assistant-source-store.ts index dff987a16..a0a3a07b7 100644 --- a/packages/harness/src/core/assistant-source-store.ts +++ b/packages/harness/src/core/assistant-source-store.ts @@ -96,6 +96,23 @@ export class FileAssistantSourceStore implements AssistantSourceStore { ); signal.throwIfAborted(); const root = await this.prepare(true, signal); + const committed = await this.read( + root, + "accepted", + `${ref.acceptanceId}.json`, + signal, + ).catch((error: unknown) => { + if (isCode(error, "ENOENT")) return null; + throw error; + }); + if (committed !== null) { + // A lost acknowledgement may retry this ID. An existing acceptance + // remains authoritative: validate its original material before any + // writes, rather than repairing source loss from pending input. + check(committed.equals(Buffer.from(encodeAssistantContext(record)))); + await this.readAccepted(ref, authority, signal); + return; + } for (const source of record.instructionSet.sources) { if (source.status !== "available") continue; const material = copies.find((item) => item.sourceId === source.id)!;