diff --git a/.changeset/durable-assistant-continuation.md b/.changeset/durable-assistant-continuation.md new file mode 100644 index 000000000..c7c554033 --- /dev/null +++ b/.changeset/durable-assistant-continuation.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Retain one durable Assistant continuation operation and child identity across retries. diff --git a/packages/harness/docs/assistant-continuation.md b/packages/harness/docs/assistant-continuation.md index 130e05902..c790d371f 100644 --- a/packages/harness/docs/assistant-continuation.md +++ b/packages/harness/docs/assistant-continuation.md @@ -19,3 +19,13 @@ 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. + +The private operation receipt lives beside the source binding, outside native +engine storage. It freezes source revisions, child identity, brief, native +creation marker, seed IDs and pending acceptance input. Creation and seeding +intent are recorded before native mutations; an uncertain phase cannot reset. +An operation lock serializes external steps, while receipt updates use a +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. diff --git a/packages/harness/src/core/assistant-continuation-store.test.ts b/packages/harness/src/core/assistant-continuation-store.test.ts new file mode 100644 index 000000000..6f4bcd08f --- /dev/null +++ b/packages/harness/src/core/assistant-continuation-store.test.ts @@ -0,0 +1,396 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { beforeEach, afterEach, expect, it, vi } from "vitest"; +import { + AssistantContinuationStore, + ASSISTANT_CONTINUATION_MAX_BYTES, + freezeContinuationCandidate, + thawContinuationCandidate, + type AssistantContinuationPatch, + type AssistantContinuationReceipt, +} from "./assistant-continuation-store.js"; +import { projectAssistantRecord } from "./assistant-record.js"; +import { + acceptedAssistantRecord, + createAssistantContextCandidate, +} from "./assistant-sources.js"; +import { sourceContext } from "./test-fixtures/assistant-context.js"; +import * as files from "./assistant-session-files.js"; + +vi.mock("./assistant-session-files.js", async (original) => { + const files = await original(); + return { ...files, writeAssistantJson: vi.fn(files.writeAssistantJson) }; +}); +const binding = { + harnessSessionId: "studio-parent", + cwd: "/workspace", + conversationId: "ses_parent", + contextAuthorityScope: "a".repeat(64), +}; +const operation = "11111111-1111-4111-8111-111111111111"; +let root: string, store: AssistantContinuationStore; +const record = () => + projectAssistantRecord( + [ + { + info: { + id: "msg_user", + role: "user", + sessionID: "ses_parent", + time: { created: 1 }, + }, + parts: [ + { + id: "prt_text", + messageID: "msg_user", + sessionID: "ses_parent", + type: "text", + text: "Preserve the current result.", + }, + ], + }, + ], + binding, + 7, + ); +const load = vi.fn(async () => record()); +const reserve = () => store.reserve(binding, 7, 3, operation, load); +const receiptPath = () => + join( + root, + "assistant-sessions", + binding.harnessSessionId, + "bindings", + binding.contextAuthorityScope, + `continuation-${operation}.json`, + ); +const linkPath = (id: string) => + join(root, "assistant-sessions", id, "continuation-preparation.json"); +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "continuation-receipt-")); + store = new AssistantContinuationStore(root); + load.mockReset().mockImplementation(async () => record()); + const actual = await vi.importActual( + "./assistant-session-files.js", + ); + vi.mocked(files.writeAssistantJson) + .mockReset() + .mockImplementation(actual.writeAssistantJson); +}); +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +async function advanceTo(target: AssistantContinuationReceipt["phase"]) { + let receipt = await reserve(); + const child = { + ...binding, + harnessSessionId: receipt.childStudioId, + conversationId: "ses_child", + contextAuthorityScope: "b".repeat(64), + }; + const context = sourceContext(); + context.session.id = child.harnessSessionId; + context.guidance.push({ + id: "continuation", + kind: "continuation", + required: true, + source: "studio:record", + revision: null, + status: "available", + text: receipt.brief.text, + }); + const candidate = createAssistantContextCandidate( + context, + child.contextAuthorityScope, + ); + const frozen = freezeContinuationCandidate( + candidate, + child, + receipt.acceptanceId, + ); + const ref = { + schemaVersion: 1 as const, + acceptanceId: receipt.acceptanceId, + conversationId: child.conversationId, + authorityScope: child.contextAuthorityScope, + revision: acceptedAssistantRecord( + candidate, + child.contextAuthorityScope, + child.conversationId, + receipt.acceptanceId, + ).revision, + }; + const patches: AssistantContinuationPatch[] = [ + { phase: "allocated" }, + { phase: "creating" }, + { phase: "associated", childBinding: child }, + { phase: "accepting", frozenCandidate: frozen }, + { phase: "seeding", acceptedRef: ref }, + { phase: "prepared" }, + ]; + for (const patch of patches) { + if (receipt.phase === target) break; + receipt = await store.update(receipt, patch); + } + return receipt; +} + +it("reserves once across concurrent calls/restart and reads the existing receipt before newer history", async () => { + const [first, duplicate] = await Promise.all([reserve(), reserve()]); + expect(duplicate).toEqual(first); + load.mockRejectedValue(new Error("latest history changed or disappeared")); + store = new AssistantContinuationStore(root); + expect(await reserve()).toEqual(first); + expect(load).toHaveBeenCalledOnce(); + expect(first.childStudioId).not.toBe(binding.harnessSessionId); + expect(first.seedMessageId).toMatch(/^msg_[a-f0-9]{12}[A-Za-z0-9]{14}$/); + expect(parseInt(first.seedPartId.slice(4, 16), 16)).toBeGreaterThan( + parseInt(first.seedMessageId.slice(4, 16), 16), + ); + expect( + JSON.parse(await readFile(linkPath(first.childStudioId), "utf8")), + ).toMatchObject({ + childStudioId: first.childStudioId, + operationId: operation, + sourceBinding: binding, + }); + expect(await store.canAttach(first.childStudioId)).toBe(false); + expect(await store.readChild(first.childStudioId)).toEqual(first); + expect(await store.readChild("ordinary-session")).toBeNull(); + expect(await store.canAttach("ordinary-session")).toBe(true); +}); + +it.each(["record", "lifecycle", "workspace", "conversation"])( + "rejects different %s reservation inputs without rereading history", + async (changed) => { + const first = await reserve(); + const source = { + ...binding, + ...(changed === "workspace" ? { cwd: "/other" } : {}), + ...(changed === "conversation" ? { conversationId: "ses_other" } : {}), + }; + await expect( + store.reserve( + source, + changed === "record" ? 8 : 7, + changed === "lifecycle" ? 4 : 3, + operation, + load, + ), + ).rejects.toThrow(); + expect(load).toHaveBeenCalledOnce(); + expect(await store.read(binding, operation)).toEqual(first); + expect( + await store.read( + { ...binding, contextAuthorityScope: "c".repeat(64) }, + operation, + ), + ).toBeNull(); + }, +); + +it.each(["empty", "missing", "revision"])( + "does not reserve a child from %s history", + async (bad) => { + const source = + bad === "empty" + ? projectAssistantRecord([], binding, 7) + : bad === "missing" + ? null + : { ...record(), revision: 8 }; + await expect( + store.reserve(binding, 7, 3, operation, async () => source), + ).rejects.toThrow(); + expect(await store.read(binding, operation)).toBeNull(); + expect(files.writeAssistantJson).not.toHaveBeenCalled(); + }, +); + +it.each(["creating", "seeding"] as const)( + "retains uncertain %s across restart and forbids a reset or stale CAS", + async (phase) => { + const current = await advanceTo(phase); + store = new AssistantContinuationStore(root); + expect(await reserve()).toEqual(current); + await expect( + store.update(current, { phase: "allocated" }), + ).rejects.toThrow(); + const next = await store.update( + current, + phase === "creating" + ? { + phase: "associated", + childBinding: { + ...binding, + harnessSessionId: current.childStudioId, + conversationId: "ses_child", + contextAuthorityScope: "b".repeat(64), + }, + } + : { phase: "prepared" }, + ); + await expect(store.update(current, { phase })).rejects.toThrow("changed"); + expect(next.revision).toBe(current.revision + 1); + expect(await store.canAttach(current.childStudioId)).toBe( + phase === "seeding", + ); + }, +); + +it("freezes child inputs and reference once, and keeps prepared admission tied to the exact receipt", async () => { + const current = await advanceTo("prepared"); + expect(await store.canAttach(current.childStudioId)).toBe(true); + const candidate = thawContinuationCandidate( + current.frozenCandidate!, + current.childBinding!, + current.acceptanceId, + ); + candidate.context.environment = "changed"; + const changed = freezeContinuationCandidate( + candidate, + current.childBinding!, + current.acceptanceId, + ); + for (const patch of [ + { childBinding: null }, + { acceptedRef: null }, + { frozenCandidate: changed }, + { phase: "creating" }, + { acceptanceId: operation }, + { brief: { ...current.brief, text: "changed" } }, + ]) + await expect( + store.update(current, patch as AssistantContinuationPatch), + ).rejects.toThrow(); + expect(await store.read(binding, operation)).toEqual(current); + await rm(receiptPath()); + await rm(`${receiptPath()}.previous`); + await expect(store.readChild(current.childStudioId)).rejects.toThrow(); + expect(await store.canAttach(current.childStudioId)).toBe(false); +}); + +it("rejects a valid child candidate whose continuation is not this frozen brief", async () => { + const current = await advanceTo("associated"); + const context = sourceContext(); + context.session.id = current.childStudioId; + context.guidance.push({ + id: "continuation", + kind: "continuation", + required: true, + source: "studio:record", + revision: null, + status: "available", + text: "Unrelated recorded brief", + }); + const candidate = createAssistantContextCandidate( + context, + current.childBinding!.contextAuthorityScope, + ); + const frozen = freezeContinuationCandidate( + candidate, + current.childBinding!, + current.acceptanceId, + ); + await expect( + store.update(current, { phase: "accepting", frozenCandidate: frozen }), + ).rejects.toThrow(); + expect(await store.read(binding, operation)).toEqual(current); +}); + +it.each(["hash", "seed-id", "accepted-scope", "base64", "size"])( + "fails closed on corrupt %s receipt data", + async (bad) => { + const current = await advanceTo("prepared"); + const invalid = JSON.parse(JSON.stringify(current)); + if (bad === "hash") invalid.brief.sha256 = "0".repeat(64); + if (bad === "seed-id") invalid.seedMessageId = `msg_${operation}`; + if (bad === "accepted-scope") + invalid.acceptedRef.authorityScope = binding.contextAuthorityScope; + if (bad === "base64") + invalid.frozenCandidate.materials[0].bytesBase64 = "!!invalid!!"; + if (bad === "size") + invalid.extra = "x".repeat(ASSISTANT_CONTINUATION_MAX_BYTES); + await writeFile(receiptPath(), JSON.stringify(invalid)); + await expect(store.read(binding, operation)).rejects.toThrow(); + await expect(store.readChild(current.childStudioId)).rejects.toThrow(); + expect(await store.canAttach(current.childStudioId)).toBe(false); + }, +); + +it.each(["before", "after"])( + "preserves truthful durable state on %s-write update failure", + async (when) => { + const current = await advanceTo("allocated"); + const actual = await vi.importActual( + "./assistant-session-files.js", + ); + vi.mocked(files.writeAssistantJson).mockImplementationOnce( + async (...args) => { + if (when === "after") await actual.writeAssistantJson(...args); + throw new Error("storage acknowledgement failed"); + }, + ); + await expect( + store.update(current, { phase: "creating" }), + ).rejects.toThrow(); + const saved = await new AssistantContinuationStore(root).read( + binding, + operation, + ); + expect(saved?.phase).toBe(when === "after" ? "creating" : "allocated"); + expect(await store.canAttach(current.childStudioId)).toBe(false); + if (when === "before") expect(saved).toEqual(current); + }, +); + +it("repairs a missing child link after interrupted reservation and rejects lookup collisions", async () => { + const actual = await vi.importActual( + "./assistant-session-files.js", + ); + vi.mocked(files.writeAssistantJson).mockImplementation(async (...args) => { + if (args[1] === "continuation-preparation.json") + throw new Error("link write failed"); + return actual.writeAssistantJson(...args); + }); + await expect(reserve()).rejects.toThrow("link write failed"); + const saved = (await store.read(binding, operation))!; + vi.mocked(files.writeAssistantJson).mockImplementation( + actual.writeAssistantJson, + ); + expect(await reserve()).toEqual(saved); + const link = JSON.parse( + await readFile(linkPath(saved.childStudioId), "utf8"), + ); + await writeFile( + linkPath(saved.childStudioId), + JSON.stringify({ + ...link, + operationId: "22222222-2222-4222-8222-222222222222", + }), + ); + await expect(reserve()).rejects.toThrow(); + await expect(store.readChild(saved.childStudioId)).rejects.toThrow(); + expect(await store.canAttach(saved.childStudioId)).toBe(false); + expect(load).toHaveBeenCalledOnce(); +}); + +it("holds an external operation lock while allowing independent receipt CAS", async () => { + const release = await store.operationLock(binding, operation); + let second = false; + const waiting = store.operationLock(binding, operation).then((unlock) => { + second = true; + return unlock; + }); + try { + const current = await reserve(); + await store.update(current, { phase: "allocated" }); + expect(second).toBe(false); + } finally { + await release(); + } + await ( + await waiting + )(); +}); diff --git a/packages/harness/src/core/assistant-continuation-store.ts b/packages/harness/src/core/assistant-continuation-store.ts new file mode 100644 index 000000000..88f7d8265 --- /dev/null +++ b/packages/harness/src/core/assistant-continuation-store.ts @@ -0,0 +1,529 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { join } from "node:path"; +import { isDeepStrictEqual } from "node:util"; +import { z } from "zod"; +import { + assistantContentHash, + assistantContextLimits, + encodeAssistantContext, + validateAcceptedContextRef, + type AcceptedContextRef, + type InstructionSet, +} from "@sapiom/opencode"; +import type { + AssistantRecord, + AssistantRecordBinding, +} from "../shared/assistant-record.js"; +import { + validateAssistantRecord, + validateAssistantRecordBinding, +} from "./assistant-record.js"; +import { buildAssistantContinuationBrief } from "./assistant-continuation-brief.js"; +import { + acceptedAssistantRecord, + type AssistantContextCandidate, +} from "./assistant-sources.js"; +import { + assistantDirectory, + AssistantStorageError, + readAssistantJson, + writeAssistantJson, +} from "./assistant-session-files.js"; +import { DurableFileLock } from "./durable-file-lock.js"; +import { + estimateBriefTokens, + RESUME_BRIEF_DEFAULT_MAX_TOKENS, + RESUME_BRIEF_DEFAULT_MAX_TURNS, +} from "./resume-brief.js"; +import type { StudioAssistantContext } from "./studio-assistant-context.js"; + +export const ASSISTANT_CONTINUATION_MAX_BYTES = 12 * 1024 * 1024; +const count = z.number().int().nonnegative().safe(); +const uuid = z.string().uuid(); +const binding = z.unknown().transform(validateAssistantRecordBinding); +const phases = [ + "reserved", + "allocated", + "creating", + "associated", + "accepting", + "seeding", + "prepared", +] as const; +const phase = z.enum(phases); +const ref = z.unknown().transform((value): AcceptedContextRef => { + validateAcceptedContextRef(value); + return value; +}); +const frozenSchema = z + .object({ + context: z.custom( + (value) => value !== null && typeof value === "object", + ), + instructionSet: z.custom( + (value) => value !== null && typeof value === "object", + ), + materials: z + .array( + z + .object({ + sourceId: z.string().min(1), + bytesBase64: z + .string() + .max(4 * Math.ceil(assistantContextLimits.bytes / 3)), + }) + .strict(), + ) + .max(assistantContextLimits.entries), + }) + .strict(); +/** Pending operation input only. Execution must read accepted content through its source owner. */ +export type FrozenContinuationCandidate = Readonly< + z.infer +>; +const receiptSchema = z + .object({ + version: z.literal(1), + revision: count.positive(), + operationId: uuid, + sourceBinding: binding, + sourceRecordRevision: count.positive(), + sourceLifecycleRevision: count, + childStudioId: uuid, + brief: z + .object({ + version: z.literal(1), + binding, + recordRevision: count.positive(), + capturedAt: z.string().datetime(), + text: z + .string() + .min(1) + .max(RESUME_BRIEF_DEFAULT_MAX_TOKENS * 4), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + estimatedTokens: count.positive().max(RESUME_BRIEF_DEFAULT_MAX_TOKENS), + retainedTurns: count.positive().max(RESUME_BRIEF_DEFAULT_MAX_TURNS), + omittedTurns: count, + }) + .strict(), + nativeCreationMarker: z.string(), + seedMessageId: z.string().regex(/^msg_[a-f0-9]{12}[A-Za-z0-9]{14}$/), + seedPartId: z.string().regex(/^prt_[a-f0-9]{12}[A-Za-z0-9]{14}$/), + acceptanceId: uuid, + attemptToken: uuid, + createdAt: count, + updatedAt: count, + phase, + childBinding: binding.nullable(), + acceptedRef: ref.nullable(), + frozenCandidate: frozenSchema.nullable(), + }) + .strict(); +export type AssistantContinuationReceipt = Readonly< + z.infer +>; +const patchSchema = receiptSchema + .pick({ + phase: true, + childBinding: true, + acceptedRef: true, + frozenCandidate: true, + }) + .partial() + .strict(); +export type AssistantContinuationPatch = Partial< + Pick< + AssistantContinuationReceipt, + "phase" | "childBinding" | "acceptedRef" | "frozenCandidate" + > +>; +const linkSchema = z + .object({ + version: z.literal(1), + childStudioId: uuid, + sourceBinding: binding, + operationId: uuid, + }) + .strict(); +const check: (value: unknown) => asserts value = (value) => { + if (!value) throw new AssistantStorageError(); +}; + +/** A stale receipt or incompatible retry must be reconciled from durable state. */ +export class AssistantContinuationConflictError extends Error { + readonly code = "CONTINUATION_CHANGED"; + constructor() { + super( + "The recorded continuation changed. Read its receipt before retrying.", + ); + } +} +function snapshot(value: unknown): unknown { + const text = JSON.stringify(value); + check( + typeof text === "string" && + Buffer.byteLength(text) <= ASSISTANT_CONTINUATION_MAX_BYTES, + ); + return JSON.parse(text); +} +function candidateRecord( + candidate: AssistantContextCandidate, + child: AssistantRecordBinding, + acceptanceId: string, +) { + const accepted = acceptedAssistantRecord( + candidate, + child.contextAuthorityScope, + child.conversationId, + acceptanceId, + ); + check( + accepted.context.session.id === child.harnessSessionId && + accepted.context.session.cwd === child.cwd, + ); + return accepted; +} +/** Persist this detached input before acceptFrozen can commit any accepted manifest. */ +export function freezeContinuationCandidate( + candidate: AssistantContextCandidate, + child: AssistantRecordBinding, + acceptanceId: string, +): FrozenContinuationCandidate { + child = validateAssistantRecordBinding(child); + const accepted = candidateRecord(candidate, child, acceptanceId); + const frozen = { + context: JSON.parse( + encodeAssistantContext(candidate.context), + ) as StudioAssistantContext, + instructionSet: accepted.instructionSet, + materials: candidate.materials.map(({ sourceId, bytes }) => ({ + sourceId, + bytesBase64: Buffer.from(bytes).toString("base64"), + })), + }; + thawContinuationCandidate(frozen, child, acceptanceId); + return frozen; +} +/** Decode pending acceptance input; never use it as fallback for missing accepted source material. */ +export function thawContinuationCandidate( + value: FrozenContinuationCandidate, + child: AssistantRecordBinding, + acceptanceId: string, +): AssistantContextCandidate { + const frozen = frozenSchema.parse(snapshot(value)); + let bytes = 0; + const materials = frozen.materials.map(({ sourceId, bytesBase64 }) => { + const material = Buffer.from(bytesBase64, "base64"); + bytes += material.length; + check( + material.toString("base64") === bytesBase64 && + bytes <= assistantContextLimits.bytes, + ); + return { sourceId, bytes: new Uint8Array(material) }; + }); + encodeAssistantContext(frozen.context); + const candidate = { + context: frozen.context, + instructionSet: frozen.instructionSet, + materials, + }; + candidateRecord( + candidate, + validateAssistantRecordBinding(child), + acceptanceId, + ); + return candidate; +} +function validateReceipt(value: unknown): AssistantContinuationReceipt { + try { + const receipt = receiptSchema.parse(snapshot(value)); + const { brief, sourceBinding, childBinding, frozenCandidate, acceptedRef } = + receipt; + check( + isDeepStrictEqual(brief.binding, sourceBinding) && + brief.recordRevision === receipt.sourceRecordRevision, + ); + check( + brief.sha256 === assistantContentHash(brief.text) && + brief.estimatedTokens === estimateBriefTokens(brief.text), + ); + check( + receipt.childStudioId !== sourceBinding.harnessSessionId && + receipt.updatedAt >= receipt.createdAt, + ); + check( + receipt.nativeCreationMarker === + `studio-continuation:${receipt.operationId}:${receipt.childStudioId}`, + ); + check( + receipt.seedMessageId.slice(4, 16) === + seedTimestamp(receipt.createdAt, 1), + ); + check( + receipt.seedPartId.slice(4, 16) === seedTimestamp(receipt.createdAt, 2), + ); + const rank = phases.indexOf(receipt.phase); + check(rank < 3 || childBinding !== null); + check(rank < 4 || frozenCandidate !== null); + check(rank < 5 || acceptedRef !== null); + if (childBinding) + check( + childBinding.harnessSessionId === receipt.childStudioId && + childBinding.cwd === sourceBinding.cwd && + childBinding.contextAuthorityScope !== + sourceBinding.contextAuthorityScope && + childBinding.conversationId !== sourceBinding.conversationId, + ); + if (frozenCandidate) { + check(childBinding !== null); + const candidate = thawContinuationCandidate( + frozenCandidate, + childBinding, + receipt.acceptanceId, + ); + const continuation = candidate.instructionSet.sources.filter( + (source) => source.kind === "continuation", + ); + check( + continuation.length === 1 && + continuation[0]!.status === "available" && + continuation[0]!.contentHash === brief.sha256, + ); + if (acceptedRef) { + check( + acceptedRef.revision === + candidateRecord(candidate, childBinding, receipt.acceptanceId) + .revision, + ); + } + } + if (acceptedRef) + check( + childBinding && + frozenCandidate && + acceptedRef.acceptanceId === receipt.acceptanceId && + acceptedRef.authorityScope === childBinding.contextAuthorityScope && + acceptedRef.conversationId === childBinding.conversationId, + ); + return receipt; + } catch { + throw new AssistantStorageError(); + } +} +function seedTimestamp(now: number, sequence: number): string { + const timestamp = BigInt(now) * 4096n + BigInt(sequence); + const bytes = Buffer.alloc(6); + for (let index = 0; index < 6; index++) + bytes[index] = Number((timestamp >> BigInt(40 - 8 * index)) & 255n); + return bytes.toString("hex"); +} +function seedId(prefix: "msg" | "prt", now: number, sequence: number): string { + const alphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + return `${prefix}_${seedTimestamp(now, sequence)}${[...randomBytes(14)].map((byte) => alphabet[byte % 62]).join("")}`; +} + +/** Durable Continue intent outside native roots. Creating/seeding never imply safe retry after a crash. */ +export class AssistantContinuationStore { + constructor(private readonly stateRoot: string) {} + + private async location(source: AssistantRecordBinding, operationId: string) { + const binding = validateAssistantRecordBinding(source); + uuid.parse(operationId); + return { + directory: await assistantDirectory( + this.stateRoot, + binding.harnessSessionId, + binding.contextAuthorityScope, + ), + name: `continuation-${operationId}.json`, + binding, + }; + } + /** Hold across external operation steps; receipt CAS uses a separate lock. */ + async operationLock(source: AssistantRecordBinding, operationId: string) { + const { directory, name } = await this.location(source, operationId); + return new DurableFileLock(join(directory, `${name}.operation`)).acquire(); + } + async read( + source: AssistantRecordBinding, + operationId: string, + ): Promise { + const { directory, name, binding } = await this.location( + source, + operationId, + ); + const value = await readAssistantJson( + join(directory, name), + ASSISTANT_CONTINUATION_MAX_BYTES, + ); + if (value === null) return null; + const receipt = validateReceipt(value); + check( + isDeepStrictEqual(receipt.sourceBinding, binding) && + receipt.operationId === operationId, + ); + return receipt; + } + async reserve( + source: AssistantRecordBinding, + expectedRecordRevision: number, + sourceLifecycleRevision: number, + operationId: string, + loadRecord: () => Promise, + signal?: AbortSignal, + ): Promise { + const { directory, name, binding } = await this.location( + source, + operationId, + ); + count.positive().parse(expectedRecordRevision); + count.parse(sourceLifecycleRevision); + const unlock = await new DurableFileLock(join(directory, name)).acquire(); + try { + signal?.throwIfAborted(); + let receipt = await this.read(binding, operationId); + if ( + receipt && + (receipt.sourceRecordRevision !== expectedRecordRevision || + receipt.sourceLifecycleRevision !== sourceLifecycleRevision) + ) + throw new AssistantContinuationConflictError(); + if (!receipt) { + const record = validateAssistantRecord(await loadRecord(), binding); + signal?.throwIfAborted(); + if (record.revision !== expectedRecordRevision) + throw new AssistantContinuationConflictError(); + const brief = buildAssistantContinuationBrief(record); + const childStudioId = randomUUID(), + now = Date.now(); + receipt = validateReceipt({ + version: 1, + revision: 1, + operationId, + sourceBinding: binding, + sourceRecordRevision: expectedRecordRevision, + sourceLifecycleRevision, + childStudioId, + brief, + nativeCreationMarker: `studio-continuation:${operationId}:${childStudioId}`, + seedMessageId: seedId("msg", now, 1), + seedPartId: seedId("prt", now, 2), + acceptanceId: randomUUID(), + attemptToken: randomUUID(), + createdAt: now, + updatedAt: now, + phase: "reserved", + childBinding: null, + acceptedRef: null, + frozenCandidate: null, + }); + await writeAssistantJson(directory, name, receipt, signal); + } + await this.ensureChildLink(receipt, signal); + signal?.throwIfAborted(); + return receipt; + } finally { + await unlock(); + } + } + async update( + current: AssistantContinuationReceipt, + input: AssistantContinuationPatch, + signal?: AbortSignal, + ): Promise { + current = validateReceipt(current); + const patch = patchSchema.parse(snapshot(input)); + const { directory, name } = await this.location( + current.sourceBinding, + current.operationId, + ); + const unlock = await new DurableFileLock(join(directory, name)).acquire(); + try { + signal?.throwIfAborted(); + const saved = await this.read(current.sourceBinding, current.operationId); + if (!saved || !isDeepStrictEqual(saved, current)) + throw new AssistantContinuationConflictError(); + const proposed = { ...saved, ...patch }; + const advance = + phases.indexOf(proposed.phase) - phases.indexOf(saved.phase); + if ( + advance < 0 || + advance > 1 || + ["childBinding", "frozenCandidate", "acceptedRef"].some((key) => { + const field = key as + | "childBinding" + | "frozenCandidate" + | "acceptedRef"; + return ( + saved[field] !== null && + !isDeepStrictEqual(saved[field], proposed[field]) + ); + }) + ) + throw new AssistantContinuationConflictError(); + const next = validateReceipt({ + ...proposed, + revision: saved.revision + 1, + updatedAt: Math.max(Date.now(), saved.updatedAt), + }); + await this.ensureChildLink(saved, signal); + if (isDeepStrictEqual(proposed, saved)) return saved; + await writeAssistantJson(directory, name, next, signal); + signal?.throwIfAborted(); + return next; + } finally { + await unlock(); + } + } + private async ensureChildLink( + receipt: AssistantContinuationReceipt, + signal?: AbortSignal, + ): Promise { + const directory = await assistantDirectory( + this.stateRoot, + receipt.childStudioId, + ); + const name = "continuation-preparation.json"; + const unlock = await new DurableFileLock(join(directory, name)).acquire(); + try { + signal?.throwIfAborted(); + const expected = { + version: 1 as const, + childStudioId: receipt.childStudioId, + sourceBinding: receipt.sourceBinding, + operationId: receipt.operationId, + }; + const raw = await readAssistantJson(join(directory, name)); + if (raw !== null) + check(isDeepStrictEqual(linkSchema.parse(raw), expected)); + else await writeAssistantJson(directory, name, expected, signal); + } finally { + await unlock(); + } + } + /** Server-only provenance lookup. A linked missing/corrupt receipt is never an ordinary session. */ + async readChild( + childId: string, + ): Promise { + const directory = await assistantDirectory(this.stateRoot, childId); + const value = await readAssistantJson( + join(directory, "continuation-preparation.json"), + ); + if (value === null) return null; + const link = linkSchema.parse(value); + check(link.childStudioId === childId); + const receipt = await this.read(link.sourceBinding, link.operationId); + check(receipt !== null && receipt.childStudioId === childId); + return receipt; + } + /** Lookup index only: an absent marker permits ordinary sessions; every linked child waits for prepared. */ + async canAttach(childId: string): Promise { + try { + const receipt = await this.readChild(childId); + return receipt === null || receipt.phase === "prepared"; + } catch { + return false; + } + } +}