diff --git a/.changeset/calm-assistant-inspection.md b/.changeset/calm-assistant-inspection.md new file mode 100644 index 000000000..c76ba3c5e --- /dev/null +++ b/.changeset/calm-assistant-inspection.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Verify selected Assistant history without creating conversations or starting work. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index 96a43d171..198da95e2 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -46,3 +46,15 @@ lifecycle and idle checkpoints can flush immediately. Native reads are capped at 16 MiB and have a three-second timeout. Failure preserves the previous record, so a successful GET can return an older `capturedAt`. Disposal and authority loss cancel capture; opening a retained record never resumes execution. +# Selected native availability + +Native inspection is explicit and separate from metadata listing. It validates +the authorized saved Studio/native association, reads only that native session +and its bounded history, and checks the saved execution context through the +shared delivery preflight. Available public history can remain readable when +native history or required retained context is unavailable. + +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. diff --git a/packages/harness/src/core/assistant-lifecycle.test.ts b/packages/harness/src/core/assistant-lifecycle.test.ts index 957433c2c..cafc900c7 100644 --- a/packages/harness/src/core/assistant-lifecycle.test.ts +++ b/packages/harness/src/core/assistant-lifecycle.test.ts @@ -17,6 +17,7 @@ const ensure = vi.fn(), associate = vi.fn(); const retire = vi.fn(), assertCurrent = vi.fn(); +const canAttach = vi.fn(); const gate = () => { let release!: () => void; const promise = new Promise((done) => { @@ -24,8 +25,10 @@ const gate = () => { }); return { promise, release }; }; -const fixture = () => +const fixture = (inspectionTimeoutMs?: number) => new AssistantLifecycleCoordinator({ + inspectionTimeoutMs, + canAttach, store, associations: { ensure: associate }, host: { @@ -47,6 +50,7 @@ beforeEach(async () => { store = new AssistantSessionStore(root); current = null; eligible = true; + canAttach.mockReset().mockResolvedValue(true); observe.mockReset(); ensure.mockReset().mockImplementation(async (id) => { if (!eligible) throw new Error("access denied"); @@ -85,6 +89,7 @@ beforeEach(async () => { coordinator = fixture(); }); afterEach(async () => { + vi.useRealTimers(); abort?.abort(); await rm(root, { recursive: true, force: true }); }); @@ -311,3 +316,155 @@ it("rejects new attaches during shutdown while old association IO ignores cancel held.release(); await rejected; }); + +it("inspection owns its provisional runtime until cleanup and Attach cannot steal it", async () => { + const held = gate(), read = vi.fn(async () => { await held.promise; return "history"; }); + const inspected = coordinator.inspect("studio-a", 0, read); + await vi.waitFor(() => expect(read).toHaveBeenCalledOnce()); + await expect(coordinator.attach("studio-a", 0)).rejects.toThrow(); + await expect(coordinator.inspect("studio-a", 0, read)).rejects.toThrow(); + expect(ensure).toHaveBeenCalledOnce(); + expect(associate).not.toHaveBeenCalled(); + held.release(); + expect(await inspected).toBe("history"); + expect(current).toBeNull(); + expect(await store.lifecycle("studio-a")).toBeNull(); + await coordinator.attach("studio-a", 0); + expect(ensure).toHaveBeenCalledTimes(2); + expect(associate).toHaveBeenCalledOnce(); +}); + +it("refuses inspection while Attach owns asynchronous association preparation", async () => { + const held = gate(), read = vi.fn(); + associate.mockImplementationOnce(async () => { await held.promise; return "ses_history"; }); + const attaching = coordinator.attach("studio-a", 0); + await vi.waitFor(() => expect(associate).toHaveBeenCalledOnce()); + await expect(coordinator.inspect("studio-a", 0, read)).rejects.toThrow(); + expect(read).not.toHaveBeenCalled(); + expect(ensure).toHaveBeenCalledOnce(); + held.release(); + await attaching; +}); + +it("reuses an enabled exact runtime and leaves it live when the selected query times out", async () => { + const attachment = await coordinator.attach("studio-a", 0); + await coordinator.enable(current!); + const existing = current!; + expect(await coordinator.inspect("studio-a", 2, async (hosted) => hosted === existing)).toBe(true); + const cancel = new AbortController(), read = vi.fn(() => new Promise(() => {})); + const inspected = coordinator.inspect("studio-a", 2, read, cancel.signal); + const rejected = expect(inspected).rejects.toThrow("timeout"); + await vi.waitFor(() => expect(read).toHaveBeenCalledOnce()); + cancel.abort(new Error("timeout")); + await rejected; + expect(retire).not.toHaveBeenCalled(); + expect(current).toBe(existing); + await expect(coordinator.use("studio-a", attachment.lease, true)).resolves.toBeDefined(); + expect(ensure).toHaveBeenCalledOnce(); +}); + +it("inspects an ended session without changing its revision or creating an association", async () => { + await store.transition("studio-a", 0, { lifecycle: "ended", execution: "paused" }); + expect(await coordinator.inspect("studio-a", 1, async () => "saved")).toBe("saved"); + expect(await store.lifecycle("studio-a")).toMatchObject({ lifecycle: "ended", revision: 1 }); + expect(associate).not.toHaveBeenCalled(); + expect(observe).not.toHaveBeenCalled(); + expect(current).toBeNull(); +}); + +it.each(["End", "shutdown"])("%s preempts inspection before pending ensure has returned a host", async (mode) => { + const held = gate(), read = vi.fn(); + ensure.mockImplementationOnce(async () => { await held.promise; throw new Error("old startup cancelled"); }); + const inspected = coordinator.inspect("studio-a", 0, read); + const rejected = expect(inspected).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + await vi.waitFor(() => expect(ensure).toHaveBeenCalledOnce()); + if (mode === "End") { + const ending = coordinator.beginEnd("studio-a"); + await ending.persistence; + await coordinator.finishEnd(ending.fence); + } else coordinator.beginShutdown(); + await rejected; + expect(retire).toHaveBeenCalledOnce(); + held.release(); + await Promise.resolve(); + expect(read).not.toHaveBeenCalled(); +}); + +it("End cancels a hung query and its late completion cannot retire a same-ID replacement", async () => { + const held = gate(), read = vi.fn(async () => { await held.promise; return "old"; }); + const inspected = coordinator.inspect("studio-a", 0, read); + const rejected = expect(inspected).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + await vi.waitFor(() => expect(read).toHaveBeenCalledOnce()); + const ending = coordinator.beginEnd("studio-a"); + expect(abort.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.attach("studio-a", opened.revision); + const replacement = current!; + held.release(); + await Promise.resolve(); + expect(current).toBe(replacement); + expect(replacement.signal.aborted).toBe(false); +}); + +it("the overall inspection deadline fences startup even before a host entry exists", async () => { + vi.useFakeTimers(); + vi.spyOn(store, "lifecycle").mockResolvedValue(null); + coordinator = fixture(50); + const held = gate(); + ensure.mockImplementationOnce(async () => { await held.promise; throw new Error("cancelled"); }); + const inspected = coordinator.inspect("studio-a", 0, vi.fn()); + const rejected = expect(inspected).rejects.toMatchObject({ failure: { code: "transport_unavailable" } }); + await vi.advanceTimersByTimeAsync(50); + await rejected; + expect(retire).toHaveBeenCalledExactlyOnceWith("studio-a", 750); + held.release(); +}); + +it("bounds a hung provisional cleanup instead of reporting a successful inspection", async () => { + vi.useFakeTimers(); + vi.spyOn(store, "lifecycle").mockResolvedValue(null); + retire.mockImplementationOnce(() => new Promise(() => {})); + const inspected = coordinator.inspect("studio-a", 0, async () => "saved"); + const rejected = expect(inspected).rejects.toMatchObject({ failure: { code: "cleanup_unconfirmed" } }); + await vi.advanceTimersByTimeAsync(750); + await rejected; + expect(vi.getTimerCount()).toBe(0); +}); + +it("reports failed provisional cleanup and rejects stale revisions before querying", async () => { + retire.mockRejectedValueOnce(new Error("shutdown not confirmed")); + await expect(coordinator.inspect("studio-a", 0, async () => "saved")).rejects.toMatchObject({ failure: { code: "cleanup_unconfirmed" } }); + const read = vi.fn(); + await expect(coordinator.inspect("studio-a", 9, read)).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + expect(read).not.toHaveBeenCalled(); +}); + +it("rechecks durable revision after asynchronous query authorization", async () => { + await coordinator.attach("studio-a", 0); + const read = vi.fn(async () => { + await store.transition("studio-a", 1, { lifecycle: "ended", execution: "paused" }); + return "stale"; + }); + await expect(coordinator.inspect("studio-a", 1, read)).rejects.toMatchObject({ failure: { code: "lifecycle_changed" } }); + expect(retire).not.toHaveBeenCalled(); +}); + +it("pending Continue children cannot attach and End fences a late admission result", async () => { + canAttach.mockResolvedValueOnce(false); + await expect(coordinator.attach("studio-a", 0)).rejects.toThrow(); + expect(ensure).not.toHaveBeenCalled(); + const held = gate(); + canAttach.mockImplementationOnce(async () => { await held.promise; return true; }); + const attaching = coordinator.attach("studio-a", 0); + const rejected = expect(attaching).rejects.toThrow(); + await vi.waitFor(() => expect(canAttach).toHaveBeenCalledTimes(2)); + const ending = coordinator.beginEnd("studio-a"); + held.release(); + await rejected; + await ending.persistence; + expect(ensure).not.toHaveBeenCalled(); + expect(associate).not.toHaveBeenCalled(); +}); diff --git a/packages/harness/src/core/assistant-lifecycle.ts b/packages/harness/src/core/assistant-lifecycle.ts index 7a547cd55..39108cb0a 100644 --- a/packages/harness/src/core/assistant-lifecycle.ts +++ b/packages/harness/src/core/assistant-lifecycle.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { clearTimeout, setTimeout } from "node:timers"; import type { AssistantLifecycle } from "../shared/assistant-session.js"; import { openCodeTransportFailure } from "../shared/opencode-errors.js"; import { @@ -25,6 +26,9 @@ export interface AssistantEndFence { readonly generation: number; } interface Options { + inspectionTimeoutMs?: number; + /** Continue keeps an allocated child closed to ordinary Attach until seed preparation commits. */ + canAttach?: (id: string) => Promise; store: Pick; host: Pick< OpenCodeHost, @@ -50,12 +54,42 @@ const initial = (id: string): AssistantLifecycle => ({ updatedAt: 0, }); +/** Cancel read-only preparation even when an injected provider ignores its signal. */ +export function awaitAssistantInspection( + operation: Promise, + signal: AbortSignal, +): Promise { + return new Promise((resolve, reject) => { + const cleanup = () => signal.removeEventListener("abort", abort); + const abort = () => { + cleanup(); + reject(signal.reason); + }; + signal.addEventListener("abort", abort, { once: true }); + operation.then( + (value) => { + cleanup(); + resolve(value); + }, + (error) => { + cleanup(); + reject(error); + }, + ); + if (signal.aborted) abort(); + }); +} +const inspectionFailure = ( + code: "transport_unavailable" | "cleanup_unconfirmed", +) => new OpenCodeTransportError(openCodeTransportFailure(code)); + /** Server-owned admission. Reading or detaching a pane never obtains a runtime lease. */ export class AssistantLifecycleCoordinator { private readonly leases = new Map(); private readonly states = new Map(); private readonly generations = new Map(); private readonly ending = new Set(); + private readonly inspections = new Map(); private readonly pending = new Map< string, { revision: number; promise: Promise } @@ -124,6 +158,7 @@ export class AssistantLifecycleCoordinator { attach(id: string, expectedRevision: number): Promise { if ( this.closed || + this.inspections.has(id) || !Number.isSafeInteger(expectedRevision) || expectedRevision < 0 ) @@ -150,6 +185,11 @@ export class AssistantLifecycleCoordinator { this.check(fence); if (state.revision !== expectedRevision) throw failure("lifecycle_changed"); if (state.lifecycle !== "open") throw failure("session_ended"); + if (this.options.canAttach) { + const allowed = await this.options.canAttach(id); + this.check(fence); + if (!allowed) throw failure("lifecycle_changed"); + } const previous = this.leases.get(id); if (previous?.hosted === this.options.host.current(id)) { await this.assertRuntime(previous.hosted); @@ -200,6 +240,134 @@ export class AssistantLifecycleCoordinator { return { conversationId, lease, lifecycle: { ...lifecycle } }; } + /** Exclusive temporary ownership, shared with Attach and future Resume. Never + * creates an association or grants execution. Callback results stay private; + * the caller revalidates its saved binding after provisional cleanup. */ + async inspect( + id: string, + expectedRevision: number, + read: (hosted: HostedOpenCode, signal: AbortSignal) => Promise, + callerSignal?: AbortSignal, + ): Promise { + if ( + this.closed || + this.pending.has(id) || + this.inspections.has(id) || + !Number.isSafeInteger(expectedRevision) || + expectedRevision < 0 + ) + throw failure("lifecycle_changed"); + const fence = { id, generation: this.generation(id) }; + this.check(fence); + const controller = new AbortController(); + this.inspections.set(id, controller); + const signal = callerSignal + ? AbortSignal.any([controller.signal, callerSignal]) + : controller.signal; + const timer = setTimeout( + () => controller.abort(inspectionFailure("transport_unavailable")), + this.options.inspectionTimeoutMs ?? 15_000, + ); + const check = () => { + signal.throwIfAborted(); + this.check(fence); + }; + const revision = async () => { + check(); + const state = await awaitAssistantInspection(this.describe(id), signal); + check(); + if (state.revision !== expectedRevision || state.lifecycle === "ending") + throw failure("lifecycle_changed"); + }; + let hosted: HostedOpenCode | undefined; + let provisional = false; + let started = false; + let complete = false; + try { + await revision(); + hosted = this.options.host.current(id) ?? undefined; + provisional = !hosted; + if (!hosted) { + started = true; + const starting = this.options.host.ensure(id); + // A provider that resolves after cancellation still belongs to this + // exact old host. Never retire by ID from this late continuation. + void starting.then( + (late) => { + if (signal.aborted || this.inspections.get(id) !== controller) + void this.options.host.retireExact(late).catch(() => {}); + }, + () => {}, + ); + hosted = await awaitAssistantInspection(starting, signal); + } + check(); + const readingSignal = AbortSignal.any([signal, hosted.signal]); + await awaitAssistantInspection( + this.options.host.assertCurrent(hosted), + readingSignal, + ); + await revision(); + const result = await awaitAssistantInspection( + read(hosted, readingSignal), + readingSignal, + ); + check(); + await awaitAssistantInspection( + this.options.host.assertCurrent(hosted), + readingSignal, + ); + await revision(); + complete = true; + return result; + } finally { + try { + if (provisional && started) { + if ( + this.inspections.get(id) === controller && + this.generation(id) === fence.generation + ) { + // With no returned host yet, this exact slot owns pending ensure. + // retireWithResult fences even startup before an entry exists. + await this.cleanInspection(id, hosted); + } else if (hosted) { + void this.options.host.retireExact(hosted).catch(() => {}); + } + } + if (complete) await revision(); + } finally { + clearTimeout(timer); + if (this.inspections.get(id) === controller) + this.inspections.delete(id); + } + } + } + + private async cleanInspection( + id: string, + hosted?: HostedOpenCode, + ): Promise { + const cleanup = hosted + ? this.options.host + .retireExact(hosted) + .then(() => ({ state: "confirmed" as const })) + : this.options.host.retireWithResult(id, 750); + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(inspectionFailure("cleanup_unconfirmed")), + 750, + ); + try { + const result = await awaitAssistantInspection(cleanup, controller.signal); + if (result.state === "unconfirmed") + throw inspectionFailure("cleanup_unconfirmed"); + } catch { + throw inspectionFailure("cleanup_unconfirmed"); + } finally { + clearTimeout(timer); + } + } + /** Exact token + exact host + durable revision; this path never calls ensure(). */ async use( id: string, @@ -272,6 +440,8 @@ export class AssistantLifecycleCoordinator { this.ending.add(id); this.leases.delete(id); this.pending.delete(id); + this.inspections.get(id)?.abort(failure("lifecycle_changed")); + this.inspections.delete(id); const native = this.options.host.retireWithResult(id); const persistence = beforePersistence ? beforePersistence.then(() => this.persistEnd(fence, "ending")) @@ -313,6 +483,9 @@ export class AssistantLifecycleCoordinator { this.closed = true; this.leases.clear(); this.pending.clear(); + for (const inspection of this.inspections.values()) + inspection.abort(failure("lifecycle_changed")); + this.inspections.clear(); this.options.host.beginShutdown(); this.changed(); } diff --git a/packages/harness/src/core/assistant-native-history.test.ts b/packages/harness/src/core/assistant-native-history.test.ts new file mode 100644 index 000000000..c282f4a05 --- /dev/null +++ b/packages/harness/src/core/assistant-native-history.test.ts @@ -0,0 +1,146 @@ +import { afterEach, expect, it, vi } from "vitest"; +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"; + +const binding: AssistantAssociation = { + version: 1, harnessSessionId: "studio-a", cwd: "/same/folder", conversationId: "ses_saved", + nativeScope: "a".repeat(64), contextAuthorityScope: "b".repeat(64), createdAt: 1, +}; +const message = (system: string | undefined = "retained-system") => ({ + info: { id: "msg_original", sessionID: binding.conversationId, role: "user", system, time: { created: 1 } }, + parts: [{ id: "part_saved", messageID: "msg_original", sessionID: binding.conversationId, type: "text", text: "task" }], +}); +function fixture(history: unknown = [message()]) { + const lifetime = new AbortController(); + const fetch = vi.fn(async (path: string, _init?: RequestInit) => Response.json( + path.endsWith("/message") ? history : { id: binding.conversationId, directory: binding.cwd }, + )); + const hosted: HostedOpenCode = { + harnessSessionId: binding.harnessSessionId, cwd: binding.cwd, contextAuthorityScope: binding.contextAuthorityScope, + stateRoot: join("/state/opencode", binding.nativeScope), model: { providerID: "sapiom", modelID: "test" }, + signal: lifetime.signal, isCurrent: () => !lifetime.signal.aborted, + server: { pid: 1, exited: new Promise(() => {}), close: vi.fn(), fetch, fetchJson: vi.fn() }, + }; + const authorize = vi.fn<() => Promise>(async () => ({ ...binding })); + const preflight = vi.fn(async () => ({ system: "validated-retained-system" })); + const calls: unknown[] = []; + let afterRead = () => {}; + const service = new AssistantNativeHistory({ + authorize, preflight, timeoutMs: 100, + lifecycle: { 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; } }; +} +afterEach(() => vi.useRealTimers()); + +it("queries only the authorized saved native ID and preflights its original system without dispatch", async () => { + const f = fixture(); + expect(await f.service.inspect("studio-a", 7)).toMatchObject({ + nativeHistory: "available", nativeResume: "available", savedSystem: "retained-system", sourceMessageId: "msg_original", + }); + expect(f.calls).toEqual([["studio-a", 7]]); + 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)); +}); + +it.each([404, 500])("distinguishes native HTTP %s from successful execution readiness", async (status) => { + const f = fixture(); + f.fetch.mockResolvedValueOnce(new Response(null, { status })); + expect(await f.service.inspect("studio-a", 0)).toMatchObject({ + nativeHistory: status === 404 ? "missing" : "unavailable", nativeResume: status === 404 ? "missing" : "unavailable", + resumeFailure: { code: status === 404 ? "native_history_missing" : "transport_unavailable" }, + }); + expect(f.preflight).not.toHaveBeenCalled(); +}); + +it("allows an empty native conversation without inventing accepted context", async () => { + const f = fixture([]); + expect(await f.service.inspect("studio-a", 0)).toEqual({ nativeHistory: "available", nativeResume: "available" }); + expect(f.preflight).not.toHaveBeenCalled(); +}); + +it("reports known missing retained context separately from missing native history", async () => { + const f = fixture(); + f.preflight.mockRejectedValue(new Error("private source path")); + const result = await f.service.inspect("studio-a", 0); + expect(result).toMatchObject({ nativeHistory: "available", nativeResume: "unavailable", resumeFailure: { code: "context_unavailable" } }); + expect(JSON.stringify(result)).not.toContain("private"); + expect(result.savedSystem).toBeUndefined(); +}); + +it.each(["missing-system", "only-assistant"])("rejects nonempty unsupported history: %s", async (kind) => { + const row = message(); + if (kind === "missing-system") delete (row.info as { system?: string }).system; + else row.info.role = "assistant"; + const f = fixture([row]); + expect(await f.service.inspect("studio-a", 0)).toMatchObject({ nativeHistory: "available", nativeResume: "unavailable", resumeFailure: { code: "context_unavailable" } }); + expect(f.preflight).not.toHaveBeenCalled(); +}); + +it("selects the original user system behind later synthetic compaction messages", async () => { + const compact = message(); + compact.info.id = "msg_compaction"; + compact.info.time.created = 2; + compact.parts[0]!.type = "compaction"; + compact.parts[0]!.messageID = compact.info.id; + const f = fixture([compact, message()]); + expect(await f.service.inspect("studio-a", 0)).toMatchObject({ sourceMessageId: "msg_original", nativeResume: "available" }); +}); + +it.each(["harnessSessionId", "cwd", "contextAuthorityScope", "nativeScope"] as const)("denies a mismatched authorized %s before querying", async (field) => { + const f = fixture(); + f.authorize.mockResolvedValue({ ...binding, [field]: field === "cwd" ? "/different" : "f".repeat(64) }); + await expect(f.service.inspect("studio-a", 0)).rejects.toMatchObject({ failure: { code: "access_denied" } }); + expect(f.fetch).not.toHaveBeenCalled(); +}); + +it("requires a saved association and revalidates account/binding after cleanup", async () => { + const f = fixture(); + f.authorize.mockResolvedValueOnce(null); + await expect(f.service.inspect("studio-a", 0)).rejects.toThrow(); + expect(f.calls).toHaveLength(0); + f.afterRead(() => f.authorize.mockResolvedValue({ ...binding, conversationId: "ses_other" })); + 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"; + const f = fixture([row]); + if (kind === "wrong-session") f.fetch.mockResolvedValueOnce(Response.json({ id: "ses_other" })); + if (kind === "malformed") f.fetch.mockResolvedValueOnce(new Response("{broken")); + if (kind === "oversized") f.fetch.mockResolvedValueOnce(new Response(new Uint8Array(65537))); + expect(await f.service.inspect("studio-a", 0)).toMatchObject({ nativeResume: "unavailable", resumeFailure: { code: "transport_unavailable" } }); + expect(f.preflight).not.toHaveBeenCalled(); +}); + +it.each(["authorization", "query", "preflight"])("bounds a hung %s provider", 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 result = f.service.inspect("studio-a", 0); + await vi.advanceTimersByTimeAsync(100); + expect(await result).toMatchObject({ nativeResume: "unavailable" }); + expect(vi.getTimerCount()).toBe(0); +}); + +it("cancels a body stream that never finishes within the overall read deadline", async () => { + vi.useFakeTimers(); + const f = fixture(), cancel = vi.fn(); + f.fetch.mockResolvedValueOnce(new Response(new ReadableStream({ pull: () => new Promise(() => {}), cancel }))); + const result = f.service.inspect("studio-a", 0); + await vi.advanceTimersByTimeAsync(100); + expect(await result).toMatchObject({ nativeResume: "unavailable", resumeFailure: { code: "transport_unavailable" } }); + expect(cancel).toHaveBeenCalledOnce(); + expect(f.preflight).not.toHaveBeenCalled(); +}); diff --git a/packages/harness/src/core/assistant-native-history.ts b/packages/harness/src/core/assistant-native-history.ts new file mode 100644 index 000000000..a01662633 --- /dev/null +++ b/packages/harness/src/core/assistant-native-history.ts @@ -0,0 +1,309 @@ +import { basename, isAbsolute } 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 AssistantLifecycleCoordinator, +} from "./assistant-lifecycle.js"; +import type { AssistantAssociation } from "./assistant-session-store.js"; +import { + OpenCodeAccessError, + OpenCodeTransportError, + type HostedOpenCode, +} from "./opencode-host.js"; + +/** Server-only result: never serialize savedSystem into a public history entry. */ +export interface AssistantNativeInspection { + nativeHistory: "available" | "missing" | "unavailable"; + nativeResume: "available" | "missing" | "unavailable"; + resumeFailure?: OpenCodeTransportFailure; + savedSystem?: string; + sourceMessageId?: string; +} +interface Options { + authorize: (id: string) => Promise; + lifecycle: Pick; + /** The shared delivery.recover preflight; validates retained content without dispatch. */ + preflight: ( + hosted: HostedOpenCode, + conversationId: string, + savedSystem: string, + signal: AbortSignal, + ) => Promise; + timeoutMs?: number; +} +const unavailable = () => + new OpenCodeTransportError(openCodeTransportFailure("transport_unavailable")); +const contextUnavailable = () => + new OpenCodeTransportError(openCodeTransportFailure("context_unavailable")); +const object = (value: unknown): Record => { + if (!value || typeof value !== "object" || Array.isArray(value)) + 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, + signal: AbortSignal, + limit: number, +): Promise { + if (!response.ok || !response.body) { + void response.body?.cancel().catch(() => {}); + throw new OpenCodeTransportError( + openCodeTransportFailure( + response.status === 404 + ? "native_history_missing" + : "transport_unavailable", + ), + ); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + signal.throwIfAborted(); + const { done, value } = await awaitAssistantInspection( + reader.read(), + signal, + ); + if (done) break; + size += value.byteLength; + if (size > limit) throw unavailable(); + chunks.push(value); + } + return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown; + } finally { + void reader.cancel().catch(() => {}); + reader.releaseLock(); + } +} + +/** Keep native availability separate from execution readiness. No association + * creation, source substitution, prompt, or model call is permitted here. */ +export class AssistantNativeHistory { + constructor(private readonly options: Options) {} + + async inspect( + id: string, + expectedRevision: number, + ): Promise { + const controller = new AbortController(); + const signal = controller.signal; + const timer = setTimeout( + () => controller.abort(unavailable()), + this.options.timeoutMs ?? 15_000, + ); + const observed: Pick = { + 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 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, + } + : {}), + }; + }, + 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"); + return result; + } catch (error) { + const code = + error instanceof OpenCodeTransportError + ? error.failure.code + : "transport_unavailable"; + if ( + ["access_denied", "access_expired", "authentication_required"].includes( + code, + ) + ) + throw error; + const missing = + code === "native_history_missing" && + observed.nativeHistory !== "available"; + return { + nativeHistory: missing ? "missing" : observed.nativeHistory, + nativeResume: missing ? "missing" : "unavailable", + resumeFailure: + code === "runtime_start_failed" + ? openCodeTransportFailure( + code, + error instanceof OpenCodeTransportError + ? error.failure.reason + : undefined, + ) + : openCodeTransportFailure(code), + }; + } finally { + clearTimeout(timer); + } + } + + private source( + value: unknown, + conversationId: string, + ): { id: string; system?: unknown } | null { + if (!Array.isArray(value) || value.length > 10_000) throw unavailable(); + if (!value.length) return null; + const messages = value + .map((row) => { + const message = object(row), + info = object(message.info), + time = object(info.time); + if ( + info.sessionID !== conversationId || + typeof info.id !== "string" || + !["user", "assistant"].includes(info.role as string) || + typeof time.created !== "number" || + !Number.isFinite(time.created) || + !Array.isArray(message.parts) + ) + throw unavailable(); + const parts = message.parts.map(object); + if ( + parts.some( + (part) => + part.sessionID !== conversationId || + part.messageID !== info.id || + typeof part.type !== "string", + ) + ) + throw unavailable(); + return { info, parts, created: time.created }; + }) + .sort((a, b) => a.created - b.created); + const source = messages + .reverse() + .find( + ({ info, parts }) => + info.role === "user" && + !parts.some( + (part) => + part.type === "compaction" || + (part.synthetic && + part.metadata && + object(part.metadata).compaction_continue === true), + ), + ); + if (!source) throw contextUnavailable(); + return { id: source.info.id as string, system: source.info.system }; + } +} diff --git a/packages/harness/src/core/opencode-host.test.ts b/packages/harness/src/core/opencode-host.test.ts index 52afda0ea..bb946cee7 100644 --- a/packages/harness/src/core/opencode-host.test.ts +++ b/packages/harness/src/core/opencode-host.test.ts @@ -613,6 +613,20 @@ describe("Studio-owned OpenCode lifecycle", () => { expect(close).toHaveBeenCalledOnce(); }); + it("a stale workspace authorization rejection cannot retire a replacement after End", async () => { + let reject!: (reason: unknown) => void; + authorize.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; })); + const stale = host.ensure("studio-a"); + const rejected = expect(stale).rejects.toThrow("old authorization failed"); + await host.retireWithResult("studio-a"); + const replacement = await host.ensure("studio-a"); + reject(new Error("old authorization failed")); + await rejected; + expect(host.current("studio-a")).toBe(replacement); + expect(replacement.signal.aborted).toBe(false); + expect(close).not.toHaveBeenCalled(); + }); + it("reports bounded pending cleanup honestly and later joins positive completion", async () => { await host.ensure("studio-a"); let release!: () => void; @@ -686,10 +700,9 @@ describe("Studio-owned OpenCode lifecycle", () => { const held = new Promise((resolve) => { release = resolve; }); - let pending!: Promise; - const checkpoint = vi.fn(() => pending); + const checkpoint = vi.fn((): Promise => pending); const { hosted, exit } = await exitFixture(checkpoint); - pending = held.then(async () => { + const pending: Promise = held.then(async () => { hosted.signal.throwIfAborted(); await writeFile(join(root, "final-checkpoint.json"), "retained"); }); diff --git a/packages/harness/src/core/opencode-host.ts b/packages/harness/src/core/opencode-host.ts index d3c59682d..0058634ae 100644 --- a/packages/harness/src/core/opencode-host.ts +++ b/packages/harness/src/core/opencode-host.ts @@ -326,12 +326,13 @@ export class OpenCodeHost { if (this.closed || !grant) throw this.accessError("Assistant access is unavailable"); const workspace = await this.workspace(id).catch(async (error) => { - await this.retire( - id, - error instanceof OpenCodeTransportError - ? error.failure - : openCodeTransportFailure("access_denied"), - ); + if ((this.generations.get(id) ?? 0) === generation) + await this.retire( + id, + error instanceof OpenCodeTransportError + ? error.failure + : openCodeTransportFailure("access_denied"), + ); throw error; }); assertAdmission(); diff --git a/packages/harness/src/shared/assistant-history.ts b/packages/harness/src/shared/assistant-history.ts index c20e9d9e1..8d196ac43 100644 --- a/packages/harness/src/shared/assistant-history.ts +++ b/packages/harness/src/shared/assistant-history.ts @@ -2,6 +2,7 @@ import type { AssistantLifecycle, AssistantSessionView, } from "./assistant-session.js"; +import type { OpenCodeTransportFailure } from "./opencode-errors.js"; /** Additive history entry: a Studio identity does not require a Terminal vendor ID. */ export interface AssistantHistoryEntry { @@ -14,5 +15,6 @@ export interface AssistantHistoryEntry { lifecycle: AssistantLifecycle; history: AssistantSessionView["history"]; nativeResume: AssistantSessionView["nativeResume"]; + resumeFailure?: OpenCodeTransportFailure; recordRevision: number | null; }