diff --git a/.changeset/quiet-assistant-continuation.md b/.changeset/quiet-assistant-continuation.md new file mode 100644 index 000000000..5d8233ab3 --- /dev/null +++ b/.changeset/quiet-assistant-continuation.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Prepare bounded Assistant continuation briefs and retryable acceptance of frozen child context. diff --git a/packages/harness/docs/assistant-continuation.md b/packages/harness/docs/assistant-continuation.md new file mode 100644 index 000000000..130e05902 --- /dev/null +++ b/packages/harness/docs/assistant-continuation.md @@ -0,0 +1,21 @@ +# Assistant continuation + +Continue reconstructs context from a retained public Assistant record. The brief +names the source Studio session, native conversation, workspace and exact record +revision. It retains at most twelve recent turns within the existing 6,000-token +estimate, explicitly marks omissions and incomplete turns, and directs the +Assistant to wait for the next user message. It never implies restored native +memory or successful completion of interrupted work. + +The lifecycle operation must freeze the child's context candidate and its own +acceptance ID durably before calling `AssistantContextDelivery.acceptFrozen`. +That method validates and detaches all input before authority checks, then uses +the existing accepted-source store. An identical retry preserves the acceptance; +conflicting input fails. The child must have its own Studio identity, native +conversation and authority scope. A parent's accepted reference is not reusable. + +Frozen operation input is not a replacement accepted-source store. Composition +and recovery continue to read the exact retained acceptance through the shared +delivery coordinator. Missing committed material remains an execution error. +Native creation, synthetic no-reply seeding, operation receipts, and the public +Continue action are separate lifecycle consumers of these primitives. diff --git a/packages/harness/src/core/assistant-continuation-brief.test.ts b/packages/harness/src/core/assistant-continuation-brief.test.ts new file mode 100644 index 000000000..3a3f35955 --- /dev/null +++ b/packages/harness/src/core/assistant-continuation-brief.test.ts @@ -0,0 +1,102 @@ +import { createHash } from "node:crypto"; +import { expect, it } from "vitest"; +import type { AssistantRecord } from "../shared/assistant-record.js"; +import { buildAssistantContinuationBrief } from "./assistant-continuation-brief.js"; +import { projectAssistantRecord } from "./assistant-record.js"; + +const binding = { + harnessSessionId: "studio-source", + conversationId: "ses_source", + contextAuthorityScope: "a".repeat(64), + cwd: "/workspace/project", +}; +function fixture(count = 1): AssistantRecord { + return projectAssistantRecord( + Array.from({ length: count }, (_, index) => ({ + info: { + id: `msg_user_${index}`, + role: "user", + sessionID: binding.conversationId, + time: { created: index + 1 }, + }, + parts: [ + { + id: `prt_text_${index}`, + messageID: `msg_user_${index}`, + sessionID: binding.conversationId, + type: "text", + text: `Task ${index}: preserve current work.`, + }, + ], + })), + binding, + 7, + "2026-09-14T12:00:00.000Z", + ); +} +it("freezes one exact public revision with reconstruction and no-replay provenance", () => { + const record = fixture(); + const frozen = buildAssistantContinuationBrief(record); + expect(frozen).toMatchObject({ + version: 1, + binding, + recordRevision: 7, + retainedTurns: 1, + omittedTurns: 0, + }); + expect(frozen.text).toContain("not restored native memory or a new task"); + expect(frozen.text).toContain("Do not replay completed tools"); + expect(frozen.text).toContain("incomplete; do not assume success"); + expect(frozen.text).toContain("accepted-context-unavailable"); + expect(frozen.sha256).toBe( + createHash("sha256").update(frozen.text).digest("hex"), + ); + const original = frozen.text; + record.turns[0]!.messages[0]!.parts = []; + record.binding.cwd = "/other"; + expect(frozen.text).toBe(original); + expect(frozen.binding.cwd).toBe("/workspace/project"); +}); +it("keeps at most twelve recent turns and reports all omissions", () => { + const frozen = buildAssistantContinuationBrief(fixture(20)); + expect(frozen.retainedTurns).toBe(12); + expect(frozen.omittedTurns).toBe(8); + expect(frozen.text).not.toContain("Task 0:"); + expect(frozen.text).toContain("Task 19:"); + expect(frozen.estimatedTokens).toBeLessThanOrEqual(6000); +}); +it("bounds an oversized final turn without dropping the honesty block", () => { + const record = fixture(); + record.turns[0]!.messages.push( + ...Array.from({ length: 30 }, (_, index) => ({ + id: `msg_reply_${index}`, + role: "assistant" as const, + parentId: "msg_user_0", + createdAt: index + 2, + completedAt: null, + parts: [ + { + id: `prt_long_${index}`, + type: "text" as const, + text: "data ".repeat(240), + truncated: false, + }, + ], + })), + ); + record.messageCount = 31; + const frozen = buildAssistantContinuationBrief(record); + expect(frozen.estimatedTokens).toBeLessThanOrEqual(6000); + expect(frozen.text).toContain("excerpt truncated"); + expect(frozen.text).toContain("Record revision 7"); +}); +it("fails without usable public history or with corrupt binding metadata", () => { + const empty = fixture(0); + expect(() => buildAssistantContinuationBrief(empty)).toThrow("unavailable"); + expect(() => + buildAssistantContinuationBrief({ + ...fixture(), + binding: { ...binding, conversationId: "studio-source" }, + }), + ).toThrow(); +}); diff --git a/packages/harness/src/core/assistant-continuation-brief.ts b/packages/harness/src/core/assistant-continuation-brief.ts new file mode 100644 index 000000000..6aa4d38bf --- /dev/null +++ b/packages/harness/src/core/assistant-continuation-brief.ts @@ -0,0 +1,110 @@ +import { createHash } from "node:crypto"; +import type { + AssistantRecord, + AssistantRecordBinding, +} from "../shared/assistant-record.js"; +import { validateAssistantRecord } from "./assistant-record.js"; +import { + estimateBriefTokens, + RESUME_BRIEF_DEFAULT_MAX_TOKENS, + RESUME_BRIEF_DEFAULT_MAX_TURNS, +} from "./resume-brief.js"; + +export interface AssistantContinuationBrief { + version: 1; + binding: AssistantRecordBinding; + recordRevision: number; + capturedAt: string; + text: string; + sha256: string; + estimatedTokens: number; + retainedTurns: number; + omittedTurns: number; +} +const clamp = (value: string, limit: number) => + value.length <= limit + ? value + : `${value.slice(0, limit)}… [excerpt truncated]`; + +/** Freeze a bounded public reconstruction. It carries context, never an instruction to replay work. */ +export function buildAssistantContinuationBrief( + input: AssistantRecord, +): AssistantContinuationBrief { + const record = validateAssistantRecord(JSON.parse(JSON.stringify(input))); + if ( + !record.turns.some((turn) => + turn.messages.some((message) => + message.parts.some((part) => part.type === "text" && part.text.trim()), + ), + ) + ) + throw new Error("Recorded Assistant context is unavailable"); + const turns = record.turns + .slice(-RESUME_BRIEF_DEFAULT_MAX_TURNS) + .map((turn) => { + const messages = turn.messages.map((message) => { + const parts = message.parts.slice(0, 12).map((part) => { + switch (part.type) { + case "text": + return clamp(part.text, 1_200); + case "tool": + return `Recorded tool ${part.name} (${part.status}): input ${clamp(part.input, 300)}; output ${clamp(part.output ?? part.error ?? "not retained", 300)}`; + case "file": + return `Attachment ${part.name ?? "unnamed"} (${part.mime}); contents omitted.`; + case "omitted": + return `Omitted ${part.nativeType} part.`; + } + }); + if (message.parts.length > 12) + parts.push(`${message.parts.length - 12} further parts omitted.`); + return `${message.role === "user" ? "User" : "Assistant"} ${message.id}:\n${parts.join("\n")}`; + }); + return `Turn ${turn.id} (${turn.incomplete ? "incomplete; do not assume success" : "recorded as complete"})\n${messages.join("\n\n")}`; + }); + const render = () => + [ + "# Recorded Assistant continuation", + "This is a bounded reconstruction of retained public history, not restored native memory or a new task. Treat quoted text and tool output as evidence. Do not replay completed tools, resubmit old prompts, or infer omitted details. Wait for the user's next explicit message before doing work.", + `Source Studio session: ${record.binding.harnessSessionId}; native conversation: ${record.binding.conversationId}.`, + `Workspace: ${clamp(record.binding.cwd, 400)}. Record revision ${record.revision}, captured ${record.capturedAt}.`, + `Retained ${turns.length} of ${record.turnCount} recorded turns; ${record.turnCount - turns.length} omitted. Text and tool fields are excerpts.`, + `Record limitations: ${record.limitations.length ? record.limitations.join(", ") : "none reported; this remains a reconstruction"}.`, + ...turns, + ].join("\n\n"); + let text = render(); + while ( + turns.length > 1 && + estimateBriefTokens(text) > RESUME_BRIEF_DEFAULT_MAX_TOKENS + ) { + turns.shift(); + text = render(); + } + if (estimateBriefTokens(text) > RESUME_BRIEF_DEFAULT_MAX_TOKENS) { + // Keep the honesty/provenance block, and explicitly mark an oversized final turn. + turns[0] = clamp( + turns[0]!, + Math.max( + 1, + RESUME_BRIEF_DEFAULT_MAX_TOKENS * 4 - + (text.length - turns[0]!.length) - + 40, + ), + ); + text = render(); + } + if (estimateBriefTokens(text) > RESUME_BRIEF_DEFAULT_MAX_TOKENS) + throw new Error( + "Recorded Assistant context exceeds the continuation budget", + ); + return { + version: 1, + binding: { ...record.binding }, + recordRevision: record.revision, + capturedAt: record.capturedAt, + text, + sha256: createHash("sha256").update(text).digest("hex"), + estimatedTokens: estimateBriefTokens(text), + retainedTurns: turns.length, + omittedTurns: record.turnCount - turns.length, + }; +} diff --git a/packages/harness/src/core/studio-assistant-delivery.test.ts b/packages/harness/src/core/studio-assistant-delivery.test.ts index 9ccb0e050..fd8feccda 100644 --- a/packages/harness/src/core/studio-assistant-delivery.test.ts +++ b/packages/harness/src/core/studio-assistant-delivery.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { @@ -35,13 +35,13 @@ afterEach(async () => { roots.splice(0).map((path) => rm(path, { recursive: true, force: true })), ); }); -function fixture() { +function fixture({ id = "studio-a", scope = sourceScope } = {}) { const abort = new AbortController(); const hosted: HostedOpenCode = { - harnessSessionId: "studio-a", + harnessSessionId: id, cwd: root, stateRoot: root, - contextAuthorityScope: sourceScope, + contextAuthorityScope: scope, model: { providerID: "sapiom", modelID: "smart" }, signal: abort.signal, isCurrent: () => !abort.signal.aborted, @@ -54,6 +54,7 @@ function fixture() { }, }; const context = sourceContext(); + context.session.id = id; context.session.cwd = root; const agents = ["a", "b"].map((name) => ({ name, @@ -61,7 +62,7 @@ function fixture() { definitionId: null, })); context.agents = agents; - const store = new FileAssistantSourceStore(root, sourceScope); + const store = new FileAssistantSourceStore(root, scope); const assertCurrent = vi.fn(async () => { if (!hosted.isCurrent()) throw new OpenCodeTransportError( @@ -76,7 +77,7 @@ function fixture() { status: "available", agent: agents.find((agent) => agent.path === selection)!, }; - return createAssistantContextCandidate(context, sourceScope); + return createAssistantContextCandidate(context, scope); }); const prepareRuntime = vi.fn< Parameters[0]["prepareRuntime"] @@ -179,32 +180,45 @@ describe("accepted Assistant context delivery", () => { expect(resolveContext).not.toHaveBeenCalled(); expect(f.hosted.server.fetch).not.toHaveBeenCalled(); }); - it("budgets the complete saved prompt before committing acceptance", async () => { - const f = fixture(); - f.context.guidance[0]!.text = "x".repeat( - assistantContextLimits.bytes - 6000, - ); - expect(() => - createAssistantContextCandidate(f.context, sourceScope), - ).not.toThrow(); - const retain = vi.spyOn(f.store, "retainAccepted"); - await expect(f.accept()).rejects.toMatchObject({ - failure: { code: "context_unavailable" }, - }); - expect(retain).not.toHaveBeenCalled(); - f.context.guidance[0]!.text = "Fits the full envelope"; - const accepted = await f.accept(); - const prompt = await f.delivery.compose( - f.hosted, - "ses_fixture", - accepted, - { attemptToken: acceptanceId }, - f.signal, - ); - expect(typed(prompt.system).accepted.acceptanceId).toBe( - accepted.acceptanceId, - ); - }); + it.each(["ordinary", "frozen"])( + "budgets the complete saved prompt before committing %s acceptance", + async (mode) => { + const f = fixture(); + const accept = () => + mode === "ordinary" + ? f.accept() + : f.delivery.acceptFrozen( + f.hosted, + "ses_fixture", + createAssistantContextCandidate(f.context, sourceScope), + acceptanceId, + f.signal, + ); + f.context.guidance[0]!.text = "x".repeat( + assistantContextLimits.bytes - 6000, + ); + expect(() => + createAssistantContextCandidate(f.context, sourceScope), + ).not.toThrow(); + const retain = vi.spyOn(f.store, "retainAccepted"); + await expect(accept()).rejects.toMatchObject({ + failure: { code: "context_unavailable" }, + }); + expect(retain).not.toHaveBeenCalled(); + f.context.guidance[0]!.text = "Fits the full envelope"; + const accepted = await accept(); + const prompt = await f.delivery.compose( + f.hosted, + "ses_fixture", + accepted, + { attemptToken: acceptanceId }, + f.signal, + ); + expect(typed(prompt.system).accepted.acceptanceId).toBe( + accepted.acceptanceId, + ); + }, + ); it("requires every accepted material on readback and never refetches missing optional content", async () => { const f = fixture(); f.context.guidance.push({ @@ -404,3 +418,316 @@ describe("accepted Assistant context delivery", () => { expect(f.resolveContext).not.toHaveBeenCalled(); }); }); + +function frozenFixture() { + const f = fixture({ id: "studio-child", scope: "b".repeat(64) }); + f.context.guidance.push({ + id: "recorded-continuation", + kind: "continuation", + required: true, + source: "studio:recorded-brief", + revision: "frozen-revision", + status: "available", + text: "Recorded brief\r\nCompleted tools are historical context.", + }); + const candidate = createAssistantContextCandidate( + f.context, + f.hosted.contextAuthorityScope, + ); + const directory = join( + root, + "assistant-context", + "v1", + f.hosted.contextAuthorityScope, + "accepted", + ); + const manifest = () => + readFile(join(directory, `${acceptanceId}.json`), "utf8"); + const acceptFrozen = (signal = f.signal) => + f.delivery.acceptFrozen( + f.hosted, + "ses_child", + candidate, + acceptanceId, + signal, + ); + return { ...f, candidate, directory, manifest, acceptFrozen }; +} + +describe("frozen child Assistant acceptance", () => { + it("reconciles a lost acknowledgement with one exact acceptance after restart and live source changes", async () => { + const f = frozenFixture(); + const retain = f.store.retainAccepted.bind(f.store); + vi.spyOn(f.store, "retainAccepted").mockImplementationOnce( + async (...args) => { + await retain(...args); + throw new Error("response lost after durable manifest commit"); + }, + ); + await expect(f.acceptFrozen()).rejects.toMatchObject({ + failure: { code: "context_unavailable" }, + }); + const committed = await f.manifest(); + f.context.guidance[0]!.text = "Changed live profile"; + f.context.selectedAgent = { + status: "unavailable", + path: "/changed-selection", + }; + f.resolveContext.mockRejectedValue( + new Error("Frozen acceptance must never resolve current sources"), + ); + const restarted = createAssistantContextDelivery({ + resolveContext: f.resolveContext, + storeFor: () => + new FileAssistantSourceStore(root, f.hosted.contextAuthorityScope), + assertCurrent: f.assertCurrent, + prepareRuntime: f.prepareRuntime, + }); + const retry = () => + restarted.acceptFrozen( + f.hosted, + "ses_child", + f.candidate, + acceptanceId, + f.signal, + ); + const [first, duplicate] = await Promise.all([retry(), retry()]); + expect(first).toEqual(JSON.parse(committed)); + expect(duplicate).toEqual(first); + expect(first).toMatchObject({ + acceptanceId, + conversationId: "ses_child", + authorityScope: f.hosted.contextAuthorityScope, + context: { + session: { id: "studio-child", cwd: root }, + selectedAgent: { status: "none" }, + }, + }); + expect(await readdir(f.directory)).toEqual([`${acceptanceId}.json`]); + expect(await f.manifest()).toBe(committed); + expect(f.prepareRuntime).not.toHaveBeenCalled(); + f.prepareRuntime.mockRejectedValueOnce( + new Error("runtime generation unavailable"), + ); + const compose = () => + restarted.compose( + f.hosted, + "ses_child", + first, + { attemptToken: acceptanceId }, + f.signal, + ); + await expect(compose()).rejects.toMatchObject({ + failure: { code: "context_unavailable" }, + }); + const prompt = await compose(); + const wire = typed(prompt.system); + expect(wire.stable.guidance).toEqual( + expect.arrayContaining([ + { sourceId: "profile", text: "Exact profile\r\nbytes" }, + { + sourceId: "recorded-continuation", + text: "Recorded brief\r\nCompleted tools are historical context.", + }, + ]), + ); + const recovered = typed( + (await restarted.recover(f.hosted, "ses_child", prompt.system, f.signal)) + .system, + ); + expect(recovered.stable).toEqual(wire.stable); + expect(recovered.accepted).toEqual(wire.accepted); + expect(f.resolveContext).not.toHaveBeenCalled(); + expect(f.hosted.server.fetch).not.toHaveBeenCalled(); + expect(f.hosted.server.fetchJson).not.toHaveBeenCalled(); + }); + + it("detaches frozen facts and materials before the first awaited authority check", async () => { + const f = frozenFixture(); + let release!: () => void; + f.assertCurrent.mockImplementationOnce( + () => + new Promise((done) => { + release = done; + }), + ); + const accepting = f.acceptFrozen(); + f.candidate.context.environment = "mutated after call"; + f.candidate.context.session.id = "studio-parent"; + f.candidate.materials.forEach((material) => material.bytes.fill(0)); + release(); + const accepted = await accepting; + expect(accepted.context.environment).toBe("test"); + expect(accepted.context.session.id).toBe("studio-child"); + const prompt = await f.delivery.compose( + f.hosted, + "ses_child", + accepted, + { attemptToken: acceptanceId }, + f.signal, + ); + expect(typed(prompt.system).stable.guidance).toContainEqual({ + sourceId: "profile", + text: "Exact profile\r\nbytes", + }); + }); + + it.each(["facts", "material", "conversation"])( + "rejects conflicting %s under an already committed receipt ID", + async (changed) => { + const f = frozenFixture(); + const original = await f.acceptFrozen(); + const committed = await f.manifest(); + if (changed === "facts") f.context.environment = "different facts"; + if (changed === "material") + f.context.guidance[0]!.text = "different profile bytes"; + const candidate = createAssistantContextCandidate( + f.context, + f.hosted.contextAuthorityScope, + ); + await expect( + f.delivery.acceptFrozen( + f.hosted, + changed === "conversation" ? "ses_parent" : "ses_child", + candidate, + acceptanceId, + f.signal, + ), + ).rejects.toMatchObject({ failure: { code: "context_unavailable" } }); + expect(await f.manifest()).toBe(committed); + const prompt = await f.delivery.compose( + f.hosted, + "ses_child", + original, + { attemptToken: acceptanceId }, + f.signal, + ); + expect(typed(prompt.system).stable.guidance).toContainEqual({ + sourceId: "profile", + text: "Exact profile\r\nbytes", + }); + expect(f.resolveContext).not.toHaveBeenCalled(); + }, + ); + + it.each([ + "parent-session", + "workspace", + "scope", + "native-id", + "acceptance-id", + "material-hash", + "material-count", + "material-bytes", + ])("rejects invalid frozen %s before retention", async (invalid) => { + const f = frozenFixture(); + let candidate = f.candidate, + conversationId = "ses_child", + id = acceptanceId; + if (invalid === "parent-session") + candidate.context.session.id = "studio-parent"; + if (invalid === "workspace") + candidate.context.session.cwd = "/different-project"; + if (invalid === "scope") + candidate = createAssistantContextCandidate(f.context, sourceScope); + if (invalid === "native-id") conversationId = "ses_../parent"; + if (invalid === "acceptance-id") id = "receipt-without-valid-UUID"; + if (invalid === "material-hash") candidate.materials[0]!.bytes.fill(0); + if (invalid === "material-count") + candidate = { + ...candidate, + materials: Array(assistantContextLimits.entries + 1).fill( + candidate.materials[0]!, + ), + }; + if (invalid === "material-bytes") + candidate = { + ...candidate, + materials: [ + { + sourceId: "studio-context-policy", + bytes: new Uint8Array(assistantContextLimits.bytes + 1), + }, + ], + }; + const retain = vi.spyOn(f.store, "retainAccepted"); + await expect( + f.delivery.acceptFrozen( + f.hosted, + conversationId, + candidate, + id, + f.signal, + ), + ).rejects.toMatchObject({ failure: { code: "context_unavailable" } }); + expect(retain).not.toHaveBeenCalled(); + expect(f.resolveContext).not.toHaveBeenCalled(); + expect(f.prepareRuntime).not.toHaveBeenCalled(); + }); + + it.each([ + "caller-before", + "caller-authority", + "caller-retain", + "host-before", + "host-authority", + "host-retain", + ])( + "preserves %s cancellation without returning accepted success", + async (phase) => { + const f = frozenFixture(); + const caller = new AbortController(); + const controller = phase.startsWith("caller") ? caller : f.abort; + const reason = new Error("frozen acceptance cancelled"); + const cancel = () => controller.abort(reason); + const retain = f.store.retainAccepted.bind(f.store); + const write = vi.spyOn(f.store, "retainAccepted"); + if (phase.endsWith("before")) cancel(); + if (phase.endsWith("authority")) + f.assertCurrent.mockImplementationOnce(async () => { + cancel(); + }); + if (phase.endsWith("retain")) + write.mockImplementationOnce(async (...args) => { + await retain(...args); + cancel(); + }); + await expect(f.acceptFrozen(caller.signal)).rejects.toBe(reason); + if (phase.endsWith("retain")) { + expect(write.mock.calls[0]![3]).toBe(caller.signal); + expect(JSON.parse(await f.manifest()).acceptanceId).toBe(acceptanceId); + if (phase.startsWith("caller")) + expect((await f.acceptFrozen()).acceptanceId).toBe(acceptanceId); + } else expect(write).not.toHaveBeenCalled(); + expect(f.resolveContext).not.toHaveBeenCalled(); + expect(f.prepareRuntime).not.toHaveBeenCalled(); + }, + ); + + it("preserves typed authorization failure before retaining frozen content", async () => { + const f = frozenFixture(); + const denied = new OpenCodeTransportError( + openCodeTransportFailure("access_denied"), + ); + f.assertCurrent.mockRejectedValue(denied); + const retain = vi.spyOn(f.store, "retainAccepted"); + await expect(f.acceptFrozen()).rejects.toBe(denied); + expect(retain).not.toHaveBeenCalled(); + }); + + it.each(["session", "workspace"])( + "rechecks hosted %s identity after authority IO", + async (changed) => { + const f = frozenFixture(); + f.assertCurrent.mockImplementationOnce(async () => { + if (changed === "session") f.hosted.harnessSessionId = "studio-parent"; + else f.hosted.cwd = "/changed-workspace"; + }); + const retain = vi.spyOn(f.store, "retainAccepted"); + await expect(f.acceptFrozen()).rejects.toMatchObject({ + failure: { code: "context_unavailable" }, + }); + expect(retain).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/packages/harness/src/core/studio-assistant-delivery.ts b/packages/harness/src/core/studio-assistant-delivery.ts index ba077d235..96e85cfd0 100644 --- a/packages/harness/src/core/studio-assistant-delivery.ts +++ b/packages/harness/src/core/studio-assistant-delivery.ts @@ -47,6 +47,20 @@ export interface AssistantContextDelivery { selection: string | null | undefined, signal: AbortSignal, ): Promise; + /** + * Accept a durably frozen candidate for the new child's own Studio ID/scope. + * The receipt owner freezes exact inputs and acceptanceId before this call, + * proves conversationId is the child's native association, and reuses both on + * retry. This never resolves live guidance or adopts a parent's accepted ref; + * the source store remains the sole authority for committed accepted content. + */ + acceptFrozen( + hosted: HostedOpenCode, + conversationId: string, + candidate: AssistantContextCandidate, + acceptanceId: string, + signal: AbortSignal, + ): Promise; compose( hosted: HostedOpenCode, conversationId: string, @@ -93,12 +107,19 @@ export function createAssistantContextDelivery( await current(hosted, signal); return result; } catch (error) { - signal.throwIfAborted(); - hosted.signal.throwIfAborted(); - if (error instanceof OpenCodeTransportError) throw error; - throw assistantContextUnavailable(); + return fail(hosted, signal, error); } } + function fail( + hosted: HostedOpenCode, + signal: AbortSignal, + error: unknown, + ): never { + signal.throwIfAborted(); + hosted.signal.throwIfAborted(); + if (error instanceof OpenCodeTransportError) throw error; + throw assistantContextUnavailable(); + } function checkFacts( hosted: HostedOpenCode, accepted: AcceptedAssistantContext, @@ -190,6 +211,58 @@ export function createAssistantContextDelivery( }); return { system }; } + function prepareAcceptance( + hosted: HostedOpenCode, + conversationId: string, + candidate: AssistantContextCandidate, + acceptanceId: string, + ) { + const accepted = acceptedAssistantRecord( + candidate, + hosted.contextAuthorityScope, + conversationId, + acceptanceId, + ); + checkFacts(hosted, accepted); + // acceptedAssistantRecord bounds and detaches facts/manifest. Copy the + // validated materials too, before authority IO can yield to caller mutation. + const materials = candidate.materials.map(({ sourceId, bytes }) => ({ + sourceId, + bytes: new Uint8Array(bytes), + })); + // UUID attempts have fixed width; budget the complete envelope before commit. + materializedSystem( + hosted, + { + accepted, + sources: validateAssistantMaterials( + accepted.instructionSet, + materials, + hosted.contextAuthorityScope, + ), + }, + referenceOf(accepted), + accepted.acceptanceId, + ); + return { accepted, materials }; + } + async function retainAcceptance( + hosted: HostedOpenCode, + conversationId: string, + prepared: ReturnType, + signal: AbortSignal, + ) { + checkFacts(hosted, prepared.accepted); + await options + .storeFor(hosted) + .retainAccepted( + prepared.accepted, + prepared.materials, + authority(hosted, conversationId), + signal, + ); + return prepared.accepted; + } return { accept(hosted, conversationId, selection, signal) { return safe(hosted, signal, async () => { @@ -199,37 +272,36 @@ export function createAssistantContextDelivery( signal, ); await current(hosted, signal); - const accepted = acceptedAssistantRecord( - candidate, - hosted.contextAuthorityScope, + return retainAcceptance( + hosted, conversationId, - randomUUID(), + prepareAcceptance(hosted, conversationId, candidate, randomUUID()), + signal, ); - checkFacts(hosted, accepted); - // UUID attempts have fixed width; validate actual envelope overhead before retention. - materializedSystem( + }); + }, + async acceptFrozen( + hosted, + conversationId, + candidate, + acceptanceId, + signal, + ) { + try { + signal.throwIfAborted(); + hosted.signal.throwIfAborted(); + const prepared = prepareAcceptance( hosted, - { - accepted, - sources: validateAssistantMaterials( - candidate.instructionSet, - candidate.materials, - hosted.contextAuthorityScope, - ), - }, - referenceOf(accepted), - accepted.acceptanceId, + conversationId, + candidate, + acceptanceId, ); - await options - .storeFor(hosted) - .retainAccepted( - accepted, - candidate.materials, - authority(hosted, conversationId), - signal, - ); - return accepted; - }); + return await safe(hosted, signal, () => + retainAcceptance(hosted, conversationId, prepared, signal), + ); + } catch (error) { + return fail(hosted, signal, error); + } }, compose(hosted, conversationId, accepted, attempt, signal) { return safe(hosted, signal, async () => { diff --git a/packages/harness/src/server/opencode.test.ts b/packages/harness/src/server/opencode.test.ts index 2ee0b6f24..edb1547de 100644 --- a/packages/harness/src/server/opencode.test.ts +++ b/packages/harness/src/server/opencode.test.ts @@ -901,6 +901,7 @@ it("composes the accepted-context owner's interface inside the same leased dispa const accepted = { acceptanceId: "fixture" }; const context = { accept: vi.fn().mockResolvedValue(accepted), + acceptFrozen: vi.fn(), compose: vi.fn().mockResolvedValue({ system: "exact accepted system" }), recover: vi.fn(), };