diff --git a/packages/harness/src/core/session-manager-dormant.test.ts b/packages/harness/src/core/session-manager-dormant.test.ts new file mode 100644 index 000000000..43836ea58 --- /dev/null +++ b/packages/harness/src/core/session-manager-dormant.test.ts @@ -0,0 +1,405 @@ +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { HarnessAdapter, HarnessSession } from "../shared/types.js"; +import { IngestCredentialRegistry } from "./ingest-credentials.js"; +import { + SessionManager, + ProjectSessionScopeUnavailableError, + type DormantSessionAllocationOptions, + type PtySpawnFn, + type SessionManagerOptions, +} from "./session-manager.js"; +import { StudioProjectCatalog } from "./studio-project-catalog.js"; + +function gate() { + let enter!: () => void; + let release!: () => void; + const entered = new Promise((done) => { + enter = done; + }); + const held = new Promise((done) => { + release = done; + }); + return { + entered, + release, + wait: async () => { + enter(); + await held; + }, + }; +} + +describe("dormant Studio allocation", () => { + let root: string; + let sessionsPath: string; + let source: HarnessSession; + let allocation: DormantSessionAllocationOptions; + let catalog: StudioProjectCatalog; + let principal: string; + let managers: SessionManager[]; + let exits: (() => void)[]; + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "dormant-studio-")); + sessionsPath = join(root, "sessions.json"); + const cwd = join(root, "project"); + await mkdir(cwd); + catalog = new StudioProjectCatalog(join(root, "projects.json")); + const reconciled = await catalog.reconcile([ + { workspaceKey: "workspace-1", cwd }, + ]); + const projectId = reconciled.projects[0]!.projectId; + principal = "user-1"; + source = { + id: "source-session", + cwd, + harness: "claude-code", + title: "Parent title", + agentSessionId: "parent-vendor", + status: "exited", + ready: false, + createdAt: "2020-01-01T00:00:00.000Z", + lastActiveAt: "2020-01-01T00:00:00.000Z", + theme: "dark", + boundWorkflowPath: join(cwd, "parent-workflow.ts"), + rehydratedFrom: "grandparent", + agentMapIdentity: { + projectId, + userId: principal, + sessionId: "source-session", + }, + projectBootstrap: { + projectId, + userId: principal, + targetSessionId: "source-session", + bootstrap: { status: "delivered", messageId: "parent-bootstrap" }, + queuedInputIds: ["parent-input"], + }, + }; + allocation = { + childSessionId: "reserved-child", + harness: "claude-code", + expectedSource: { cwd, projectId, userId: principal }, + }; + await writeFile(sessionsPath, JSON.stringify([source])); + managers = []; + exits = []; + }); + + afterEach(async () => { + exits.forEach((exit) => exit()); + await Promise.all(managers.map((manager) => manager.flush())); + await rm(root, { recursive: true, force: true }); + }); + + async function make(options: Partial = {}) { + const spec = { + command: "fake-terminal", + args: [], + env: {}, + cwd: source.cwd, + }; + const adapter: HarnessAdapter = { + id: "claude-code", + eventSource: "hooks", + doctor: vi.fn(async () => []), + launch: vi.fn(() => spec), + resume: vi.fn(() => spec), + canResume: vi.fn(async () => true), + listPastSessions: vi.fn(async () => []), + }; + const spawnPty = vi.fn(() => ({ + pid: 999_998, + kill: vi.fn(), + write: vi.fn(), + resize: vi.fn(), + onData: () => ({ dispose: () => {} }), + onExit: (listener: (event: { exitCode: number }) => void) => { + exits.push(() => listener({ exitCode: 0 })); + return { dispose: () => {} }; + }, + })) as unknown as PtySpawnFn; + const hooks = { + buildLaunchOpts: vi.fn(async () => ({})), + prepareProjectSession: vi.fn(async () => ({})), + onProjectBootstrapSession: vi.fn(), + onRuntimeEpochTransition: vi.fn(), + writeWorkspaceContext: vi.fn(async () => {}), + prepareWorkspaceContext: vi.fn(async () => {}), + ensureCanvasTemplate: vi.fn(async () => {}), + }; + const resolveAgentMapIdentity: NonNullable< + SessionManagerOptions["resolveAgentMapIdentity"] + > = async (sessionId, cwd, persisted) => { + const project = await catalog.resolveIdentityForPath(cwd); + if ( + !project || + (persisted && + (persisted.userId !== principal || + persisted.projectId !== project.projectId || + persisted.sessionId !== sessionId)) + ) + throw new ProjectSessionScopeUnavailableError(sessionId); + return { userId: principal, sessionId, projectId: project.projectId }; + }; + const manager = new SessionManager({ + adapters: { "claude-code": adapter }, + sessionsPath, + ingestUrl: "http://127.0.0.1:4100", + ingestCredentials: new IngestCredentialRegistry(() => "boot"), + spawnPty, + isPidAlive: () => false, + resolveAgentMapIdentity, + ...hooks, + ...options, + }); + managers.push(manager); + await manager.init(); + return { manager, adapter, spawnPty, hooks, resolveAgentMapIdentity }; + } + + it("persists one distinct inert child without invoking Terminal preparation or inheriting parent execution state", async () => { + const { manager, spawnPty, adapter, hooks } = await make(); + const [child, duplicate] = await Promise.all([ + manager.allocateDormant(source.id, allocation), + manager.allocateDormant(source.id, allocation), + ]); + expect(duplicate).toBe(child); + expect(child).toEqual({ + id: allocation.childSessionId, + harness: "claude-code", + cwd: source.cwd, + title: "project", + status: "exited", + terminalState: "not-started", + ready: false, + agentSessionId: null, + exitCode: null, + boundWorkflowPath: null, + rehydratedFrom: null, + createdAt: expect.any(String), + lastActiveAt: expect.any(String), + agentMapIdentity: { + ...source.agentMapIdentity, + sessionId: allocation.childSessionId, + }, + }); + expect(child.createdAt).not.toBe(source.createdAt); + expect(manager.get(source.id)).toEqual(source); + expect(JSON.parse(await readFile(sessionsPath, "utf8"))).toEqual([ + source, + child, + ]); + expect(await manager.canResumeSession(child.id)).toBe(false); + expect(manager.getRuntimeEpoch(child.id)).toBeNull(); + expect(spawnPty).not.toHaveBeenCalled(); + Object.values(hooks).forEach((hook) => expect(hook).not.toHaveBeenCalled()); + Object.values(adapter) + .filter((value) => typeof value === "function") + .forEach((hook) => expect(hook).not.toHaveBeenCalled()); + }); + + it("keeps exact retries stable after reload and rejects a different same-folder parent", async () => { + const other = { + ...source, + id: "other-source", + agentSessionId: "other-vendor", + projectBootstrap: undefined, + agentMapIdentity: { + ...source.agentMapIdentity!, + sessionId: "other-source", + }, + }; + await writeFile(sessionsPath, JSON.stringify([source, other])); + const { manager } = await make(); + const child = await manager.allocateDormant(source.id, allocation); + const { manager: restarted, spawnPty } = await make(); + expect(await restarted.allocateDormant(source.id, allocation)).toEqual( + child, + ); + await expect( + restarted.allocateDormant(other.id, allocation), + ).rejects.toMatchObject({ code: "DORMANT_SESSION_ALLOCATION_MISMATCH" }); + expect(restarted.list()).toHaveLength(3); + expect(spawnPty).not.toHaveBeenCalled(); + }); + + it("does not adopt a matching public dormant row without private allocation proof", async () => { + const foreign = { + ...source, + id: allocation.childSessionId, + agentSessionId: null, + terminalState: "not-started", + projectBootstrap: undefined, + agentMapIdentity: { + ...source.agentMapIdentity!, + sessionId: allocation.childSessionId, + }, + }; + await writeFile(sessionsPath, JSON.stringify([source, foreign])); + const { manager } = await make(); + await expect( + manager.allocateDormant(source.id, allocation), + ).rejects.toMatchObject({ code: "DORMANT_SESSION_ALLOCATION_MISMATCH" }); + expect(manager.get(foreign.id)).toEqual(foreign); + }); + + it.each([ + "principal", + "root", + "snapshot", + "missing-identity", + "missing-resolver", + ])("rejects unavailable or changed %s without allocating", async (reason) => { + const { manager, spawnPty } = await make( + reason === "missing-resolver" + ? { resolveAgentMapIdentity: undefined } + : {}, + ); + if (reason === "principal") principal = "another-user"; + if (reason === "root") await catalog.reconcile([]); + if (reason === "snapshot") + allocation.expectedSource = { + ...allocation.expectedSource, + projectId: "foreign-project", + }; + if (reason === "missing-identity") + delete manager.get(source.id)!.agentMapIdentity; + await expect( + manager.allocateDormant(source.id, allocation), + ).rejects.toBeInstanceOf(ProjectSessionScopeUnavailableError); + expect(manager.get(allocation.childSessionId)).toBeUndefined(); + expect(spawnPty).not.toHaveBeenCalled(); + }); + + it.each(["child-end", "source-end", "shutdown"])( + "does not publish after %s during authority validation", + async (reason) => { + const held = gate(); + const { manager } = await make({ + resolveAgentMapIdentity: async (sessionId, _cwd, persisted) => { + await held.wait(); + return { ...persisted!, sessionId }; + }, + }); + const allocating = manager.allocateDormant(source.id, allocation); + await held.entered; + if (reason === "shutdown") manager.beginShutdown(); + else + await manager.close( + reason === "child-end" ? allocation.childSessionId : source.id, + ); + held.release(); + await expect(allocating).rejects.toMatchObject({ + code: + reason === "shutdown" + ? "SESSION_MANAGER_CLOSING" + : "SESSION_PREPARATION_CANCELLED", + }); + expect(manager.get(allocation.childSessionId)).toBeUndefined(); + }, + ); + + it("repairs a failed candidate write and lets only the same reserved operation retry after restart", async () => { + let fail = true; + const { manager } = await make({ + generateId: () => allocation.childSessionId, + writeSessionRegistry: async (file, text) => { + await writeFile(file, text); + if (fail && text.includes(allocation.childSessionId)) { + fail = false; + throw new Error("lost registry acknowledgement"); + } + }, + }); + await expect( + manager.allocateDormant(source.id, allocation), + ).rejects.toThrow("lost registry acknowledgement"); + expect(manager.get(allocation.childSessionId)).toBeUndefined(); + expect(JSON.parse(await readFile(sessionsPath, "utf8"))).toEqual([source]); + await expect( + manager.create({ cwd: source.cwd, harness: "claude-code" }), + ).rejects.toMatchObject({ code: "DORMANT_SESSION_ALLOCATION_MISMATCH" }); + const { manager: restarted } = await make(); + expect((await restarted.allocateDormant(source.id, allocation)).id).toBe( + allocation.childSessionId, + ); + }); + + it("revalidates after disk publication and releases its fence before repairing queued writes", async () => { + const held = gate(); + const { manager } = await make({ + writeSessionRegistry: async (file, text) => { + await writeFile(file, text); + if (text.includes(allocation.childSessionId)) await held.wait(); + }, + }); + const allocating = manager.allocateDormant(source.id, allocation); + await held.entered; + expect(manager.get(allocation.childSessionId)).toBeUndefined(); + manager.setTitle(source.id, "Updated while waiting"); + principal = "another-user"; + held.release(); + await expect(allocating).rejects.toBeInstanceOf( + ProjectSessionScopeUnavailableError, + ); + await manager.flush(); + const persisted = JSON.parse( + await readFile(sessionsPath, "utf8"), + ) as HarnessSession[]; + expect(persisted).toHaveLength(1); + expect(persisted[0]!.title).toBe("Updated while waiting"); + }); + + it("fails closed on malformed private allocation proof", async () => { + await writeFile( + `${sessionsPath}.dormant-allocations.json`, + JSON.stringify({ version: 1, allocations: { child: "bad-digest" } }), + ); + await expect(make()).rejects.toMatchObject({ + code: "DORMANT_SESSION_ALLOCATION_MISMATCH", + }); + }); + + it("does not publish a child when private reservation persistence fails", async () => { + const { manager } = await make(); + const proof = `${sessionsPath}.dormant-allocations.json`; + await mkdir(proof); + await expect( + manager.allocateDormant(source.id, allocation), + ).rejects.toThrow(); + expect(manager.get(allocation.childSessionId)).toBeUndefined(); + expect(JSON.parse(await readFile(sessionsPath, "utf8"))).toEqual([source]); + await rm(proof, { recursive: true }); + expect((await manager.allocateDormant(source.id, allocation)).id).toBe( + allocation.childSessionId, + ); + }); + + it.each(["source-session", "../foreign", ""])( + "rejects invalid or non-distinct reserved ID %s", + async (childSessionId) => { + const { manager } = await make(); + await expect( + manager.allocateDormant(source.id, { ...allocation, childSessionId }), + ).rejects.toMatchObject({ code: "DORMANT_SESSION_ALLOCATION_MISMATCH" }); + expect(manager.list()).toEqual([source]); + }, + ); + + it("preserves normal Terminal creation", async () => { + const { manager, spawnPty, hooks } = await make(); + const created = await manager.create({ + cwd: source.cwd, + harness: "claude-code", + }); + expect(created.status).toBe("running"); + expect(created.terminalState).toBeUndefined(); + expect(spawnPty).toHaveBeenCalledOnce(); + expect(hooks.buildLaunchOpts).toHaveBeenCalledOnce(); + expect(hooks.prepareProjectSession).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/harness/src/core/session-manager.ts b/packages/harness/src/core/session-manager.ts index 76eca3704..70956830e 100644 --- a/packages/harness/src/core/session-manager.ts +++ b/packages/harness/src/core/session-manager.ts @@ -6,6 +6,11 @@ */ import type { FocusedSessionContextProjection } from "./focused-session-context.js"; +import { + readAssistantJson, + studioIdPattern, + writeAssistantJson, +} from "./assistant-session-files.js"; import { createHash, randomUUID } from "node:crypto"; import { EventEmitter } from "node:events"; import { @@ -17,7 +22,7 @@ import { rm, writeFile, } from "node:fs/promises"; -import { basename, dirname, join, resolve, sep } from "node:path"; +import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { createRequire } from "node:module"; import { @@ -583,6 +588,23 @@ export interface TrustedSessionCreateOptions { requireProjectBootstrapClaim?: boolean; } +/** Server/receipt-authored allocation identity, never accepted from generic create. */ +export interface DormantSessionAllocationOptions { + childSessionId: string; + harness: HarnessKind; + expectedSource: Pick & { + cwd: string; + }; +} + +export class DormantSessionAllocationMismatchError extends Error { + readonly code = "DORMANT_SESSION_ALLOCATION_MISMATCH"; + constructor() { + super("the reserved Studio session does not match this allocation"); + this.name = "DormantSessionAllocationMismatchError"; + } +} + export interface TrustedSessionResumeOptions { /** Recomputed focused context for the resumed process. */ promptAppendix?: string; @@ -997,6 +1019,8 @@ export class SessionManager { private readonly retiringPtys = new Map(); /** Matching positive evidence remains available after its handle is released. */ private readonly confirmedCleanupEpochs = new Map(); + private readonly dormantAllocations = new Map(); + private dormantAllocationsLoaded = false; private assertAdmission(id: string, generation: number): void { if (this.closing) throw new SessionManagerClosingError(); @@ -1271,6 +1295,7 @@ export class SessionManager { } dirty = (await this.loadAgentSessionOwners(persisted)) || dirty; await this.loadSubsessionBindings(); + await this.loadDormantAllocations(); if (dirty) await this.persist(); } @@ -1435,6 +1460,198 @@ export class SessionManager { return this.createWithId(this.generateId(), req, trusted); } + /** Allocate only an inert Studio row. Continue owns frozen content and native seeding. */ + async allocateDormant( + sourceId: string, + input: DormantSessionAllocationOptions, + ): Promise { + const { childSessionId: id, harness } = input; + const expected = { ...input.expectedSource }; + if ( + typeof sourceId !== "string" || + !studioIdPattern.test(sourceId) || + typeof id !== "string" || + !studioIdPattern.test(id) || + id === sourceId || + typeof expected.cwd !== "string" || + !isAbsolute(expected.cwd) || + expected.cwd.length > 4096 || + ![expected.projectId, expected.userId].every( + (value) => + typeof value === "string" && value.length > 0 && value.length <= 256, + ) + ) + throw new DormantSessionAllocationMismatchError(); + this.getAdapter(harness); + const sourceGeneration = this.closeGenerations.get(sourceId) ?? 0; + const childGeneration = this.closeGenerations.get(id) ?? 0; + this.assertAdmission(sourceId, sourceGeneration); + this.assertAdmission(id, childGeneration); + const source = this.sessions.get(sourceId); + if (!source) throw new UnknownSessionError(sourceId); + const sourceIdentity: ProjectAgentSession = { + sessionId: sourceId, + projectId: expected.projectId, + userId: expected.userId, + }; + const childIdentity = { ...sourceIdentity, sessionId: id }; + const assertSource = (): void => { + this.assertAdmission(sourceId, sourceGeneration); + this.assertAdmission(id, childGeneration); + if ( + this.sessions.get(sourceId) !== source || + source.cwd !== expected.cwd || + !source.agentMapIdentity || + !sameProjectAgent(source.agentMapIdentity, sourceIdentity) || + this.rejectedProjectSessionMetadata.has(sourceId) || + !this.resolveAgentMapIdentity + ) + throw new ProjectSessionScopeUnavailableError(sourceId); + }; + const authorize = async (): Promise => { + assertSource(); + // Supplying the existing principal keeps the production resolver read-only; + // resolving an unbound cwd instead could claim a project/bootstrap lifecycle. + await this.revalidateAgentMapIdentity( + sourceId, + expected.cwd, + sourceIdentity, + ); + await this.revalidateAgentMapIdentity(id, expected.cwd, childIdentity); + assertSource(); + }; + const digest = createHash("sha256") + .update( + JSON.stringify([ + sourceId, + id, + expected.cwd, + expected.projectId, + expected.userId, + harness, + ]), + ) + .digest("hex"); + return this.serializeAgentSessionIdentity(async () => { + await authorize(); + await this.loadDormantAllocations(); + const reserved = this.dormantAllocations.get(id); + if ( + (reserved !== undefined && reserved !== digest) || + this.subsessionBindings.has(id) + ) + throw new DormantSessionAllocationMismatchError(); + const existing = this.sessions.get(id); + if (existing) { + if ( + reserved !== digest || + existing.cwd !== expected.cwd || + existing.harness !== harness || + !existing.agentMapIdentity || + !sameProjectAgent(existing.agentMapIdentity, childIdentity) || + this.rejectedProjectSessionMetadata.has(id) + ) + throw new DormantSessionAllocationMismatchError(); + await authorize(); + return existing; + } + return this.prepareSession( + id, + async () => { + if (reserved === undefined && this.dormantAllocations.size >= 10_000) + throw new DormantSessionAllocationMismatchError(); + this.dormantAllocations.set(id, digest); + // Keep a failed reservation: only the exact operation may retry this ID. + await this.persistDormantAllocations(); + await authorize(); + const createdAt = this.now(); + const candidate: HarnessSession = { + id, + harness, + cwd: expected.cwd, + agentSessionId: null, + title: basename(expected.cwd) || expected.cwd, + status: "exited", + terminalState: "not-started", + ready: false, + createdAt, + lastActiveAt: createdAt, + exitCode: null, + boundWorkflowPath: null, + rehydratedFrom: null, + agentMapIdentity: childIdentity, + }; + let releaseFence!: () => void; + const fence = new Promise((done) => { + releaseFence = done; + }); + this.sessionRegistryIdentityFence = fence; + let failure: { error: unknown } | undefined; + try { + await this.persistIdentityCandidate(candidate); + await authorize(); + this.sessions.set(id, candidate); + } catch (error) { + failure = { error }; + } finally { + this.sessionRegistryIdentityFence = null; + releaseFence(); + } + if (failure) { + // A rejected write can have reached rename. Release our fence before + // repairing, since an ordinary queued write may already await it. + await this.persist().catch(() => {}); + throw failure.error; + } + return candidate; + }, + childGeneration, + ); + }); + } + + private async loadDormantAllocations(): Promise { + if (this.dormantAllocationsLoaded) return; + const value = await readAssistantJson( + `${this.sessionsPath}.dormant-allocations.json`, + 4 * 1024 * 1024, + ); + if (value !== null) { + if ( + !isRecord(value) || + Object.keys(value).sort().join(",") !== "allocations,version" || + value.version !== 1 || + !isRecord(value.allocations) + ) + throw new DormantSessionAllocationMismatchError(); + const entries = Object.entries(value.allocations); + if ( + entries.length > 10_000 || + entries.some( + ([id, digest]) => + !studioIdPattern.test(id) || + typeof digest !== "string" || + !/^[a-f0-9]{64}$/u.test(digest), + ) + ) + throw new DormantSessionAllocationMismatchError(); + for (const [id, digest] of entries) + this.dormantAllocations.set(id, digest as string); + } + this.dormantAllocationsLoaded = true; + } + + private async persistDormantAllocations(): Promise { + if (this.dormantAllocations.size > 10_000) + throw new DormantSessionAllocationMismatchError(); + const file = `${this.sessionsPath}.dormant-allocations.json`; + await mkdir(dirname(file), { recursive: true }); + await writeAssistantJson(dirname(file), basename(file), { + version: 1, + allocations: Object.fromEntries(this.dormantAllocations), + }); + } + /** * Registers a purely historical (never-launched-by-this-harness) session so * it can subsequently be resumed via `resume()`. Called by @@ -3599,6 +3816,8 @@ export class SessionManager { if (!marker) throw new SubsessionBindingMismatchError(); const operation = async (): Promise => { this.assertAdmission(reservedSessionId, closeGeneration); + if (this.dormantAllocations.has(reservedSessionId)) + throw new DormantSessionAllocationMismatchError(); const existingMarker = this.subsessionBindings.get(reservedSessionId); const existingSession = this.sessions.get(reservedSessionId); if (existingMarker) { @@ -3692,6 +3911,8 @@ export class SessionManager { expectedSubsessionBinding?: TrustedSubsessionBindingMarker, ): Promise { if (this.closing) throw new SessionManagerClosingError(); + if (this.dormantAllocations.has(id)) + throw new DormantSessionAllocationMismatchError(); const marker = this.subsessionBindings.get(id); if ( (marker !== undefined || expectedSubsessionBinding !== undefined) && diff --git a/packages/harness/src/shared/types.ts b/packages/harness/src/shared/types.ts index 86fcc0c9c..dea5c2415 100644 --- a/packages/harness/src/shared/types.ts +++ b/packages/harness/src/shared/types.ts @@ -166,6 +166,8 @@ export interface HarnessSession { /** Display title (first prompt, or directory basename until known). */ title: string; status: SessionStatus; + /** Allocated without Terminal; cleared only when its first PTY starts. */ + terminalState?: "not-started"; /** * Whether this live process was launched against the current Sapiom MCP * credential. The underlying generation and key remain server-private.