diff --git a/apps/server/src/j5/a2a/ArchiveAgentService.test.ts b/apps/server/src/j5/a2a/ArchiveAgentService.test.ts index b3ac7d8548f1..d7151220d9f7 100644 --- a/apps/server/src/j5/a2a/ArchiveAgentService.test.ts +++ b/apps/server/src/j5/a2a/ArchiveAgentService.test.ts @@ -226,7 +226,7 @@ const makeHarness = (options: HarnessOptions = {}) => { }, }), Layer.mock(ThreadManagementService)({ - getThreadProjection: () => Effect.succeed(projection()), + getThreadRecords: () => Effect.succeed(projection()), dispatch: (command) => { order.push(command.type === "thread.stop" ? "interrupt_requested" : command.type); return Effect.succeed({ sequence: 1, storedEvents: [] }); @@ -477,7 +477,7 @@ const readFactsFor = (home: "none" | "registered", thread: "missing" | "unreadab ), }), Layer.mock(ThreadManagementService)({ - getThreadProjection: () => + getThreadRecords: () => thread === "present" ? Effect.succeed({ thread: { id: threadId, projectId, archivedAt: null }, diff --git a/apps/server/src/j5/a2a/ArchiveAgentService.ts b/apps/server/src/j5/a2a/ArchiveAgentService.ts index 87e1aad2f2c5..e97a9e5b0d2f 100644 --- a/apps/server/src/j5/a2a/ArchiveAgentService.ts +++ b/apps/server/src/j5/a2a/ArchiveAgentService.ts @@ -1,10 +1,4 @@ -import { - CommandId, - OrchestrationV2RunStatus, - RunId, - ThreadId, - type OrchestrationV2ThreadProjection, -} from "@t3tools/contracts"; +import { CommandId, OrchestrationV2RunStatus, RunId, ThreadId } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; @@ -20,6 +14,7 @@ import { signPayload, timingSafeEqualBase64Url, } from "../../auth/utils.ts"; +import type { ProjectionRecords } from "../../orchestration-v2/ProjectionStore.ts"; import { ThreadLifecycleService } from "../../orchestration-v2/ThreadLifecycleService.ts"; import { ThreadManagementService, @@ -33,7 +28,7 @@ import { import { A2ALedger } from "./LedgerService.ts"; import { A2ALifecycleService } from "./LifecycleService.ts"; import { stopThread } from "./stopThread.ts"; -import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; +import { getThreadRecordsIfPresent } from "./threadProjectionReads.ts"; import { ExchangeDroppedPayload, ExchangeId, @@ -217,7 +212,7 @@ const decodeExchangeDroppedOption = Schema.decodeUnknownOption(ExchangeDroppedPa const decodeMessageSentOption = Schema.decodeUnknownOption(MessageSentPayload); interface ReadState { - readonly projection: OrchestrationV2ThreadProjection; + readonly projection: ProjectionRecords<"runs">; readonly retired: boolean; readonly archived: boolean; readonly facts: ArchiveAgentConsequenceFacts; @@ -367,7 +362,7 @@ export const layer = Layer.effect( facts: ThreadPreArchiveFacts, ) { const projection = yield* threadManagement - .getThreadProjection(target.threadId) + .getThreadRecords(target.threadId, ["runs"]) .pipe(Effect.mapError(operationError("reading the target thread projection"))); if ( facts.state !== "registered" || @@ -651,9 +646,10 @@ export const layer = Layer.effect( )(function* (target) { const facts = yield* readArchiveFacts(target); if (facts.state === "not-an-a2a-participant") { - const projection = yield* getThreadProjectionIfPresent( + const projection = yield* getThreadRecordsIfPresent( threadManagement, target.threadId, + [], ).pipe(Effect.mapError(operationError("reading the target thread projection"))); if (projection === null) return null; } diff --git a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts index ba5470099c42..b461fdad6839 100644 --- a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts +++ b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts @@ -147,7 +147,7 @@ it.effect( ), }), Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => threadId === captainThread ? Effect.succeed(captainProjection("2026-09-17T08:00:00.000Z")) : threadId === liveCaptain @@ -399,7 +399,7 @@ it.effect("unarchiving a Captain brings back the Crews that retired with it", () Layer.mock(ArchiveCrewService)({}), Layer.mock(ThreadManagementService)({ // The builder's thread was archived with the Crew; the critic's was never created. - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => threadId === criticThread ? Effect.fail( new OrchestratorProjectionError({ @@ -474,7 +474,7 @@ it.effect("a Captain archived again after an unarchive retires its Crew again", }), }), Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => Effect.map(Ref.get(seatArchived), (archived) => seatProjection(threadId, { archivedAt: archived ? "2026-09-17T08:00:00.000Z" : null, diff --git a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts index 0ed55556e207..ad1fecbb8fa2 100644 --- a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts +++ b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts @@ -17,7 +17,10 @@ import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewIns import { ArchiveCrewService } from "./ArchiveCrewService.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; import { crewSeatRequestKey, lifecycleCommandId } from "./spawnIds.ts"; -import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; +import { + getThreadProjectionIfPresent, + getThreadRecordsIfPresent, +} from "./threadProjectionReads.ts"; const CASCADE_SESSION = "j5-captain-archive-cascade"; @@ -194,7 +197,7 @@ export const layer = Layer.effect( instance.id, Effect.gen(function* () { for (const member of instance.members) { - const seat = yield* getThreadProjectionIfPresent(threads, member.threadId); + const seat = yield* getThreadRecordsIfPresent(threads, member.threadId, []); if (seat === null || seat.thread.archivedAt === null) continue; yield* threads.dispatch({ type: "thread.unarchive", @@ -287,7 +290,7 @@ export const layer = Layer.effect( const captainGoneAt = Effect.fn("j5.a2a.captainArchiveCascade.captainGoneAt")(function* ( instance: AgentCrewInstance, ) { - const read = yield* Effect.result(threads.getThreadProjection(instance.captainThreadId)); + const read = yield* Effect.result(threads.getThreadRecords(instance.captainThreadId, [])); if (Result.isFailure(read)) { yield* Effect.logWarning("J5 Captain archive sweep could not read a Captain thread", { captainThreadId: instance.captainThreadId, diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 7fd278ad4f7c..83ca67ec5f56 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -1720,6 +1720,7 @@ const playbookFixture = Effect.gen(function* () { thread: thread(threadId), messages: [], } as unknown as OrchestrationV2ThreadProjection), + getThreadRecords: (threadId) => Effect.succeed({ thread: thread(threadId) } as never), dispatch: (command) => Ref.update(commands, (items) => [...items, command]).pipe( Effect.as({ events: [], effects: [] } as never), diff --git a/apps/server/src/j5/a2a/CrewRuntimeRequestService.test.ts b/apps/server/src/j5/a2a/CrewRuntimeRequestService.test.ts index 68a2c8d29554..b8eb3a4256bb 100644 --- a/apps/server/src/j5/a2a/CrewRuntimeRequestService.test.ts +++ b/apps/server/src/j5/a2a/CrewRuntimeRequestService.test.ts @@ -144,7 +144,7 @@ const makeThreads = () => { }; const layer = Layer.mock(ThreadManagementService)({ // Fails the way the real service does: a typed projection error whose cause says why. - getThreadProjection: (threadId) => { + getThreadRecords: (threadId) => { const projection = state.get(threadId); if (broken.has(threadId)) return Effect.fail( diff --git a/apps/server/src/j5/a2a/CrewRuntimeRequestService.ts b/apps/server/src/j5/a2a/CrewRuntimeRequestService.ts index 586e7f224289..91ec62267546 100644 --- a/apps/server/src/j5/a2a/CrewRuntimeRequestService.ts +++ b/apps/server/src/j5/a2a/CrewRuntimeRequestService.ts @@ -18,7 +18,7 @@ import { type ThreadManagementProviderInstanceDisabledError, } from "../../orchestration-v2/ThreadManagementService.ts"; import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewInstanceService.ts"; -import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; +import { getThreadRecordsIfPresent } from "./threadProjectionReads.ts"; import { makeNativeQuestionInboxRead } from "./nativeQuestionInboxRead.ts"; /** A seat's thread, and the Crew that holds the seat. */ @@ -128,7 +128,9 @@ export const layer = Layer.effect( * null. Any other store failure propagates, so an outage is an error, not an empty Inbox. */ const liveProjection = (threadId: ThreadId) => - getThreadProjectionIfPresent(threads, threadId).pipe( + getThreadRecordsIfPresent(threads, threadId, ["runtimeRequests", "turnItems"], { + turnItemTypes: ["approval_request"], + }).pipe( Effect.map((projection) => projection !== null && projection.thread.archivedAt === null ? projection : null, ), diff --git a/apps/server/src/j5/a2a/CrewSeatFinishNotifier.test.ts b/apps/server/src/j5/a2a/CrewSeatFinishNotifier.test.ts index 1593d712680b..04f4b582b95f 100644 --- a/apps/server/src/j5/a2a/CrewSeatFinishNotifier.test.ts +++ b/apps/server/src/j5/a2a/CrewSeatFinishNotifier.test.ts @@ -269,7 +269,7 @@ it.effect("tells the Captain how each finished seat ended, and settles nothing", ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => Effect.succeed(projection(threadId)), + getThreadRecords: (threadId) => Effect.succeed(projection(threadId)), dispatch: (command) => Ref.update(dispatched, (items) => [...items, command]).pipe( Effect.as({ events: [], effects: [] } as never), @@ -490,7 +490,7 @@ it.effect( ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => threadId === captainThread ? Ref.get(captain) : Effect.succeed(projection(threadId)), dispatch: (command) => Ref.update(dispatched, (items) => [...items, command]).pipe( @@ -622,7 +622,7 @@ it.effect( ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => Effect.succeed(projection(threadId)), + getThreadRecords: (threadId) => Effect.succeed(projection(threadId)), dispatch: (command) => Ref.get(noticesFail).pipe( Effect.flatMap((fail) => @@ -739,7 +739,7 @@ it.effect( ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => threadId === captainThread ? Ref.get(captain) : Effect.succeed( @@ -885,7 +885,7 @@ it.effect("the boot sweep tells the Captain about a finished seat nothing report ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => Effect.succeed( threadId === scoutThread ? finished(threadId) @@ -987,7 +987,7 @@ it.effect( ), Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => Effect.succeed(projection(threadId)), + getThreadRecords: (threadId) => Effect.succeed(projection(threadId)), dispatch: (command) => Ref.update(dispatched, (items) => [...items, command]).pipe( Effect.as({ events: [], effects: [] } as never), diff --git a/apps/server/src/j5/a2a/CrewSeatFinishNotifier.ts b/apps/server/src/j5/a2a/CrewSeatFinishNotifier.ts index 2fc9051ee162..d2ba057474d1 100644 --- a/apps/server/src/j5/a2a/CrewSeatFinishNotifier.ts +++ b/apps/server/src/j5/a2a/CrewSeatFinishNotifier.ts @@ -93,7 +93,7 @@ const sectionParticipant = (section: string) => * (reviewer, builder), so two Crews' reviewers must not replace each other's baseline. */ export const latestSeatNotice = ( - captain: OrchestrationV2ThreadProjection, + captain: Pick, participantId: string, ): string | null => { const newestFirst = captain.messages @@ -109,7 +109,9 @@ export const latestSeatNotice = ( }; /** A seat notice still queued behind the Captain's running turn; a new notice folds into it. */ -export const queuedSeatDigest = (captain: OrchestrationV2ThreadProjection) => { +export const queuedSeatDigest = ( + captain: Pick, +) => { if (ThreadManagement.latestActiveRun(captain) === undefined) return null; for (const run of captain.runs) { if (run.status !== "queued") continue; @@ -223,7 +225,7 @@ const makeLayer = (daemon: boolean) => * fails it, for the next finish or the boot sweep. */ const handoffFact = Effect.fn("j5.a2a.crewSeatFinish.handoffFact")(function* ( - projection: OrchestrationV2ThreadProjection, + projection: Pick, kind: string | null, ): Effect.fn.Return { const assignment = projection.thread.agentPersonaAssignment; @@ -271,12 +273,17 @@ const makeLayer = (daemon: boolean) => const notifyCaptain = Effect.fn("j5.a2a.crewSeatFinish.notifyCaptain")(function* ( instance: AgentCrewInstance, seatName: string, - projection: OrchestrationV2ThreadProjection, + projection: Pick, run: OrchestrationV2Run, handoff: SeatHandoffFact, ) { const threadId = projection.thread.id; - const captain = yield* threads.getThreadProjection(instance.captainThreadId); + // Seat notices are system-authored user messages; the digest is a queued run's user message. + const captain = yield* threads.getThreadRecords( + instance.captainThreadId, + ["runs", "messages"], + { messageRoles: ["user"] }, + ); const stable = { providerSessionId: FINISH_SESSION, requestKey: `${threadId}:${run.id}` }; const text = seatFinishedNoticeText({ seatName, @@ -328,7 +335,10 @@ const makeLayer = (daemon: boolean) => if (membership === null) return null; const instance = yield* crews.read(membership.crewInstanceId); if (instance === null || instance.archivedAt !== null) return null; - const projection = yield* threads.getThreadProjection(threadId); + const projection = yield* threads.getThreadRecords(threadId, ["runs", "turnItems"], { + turnItemRunId: run.id, + turnItemTypes: ["error"], + }); if (projection.thread.archivedAt !== null) return null; if (ThreadManagement.latestActiveRun(projection) !== undefined) return null; if (run.status === "failed") @@ -360,7 +370,7 @@ const makeLayer = (daemon: boolean) => }); /** Only report the latest run, never an older finish hidden behind a later interruption. */ - const outstandingFinish = (projection: OrchestrationV2ThreadProjection) => { + const outstandingFinish = (projection: Pick) => { if (ThreadManagement.latestActiveRun(projection) !== undefined) return undefined; const newest = projection.runs.toSorted((a, b) => b.ordinal - a.ordinal)[0]; return newest?.status === "completed" || newest?.status === "failed" ? newest : undefined; @@ -372,7 +382,7 @@ const makeLayer = (daemon: boolean) => for (const member of instance.members) { // A seat whose thread cannot be read (gone, or the store hiccuped) is skipped this pass. const projection = yield* threads - .getThreadProjection(member.threadId) + .getThreadRecords(member.threadId, ["runs"]) .pipe(Effect.catchCause(() => Effect.succeed(null))); if (projection === null) continue; if (projection.thread.archivedAt !== null) continue; diff --git a/apps/server/src/j5/a2a/CrewStopService.test.ts b/apps/server/src/j5/a2a/CrewStopService.test.ts index 9ac47a0cca2c..78b0426f882c 100644 --- a/apps/server/src/j5/a2a/CrewStopService.test.ts +++ b/apps/server/src/j5/a2a/CrewStopService.test.ts @@ -96,7 +96,7 @@ it.effect("stops every live seat, for the Captain or a person, and nobody else", const layer = crewStopLayer.pipe( Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => Effect.succeed(projection(threadId)), + getThreadRecords: (threadId) => Effect.succeed(projection(threadId)), dispatch: (command) => Ref.update(interrupts, (items) => [ ...items, @@ -223,7 +223,7 @@ const ghostFixture = (ghost: "missing" | "unreadable" | "homed") => const layer = crewStopLayer.pipe( Layer.provideMerge( Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => threadId !== ghostThread ? Effect.succeed(projection(threadId)) : Effect.fail( diff --git a/apps/server/src/j5/a2a/CrewStopService.ts b/apps/server/src/j5/a2a/CrewStopService.ts index 668981e6c3b9..ffb605e3e830 100644 --- a/apps/server/src/j5/a2a/CrewStopService.ts +++ b/apps/server/src/j5/a2a/CrewStopService.ts @@ -12,7 +12,7 @@ import { AgentCrewInstanceService, type AgentCrewMember } from "./AgentCrewInsta import { A2AArchiveFacts } from "./ArchiveFactsService.ts"; import type { ParticipantId, LedgerProjectId } from "./contracts.ts"; import { AGENT_STOP_REASON, stopThread } from "./stopThread.ts"; -import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; +import { getThreadRecordsIfPresent } from "./threadProjectionReads.ts"; /** `never_created`: the seat's row was recorded but its thread never came to exist. */ export type CrewSeatStopResult = @@ -99,7 +99,7 @@ export const layer = Layer.effect( * with no thread behind it, fails the stop rather than skipping a seat that may be live. */ const readSeat = Effect.fn("j5.a2a.crewStop.readSeat")(function* (member: AgentCrewMember) { - const projection = yield* getThreadProjectionIfPresent(threads, member.threadId).pipe( + const projection = yield* getThreadRecordsIfPresent(threads, member.threadId, ["runs"]).pipe( Effect.mapError(seatError("reading a seat", member.seatName)), ); if (projection !== null) return projection; diff --git a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts index 58f0bc9d2d42..b4c8727e8b48 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts @@ -415,11 +415,11 @@ const makeTestLayer = ( const threads = yield* ThreadManagementService; return ThreadManagementService.of({ ...threads, - getThreadProjection: (threadId) => + getThreadRecords: (threadId, fields, filter) => Ref.get(harness.staleProjection).pipe( Effect.filterOrElse( (stale) => stale !== undefined, - () => threads.getThreadProjection(threadId), + () => threads.getThreadRecords(threadId, fields, filter), ), ), sendToThread: (input) => diff --git a/apps/server/src/j5/a2a/DeliveryTransport.ts b/apps/server/src/j5/a2a/DeliveryTransport.ts index 5fdcdb2c96e6..35028126ad07 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.ts @@ -490,7 +490,11 @@ export const live: Layer.Layer< const outcome = yield* settledEffect(steer.id); return outcome.status === "succeeded" ? ("delivered" as const) : ("cancelled" as const); } - const projection = yield* threads.getThreadProjection(participant.threadId); + const projection = yield* threads.getThreadRecords( + participant.threadId, + ["messages", "runs"], + { messageIds: [deliveryMessageId(input.messageId)] }, + ); const message = projection.messages.find( (entry) => entry.id === deliveryMessageId(input.messageId), ); @@ -544,7 +548,19 @@ export const live: Layer.Layer< state: "participant is not an addressable agent thread", }); } - const target = yield* threads.getThreadProjection(participant.threadId); + // Error items are all the usage-limit hold reads; the one message is the accepted check. + const target = yield* threads.getThreadRecords( + participant.threadId, + [ + "runs", + "messages", + "turnItems", + "providerTurns", + "providerThreads", + "providerSessions", + ], + { messageIds: [deliveryMessageId(input.messageId)], turnItemTypes: ["error"] }, + ); if (target.thread.archivedAt !== null) { return yield* new A2ADeliveryTargetError({ participantId: input.receiverId, @@ -702,7 +718,11 @@ export const live: Layer.Layer< } // A restart, and a steer the provider takes by interrupting and restarting, leave // no steer effect: the message in the thread is the proof. - const accepted = yield* orchestrator.getThreadProjection(participant.threadId); + const accepted = yield* orchestrator.getThreadRecords( + participant.threadId, + ["messages", "runs"], + { messageIds: [sendInput.messageId] }, + ); if (!accepted.messages.some((message) => message.id === sendInput.messageId)) { return false; } diff --git a/apps/server/src/j5/a2a/DeliveryWorker.test.ts b/apps/server/src/j5/a2a/DeliveryWorker.test.ts index 4cb0ba0b4834..41eaf3b57741 100644 --- a/apps/server/src/j5/a2a/DeliveryWorker.test.ts +++ b/apps/server/src/j5/a2a/DeliveryWorker.test.ts @@ -613,7 +613,7 @@ it.effect("keeps a message queued behind a held receiver queue undelivered until Layer.provide(database), ); const threadManagement = Layer.mock(ThreadManagementService)({ - getThreadProjection: () => + getThreadRecords: () => Effect.succeed({ thread: { projectId: "project:held", archivedAt: null }, messages: [], diff --git a/apps/server/src/j5/a2a/SilenceDetector.test.ts b/apps/server/src/j5/a2a/SilenceDetector.test.ts index a0f7805fcf18..a5e7f1d4e74b 100644 --- a/apps/server/src/j5/a2a/SilenceDetector.test.ts +++ b/apps/server/src/j5/a2a/SilenceDetector.test.ts @@ -7,7 +7,6 @@ import { type OrchestrationV2ProviderFailure, type OrchestrationV2Run, type OrchestrationV2StoredEvent, - type OrchestrationV2ThreadProjection, ProviderInstanceId, RunId, ThreadId, @@ -147,17 +146,21 @@ const makeTestLayer = () => { Layer.provide(database), ); const threads = threadMock({ - getThreadProjection: () => - Effect.succeed({ - turnItems: [ - { - runId: RunId.make("run:silence:test"), - type: "error", - status: "failed", - failure: failureDetail, - }, - ], - } as unknown as OrchestrationV2ThreadProjection), + getThreadRecords: ((_threadId: ThreadId, fields: ReadonlyArray) => + Effect.succeed( + fields.includes("turnItems") + ? { + turnItems: [ + { + runId: RunId.make("run:silence:test"), + type: "error", + status: "failed", + failure: failureDetail, + }, + ], + } + : thread, + )) as never, }); const transport = Layer.succeed( A2ADeliveryTransport, diff --git a/apps/server/src/j5/a2a/SilenceDetector.ts b/apps/server/src/j5/a2a/SilenceDetector.ts index bae8e0b0d866..fa55581425fa 100644 --- a/apps/server/src/j5/a2a/SilenceDetector.ts +++ b/apps/server/src/j5/a2a/SilenceDetector.ts @@ -295,7 +295,10 @@ const makeLayer = (daemon: boolean) => threadId: ThreadId, runId: RunId, ) { - const projection = yield* threads.getThreadProjection(threadId); + const projection = yield* threads.getThreadRecords(threadId, ["turnItems"], { + turnItemRunId: runId, + turnItemTypes: ["error"], + }); const item = projection.turnItems.findLast( (candidate) => candidate.runId === runId && diff --git a/apps/server/src/j5/a2a/ThreadLineage.ts b/apps/server/src/j5/a2a/ThreadLineage.ts index c4588130f04a..650721daedd2 100644 --- a/apps/server/src/j5/a2a/ThreadLineage.ts +++ b/apps/server/src/j5/a2a/ThreadLineage.ts @@ -47,7 +47,7 @@ export const layer = Layer.effect( const result = yield* inner.dispatch(command); if (source === null) return result; yield* Effect.gen(function* () { - const target = yield* inner.getThreadProjection(command.targetThreadId); + const target = yield* inner.getThreadRecords(command.targetThreadId, []); yield* composition.recordFacts({ homeCommandId: registrationCommandId(command.targetThreadId), placementCommandId: PlacementCommandId.make( diff --git a/apps/server/src/j5/a2a/runFailures.ts b/apps/server/src/j5/a2a/runFailures.ts index 42eedbab2531..c8a6f88f5a95 100644 --- a/apps/server/src/j5/a2a/runFailures.ts +++ b/apps/server/src/j5/a2a/runFailures.ts @@ -10,7 +10,7 @@ import type { * answer is nullable and callers say "no detail" rather than inventing one. */ export const runFailureDetail = ( - projection: OrchestrationV2ThreadProjection, + projection: Pick, runId: RunId, ): OrchestrationV2ProviderFailure | null => { const item = projection.turnItems.findLast( diff --git a/apps/server/src/j5/a2a/threadProjectionReads.ts b/apps/server/src/j5/a2a/threadProjectionReads.ts index ee28eab9132d..b5067e14df3f 100644 --- a/apps/server/src/j5/a2a/threadProjectionReads.ts +++ b/apps/server/src/j5/a2a/threadProjectionReads.ts @@ -2,7 +2,12 @@ import type { OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contrac import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { ProjectionStoreThreadNotFoundError } from "../../orchestration-v2/ProjectionStore.ts"; +import { + type ProjectionRecordField, + type ProjectionRecordFilter, + type ProjectionRecords, + ProjectionStoreThreadNotFoundError, +} from "../../orchestration-v2/ProjectionStore.ts"; import type { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; /** @@ -24,3 +29,18 @@ export const getThreadProjectionIfPresent = ( isThreadNotFound(error.cause) ? Effect.succeed(null) : Effect.fail(error), }), ); + +/** The same not-found rule as `getThreadProjectionIfPresent`, reading only `fields`. */ +export const getThreadRecordsIfPresent = ( + threads: Pick, + threadId: ThreadId, + fields: ReadonlyArray, + filter?: ProjectionRecordFilter, +) => + threads.getThreadRecords(threadId, fields, filter).pipe( + Effect.map((records): ProjectionRecords | null => records), + Effect.catchTags({ + OrchestratorProjectionError: (error) => + isThreadNotFound(error.cause) ? Effect.succeed(null) : Effect.fail(error), + }), + ); diff --git a/apps/server/src/j5/agents/agentHandoffObserver.ts b/apps/server/src/j5/agents/agentHandoffObserver.ts index d673b9e20e9f..593adda42268 100644 --- a/apps/server/src/j5/agents/agentHandoffObserver.ts +++ b/apps/server/src/j5/agents/agentHandoffObserver.ts @@ -36,7 +36,9 @@ export const layer = Layer.effect( readonly threadId: ThreadId; readonly runId: RunId; }) { - const projection = yield* projections.getThreadProjection(input.threadId); + const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], { + runIds: [input.runId], + }); const assignment = projection.thread.agentPersonaAssignment; if (assignment === undefined) return; const run = projection.runs.find((candidate) => candidate.id === input.runId); diff --git a/apps/server/src/j5/agents/agentInvocation.test.ts b/apps/server/src/j5/agents/agentInvocation.test.ts index 78fb48bbdbb6..13557218ed4c 100644 --- a/apps/server/src/j5/agents/agentInvocation.test.ts +++ b/apps/server/src/j5/agents/agentInvocation.test.ts @@ -126,7 +126,7 @@ const fixture = Effect.gen(function* () { Effect.provide( Layer.mergeAll( Layer.mock(ThreadManagementService)({ - getThreadProjection: () => Effect.succeed(parent), + getThreadRecords: () => Effect.succeed(parent), }), Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed(available) }), Layer.mock(OrchestratorMcpService)({ diff --git a/apps/server/src/j5/agents/agentInvocation.ts b/apps/server/src/j5/agents/agentInvocation.ts index 942f25f9f434..14befa31812b 100644 --- a/apps/server/src/j5/agents/agentInvocation.ts +++ b/apps/server/src/j5/agents/agentInvocation.ts @@ -43,7 +43,7 @@ export const invokeAgent = Effect.fn("j5.invokeAgent")(function* ( const registry = yield* ProviderRegistry; const library = yield* makeAgentPersonaLibrary; const parent = yield* threads - .getThreadProjection(thread.threadId) + .getThreadRecords(thread.threadId, []) .pipe( Effect.mapError( (error) => diff --git a/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.test.ts b/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.test.ts index 7c77e7baa769..60e53b1e0153 100644 --- a/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.test.ts +++ b/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.test.ts @@ -1,14 +1,21 @@ import { assert, it, vi } from "@effect/vitest"; import { + EventId, + NodeId, + PlanId, ProjectId, + ProviderInstanceId, RunId, ThreadId, + TurnItemId, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import * as RunFinalization from "../../orchestration-v2/RunFinalizationService.ts"; import { layer } from "./ArtifactRunFinalizationObserver.ts"; import { ArtifactWorkspace } from "./ArtifactWorkspace.ts"; @@ -46,7 +53,7 @@ it.effect("exports a completed plan into shared project application storage", () Layer.provide( Layer.mergeAll( Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: () => Effect.succeed(projection), + getThreadRecords: () => Effect.succeed(projection), }), Layer.succeed(RunFinalization.RunFinalizationObserver, { refresh, @@ -71,3 +78,120 @@ it.effect("exports a completed plan into shared project application storage", () ]); }).pipe(Effect.provide(testLayer)); }); + +it.effect("exports the finished run's plan from the store, not a later run's", () => { + const projectId = ProjectId.make("project:plan-per-run"); + const threadId = ThreadId.make("thread:plan-per-run"); + const finished = RunId.make("run:plan-finished"); + const later = RunId.make("run:plan-later"); + const instanceId = ProviderInstanceId.make("codex"); + const exportPlan = vi.fn(() => Effect.void); + const store = ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)); + const testLayer = Layer.mergeAll( + store, + layer.pipe( + Layer.provide( + Layer.mergeAll( + store, + Layer.succeed(RunFinalization.RunFinalizationObserver, { + refresh: () => Effect.void, + refreshAfterTurn: () => Effect.void, + }), + Layer.mock(ArtifactWorkspace)({ exportPlan }), + ), + ), + ), + ); + + return Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make("event:plan-per-run:thread"), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + id: threadId, + projectId, + title: "Plans", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "test" }, + runtimeMode: "full-access", + interactionMode: "plan", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + // The later run's plan item is newer, and a non-plan item sits in the finished run. + for (const [ordinal, runId, type] of [ + [1, finished, "proposed_plan"], + [2, finished, "reasoning"], + [3, later, "proposed_plan"], + ] as const) { + const planId = PlanId.make(`plan:${runId}`); + if (type === "proposed_plan") + yield* projections.apply({ + id: EventId.make(`event:plan:${runId}`), + type: "plan.updated", + threadId, + occurredAt: now, + payload: { + id: planId, + threadId, + runId, + nodeId: NodeId.make(`node:${runId}`), + kind: "proposed_plan", + status: "active", + markdown: `# Plan for ${runId}`, + }, + }); + const base = { + id: TurnItemId.make(`item:${ordinal}`), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + }; + yield* projections.apply({ + id: EventId.make(`event:item:${ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: now, + payload: + type === "proposed_plan" + ? { ...base, type, planId, markdown: `# Plan for ${runId}`, streaming: false } + : { ...base, type, text: "Thinking about the plan.", streaming: false }, + }); + } + + const observer = yield* RunFinalization.RunFinalizationObserver; + yield* observer.refresh({ cwd: "/thread-worktree", threadId, runId: finished }); + + assert.deepStrictEqual(exportPlan.mock.calls, [ + [{ projectId, markdown: `# Plan for ${finished}` }], + ]); + }).pipe(Effect.provide(testLayer)); +}); diff --git a/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.ts b/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.ts index c637029b3af2..1061de530109 100644 --- a/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.ts +++ b/apps/server/src/j5/artifacts/ArtifactRunFinalizationObserver.ts @@ -7,7 +7,7 @@ import * as RunFinalization from "../../orchestration-v2/RunFinalizationService. import { ArtifactWorkspace } from "./ArtifactWorkspace.ts"; export function selectCurrentProposedPlan( - projection: OrchestrationV2ThreadProjection, + projection: Pick, runId: RunId, ): Extract | null { type ProposedPlan = Extract< @@ -42,7 +42,11 @@ export const layer = Layer.effect( return upstream.refresh(input).pipe( Effect.andThen( Effect.gen(function* () { - const projection = yield* projections.getThreadProjection(input.threadId); + const projection = yield* projections.getThreadRecords( + input.threadId, + ["plans", "turnItems"], + { turnItemRunId: input.runId, turnItemTypes: ["proposed_plan"] }, + ); const plan = selectCurrentProposedPlan(projection, input.runId); if (plan === null) return; yield* artifacts.exportPlan({ diff --git a/apps/server/src/j5/playbooks/PlaybookCrewRelay.test.ts b/apps/server/src/j5/playbooks/PlaybookCrewRelay.test.ts index 1900063be896..c269caf53c66 100644 --- a/apps/server/src/j5/playbooks/PlaybookCrewRelay.test.ts +++ b/apps/server/src/j5/playbooks/PlaybookCrewRelay.test.ts @@ -124,7 +124,7 @@ const fixture = Effect.gen(function* () { // A thread whose projection can't be read right now (not missing: the store can't answer). const projectionFault = yield* Ref.make(null); const threads = ThreadManagementService.of({ - getThreadProjection: (threadId: ThreadId) => + getThreadRecords: (threadId: ThreadId) => Effect.all([Ref.get(seats), Ref.get(projectionFault)]).pipe( Effect.flatMap(([current, unreadable]) => { if (unreadable === threadId) diff --git a/apps/server/src/j5/playbooks/PlaybookCrewRelay.ts b/apps/server/src/j5/playbooks/PlaybookCrewRelay.ts index ce38b399cb42..875ae46ea28c 100644 --- a/apps/server/src/j5/playbooks/PlaybookCrewRelay.ts +++ b/apps/server/src/j5/playbooks/PlaybookCrewRelay.ts @@ -16,7 +16,7 @@ import { type AgentCrewInstance, } from "../a2a/AgentCrewInstanceService.ts"; import { lifecycleCommandId, lifecycleId } from "../a2a/spawnIds.ts"; -import { getThreadProjectionIfPresent } from "../a2a/threadProjectionReads.ts"; +import { getThreadRecordsIfPresent } from "../a2a/threadProjectionReads.ts"; import { crewStepNoticeText } from "./crewStepNotice.ts"; import { PlaybookStore, @@ -97,7 +97,7 @@ export const makePlaybookCrewRelay = Effect.gen(function* () { ) { const owner = stepOwner(instance, stepId); if (owner === null) return { seat: null, threadId: instance.captainThreadId }; - const projection = yield* getThreadProjectionIfPresent(threads, owner.threadId); + const projection = yield* getThreadRecordsIfPresent(threads, owner.threadId, []); const live = projection !== null && projection.thread.archivedAt === null && @@ -153,7 +153,7 @@ export const makePlaybookCrewRelay = Effect.gen(function* () { return settled(yield* store.resolveLanding(runId, requestId, "captain")); const seatThreadId = ThreadId.make(landing.targetThreadId!); const outcome = yield* Effect.gen(function* () { - const seat = yield* getThreadProjectionIfPresent(threads, seatThreadId); + const seat = yield* getThreadRecordsIfPresent(threads, seatThreadId, []); if (seat === null) return "captain" as const; yield* threads.dispatch({ type: "message.dispatch", diff --git a/apps/server/src/j5/playbooks/mcp.test.ts b/apps/server/src/j5/playbooks/mcp.test.ts index 31247e010e2e..74aa23180b43 100644 --- a/apps/server/src/j5/playbooks/mcp.test.ts +++ b/apps/server/src/j5/playbooks/mcp.test.ts @@ -114,7 +114,7 @@ const makeFixture = ( Layer.mock(ThreadManagementService)({ // The access gate reads the calling thread before each tool. getThreadShell: (threadId) => Effect.succeed(shell(threadId)), - getThreadProjection: (threadId) => + getThreadRecords: (threadId) => Effect.succeed( emptyProjection({ id: EventId.make(`created:${threadId}`), diff --git a/apps/server/src/j5/playbooks/playbookRpc.test.ts b/apps/server/src/j5/playbooks/playbookRpc.test.ts index 4675bf563845..dfd2d51ed365 100644 --- a/apps/server/src/j5/playbooks/playbookRpc.test.ts +++ b/apps/server/src/j5/playbooks/playbookRpc.test.ts @@ -98,7 +98,7 @@ const fixture = Effect.gen(function* () { ), }); const threads = Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => { + getThreadRecords: (threadId) => { if (threadId === missingThread || threadId === unavailableThread) { return Effect.fail( new OrchestratorProjectionError({ diff --git a/apps/server/src/j5/playbooks/workspace.ts b/apps/server/src/j5/playbooks/workspace.ts index ec0dfb5948cd..32352abf03cc 100644 --- a/apps/server/src/j5/playbooks/workspace.ts +++ b/apps/server/src/j5/playbooks/workspace.ts @@ -14,7 +14,7 @@ export const playbookWorkspaceRoot = Effect.fn("j5.playbooks.workspace.playbookW function* (threadId: ThreadId) { const threads = yield* ThreadManagementService; const projects = yield* ProjectService; - const { thread } = yield* threads.getThreadProjection(threadId); + const { thread } = yield* threads.getThreadRecords(threadId, []); if (thread.deletedAt !== null) return yield* playbookError("thread_not_found", "The owner thread was deleted."); const project = yield* projects.getById(thread.projectId); diff --git a/apps/server/src/j5/playbooks/workspaceRoot.ts b/apps/server/src/j5/playbooks/workspaceRoot.ts index 2132f173948c..599411f541e6 100644 --- a/apps/server/src/j5/playbooks/workspaceRoot.ts +++ b/apps/server/src/j5/playbooks/workspaceRoot.ts @@ -17,7 +17,7 @@ export const resolvePlaybookWorkspaceRoot = Effect.fn( "j5.playbooks.workspaceRoot.resolvePlaybookWorkspaceRoot", )(function* ( projects: Pick, - threads: Pick, + threads: Pick, input: PlaybookLibraryRequest, ) { if (input.projectId === undefined) return input.threadId === undefined ? "" : null; @@ -25,7 +25,7 @@ export const resolvePlaybookWorkspaceRoot = Effect.fn( if (Option.isNone(project) || project.value.deletedAt !== null) return null; let root = project.value.workspaceRoot; if (input.threadId !== undefined) { - const projection = yield* threads.getThreadProjection(input.threadId).pipe( + const projection = yield* threads.getThreadRecords(input.threadId, []).pipe( Effect.catchTags({ OrchestratorProjectionError: (error) => isMissingThread(error.cause) ? Effect.succeed(null) : Effect.fail(error), diff --git a/apps/server/src/j5/run-observability/QueuedRunWatchdog.test.ts b/apps/server/src/j5/run-observability/QueuedRunWatchdog.test.ts index bd4572f430ba..dac10a6bc46a 100644 --- a/apps/server/src/j5/run-observability/QueuedRunWatchdog.test.ts +++ b/apps/server/src/j5/run-observability/QueuedRunWatchdog.test.ts @@ -1,9 +1,13 @@ import { + EventId, + MessageId, + ProjectId, ProviderInstanceId, VcsProcessExitError, RunAttemptId, RunId, ThreadId, + type OrchestrationV2Run, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -21,6 +25,7 @@ import * as EventSink from "../../orchestration-v2/EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { QueuedRunCandidates, type CandidateQuery } from "./QueuedRunCandidates.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import { layer, QueuedRunWatchdog, @@ -77,7 +82,7 @@ it("records one durable waiting fact for a promoted run that has not dispatched" }), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: (id) => + getThreadRecords: (id) => Effect.sync(() => { projectionReadIds.push(id); return projection; @@ -130,6 +135,105 @@ it("records one durable waiting fact for a promoted run that has not dispatched" }); }).pipe(Effect.runPromise)); +it("dedupes the waiting fact against the store's own error items for the run", async () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread_queued_run_watchdog_store"); + const runId = RunId.make("run_queued_run_watchdog_store"); + const instanceId = ProviderInstanceId.make("codex"); + const now = yield* DateTime.now; + const run: OrchestrationV2Run = { + id: runId, + threadId, + ordinal: 1, + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5.4" }, + providerThreadId: null, + userMessageId: MessageId.make("message_queued_run_watchdog_store"), + rootNodeId: null, + activeAttemptId: RunAttemptId.make("attempt_queued_run_watchdog_store"), + status: "starting", + requestedAt: DateTime.makeUnsafe(DateTime.toEpochMillis(now) - QUEUED_RUN_WATCHDOG_DELAY_MS), + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const written: Array = []; + const store = ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)); + const testLayer = layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + Layer.mock(QueuedRunCandidates)({ list: () => Effect.succeed([run]) }), + Layer.effect( + EventSink.EventSinkV2, + Effect.map(ProjectionStore.ProjectionStoreV2, (projections) => + EventSink.EventSinkV2.of({ + writeIfRunCurrent: ( + input: Parameters[0], + ) => + Effect.forEach(input.events, (event) => projections.apply(event)).pipe( + Effect.tap(() => Effect.sync(() => written.push(input))), + Effect.as({ committed: true, storedEvents: [] } as never), + Effect.orDie, + ), + } as never), + ), + ), + IdAllocator.layer, + ), + ), + Layer.provideMerge(store), + ); + + yield* Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + yield* projections.apply({ + id: EventId.make("event:watchdog-store:thread"), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + id: threadId, + projectId: ProjectId.make("project:watchdog-store"), + title: "Watchdog", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + yield* projections.apply({ + id: EventId.make("event:watchdog-store:run"), + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: run, + }); + const watchdog = yield* QueuedRunWatchdog; + yield* watchdog.scan(); + yield* watchdog.scan(); + const { turnItems } = yield* projections.getThreadRecords(threadId, ["turnItems"]); + expect(turnItems.map((item) => item.type)).toEqual(["error"]); + }).pipe(Effect.provide(testLayer)); + + expect(written).toHaveLength(1); + }).pipe(Effect.runPromise)); + it("fairly observes more than 100 stale runs within bounded watchdog ticks", async () => Effect.gen(function* () { const threadId = ThreadId.make("thread_queued_run_watchdog_fairness"); @@ -181,7 +285,7 @@ it("fairly observes more than 100 stale runs within bounded watchdog ticks", asy }), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: () => Effect.succeed(projection), + getThreadRecords: () => Effect.succeed(projection), }), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent: (input) => @@ -252,7 +356,7 @@ it("records one sanitized VCS observation fact without changing the run", async Layer.provide( Layer.mergeAll( Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: () => Effect.succeed(projection), + getThreadRecords: () => Effect.succeed(projection), }), Layer.mock(EventSink.EventSinkV2)({ write: (input) => diff --git a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts index d0d152056318..c06db6f0b3fb 100644 --- a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts +++ b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts @@ -51,7 +51,7 @@ function waitingMinutes(run: OrchestrationV2Run, now: DateTime.Utc): number { } function hasFact( - projection: OrchestrationV2ThreadProjection, + projection: Pick, run: OrchestrationV2Run, signal: string, ) { @@ -80,8 +80,18 @@ export const layer = Layer.effect( const candidatesStore = yield* QueuedRunCandidates; const startingRunCursor = yield* Ref.make(undefined); + // The run, and its error items: the signal facts this writes are error items of that run. + const readRunFacts = ( + threadId: OrchestrationV2Run["threadId"], + runId: OrchestrationV2Run["id"], + ) => + projections.getThreadRecords(threadId, ["runs", "turnItems"], { + runIds: [runId], + turnItemRunId: runId, + turnItemTypes: ["error"], + }); const writeFact = Effect.fn("QueuedRunWatchdog.writeFact")(function* (input: { - readonly projection: OrchestrationV2ThreadProjection; + readonly projection: Pick; readonly run: OrchestrationV2Run; readonly signal: string; readonly title: string; @@ -157,9 +167,8 @@ export const layer = Layer.effect( candidates, (candidate) => Effect.gen(function* () { - // A full projection is only needed for a bounded candidate, where - // it provides deduplication and rechecks current run state. - const projection = yield* projections.getThreadProjection(candidate.threadId); + // Read per bounded candidate, for deduplication and to recheck current run state. + const projection = yield* readRunFacts(candidate.threadId, candidate.id); const run = projection.runs.find((current) => current.id === candidate.id); if ( run === undefined || @@ -195,7 +204,7 @@ export const layer = Layer.effect( }) { const vcsError = findVcsError(input.cause); if (vcsError === undefined) return; - const projection = yield* projections.getThreadProjection(input.threadId); + const projection = yield* readRunFacts(input.threadId, input.runId); const run = projection.runs.find((candidate) => candidate.id === input.runId); if (run === undefined) return; // Upstream no longer copies arbitrary cause text; VCS errors format their own redacted message. diff --git a/apps/server/src/j5/run-observability/VcsFailureObservation.test.ts b/apps/server/src/j5/run-observability/VcsFailureObservation.test.ts index 89b0de246e2f..22ddebc80a39 100644 --- a/apps/server/src/j5/run-observability/VcsFailureObservation.test.ts +++ b/apps/server/src/j5/run-observability/VcsFailureObservation.test.ts @@ -60,7 +60,7 @@ function fixture() { turnItems, } as unknown as OrchestrationV2ThreadProjection; const projections = Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: () => Effect.succeed(projection), + getThreadRecords: () => Effect.succeed(projection), getCheckpointContext: () => Effect.succeed(projection as never), }); const events = Layer.mock(EventSink.EventSinkV2)({ @@ -163,7 +163,7 @@ it.effect("ignores ordinary and cyclic causes before reading projection state", Layer.provide( Layer.mergeAll( Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadProjection: () => + getThreadRecords: () => Effect.sync(() => { reads += 1; throw new Error("unexpected read");