diff --git a/.changeset/resume-saved-assistant-preflight.md b/.changeset/resume-saved-assistant-preflight.md new file mode 100644 index 000000000..c6cce4f14 --- /dev/null +++ b/.changeset/resume-saved-assistant-preflight.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Validate saved native history and original context before resuming the same Assistant session. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index 5c2e65448..89174201d 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -80,3 +80,10 @@ Inspection never creates an association, posts a prompt, or grants execution. It holds a per-session admission slot, obeys End and shutdown, and retires only its own provisional runtime. Existing running runtimes remain running. Startup and reads have a deadline; uncertain provisional cleanup is reported explicitly. + +Resume uses the same bounded native read and original-context preflight inside +the coordinator's retained runtime. It validates the complete saved association +before and after IO. Missing native history never creates a replacement session; +missing retained context blocks execution while public history remains readable. +An empty saved conversation needs no invented context. Public attachments contain +only native identity, lease and lifecycle state, never saved system text. diff --git a/packages/harness/src/core/assistant-native-history.test.ts b/packages/harness/src/core/assistant-native-history.test.ts index c282f4a05..a9a467621 100644 --- a/packages/harness/src/core/assistant-native-history.test.ts +++ b/packages/harness/src/core/assistant-native-history.test.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { AssistantNativeHistory } from "./assistant-native-history.js"; import type { HostedOpenCode } from "./opencode-host.js"; import type { AssistantAssociation } from "./assistant-session-store.js"; +import type { AssistantAttachment, AssistantResumePreparation } from "./assistant-lifecycle.js"; const binding: AssistantAssociation = { version: 1, harnessSessionId: "studio-a", cwd: "/same/folder", conversationId: "ses_saved", @@ -27,16 +28,24 @@ function fixture(history: unknown = [message()]) { const preflight = vi.fn(async () => ({ system: "validated-retained-system" })); const calls: unknown[] = []; let afterRead = () => {}; + const resume = vi.fn(async (id: string, revision: number, _operationId: string, prepare: AssistantResumePreparation, signal?: AbortSignal): Promise => { + const active = signal ?? lifetime.signal; + const saved = await prepare.authorize(active); + await prepare.read(hosted, saved, active); + return { conversationId: saved.conversationId, lease: "f1872aaa-b7c0-44f1-a9bc-3f9613b4a52c", lifecycle: { + version: 1, harnessSessionId: id, revision: revision + 1, lifecycle: "open", execution: "paused", updatedAt: 1, + } }; + }); const service = new AssistantNativeHistory({ authorize, preflight, timeoutMs: 100, - lifecycle: { inspect: async (id: string, revision: number, read: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, signal?: AbortSignal): Promise => { + lifecycle: { resume, inspect: async (id: string, revision: number, read: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, signal?: AbortSignal): Promise => { calls.push([id, revision]); const result = await read(hosted, signal ?? lifetime.signal); afterRead(); return result; } }, }); - return { service, hosted, fetch, authorize, preflight, calls, afterRead: (run: () => void) => { afterRead = run; } }; + return { service, hosted, fetch, authorize, preflight, calls, resume, afterRead: (run: () => void) => { afterRead = run; } }; } afterEach(() => vi.useRealTimers()); @@ -111,6 +120,12 @@ it("requires a saved association and revalidates account/binding after cleanup", await expect(f.service.inspect("studio-a", 0)).rejects.toMatchObject({ failure: { code: "access_denied" } }); }); +it("revalidates the complete saved association even when native identity stays unchanged", async () => { + const f = fixture(); + f.afterRead(() => f.authorize.mockResolvedValue({ ...binding, createdAt: 2 })); + await expect(f.service.inspect("studio-a", 0)).rejects.toMatchObject({ failure: { code: "access_denied" } }); +}); + it.each(["wrong-session", "wrong-message", "malformed", "oversized"])("fails closed for %s native payloads", async (kind) => { const row = message(); if (kind === "wrong-message") row.info.sessionID = "ses_other"; @@ -144,3 +159,43 @@ it("cancels a body stream that never finishes within the overall read deadline", expect(cancel).toHaveBeenCalledOnce(); expect(f.preflight).not.toHaveBeenCalled(); }); + +const operation = "ac243472-d1ef-4926-bf47-2a32bd28e912"; +it("Resume composes exact native read and preflight under the retained coordinator runtime", async () => { + const f = fixture(); + const attached = await f.service.resume("studio-a", 7, operation); + expect(attached).toMatchObject({ conversationId: "ses_saved", lifecycle: { harnessSessionId: "studio-a", revision: 8, execution: "paused" } }); + expect(f.calls).toEqual([]); + expect(f.resume).toHaveBeenCalledExactlyOnceWith("studio-a", 7, operation, expect.any(Object), expect.any(AbortSignal)); + expect(f.fetch.mock.calls.map(([path]) => path)).toEqual(["/session/ses_saved", "/session/ses_saved/message"]); + expect(f.fetch.mock.calls.every(([, init]) => init?.method === "GET")).toBe(true); + expect(f.preflight).toHaveBeenCalledExactlyOnceWith(f.hosted, "ses_saved", "retained-system", expect.any(AbortSignal)); + expect(JSON.stringify(attached)).not.toMatch(/retained-system|savedSystem|sourceMessageId/); +}); + +it.each(["missing", "context", "authority"])("Resume rejects %s before granting an attachment", async (failure) => { + const f = fixture(); + if (failure === "missing") f.fetch.mockResolvedValueOnce(new Response(null, { status: 404 })); + if (failure === "context") f.preflight.mockRejectedValueOnce(new Error("private retained path")); + if (failure === "authority") f.authorize.mockResolvedValueOnce(null); + await expect(f.service.resume("studio-a", 7, operation)).rejects.toMatchObject({ failure: { code: failure === "missing" ? "native_history_missing" : failure === "context" ? "context_unavailable" : "access_denied" } }); +}); + +it("Resume allows an empty saved conversation without creating accepted context", async () => { + const f = fixture([]); + expect(await f.service.resume("studio-a", 0, operation)).toMatchObject({ conversationId: "ses_saved" }); + expect(f.preflight).not.toHaveBeenCalled(); +}); + +it.each(["authorization", "query", "preflight"])("Resume bounds a hung %s provider through the coordinator signal", async (stage) => { + vi.useFakeTimers(); + const f = fixture(); + if (stage === "authorization") f.authorize.mockImplementationOnce(() => new Promise(() => {})); + if (stage === "query") f.fetch.mockImplementationOnce(() => new Promise(() => {})); + if (stage === "preflight") f.preflight.mockImplementationOnce(() => new Promise(() => {})); + const resumed = f.service.resume("studio-a", 7, operation); + const rejected = expect(resumed).rejects.toMatchObject({ failure: { code: "transport_unavailable" } }); + await vi.advanceTimersByTimeAsync(100); + await rejected; + expect(vi.getTimerCount()).toBe(0); +}); diff --git a/packages/harness/src/core/assistant-native-history.ts b/packages/harness/src/core/assistant-native-history.ts index a01662633..84a8da7f6 100644 --- a/packages/harness/src/core/assistant-native-history.ts +++ b/packages/harness/src/core/assistant-native-history.ts @@ -1,15 +1,18 @@ -import { basename, isAbsolute } from "node:path"; +import { basename } from "node:path"; import { clearTimeout, setTimeout } from "node:timers"; -import { isConversationId } from "../shared/assistant-state.js"; import { openCodeTransportFailure, type OpenCodeTransportFailure, } from "../shared/opencode-errors.js"; import { awaitAssistantInspection, + type AssistantAttachment, type AssistantLifecycleCoordinator, } from "./assistant-lifecycle.js"; -import type { AssistantAssociation } from "./assistant-session-store.js"; +import { + assistantResumeBindingDigest, + type AssistantAssociation, +} from "./assistant-session-store.js"; import { OpenCodeAccessError, OpenCodeTransportError, @@ -26,7 +29,8 @@ export interface AssistantNativeInspection { } interface Options { authorize: (id: string) => Promise; - lifecycle: Pick; + lifecycle: Pick & + Partial>; /** The shared delivery.recover preflight; validates retained content without dispatch. */ preflight: ( hosted: HostedOpenCode, @@ -45,13 +49,6 @@ const object = (value: unknown): Record => { throw unavailable(); return value as Record; }; -const same = (a: AssistantAssociation, b: AssistantAssociation | null) => - !!b && - a.harnessSessionId === b.harnessSessionId && - a.conversationId === b.conversationId && - a.cwd === b.cwd && - a.contextAuthorityScope === b.contextAuthorityScope && - a.nativeScope === b.nativeScope; async function json( response: Response, @@ -95,6 +92,38 @@ async function json( export class AssistantNativeHistory { constructor(private readonly options: Options) {} + /** Retain the coordinator's exact validated runtime; never inspect/retire it + * first or return private saved context in the public attachment. */ + async resume( + id: string, + expectedRevision: number, + operationId: string, + ): Promise { + if (!this.options.lifecycle.resume) throw unavailable(); + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(unavailable()), + this.options.timeoutMs ?? 15_000, + ); + try { + return await this.options.lifecycle.resume( + id, + expectedRevision, + operationId, + { + authorize: (signal) => this.authorized(id, signal), + read: (hosted, binding, signal) => + this.read(hosted, binding, signal, { + nativeHistory: "unavailable", + }), + }, + controller.signal, + ); + } finally { + clearTimeout(timer); + } + } + async inspect( id: string, expectedRevision: number, @@ -109,121 +138,16 @@ export class AssistantNativeHistory { nativeHistory: "unavailable", }; try { - const saved = await awaitAssistantInspection( - this.options.authorize(id), - signal, - ); - if ( - !saved || - saved.harnessSessionId !== id || - !isConversationId(saved.conversationId) || - saved.conversationId === id || - !isAbsolute(saved.cwd) || - !/^[a-f0-9]{64}$/.test(saved.contextAuthorityScope) || - !/^[a-f0-9]{64}$/.test(saved.nativeScope) - ) - throw new OpenCodeAccessError("Assistant binding unavailable"); - const binding = { ...saved }; + const binding = await this.authorized(id, signal); const result = await this.options.lifecycle.inspect( id, expectedRevision, - async (hosted, readSignal) => { - if ( - hosted.harnessSessionId !== id || - hosted.cwd !== binding.cwd || - hosted.contextAuthorityScope !== binding.contextAuthorityScope || - basename(hosted.stateRoot) !== binding.nativeScope - ) - throw new OpenCodeAccessError("Assistant binding changed"); - const get = async (path: string, limit: number) => - json( - await awaitAssistantInspection( - hosted.server.fetch(path, { - method: "GET", - signal: readSignal, - }), - readSignal, - ), - readSignal, - limit, - ); - const session = object( - await get(`/session/${binding.conversationId}`, 64 * 1024), - ); - if ( - session.id !== binding.conversationId || - (session.directory !== undefined && - session.directory !== binding.cwd) - ) - throw unavailable(); - const history = await get( - `/session/${binding.conversationId}/message`, - 16 * 1024 * 1024, - ); - let source: ReturnType; - try { - source = this.source(history, binding.conversationId); - } catch (error) { - if ( - error instanceof OpenCodeTransportError && - error.failure.code === "context_unavailable" - ) - observed.nativeHistory = "available"; - throw error; - } - observed.nativeHistory = "available"; - if (source) { - if (typeof source.system !== "string" || !source.system.trim()) - throw contextUnavailable(); - try { - await awaitAssistantInspection( - this.options.preflight( - hosted, - binding.conversationId, - source.system, - readSignal, - ), - readSignal, - ); - } catch (error) { - readSignal.throwIfAborted(); - throw error instanceof OpenCodeTransportError - ? error - : contextUnavailable(); - } - } - readSignal.throwIfAborted(); - if ( - !same( - binding, - await awaitAssistantInspection( - this.options.authorize(id), - readSignal, - ), - ) - ) - throw new OpenCodeAccessError("Assistant binding changed"); - return { - nativeHistory: observed.nativeHistory, - nativeResume: "available" as const, - ...(source - ? { - savedSystem: source.system as string, - sourceMessageId: source.id, - } - : {}), - }; - }, + (hosted, readSignal) => + this.read(hosted, binding, readSignal, observed), signal, ); // The provisional runtime has now retired; refresh authority after cleanup IO. - if ( - !same( - binding, - await awaitAssistantInspection(this.options.authorize(id), signal), - ) - ) - throw new OpenCodeAccessError("Assistant binding changed"); + await this.assertBinding(binding, signal); return result; } catch (error) { const code = @@ -257,6 +181,123 @@ export class AssistantNativeHistory { } } + private async authorized( + id: string, + signal: AbortSignal, + ): Promise { + const binding = await awaitAssistantInspection( + this.options.authorize(id), + signal, + ); + try { + if ( + !binding || + binding.harnessSessionId !== id || + binding.conversationId === id + ) + throw new Error("invalid binding"); + assistantResumeBindingDigest(binding); + return { ...binding }; + } catch { + throw new OpenCodeAccessError("Assistant binding unavailable"); + } + } + + private async assertBinding( + binding: AssistantAssociation, + signal: AbortSignal, + ): Promise { + const current = await this.authorized(binding.harnessSessionId, signal); + if ( + assistantResumeBindingDigest(current) !== + assistantResumeBindingDigest(binding) + ) + throw new OpenCodeAccessError("Assistant binding changed"); + } + + private async read( + hosted: HostedOpenCode, + binding: AssistantAssociation, + readSignal: AbortSignal, + observed: Pick, + ): Promise { + if ( + hosted.harnessSessionId !== binding.harnessSessionId || + hosted.cwd !== binding.cwd || + hosted.contextAuthorityScope !== binding.contextAuthorityScope || + basename(hosted.stateRoot) !== binding.nativeScope + ) + throw new OpenCodeAccessError("Assistant binding changed"); + const get = async (path: string, limit: number) => + json( + await awaitAssistantInspection( + hosted.server.fetch(path, { + method: "GET", + signal: readSignal, + }), + readSignal, + ), + readSignal, + limit, + ); + const session = object( + await get(`/session/${binding.conversationId}`, 64 * 1024), + ); + if ( + session.id !== binding.conversationId || + (session.directory !== undefined && session.directory !== binding.cwd) + ) + throw unavailable(); + const history = await get( + `/session/${binding.conversationId}/message`, + 16 * 1024 * 1024, + ); + let source: ReturnType; + try { + source = this.source(history, binding.conversationId); + } catch (error) { + if ( + error instanceof OpenCodeTransportError && + error.failure.code === "context_unavailable" + ) + observed.nativeHistory = "available"; + throw error; + } + observed.nativeHistory = "available"; + if (source) { + if (typeof source.system !== "string" || !source.system.trim()) + throw contextUnavailable(); + try { + await awaitAssistantInspection( + this.options.preflight( + hosted, + binding.conversationId, + source.system, + readSignal, + ), + readSignal, + ); + } catch (error) { + readSignal.throwIfAborted(); + throw error instanceof OpenCodeTransportError + ? error + : contextUnavailable(); + } + } + readSignal.throwIfAborted(); + await this.assertBinding(binding, readSignal); + return { + nativeHistory: observed.nativeHistory, + nativeResume: "available" as const, + ...(source + ? { + savedSystem: source.system as string, + sourceMessageId: source.id, + } + : {}), + }; + } + private source( value: unknown, conversationId: string,