import { expect, it } from "@effect/vitest"; import { CommandId, MessageId, NodeId, type OrchestrationV2Command, type OrchestrationV2Run, type OrchestrationV2StoredEvent, type OrchestrationV2ThreadProjection, ProjectId, ProviderInstanceId, RunId, ThreadId, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; it("stamps authoritative provenance on commands that create threads or messages", () => { const command: OrchestrationV2Command = { type: "thread.create", createdBy: "agent", creationSource: "mcp", commandId: CommandId.make("command:thread-management:create"), threadId: ThreadId.make("thread:thread-management:create"), projectId: ProjectId.make("project:thread-management"), title: "Thread management", modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null, }; expect( ThreadManagementService.withCreationProvenance(command, { createdBy: "user", creationSource: "web", }), ).toMatchObject({ createdBy: "user", creationSource: "web", }); }); it("leaves commands that do not create durable authored content unchanged", () => { const command: OrchestrationV2Command = { type: "run.interrupt", commandId: CommandId.make("command:thread-management:interrupt"), threadId: ThreadId.make("thread:thread-management:interrupt"), runId: RunId.make("run:thread-management:interrupt"), }; expect( ThreadManagementService.withCreationProvenance(command, { createdBy: "user", creationSource: "web", }), ).toBe(command); }); it("identifies every existing thread that must be hydrated before dispatch", () => { const sourceThreadId = ThreadId.make("thread:thread-management:source"); const targetThreadId = ThreadId.make("thread:thread-management:target"); const parentThreadId = ThreadId.make("thread:thread-management:parent"); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.create", createdBy: "user", creationSource: "web", commandId: CommandId.make("command:thread-management:create"), threadId: targetThreadId, projectId: ProjectId.make("project:thread-management"), title: "Created thread", modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null, }), ).toEqual([]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.archive", commandId: CommandId.make("command:thread-management:archive"), threadId: targetThreadId, }), ).toEqual([targetThreadId]); // Read-state commands skip transcript hydration entirely: they fire on // every activity bump while a thread is open and never touch messages. expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.visit", commandId: CommandId.make("command:thread-management:visit"), threadId: targetThreadId, visitedAt: "2026-07-30T00:00:00.000Z", }), ).toEqual([]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.mark-unread", commandId: CommandId.make("command:thread-management:mark-unread"), threadId: targetThreadId, }), ).toEqual([]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.fork", createdBy: "user", creationSource: "web", commandId: CommandId.make("command:thread-management:fork"), sourceThreadId, targetThreadId, sourcePoint: { type: "run", runId: RunId.make("run:thread-management:source"), }, }), ).toEqual([sourceThreadId]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.merge_back", createdBy: "user", creationSource: "web", commandId: CommandId.make("command:thread-management:merge"), sourceThreadId, targetThreadId, sourcePoint: { type: "run", runId: RunId.make("run:thread-management:source"), }, }), ).toEqual([sourceThreadId, targetThreadId]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "delegated_task.request", createdBy: "agent", creationSource: "provider", commandId: CommandId.make("command:thread-management:delegate"), parentThreadId, parentRunId: RunId.make("run:thread-management:parent"), parentNodeId: NodeId.make("node:thread-management:parent"), task: "Inspect the migration", modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", interactionMode: "default", }), ).toEqual([parentThreadId]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "delegated_task.wake-policy", commandId: CommandId.make("command:thread-management:wake-policy"), parentThreadId, taskId: NodeId.make("node:thread-management:delegated"), completionWake: "always", }), ).toEqual([parentThreadId]); expect( ThreadManagementService.existingThreadIdsForCommand({ type: "thread.created.record", commandId: CommandId.make("command:thread-management:record"), parentThreadId, parentRunId: RunId.make("run:thread-management:parent"), parentNodeId: NodeId.make("node:thread-management:parent"), targetThreadId, targetRunId: null, }), ).toEqual([parentThreadId, targetThreadId]); }); it("derives thread management messages from structural error attributes", () => { const projectId = ProjectId.make("project:thread-management:errors"); const threadId = ThreadId.make("thread:thread-management:errors"); const runId = RunId.make("run:thread-management:errors"); const messageId = MessageId.make("message:thread-management:errors"); const infrastructureCause = new Error("private sqlite detail"); const threadNotFound = new ThreadManagementService.ThreadManagementThreadNotFoundError({ projectId, threadId, }); expect(threadNotFound).toMatchObject({ projectId, threadId }); expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`); const runNotFound = new ThreadManagementService.ThreadManagementRunNotFoundError({ threadId, runId, }); expect(runNotFound).toMatchObject({ threadId, runId }); expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`); const archived = new ThreadManagementService.ThreadManagementThreadArchivedError({ threadId, }); expect(archived).toMatchObject({ threadId }); expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`); const notSteerable = new ThreadManagementService.ThreadManagementNoSteerableRunError({ threadId, mode: "restart", }); expect(notSteerable).toMatchObject({ threadId, mode: "restart", }); expect(notSteerable.message).toBe( `Thread ${threadId} has no running turn that can be restarted.`, ); const notInterruptible = new ThreadManagementService.ThreadManagementThreadNotInterruptibleError({ threadId, runId, }); expect(notInterruptible).toMatchObject({ threadId, runId }); expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`); const listFailure = new ThreadManagementService.ThreadManagementProjectThreadsListError({ projectId, cause: infrastructureCause, }); expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause }); expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`); expect(listFailure.message).not.toContain(infrastructureCause.message); const durableProjectionFailure = new ThreadManagementService.ThreadManagementDurableRunProjectionError({ threadId, messageId, }); expect(durableProjectionFailure).toMatchObject({ threadId, messageId }); expect(durableProjectionFailure.message).toBe( `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`, ); }); it.effect("classifies projection infrastructure failures separately from a missing thread", () => { const projectId = ProjectId.make("project:thread-management:projection-failure"); const threadId = ThreadId.make("thread:thread-management:projection-failure"); const infrastructureCause = new Error("sqlite read failed"); const projectionError = new Orchestrator.OrchestratorProjectionError({ threadId, cause: infrastructureCause, }); const layerTest = ThreadManagementService.layer.pipe( Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ getThreadProjection: () => Effect.fail(projectionError), }), ), ); return Effect.gen(function* () { const service = yield* ThreadManagementService.ThreadManagementService; const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId })); expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementProjectionLoadError); expect(error).toMatchObject({ projectId, threadId, cause: projectionError, }); expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`); }).pipe(Effect.provide(layerTest)); }); it.effect("uses thread-not-found only after a projection loads outside the project", () => { const projectId = ProjectId.make("project:thread-management:requested"); const otherProjectId = ProjectId.make("project:thread-management:other"); const threadId = ThreadId.make("thread:thread-management:wrong-project"); const projection = { thread: { id: threadId, projectId: otherProjectId, deletedAt: null, }, } as OrchestrationV2ThreadProjection; const layerTest = ThreadManagementService.layer.pipe( Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ getThreadProjection: () => Effect.succeed(projection), }), ), ); return Effect.gen(function* () { const service = yield* ThreadManagementService.ThreadManagementService; const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId })); expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementThreadNotFoundError); expect(error).toMatchObject({ projectId, threadId }); expect("cause" in error).toBe(false); }).pipe(Effect.provide(layerTest)); }); it.effect("preserves failed legacy materialization when reading checkpoint context", () => { const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure"); const importError = new LegacyV1ThreadImporter.LegacyV1ThreadImportError({ threadId, operation: "hydrate transcript for", cause: new Error("checkpoint import failed"), }); const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe( Layer.provide( Layer.mergeAll( Layer.mock(Orchestrator.OrchestratorV2)({ getCheckpointContext: () => Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }), }), Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ ensureTranscript: () => Effect.fail(importError), }), ), ), ); return Effect.gen(function* () { const service = yield* ThreadManagementService.ThreadManagementService; const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip); expect(error).toBeInstanceOf(Orchestrator.OrchestratorProjectionError); expect(error).toMatchObject({ threadId, cause: importError }); }).pipe(Effect.provide(layerTest)); }); it.effect.each([ { finalStatus: "completed" as const, timedOut: false }, { finalStatus: "failed" as const, timedOut: false }, { finalStatus: "cancelled" as const, timedOut: false }, { finalStatus: "interrupted" as const, timedOut: false }, { finalStatus: "rolled_back" as const, timedOut: false }, { finalStatus: "running" as const, timedOut: true }, { finalStatus: "missing" as const }, ])("waitForThread timeout final read when selected run is $finalStatus", (scenario) => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-timeout"); const threadId = ThreadId.make("thread:thread-management:wait-timeout"); const runId = RunId.make("run:thread-management:wait-timeout"); const subscribed = yield* Deferred.make(); let reads = 0; const projection = (status: OrchestrationV2Run["status"] | "missing") => ({ thread: { id: threadId, projectId, deletedAt: null }, runs: status === "missing" ? [] : [{ id: runId, status }], }) as unknown as OrchestrationV2ThreadProjection; const layerTest = ThreadManagementService.layer.pipe( Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ getThreadEventSequence: () => Effect.succeed(0), // No run update arrives, so the timeout path runs while a final // projection read can still observe a terminal run. streamStoredEventsFrom: () => Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( Stream.drain, Stream.concat(Stream.never), ), getThreadRecords: () => Effect.sync(() => { reads += 1; return projection(reads === 1 ? "running" : scenario.finalStatus); }), }), ), ); const service = yield* ThreadManagementService.ThreadManagementService.pipe( Effect.provide(layerTest), ); const fiber = yield* service .waitForThread({ projectId, threadId, runId, timeoutMs: 1, }) .pipe(Effect.result, Effect.forkChild); yield* Deferred.await(subscribed); yield* TestClock.adjust(Duration.millis(1)); const result = yield* Fiber.join(fiber); if (scenario.finalStatus === "missing") { expect(result._tag).toBe("Failure"); expect(result).toMatchObject({ failure: expect.any(ThreadManagementService.ThreadManagementRunNotFoundError), }); expect(result).toMatchObject({ failure: { threadId, runId }, }); } else { expect(result._tag).toBe("Success"); expect(result).toMatchObject({ success: { threadId, timedOut: scenario.timedOut, run: { id: runId, status: scenario.finalStatus }, }, }); } }), ); it.effect("waitForThread reads the run again only when the run updates", () => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-event"); const threadId = ThreadId.make("thread:thread-management:wait-event"); const runId = RunId.make("run:thread-management:wait-event"); const subscribed = yield* Deferred.make(); const events = yield* Queue.unbounded(); let status: OrchestrationV2Run["status"] = "running"; let reads = 0; const stored = (sequence: number, event: object) => ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent; const layerTest = ThreadManagementService.layer.pipe( Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ getThreadEventSequence: () => Effect.succeed(0), // Only the run.updated stream carries events in this test. streamStoredEventsFrom: (input) => input?.eventType === "run.updated" ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( Stream.drain, Stream.concat(Stream.fromQueue(events)), ) : Stream.never, getThreadRecords: () => Effect.sync(() => { reads += 1; return { thread: { id: threadId, projectId, deletedAt: null }, runs: [{ id: runId, status }], } as unknown as OrchestrationV2ThreadProjection; }), }), ), ); const service = yield* ThreadManagementService.ThreadManagementService.pipe( Effect.provide(layerTest), ); const fiber = yield* service .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }) .pipe(Effect.forkChild); yield* Deferred.await(subscribed); status = "completed"; yield* Queue.offer(events, stored(1, { type: "run.updated", payload: { id: "other-run" } })); yield* Queue.offer(events, stored(2, { type: "run.updated", payload: { id: runId, status } })); const result = yield* Fiber.join(fiber); expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "completed" } }); // The first read plus one for this run's update. The other run caused none. expect(reads).toBe(2); }), );