TypeScript
refactor(orchestration): trace storage operations without per-event spans (#21994)
Julius Marminge236c11962fdc
diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.tsindex cb41dc73651..18c2283fb3d 100644--- a/apps/server/src/orchestration-v2/EffectOutbox.ts+++ b/apps/server/src/orchestration-v2/EffectOutbox.ts@@ -370,8 +370,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La);const service: EffectOutboxV2Shape = {- enqueue: (effects) =>- Effect.gen(function* () {+ enqueue: Effect.fn("EffectOutbox.enqueue")(+ function* (effects) {const now = yield* DateTime.now;const nowIso = DateTime.formatIso(now);yield* Effect.forEach(@@ -406,7 +406,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La{ concurrency: 1, discard: true },);// EventSink owns the corresponding post-commit notification.- }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),+ },+ Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause })),+ ),get: (effectId) =>sql<EffectRow>`SELECT *@@ -438,8 +440,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La: new EffectOutboxError({ operation: "list", cause }),),),- cancelUnsettled: ({ threadId, effectTypes, reason }) =>- Effect.gen(function* () {+ cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(+ function* ({ threadId, effectTypes, reason }) {if (effectTypes.length === 0) return [];const now = DateTime.formatIso(yield* DateTime.now);const rows = yield* sql<{ readonly effect_id: string }>`@@ -457,40 +459,36 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = LaRETURNING effect_id`;return rows.map(({ effect_id }) => effect_id);- }).pipe(- Effect.mapError(- (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),- ),- ),- signalCancellations: (effectIds) =>- Effect.gen(function* () {- yield* Effect.forEach(- effectIds,- (effectId) => {- const signal = cancellationSignals.get(effectId);- return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);- },- { discard: true },- );- yield* signalSettled(effectIds);- if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);- }),+ },+ Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),+ ),+ signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {+ yield* Effect.forEach(+ effectIds,+ (effectId) => {+ const signal = cancellationSignals.get(effectId);+ return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);+ },+ { discard: true },+ );+ yield* signalSettled(effectIds);+ if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);+ }),awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),clearCancellation: (effectId) =>Effect.sync(() => {cancellationSignals.delete(effectId);}),- awaitSettled: (effectId) =>- Effect.gen(function* () {- // Registered before the read, so a settle right after it still resolves.- const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();- settledSignals.set(effectId, signal);- const effect = yield* service.get(effectId);- if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {- return yield* Deferred.await(signal);- }- yield* signalSettled([effectId]);- }),+ awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {+ // Registered before the read, so a settle right after it still resolves.+ const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();+ settledSignals.set(effectId, signal);+ const effect = yield* service.get(effectId);+ if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {+ return yield* Deferred.await(signal);+ }+ yield* signalSettled([effectId]);+ }),reconcileAfterProcessLoss: Effect.gen(function* () {const now = DateTime.formatIso(yield* DateTime.now);const cancelledRows = yield* sql<{ readonly effect_id: string }>`@@ -526,8 +524,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La(cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),),),- claimNext: ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) =>- Effect.gen(function* () {+ // The worker polls for the next effect even when there is no work to claim.+ claimNext: Effect.fnUntraced(+ function* ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) {const now = yield* DateTime.now;const nowIso = DateTime.formatIso(now);const leaseExpiresAt = DateTime.formatIso(@@ -560,7 +559,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Laif (row === undefined) return Option.none();cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());return Option.some(yield* rowToEffect(row));- }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),+ },+ Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })),+ ),nextClaimableAt: Effect.gen(function* () {const rows = yield* sql<{ readonly available_at: string | null }>`SELECT MIN(candidate.available_at) AS available_at@@ -584,8 +585,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La: new EffectOutboxError({ operation: "next-claimable", cause }),),),- succeed: ({ effectId, workerId }) =>- Effect.gen(function* () {+ succeed: Effect.fn("EffectOutbox.succeed")(+ function* ({ effectId, workerId }) {const now = DateTime.formatIso(yield* DateTime.now);const rows = yield* sql<{ readonly effect_id: string }>`UPDATE orchestration_v2_effect_outbox@@ -607,13 +608,16 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layield* notifyAvailable();}return rows.length === 1;- }).pipe(- Effect.mapError(- (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),+ },+ (effect, { effectId }) =>+ effect.pipe(+ Effect.mapError(+ (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),+ ),),- ),- retry: ({ effectId, workerId, error, delayMs }) =>- Effect.gen(function* () {+ ),+ retry: Effect.fn("EffectOutbox.retry")(+ function* ({ effectId, workerId, error, delayMs }) {const now = yield* DateTime.now;const nowIso = DateTime.formatIso(now);const availableAt = DateTime.formatIso(@@ -638,13 +642,16 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layield* notifyAvailable();}return rows.length === 1;- }).pipe(- Effect.mapError(- (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),+ },+ (effect, { effectId }) =>+ effect.pipe(+ Effect.mapError(+ (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),+ ),),- ),- fail: ({ effectId, workerId, error }) =>- Effect.gen(function* () {+ ),+ fail: Effect.fn("EffectOutbox.fail")(+ function* ({ effectId, workerId, error }) {const now = DateTime.formatIso(yield* DateTime.now);const rows = yield* sql<{ readonly effect_id: string }>`UPDATE orchestration_v2_effect_outbox@@ -666,9 +673,14 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layield* notifyAvailable();}return rows.length === 1;- }).pipe(- Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),- ),+ },+ (effect, { effectId }) =>+ effect.pipe(+ Effect.mapError(+ (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),+ ),+ ),+ ),pruneSettled: Effect.gen(function* () {const cutoff = DateTime.formatIso(DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.tsindex 13916b40f9d..6294638a9b0 100644--- a/apps/server/src/orchestration-v2/EventSink.ts+++ b/apps/server/src/orchestration-v2/EventSink.ts@@ -227,8 +227,9 @@ const layerBase: Layer.Layer<OrchestrationV2DomainEvent["type"],PubSub.PubSub<OrchestrationV2StoredEvent>>();- const publishLiveEvents = (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>- Effect.gen(function* () {+ const publishLiveEvents =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {yield* PubSub.publishAll(liveEvents, events);for (const [type, pubsub] of liveEventsByType) {yield* PubSub.publishAll(@@ -271,8 +272,9 @@ const layerBase: Layer.Layer<// A user can answer after terminal normalization reads the pending request.// Recheck inside the write transaction so stale cleanup cannot erase answers.- const guardUserInputCancellations = (events: ReadonlyArray<OrchestrationV2DomainEvent>) =>- Effect.gen(function* () {+ const guardUserInputCancellations =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {const staleRequests = new Set<RuntimeRequestId>();const staleNodes = new Set<NodeId>();for (const event of events) {@@ -337,8 +339,9 @@ const layerBase: Layer.Layer<);};- const applyStoredEvents = (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) =>- Effect.gen(function* () {+ const applyStoredEvents =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {concurrency: 1,});@@ -564,8 +567,9 @@ const layerBase: Layer.Layer<);});- const existingCommandResult = (commandId: CommandId) =>- Effect.gen(function* () {+ const existingCommandResult =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (commandId: CommandId) {const existing = yield* commandReceipts.getByCommandId(commandId);if (Option.isNone(existing)) {return yield* Effect.die(diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.tsindex c7133e41abc..d7048383998 100644--- a/apps/server/src/orchestration-v2/LiveStreamBudget.ts+++ b/apps/server/src/orchestration-v2/LiveStreamBudget.ts@@ -207,45 +207,41 @@ type LiveStreamLimits = {readonly maxSerializedBytes?: number;};-const retainLiveStream = <A extends object, E, R>(- source: Stream.Stream<A, E, R>,- budget: LiveStreamBudget,-) =>- Effect.gen(function* () {- const queue = yield* Queue.unbounded<- RetainedLiveItem<A>,- E | LiveStreamBufferError | Cause.Done- >();- let closed = false;- const close = (error?: LiveStreamBufferError) =>- Effect.gen(function* () {- if (closed) return;- closed = true;- budget.release(yield* Queue.clear(queue).pipe(Effect.orElseSucceed(() => [])));- if (error) yield* Queue.fail(queue, error);- yield* Queue.shutdown(queue);- });- yield* Effect.addFinalizer(() => close());- yield* budget.failed.pipe(- Effect.catchTags({ LiveStreamBufferError: close }),- Effect.forkScoped,- );- yield* source.pipe(- Stream.runForEach((value) =>- budget.retain(value).pipe(- Effect.flatMap((item) => Queue.offer(queue, item)),- Effect.uninterruptible,- ),- ),- Effect.raceFirst(budget.failed),- Effect.exit,- Effect.flatMap((exit) =>- Exit.isFailure(exit) ? Queue.failCause(queue, exit.cause) : Queue.end(queue),- ),- Effect.forkScoped({ startImmediately: true }),- );- return Stream.fromQueue(queue);+const retainLiveStream = Effect.fn("LiveStreamBudget.retainLiveStream")(function* <+ A extends object,+ E,+ R,+>(source: Stream.Stream<A, E, R>, budget: LiveStreamBudget) {+ const queue = yield* Queue.unbounded<+ RetainedLiveItem<A>,+ E | LiveStreamBufferError | Cause.Done+ >();+ let closed = false;+ const close = Effect.fn("LiveStreamBudget.close")(function* (error?: LiveStreamBufferError) {+ if (closed) return;+ closed = true;+ budget.release(yield* Queue.clear(queue).pipe(Effect.orElseSucceed(() => [])));+ if (error) yield* Queue.fail(queue, error);+ yield* Queue.shutdown(queue);});+ yield* Effect.addFinalizer(() => close());+ yield* budget.failed.pipe(Effect.catchTags({ LiveStreamBufferError: close }), Effect.forkScoped);+ yield* source.pipe(+ Stream.runForEach((value) =>+ budget.retain(value).pipe(+ Effect.flatMap((item) => Queue.offer(queue, item)),+ Effect.uninterruptible,+ ),+ ),+ Effect.raceFirst(budget.failed),+ Effect.exit,+ Effect.flatMap((exit) =>+ Exit.isFailure(exit) ? Queue.failCause(queue, exit.cause) : Queue.end(queue),+ ),+ Effect.forkScoped({ startImmediately: true }),+ );+ return Stream.fromQueue(queue);+});export const bufferLiveStream = <A extends object, E, R>(source: Stream.Stream<A, E, R>,diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 2aaa3875171..f29472aaad8 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -1886,42 +1886,44 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =END`;- const apply: ProjectionStoreV2Shape["apply"] = (event) =>- Effect.gen(function* () {- switch (event.type) {- case "thread.pull-request-link-updated": {- const thread = yield* getThread(event.threadId);- yield* apply({- ...event,- type: "thread.pull-request-synced",- payload: applyThreadPullRequestLinkUpdate(thread, event.payload),- });- break;- }- case "thread.created":- case "thread.archived":- case "thread.unarchived":- case "thread.deleted":- case "thread.settled":- case "thread.unsettled":- case "thread.snoozed":- case "thread.unsnoozed":- case "thread.auto-settle-set":- case "thread.pinned":- case "thread.unpinned":- case "thread.pin-reordered":- case "thread.active-reordered":- case "thread.visited":- case "thread.marked-unread":- case "thread.metadata-updated":- case "thread.pull-request-synced":- case "thread.runtime-mode-updated":- case "thread.interaction-mode-updated":- case "thread.model-selection-updated":- case "thread.provider-switched": {- const payloadJson = yield* encodeThreadPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ const apply: ProjectionStoreV2Shape["apply"] =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(+ function* (event) {+ switch (event.type) {+ case "thread.pull-request-link-updated": {+ const thread = yield* getThread(event.threadId);+ yield* apply({+ ...event,+ type: "thread.pull-request-synced",+ payload: applyThreadPullRequestLinkUpdate(thread, event.payload),+ });+ break;+ }+ case "thread.created":+ case "thread.archived":+ case "thread.unarchived":+ case "thread.deleted":+ case "thread.settled":+ case "thread.unsettled":+ case "thread.snoozed":+ case "thread.unsnoozed":+ case "thread.auto-settle-set":+ case "thread.pinned":+ case "thread.unpinned":+ case "thread.pin-reordered":+ case "thread.active-reordered":+ case "thread.visited":+ case "thread.marked-unread":+ case "thread.metadata-updated":+ case "thread.pull-request-synced":+ case "thread.runtime-mode-updated":+ case "thread.interaction-mode-updated":+ case "thread.model-selection-updated":+ case "thread.provider-switched": {+ const payloadJson = yield* encodeThreadPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_threads (thread_id,project_id,@@ -1967,13 +1969,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =deleted_at = excluded.deleted_at,payload_json = excluded.payload_json`;- break;- }- case "run.created":- case "run.updated": {- const payloadJson = yield* encodeRunPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "run.created":+ case "run.updated": {+ const payloadJson = yield* encodeRunPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_runs (run_id,thread_id,@@ -2013,14 +2015,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> ="$.restartCancelledBackgroundWork",)}`;- break;- }- case "run.background-work-cancelled": {- // Only this field changes, so a concurrent lifecycle write is never regressed.- const workJson = yield* encodeRestartCancelledBackgroundWork(- event.payload.restartCancelledBackgroundWork,- );- yield* sql`+ break;+ }+ case "run.background-work-cancelled": {+ // Only this field changes, so a concurrent lifecycle write is never regressed.+ const workJson = yield* encodeRestartCancelledBackgroundWork(+ event.payload.restartCancelledBackgroundWork,+ );+ yield* sql`UPDATE orchestration_v2_projection_runsSET payload_json = json_set(payload_json,@@ -2029,12 +2031,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)WHERE run_id = ${event.payload.runId} AND thread_id = ${event.threadId}`;- break;- }- case "run-attempt.created":- case "run-attempt.updated": {- const payloadJson = yield* encodeRunAttemptPayload(event.payload);- yield* sql`+ break;+ }+ case "run-attempt.created":+ case "run-attempt.updated": {+ const payloadJson = yield* encodeRunAttemptPayload(event.payload);+ yield* sql`INSERT INTO orchestration_v2_projection_run_attempts (attempt_id,thread_id,@@ -2074,12 +2076,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =status = excluded.status,payload_json = excluded.payload_json`;- break;- }- case "node.updated": {- const payloadJson = yield* encodeNodePayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "node.updated": {+ const payloadJson = yield* encodeNodePayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_nodes (node_id,thread_id,@@ -2128,12 +2130,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =completed_at = excluded.completed_at,payload_json = excluded.payload_json`;- break;- }- case "subagent.updated": {- const payloadJson = yield* encodeSubagentPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "subagent.updated": {+ const payloadJson = yield* encodeSubagentPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_subagents (subagent_id,thread_id,@@ -2197,13 +2199,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =ELSE excluded.payload_jsonEND`;- break;- }- case "provider-session.attached":- case "provider-session.updated": {- const payloadJson = yield* encodeProviderSessionPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "provider-session.attached":+ case "provider-session.updated": {+ const payloadJson = yield* encodeProviderSessionPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions (provider_session_id,thread_id,@@ -2237,29 +2239,29 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- if (event.type === "provider-session.attached") {- yield* sql`+ if (event.type === "provider-session.attached") {+ yield* sql`INSERT OR IGNORE INTO orchestration_v2_projection_provider_session_bindings (provider_session_id,thread_id)VALUES (${event.payload.id}, ${event.threadId})`;+ }+ break;}- break;- }- case "provider-session.detached": {- yield* sql`+ case "provider-session.detached": {+ yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindingsWHERE provider_session_id = ${event.payload.providerSessionId}AND thread_id = ${event.threadId}`;- break;- }- case "provider-thread.updated": {- const payloadJson = yield* encodeProviderThreadPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "provider-thread.updated": {+ const payloadJson = yield* encodeProviderThreadPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_provider_threads (provider_thread_id,thread_id,@@ -2302,26 +2304,26 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- if (- event.payload.appThreadId !== null &&- !isQueuedProviderThreadPlaceholder(event.payload)- ) {- const threadRows = yield* sql<PayloadRow>`+ if (+ event.payload.appThreadId !== null &&+ !isQueuedProviderThreadPlaceholder(event.payload)+ ) {+ const threadRows = yield* sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_threadsWHERE thread_id = ${event.payload.appThreadId}LIMIT 1`;- const threadRow = threadRows[0];- if (threadRow !== undefined) {- const thread = yield* decodeThreadPayload(threadRow.payload_json);- const updatedThread = {- ...thread,- activeProviderThreadId: event.payload.id,- updatedAt: event.payload.updatedAt,- };- const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread);- yield* sql`+ const threadRow = threadRows[0];+ if (threadRow !== undefined) {+ const thread = yield* decodeThreadPayload(threadRow.payload_json);+ const updatedThread = {+ ...thread,+ activeProviderThreadId: event.payload.id,+ updatedAt: event.payload.updatedAt,+ };+ const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread);+ yield* sql`UPDATE orchestration_v2_projection_threadsSETactive_provider_thread_id = ${event.payload.id},@@ -2329,31 +2331,31 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =payload_json = ${updatedThreadPayloadJson}WHERE thread_id = ${event.payload.appThreadId}`;+ }}+ break;}- break;- }- case "provider-turn.updated": {- const existingRows =- event.payload.tokenUsage === undefined- ? yield* sql<PayloadRow>`+ case "provider-turn.updated": {+ const existingRows =+ event.payload.tokenUsage === undefined+ ? yield* sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_provider_turnsWHERE provider_turn_id = ${event.payload.id}LIMIT 1`- : [];- const existing = existingRows[0];- const providerTurn =- existing === undefined- ? event.payload- : upsertProviderTurn(- [yield* decodeProviderTurnPayload(existing.payload_json)],- event.payload,- )[0]!;- const payloadJson = yield* encodeProviderTurnPayload(providerTurn);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ : [];+ const existing = existingRows[0];+ const providerTurn =+ existing === undefined+ ? event.payload+ : upsertProviderTurn(+ [yield* decodeProviderTurnPayload(existing.payload_json)],+ event.payload,+ )[0]!;+ const payloadJson = yield* encodeProviderTurnPayload(providerTurn);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_provider_turns (provider_turn_id,thread_id,@@ -2390,12 +2392,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =completed_at = excluded.completed_at,payload_json = excluded.payload_json`;- break;- }- case "runtime-request.updated": {- const payloadJson = yield* encodeRuntimeRequestPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "runtime-request.updated": {+ const payloadJson = yield* encodeRuntimeRequestPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_runtime_requests (runtime_request_id,thread_id,@@ -2429,12 +2431,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =resolved_at = excluded.resolved_at,payload_json = excluded.payload_json`;- break;- }- case "message.updated": {- const payloadJson = yield* encodeMessagePayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "message.updated": {+ const payloadJson = yield* encodeMessagePayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_messages (message_id,thread_id,@@ -2468,11 +2470,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- break;- }- case "plan.updated": {- const payloadJson = yield* encodePlanPayload(event.payload);- yield* sql`+ break;+ }+ case "plan.updated": {+ const payloadJson = yield* encodePlanPayload(event.payload);+ yield* sql`INSERT INTO orchestration_v2_projection_plans (plan_id,thread_id,@@ -2500,12 +2502,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =status = excluded.status,payload_json = excluded.payload_json`;- break;- }- case "turn-item.updated": {- const payloadJson = yield* encodeTurnItemPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "turn-item.updated": {+ const payloadJson = yield* encodeTurnItemPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_turn_items (turn_item_id,thread_id,@@ -2548,12 +2550,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- break;- }- case "checkpoint-scope.created": {- const payloadJson = yield* encodeCheckpointScopePayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "checkpoint-scope.created": {+ const payloadJson = yield* encodeCheckpointScopePayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_checkpoint_scopes (scope_id,thread_id,@@ -2593,12 +2595,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =created_at = excluded.created_at,payload_json = excluded.payload_json`;- break;- }- case "checkpoint.captured": {- const payloadJson = yield* encodeCheckpointPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "checkpoint.captured": {+ const payloadJson = yield* encodeCheckpointPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_checkpoints (checkpoint_id,thread_id,@@ -2638,14 +2640,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =captured_at = excluded.captured_at,payload_json = excluded.payload_json`;- break;- }- case "checkpoint.rollback-requested":- break;- case "context-handoff.updated": {- const payloadJson = yield* encodeContextHandoffPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "checkpoint.rollback-requested":+ break;+ case "context-handoff.updated": {+ const payloadJson = yield* encodeContextHandoffPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_context_handoffs (context_handoff_id,thread_id,@@ -2676,13 +2678,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- break;- }- case "context-transfer.created":- case "context-transfer.updated": {- const payloadJson = yield* encodeContextTransferPayload(event.payload);- const payload = parseEncodedPayload(payloadJson);- yield* sql`+ break;+ }+ case "context-transfer.created":+ case "context-transfer.updated": {+ const payloadJson = yield* encodeContextTransferPayload(event.payload);+ const payload = parseEncodedPayload(payloadJson);+ yield* sql`INSERT INTO orchestration_v2_projection_context_transfers (context_transfer_id,source_thread_id,@@ -2725,66 +2727,69 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updated_at = excluded.updated_at,payload_json = excluded.payload_json`;- break;+ break;+ }}- }- if (- event.type !== "thread.created" &&- event.type !== "thread.archived" &&- event.type !== "thread.unarchived" &&- event.type !== "thread.deleted" &&- event.type !== "thread.settled" &&- event.type !== "thread.unsettled" &&- event.type !== "thread.snoozed" &&- event.type !== "thread.unsnoozed" &&- event.type !== "thread.auto-settle-set" &&- event.type !== "thread.pinned" &&- event.type !== "thread.unpinned" &&- event.type !== "thread.pin-reordered" &&- event.type !== "thread.active-reordered" &&- event.type !== "thread.visited" &&- event.type !== "thread.marked-unread" &&- event.type !== "thread.metadata-updated" &&- event.type !== "thread.pull-request-synced" &&- event.type !== "thread.pull-request-link-updated" &&- event.type !== "thread.runtime-mode-updated" &&- event.type !== "thread.interaction-mode-updated" &&- event.type !== "thread.model-selection-updated" &&- event.type !== "thread.provider-switched"- ) {- const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);- yield* sql`+ if (+ event.type !== "thread.created" &&+ event.type !== "thread.archived" &&+ event.type !== "thread.unarchived" &&+ event.type !== "thread.deleted" &&+ event.type !== "thread.settled" &&+ event.type !== "thread.unsettled" &&+ event.type !== "thread.snoozed" &&+ event.type !== "thread.unsnoozed" &&+ event.type !== "thread.auto-settle-set" &&+ event.type !== "thread.pinned" &&+ event.type !== "thread.unpinned" &&+ event.type !== "thread.pin-reordered" &&+ event.type !== "thread.active-reordered" &&+ event.type !== "thread.visited" &&+ event.type !== "thread.marked-unread" &&+ event.type !== "thread.metadata-updated" &&+ event.type !== "thread.pull-request-synced" &&+ event.type !== "thread.pull-request-link-updated" &&+ event.type !== "thread.runtime-mode-updated" &&+ event.type !== "thread.interaction-mode-updated" &&+ event.type !== "thread.model-selection-updated" &&+ event.type !== "thread.provider-switched"+ ) {+ const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);+ yield* sql`UPDATE orchestration_v2_projection_threadsSETupdated_at = ${updatedAt},payload_json = json_set(payload_json, '$.updatedAt', ${updatedAt})WHERE thread_id = ${event.threadId}`;- }- }).pipe(- Effect.mapError(- (cause) =>- new ProjectionStoreApplyEventError({- eventType: event.type,- cause,- }),- ),+ }+ },+ (effect, event) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProjectionStoreApplyEventError({+ eventType: event.type,+ cause,+ }),+ ),+ ),);- const readCanonicalProjection = (- threadId: ThreadId,- window?: {- readonly rowLimit: number;- readonly userTurnLimit?: number | undefined;- readonly anchorItemId?: TurnItemId | undefined;- readonly requiredRunId?: RunId | undefined;- readonly suppressLocal?: boolean | undefined;- },- fields?: ReadonlyArray<ProjectionRecordField>,- filter?: ProjectionRecordFilter,- ) =>- Effect.gen(function* () {+ const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")(+ function* (+ threadId: ThreadId,+ window?: {+ readonly rowLimit: number;+ readonly userTurnLimit?: number | undefined;+ readonly anchorItemId?: TurnItemId | undefined;+ readonly requiredRunId?: RunId | undefined;+ readonly suppressLocal?: boolean | undefined;+ },+ fields?: ReadonlyArray<ProjectionRecordField>,+ filter?: ProjectionRecordFilter,+ ) {const threadRows = yield* sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_threads@@ -3425,18 +3430,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =updatedAt: thread.updatedAt,} satisfies OrchestrationV2ThreadProjection;return projection;- }).pipe(- Effect.mapError((cause) =>- isProjectionStoreThreadNotFoundError(cause)- ? cause- : new ProjectionStoreReadError({- threadId,- cause,- }),+ },+ (effect, threadId, _window?, _fields?, _filter?) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProjectionStoreThreadNotFoundError(cause)+ ? cause+ : new ProjectionStoreReadError({+ threadId,+ cause,+ }),+ ),),- );+ );- const readProjection = (+ const readProjection: (threadId: ThreadId,seenThreadIds: ReadonlySet<ThreadId>,window?: {@@ -3449,8 +3457,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =| { readonly threadId: ThreadId; readonly itemId: TurnItemId }| undefined;},- ): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>- Effect.gen(function* () {+ ) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> = Effect.fn(+ "ProjectionStore.readProjection",+ )(+ function* (+ threadId: ThreadId,+ seenThreadIds: ReadonlySet<ThreadId>,+ window?: {+ readonly rowLimit: number;+ readonly userTurnLimit?: number | undefined;+ readonly anchorItemId?: TurnItemId | undefined;+ readonly requiredRunId?: RunId | undefined;+ readonly suppressLocal?: boolean | undefined;+ readonly historyAnchor?:+ | { readonly threadId: ThreadId; readonly itemId: TurnItemId }+ | undefined;+ },+ ) {const localWindow =window?.suppressLocal === true ||(window?.historyAnchor !== undefined && window.historyAnchor.threadId !== threadId)@@ -3579,13 +3602,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =sourceProjection,}),};- }).pipe(- Effect.mapError((cause) =>- isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)- ? cause- : new ProjectionStoreReadError({ threadId, cause }),+ },+ (effect, threadId, _seenThreadIds, _window?) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)+ ? cause+ : new ProjectionStoreReadError({ threadId, cause }),+ ),),- );+ );const getLimitRecoveryCandidates = Effect.fn("ProjectionStore.getLimitRecoveryCandidates")(function* (options: Parameters<ProjectionStoreV2Shape["getLimitRecoveryCandidates"]>[0]) {@@ -4106,8 +4132,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =),);- const getTurnStartHistory: ProjectionStoreV2Shape["getTurnStartHistory"] = (threadId, runIds) =>- Effect.gen(function* () {+ const getTurnStartHistory: ProjectionStoreV2Shape["getTurnStartHistory"] = Effect.fn(+ "ProjectionStore.getTurnStartHistory",+ )(+ function* (threadId, runIds) {const rows = yield* sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_turn_itemsWHERE thread_id = ${threadId}@@ -4117,37 +4145,39 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =ORDER BY ordinal ASC, turn_item_id ASC`;return yield* decodeRows(decodeTurnItemPayload, threadId)(rows);- }).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));+ },+ (effect, threadId, _runIds) =>+ effect.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))),+ );const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>readProjection(threadId, new Set());- const getRuntimeRecoveryProjection: ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] = (- threadId,- ) =>- Effect.gen(function* () {- const threadRows = yield* sql<PayloadRow>`+ const getRuntimeRecoveryProjection: ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] =+ Effect.fn("ProjectionStore.getRuntimeRecoveryProjection")(+ function* (threadId) {+ const threadRows = yield* sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_threadsWHERE thread_id = ${threadId}`;- if (threadRows[0] === undefined) {- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- }- const [- thread,- runRows,- attemptRows,- nodeRows,- subagentRows,- providerSessionRows,- providerThreadRows,- providerTurnRows,- runtimeRequestRows,- messageRows,- turnItemRows,- ] = yield* Effect.all([- decodeThreadPayload(threadRows[0].payload_json),- sql<PayloadRow>`+ if (threadRows[0] === undefined) {+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ }+ const [+ thread,+ runRows,+ attemptRows,+ nodeRows,+ subagentRows,+ providerSessionRows,+ providerThreadRows,+ providerTurnRows,+ runtimeRequestRows,+ messageRows,+ turnItemRows,+ ] = yield* Effect.all([+ decodeThreadPayload(threadRows[0].payload_json),+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_runs AS runWHERE run.thread_id = ${threadId}AND (@@ -4190,7 +4220,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY run.ordinal ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT attempt.payload_jsonFROM orchestration_v2_projection_run_attempts AS attemptWHERE attempt.thread_id = ${threadId}@@ -4201,7 +4231,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY attempt.run_id ASC, attempt.attempt_ordinal ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT node.payload_json FROM orchestration_v2_projection_nodes AS nodeWHERE node.thread_id = ${threadId}AND node.status IN ('pending', 'starting', 'running', 'waiting')@@ -4232,7 +4262,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY COALESCE(node.started_at, ''), node.node_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT subagent.payload_json FROM orchestration_v2_projection_subagents AS subagentWHERE subagent.thread_id = ${threadId}AND subagent.status IN ('pending', 'starting', 'running', 'waiting')@@ -4252,7 +4282,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY COALESCE(subagent.started_at, ''), subagent.subagent_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT session.payload_jsonFROM orchestration_v2_projection_provider_sessions AS sessionWHERE (@@ -4287,7 +4317,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY session.updated_at ASC, session.provider_session_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT provider_thread.payload_jsonFROM orchestration_v2_projection_provider_threads AS provider_threadWHERE (@@ -4331,7 +4361,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY COALESCE(provider_thread.first_run_ordinal, 0), provider_thread.provider_thread_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT provider_turn.payload_jsonFROM orchestration_v2_projection_provider_turns AS provider_turnWHERE provider_turn.thread_id = ${threadId}@@ -4347,12 +4377,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY provider_turn.provider_thread_id ASC, provider_turn.ordinal ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_runtime_requestsWHERE thread_id = ${threadId} AND status = 'pending'ORDER BY created_at ASC, runtime_request_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT message.payload_json FROM orchestration_v2_projection_messages AS messageWHERE message.thread_id = ${threadId} AND message.streaming = 1AND message.run_id IN (@@ -4362,7 +4392,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY message.created_at ASC, message.message_id ASC`,- sql<PayloadRow>`+ sql<PayloadRow>`SELECT item.payload_json FROM orchestration_v2_projection_turn_items AS itemWHERE item.thread_id = ${threadId}AND item.status IN ('pending', 'running', 'waiting')@@ -4386,53 +4416,56 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)ORDER BY item.ordinal ASC, item.turn_item_id ASC`,- ]);- const [- runs,- attempts,- nodes,- subagents,- providerSessions,- providerThreads,- providerTurns,- runtimeRequests,- messages,- turnItems,- ] = yield* Effect.all([- decodeRows(decodeRunPayload, threadId)(runRows),- decodeRows(decodeRunAttemptPayload, threadId)(attemptRows),- decodeRows(decodeNodePayload, threadId)(nodeRows),- decodeRows(decodeSubagentPayload, threadId)(subagentRows),- decodeRows(decodeProviderSessionPayload, threadId)(providerSessionRows),- decodeRows(decodeProviderThreadPayload, threadId)(providerThreadRows),- decodeRows(decodeProviderTurnPayload, threadId)(providerTurnRows),- decodeRows(decodeRuntimeRequestPayload, threadId)(runtimeRequestRows),- decodeRows(decodeMessagePayload, threadId)(messageRows),- decodeRows(decodeTurnItemPayload, threadId)(turnItemRows),- ]);- return {- thread,- runs,- attempts,- nodes,- subagents,- providerSessions,- providerThreads,- providerTurns,- runtimeRequests,- messages,- turnItems,- } satisfies ProjectionRuntimeRecoveryState;- }).pipe(- Effect.mapError((cause) =>- isProjectionStoreThreadNotFoundError(cause)- ? cause- : new ProjectionStoreReadError({ threadId, cause }),- ),+ ]);+ const [+ runs,+ attempts,+ nodes,+ subagents,+ providerSessions,+ providerThreads,+ providerTurns,+ runtimeRequests,+ messages,+ turnItems,+ ] = yield* Effect.all([+ decodeRows(decodeRunPayload, threadId)(runRows),+ decodeRows(decodeRunAttemptPayload, threadId)(attemptRows),+ decodeRows(decodeNodePayload, threadId)(nodeRows),+ decodeRows(decodeSubagentPayload, threadId)(subagentRows),+ decodeRows(decodeProviderSessionPayload, threadId)(providerSessionRows),+ decodeRows(decodeProviderThreadPayload, threadId)(providerThreadRows),+ decodeRows(decodeProviderTurnPayload, threadId)(providerTurnRows),+ decodeRows(decodeRuntimeRequestPayload, threadId)(runtimeRequestRows),+ decodeRows(decodeMessagePayload, threadId)(messageRows),+ decodeRows(decodeTurnItemPayload, threadId)(turnItemRows),+ ]);+ return {+ thread,+ runs,+ attempts,+ nodes,+ subagents,+ providerSessions,+ providerThreads,+ providerTurns,+ runtimeRequests,+ messages,+ turnItems,+ } satisfies ProjectionRuntimeRecoveryState;+ },+ (effect, threadId) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProjectionStoreThreadNotFoundError(cause)+ ? cause+ : new ProjectionStoreReadError({ threadId, cause }),+ ),+ ),);- const getThread: ProjectionStoreV2Shape["getThread"] = (threadId) =>- Effect.gen(function* () {+ const getThread: ProjectionStoreV2Shape["getThread"] = Effect.fn("ProjectionStore.getThread")(+ function* (threadId) {const rows = yield* sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_threadsWHERE thread_id = ${threadId}@@ -4441,21 +4474,25 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =return yield* new ProjectionStoreThreadNotFoundError({ threadId });}return yield* decodeThreadPayload(rows[0].payload_json);- }).pipe(- Effect.mapError((cause) =>- isProjectionStoreThreadNotFoundError(cause)- ? cause- : new ProjectionStoreReadError({ threadId, cause }),+ },+ (effect, threadId) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProjectionStoreThreadNotFoundError(cause)+ ? cause+ : new ProjectionStoreReadError({ threadId, cause }),+ ),),- );+ );- const requireThread = (threadId: ThreadId) =>- Effect.gen(function* () {- const rows = yield* sql<{ readonly thread_id: string }>`+ const requireThread = Effect.fn("ProjectionStore.requireThread")(function* (+ threadId: ThreadId,+ ) {+ const rows = yield* sql<{ readonly thread_id: string }>`SELECT thread_id FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1`;- if (rows.length === 0) return yield* new ProjectionStoreThreadNotFoundError({ threadId });- });+ if (rows.length === 0) return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ });const controlReadError = (threadId: ThreadId) => (cause: unknown) =>isProjectionStoreThreadNotFoundError(cause)? cause@@ -4518,8 +4555,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =.pipe(Effect.mapError(controlReadError(threadId)));const hasUnpairedRunInterruptRequest: ProjectionStoreV2Shape["hasUnpairedRunInterruptRequest"] =- (threadId, requestId, resultId) =>- Effect.gen(function* () {+ Effect.fn("ProjectionStore.hasUnpairedRunInterruptRequest")(+ function* (threadId, requestId, resultId) {const rows = yield* sql<{ pending: number }>`SELECT EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items@@ -4530,16 +4567,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =) AS pending`;return rows[0]?.pending === 1;- }).pipe(Effect.mapError(controlReadError(threadId)));+ },+ (effect, threadId, _requestId, _resultId) =>+ effect.pipe(Effect.mapError(controlReadError(threadId))),+ );- const isNodeStored: ProjectionStoreV2Shape["isNodeStored"] = (node) =>- Effect.gen(function* () {+ const isNodeStored: ProjectionStoreV2Shape["isNodeStored"] = Effect.fn(+ "ProjectionStore.isNodeStored",+ )(+ function* (node) {const payloadJson = yield* encodeNodePayload(node);const rows = yield* sql<PayloadRow>`SELECT payload_json FROM orchestration_v2_projection_nodes WHERE node_id = ${node.id}`;return rows[0]?.payload_json === payloadJson;- }).pipe(Effect.mapError(controlReadError(node.threadId)));+ },+ (effect, node) => effect.pipe(Effect.mapError(controlReadError(node.threadId))),+ );const getRuntimeRequest: ProjectionStoreV2Shape["getRuntimeRequest"] = (threadId, requestId) =>sql@@ -5107,18 +5151,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =readonly item: TimelineIndexItem;readonly synthetic?: OrchestrationV2TurnItem;};- const readTimelineIndex = (+ const readTimelineIndex: (threadId: ThreadId,seen: ReadonlySet<ThreadId>,- ): Effect.Effect<+ ) => Effect.Effect<{readonly records: ProjectionRecords<"runs" | "attempts">;readonly local: ReadonlyArray<TimelineIndexRow>;readonly visible: ReadonlyArray<TimelineIndexRow>;},ProjectionStoreV2Error- > =>- Effect.gen(function* () {+ > = Effect.fn("ProjectionStore.readTimelineIndex")(+ function* (threadId: ThreadId, seen: ReadonlySet<ThreadId>) {const records = yield* getThreadRecords(threadId, ["runs", "attempts"]);const rows = yield* sql<{turn_item_id: string;@@ -5204,13 +5248,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =...visible,],};- }).pipe(- Effect.mapError((cause) =>- isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)- ? cause- : new ProjectionStoreReadError({ threadId, cause }),+ },+ (effect, threadId, _seen) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)+ ? cause+ : new ProjectionStoreReadError({ threadId, cause }),+ ),),- );+ );const { searchThread, searchThreadStream } = yield* makeThreadFind((threadId) =>readTimelineIndex(threadId, new Set()).pipe(Effect.map((index) => index.visible)),@@ -5720,47 +5767,46 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =return { runOrdinalsByThreadId, itemCountsByThreadId };};- const pendingBackgroundDataByThreadId = (input: {+ const pendingBackgroundDataByThreadId = Effect.fn(+ "ProjectionStore.pendingBackgroundDataByThreadId",+ )(function* (input: {readonly providerThreadRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;readonly pendingTurnItemRows: ReadonlyArray<ShellPendingTurnItemRow>;- }) =>- Effect.gen(function* () {- const providerThreadsByThreadId = new Map<- ThreadId,- Array<OrchestrationV2ThreadProjection["providerThreads"][number]>- >();- for (const row of input.providerThreadRows) {- const providerThread = yield* decodeProviderThreadPayload(row.payload_json);- const threadId =- row.thread_id.length > 0 ? ThreadId.make(row.thread_id) : providerThread.appThreadId;- if (threadId === null) {- continue;- }- const existing = providerThreadsByThreadId.get(threadId) ?? [];- existing.push(providerThread);- providerThreadsByThreadId.set(threadId, existing);+ }) {+ const providerThreadsByThreadId = new Map<+ ThreadId,+ Array<OrchestrationV2ThreadProjection["providerThreads"][number]>+ >();+ for (const row of input.providerThreadRows) {+ const providerThread = yield* decodeProviderThreadPayload(row.payload_json);+ const threadId =+ row.thread_id.length > 0 ? ThreadId.make(row.thread_id) : providerThread.appThreadId;+ if (threadId === null) {+ continue;}+ const existing = providerThreadsByThreadId.get(threadId) ?? [];+ existing.push(providerThread);+ providerThreadsByThreadId.set(threadId, existing);+ }- const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();- for (const row of input.pendingTurnItemRows) {- const turnItem = {- ...(yield* decodeTurnItemPayload(row.payload_json)),- ...(row.owning_provider_instance_id === null- ? {}- : {- owningProviderInstanceId: ProviderInstanceId.make(- row.owning_provider_instance_id,- ),- }),- };- const threadId = ThreadId.make(row.thread_id);- const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];- existing.push(turnItem);- pendingTurnItemsByThreadId.set(threadId, existing);- }+ const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();+ for (const row of input.pendingTurnItemRows) {+ const turnItem = {+ ...(yield* decodeTurnItemPayload(row.payload_json)),+ ...(row.owning_provider_instance_id === null+ ? {}+ : {+ owningProviderInstanceId: ProviderInstanceId.make(row.owning_provider_instance_id),+ }),+ };+ const threadId = ThreadId.make(row.thread_id);+ const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];+ existing.push(turnItem);+ pendingTurnItemsByThreadId.set(threadId, existing);+ }- return { providerThreadsByThreadId, pendingTurnItemsByThreadId };- });+ return { providerThreadsByThreadId, pendingTurnItemsByThreadId };+ });const getSettlementCandidates: ProjectionStoreV2Shape["getSettlementCandidates"] = (threadId) =>sql@@ -5874,11 +5920,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));- const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = (- threadId,- ) =>- Effect.gen(function* () {- const rows = yield* sql<PayloadRow>`+ const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] =+ Effect.fn("ProjectionStore.getThreadsWithPullRequests")(+ function* (threadId) {+ const rows = yield* sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_threadsWHERE deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND thread_id = ${threadId}`}@@ -5886,19 +5931,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =AND json_array_length(payload_json, '$.pullRequests') > 0ORDER BY updated_at ASC, thread_id ASC`;- return yield* Effect.forEach(rows, (row) =>- decodeThreadPayload(row.payload_json).pipe(- Effect.map((thread): ProjectionThreadPullRequests => ({- id: thread.id,- projectId: thread.projectId,- lineage: thread.lineage,- settledOverride: thread.settledOverride,- settledAt: thread.settledAt,- pullRequests: thread.pullRequests ?? [],- })),- ),- );- }).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));+ return yield* Effect.forEach(rows, (row) =>+ decodeThreadPayload(row.payload_json).pipe(+ Effect.map((thread): ProjectionThreadPullRequests => ({+ id: thread.id,+ projectId: thread.projectId,+ lineage: thread.lineage,+ settledOverride: thread.settledOverride,+ settledAt: thread.settledAt,+ pullRequests: thread.pullRequests ?? [],+ })),+ ),+ );+ },+ Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),+ );const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = (options) =>sql<{ readonly thread_id: string; readonly worktree_path: string }>`@@ -5917,20 +5964,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),);- const shellThreadStateFromRow = (input: {- readonly row: ShellThreadRow;- readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;- readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;- readonly providerThreadsByThreadId: ReadonlyMap<- ThreadId,- ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>- >;- readonly pendingTurnItemsByThreadId: ReadonlyMap<- ThreadId,- ReadonlyArray<OrchestrationV2TurnItem>- >;- }) =>- Effect.gen(function* () {+ const shellThreadStateFromRow =+ /* Runs once per shell row; the enclosing snapshot or thread read owns the span. */+ Effect.fnUntraced(function* (input: {+ readonly row: ShellThreadRow;+ readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;+ readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;+ readonly providerThreadsByThreadId: ReadonlyMap<+ ThreadId,+ ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>+ >;+ readonly pendingTurnItemsByThreadId: ReadonlyMap<+ ThreadId,+ ReadonlyArray<OrchestrationV2TurnItem>+ >;+ }) {const {row,runOrdinalsByThreadId,@@ -6069,62 +6117,61 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const shellSnapshotReadError = (cause: unknown) =>new ProjectionStoreReadError({ threadId: ThreadId.make("thread:shell"), cause });- const readShellSnapshotRows = (options: ShellSnapshotOptions | undefined) =>- Effect.gen(function* () {- const targetThreadRows = yield* selectShellThreadRows(undefined, options);- const targetThreadIds = new Set(- targetThreadRows.map((row) => ThreadId.make(row.thread_id)),- );- const rowsByThreadId = new Map(- targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const),- );- const pendingSourceIds = targetThreadRows.flatMap((row) =>- row.forked_from_run_source_thread_id === null- ? []- : [ThreadId.make(row.forked_from_run_source_thread_id)],- );- while (pendingSourceIds.length > 0) {- const sourceId = pendingSourceIds.pop();- if (sourceId === undefined || rowsByThreadId.has(sourceId)) continue;- const source = (yield* selectShellThreadRows(sourceId))[0];- if (source === undefined) continue;- rowsByThreadId.set(sourceId, source);- if (source.forked_from_run_source_thread_id !== null) {- pendingSourceIds.push(ThreadId.make(source.forked_from_run_source_thread_id));- }+ const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* (+ options: ShellSnapshotOptions | undefined,+ ) {+ const targetThreadRows = yield* selectShellThreadRows(undefined, options);+ const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id)));+ const rowsByThreadId = new Map(+ targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const),+ );+ const pendingSourceIds = targetThreadRows.flatMap((row) =>+ row.forked_from_run_source_thread_id === null+ ? []+ : [ThreadId.make(row.forked_from_run_source_thread_id)],+ );+ while (pendingSourceIds.length > 0) {+ const sourceId = pendingSourceIds.pop();+ if (sourceId === undefined || rowsByThreadId.has(sourceId)) continue;+ const source = (yield* selectShellThreadRows(sourceId))[0];+ if (source === undefined) continue;+ rowsByThreadId.set(sourceId, source);+ if (source.forked_from_run_source_thread_id !== null) {+ pendingSourceIds.push(ThreadId.make(source.forked_from_run_source_thread_id));}- const threadRows = [...rowsByThreadId.values()];- const threadIds = [...rowsByThreadId.keys()];- const forkSourceIds = shellForkSourceIds(threadRows);- const readForThreadIds = <A>(- read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,- ids: ReadonlyArray<ThreadId> = threadIds,- ) => (ids.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : read(ids));- const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] =- yield* Effect.all([- readForThreadIds(selectShellRunRows, forkSourceIds),- readForThreadIds(selectShellRunItemCounts, forkSourceIds),- sql<{ readonly snapshot_sequence: number | null }>`+ }+ const threadRows = [...rowsByThreadId.values()];+ const threadIds = [...rowsByThreadId.keys()];+ const forkSourceIds = shellForkSourceIds(threadRows);+ const readForThreadIds = <A>(+ read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,+ ids: ReadonlyArray<ThreadId> = threadIds,+ ) => (ids.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : read(ids));+ const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] =+ yield* Effect.all([+ readForThreadIds(selectShellRunRows, forkSourceIds),+ readForThreadIds(selectShellRunItemCounts, forkSourceIds),+ sql<{ readonly snapshot_sequence: number | null }>`SELECT MAX(sequence) AS snapshot_sequenceFROM orchestration_eventsWHERE application_event_version = 2AND aggregate_kind = 'thread'`,- readForThreadIds(selectShellProviderThreadRows),- readForThreadIds(selectShellPendingTurnItemRows),- ]);- return {- targetThreadIds,- threadRows,- runRows,- itemCountRows,- sequenceRows,- providerThreadRows,- pendingTurnItemRows,- };- });+ readForThreadIds(selectShellProviderThreadRows),+ readForThreadIds(selectShellPendingTurnItemRows),+ ]);+ return {+ targetThreadIds,+ threadRows,+ runRows,+ itemCountRows,+ sequenceRows,+ providerThreadRows,+ pendingTurnItemRows,+ };+ });- const decodeShellSnapshot = ({+ const decodeShellSnapshot = Effect.fn("ProjectionStore.decodeShellSnapshot")(function* ({targetThreadIds,threadRows,runRows,@@ -6132,44 +6179,43 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =sequenceRows,providerThreadRows,pendingTurnItemRows,- }: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) =>- Effect.gen(function* () {- const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({- runRows,- itemCountRows,- });- const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =- yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });- const states = yield* Effect.forEach(threadRows, (row) =>- shellThreadStateFromRow({- row,- runOrdinalsByThreadId,- itemCountsByThreadId,- providerThreadsByThreadId,- pendingTurnItemsByThreadId,+ }: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) {+ const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({+ runRows,+ itemCountRows,+ });+ const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =+ yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });+ const states = yield* Effect.forEach(threadRows, (row) =>+ shellThreadStateFromRow({+ row,+ runOrdinalsByThreadId,+ itemCountsByThreadId,+ providerThreadsByThreadId,+ pendingTurnItemsByThreadId,+ }),+ );+ const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));++ const shells = states+ .filter((state) => targetThreadIds.has(state.thread.id))+ .map((state) =>+ shellFromState({+ state,+ visibleItemCount: visibleItemCountForShell({+ threadId: state.thread.id,+ statesByThreadId,+ }),}),);- const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));- const shells = states- .filter((state) => targetThreadIds.has(state.thread.id))- .map((state) =>- shellFromState({- state,- visibleItemCount: visibleItemCountForShell({- threadId: state.thread.id,- statesByThreadId,- }),- }),- );-- return {- schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,- snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,- threads: shells.filter((thread) => thread.archivedAt === null),- archivedThreads: shells.filter((thread) => thread.archivedAt !== null),- };- }).pipe(Effect.mapError(shellSnapshotReadError));+ return {+ schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,+ snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,+ threads: shells.filter((thread) => thread.archivedAt === null),+ archivedThreads: shells.filter((thread) => thread.archivedAt !== null),+ };+ }, Effect.mapError(shellSnapshotReadError));const readShellSnapshot: ProjectionStoreV2Shape["readShellSnapshot"] = (options) =>readShellSnapshotRows(options).pipe(@@ -6301,8 +6347,9 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(const sequence = yield* Ref.make(0);const service: ProjectionStoreV2Shape = {- apply: (event) =>- Effect.gen(function* () {+ apply:+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (event) {const result = yield* Ref.modify(replayState, (existing) => {const next: ProjectionReplayState = {projections: new Map(existing.projections),@@ -6323,65 +6370,62 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(}yield* Ref.update(sequence, (current) => current + 1);}),- getShellSnapshot: (options) =>- Effect.gen(function* () {- const existing = (yield* Ref.get(replayState)).projections;- const selectedThreadIds = [...existing.entries()]- .filter(([, projection]) => {- if (- options?.projectId !== undefined &&- projection.thread.projectId !== options.projectId- ) {- return false;- }- if (- options?.unsettledOnly &&- (projection.thread.settledAt !== null ||- projection.thread.settledOverride === "settled")- ) {- return false;- }- if (options?.location === "active") return projection.thread.archivedAt === null;- if (options?.location === "archive") return projection.thread.archivedAt !== null;- return true;- })- .map(([threadId]) => threadId);- const shells = yield* Effect.forEach(- selectedThreadIds.toSorted((left, right) => String(left).localeCompare(String(right))),- (threadId) =>- service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),- );- const visible = shells.filter((thread) => thread.deletedAt === null);- return {- schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,- snapshotSequence: yield* Ref.get(sequence),- threads: visible.filter((thread) => thread.archivedAt === null),- archivedThreads: visible.filter((thread) => thread.archivedAt !== null),- };- }),+ getShellSnapshot: Effect.fn("ProjectionStore.getShellSnapshot")(function* (options) {+ const existing = (yield* Ref.get(replayState)).projections;+ const selectedThreadIds = [...existing.entries()]+ .filter(([, projection]) => {+ if (+ options?.projectId !== undefined &&+ projection.thread.projectId !== options.projectId+ ) {+ return false;+ }+ if (+ options?.unsettledOnly &&+ (projection.thread.settledAt !== null ||+ projection.thread.settledOverride === "settled")+ ) {+ return false;+ }+ if (options?.location === "active") return projection.thread.archivedAt === null;+ if (options?.location === "archive") return projection.thread.archivedAt !== null;+ return true;+ })+ .map(([threadId]) => threadId);+ const shells = yield* Effect.forEach(+ selectedThreadIds.toSorted((left, right) => String(left).localeCompare(String(right))),+ (threadId) =>+ service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),+ );+ const visible = shells.filter((thread) => thread.deletedAt === null);+ return {+ schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,+ snapshotSequence: yield* Ref.get(sequence),+ threads: visible.filter((thread) => thread.archivedAt === null),+ archivedThreads: visible.filter((thread) => thread.archivedAt !== null),+ };+ }),readShellSnapshot: (options) =>service.getShellSnapshot(options).pipe(Effect.map(Effect.succeed)),- getThreadShell: (threadId) =>- Effect.gen(function* () {- const existing = (yield* Ref.get(replayState)).projections;- if (!existing.has(threadId)) {- return null;- }- const shell = yield* service- .getThreadProjection(threadId)- .pipe(Effect.map(threadShellFromProjection));- return shell.deletedAt === null ? shell : null;- }),- getThread: (threadId) =>- Effect.gen(function* () {- const projection = (yield* Ref.get(replayState)).projections.get(threadId);- if (projection === undefined) {- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- }- return projection.thread;- }),- getSettlementCandidates: (threadId) =>- Effect.gen(function* () {+ getThreadShell: Effect.fn("ProjectionStore.getThreadShell")(function* (threadId) {+ const existing = (yield* Ref.get(replayState)).projections;+ if (!existing.has(threadId)) {+ return null;+ }+ const shell = yield* service+ .getThreadProjection(threadId)+ .pipe(Effect.map(threadShellFromProjection));+ return shell.deletedAt === null ? shell : null;+ }),+ getThread: Effect.fn("ProjectionStore.getThread")(function* (threadId) {+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);+ if (projection === undefined) {+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ }+ return projection.thread;+ }),+ getSettlementCandidates: Effect.fn("ProjectionStore.getSettlementCandidates")(+ function* (threadId) {const projections = (yield* Ref.get(replayState)).projections;return [...projections.values()].filter(@@ -6408,7 +6452,8 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(DateTime.toEpochMillis(left.updatedAt) - DateTime.toEpochMillis(right.updatedAt) ||left.id.localeCompare(right.id),);- }),+ },+ ),getThreadWorktreePaths: (options) =>Ref.get(replayState).pipe(Effect.map((state) =>@@ -6490,30 +6535,29 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(.toSorted((left, right) => left.id.localeCompare(right.id)),),),- getRecoveryThreadIds: (kind) =>- Effect.gen(function* () {- const projections = (yield* Ref.get(replayState)).projections;- return [...projections.values()]- .filter((projection) =>- needsRecovery(- projection,- kind,- projection.thread.lineage.parentThreadId === null- ? undefined- : projections.get(projection.thread.lineage.parentThreadId),- ),- )- .toSorted(- (left, right) =>- DateTime.toEpochMillis(left.thread.updatedAt) -- DateTime.toEpochMillis(right.thread.updatedAt) ||- left.thread.id.localeCompare(right.thread.id),- )- .map((projection) => projection.thread.id);- }),+ getRecoveryThreadIds: Effect.fn("ProjectionStore.getRecoveryThreadIds")(function* (kind) {+ const projections = (yield* Ref.get(replayState)).projections;+ return [...projections.values()]+ .filter((projection) =>+ needsRecovery(+ projection,+ kind,+ projection.thread.lineage.parentThreadId === null+ ? undefined+ : projections.get(projection.thread.lineage.parentThreadId),+ ),+ )+ .toSorted(+ (left, right) =>+ DateTime.toEpochMillis(left.thread.updatedAt) -+ DateTime.toEpochMillis(right.thread.updatedAt) ||+ left.thread.id.localeCompare(right.thread.id),+ )+ .map((projection) => projection.thread.id);+ }),getUnreadableThreadIds: () => Effect.succeed([]),- getPendingNativeUserInputs: (threadId, providerTurnId) =>- Effect.gen(function* () {+ getPendingNativeUserInputs: Effect.fn("ProjectionStore.getPendingNativeUserInputs")(+ function* (threadId, providerTurnId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined) return { runtimeRequests: [], nodes: [], turnItems: [] };const runtimeRequests = projection.runtimeRequests.filter(@@ -6532,23 +6576,24 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect((item) => item.type === "user_input_request" && requestIds.has(item.requestId),),};- }),- getPlan: (threadId, planId) =>- Effect.gen(function* () {- const projection = (yield* Ref.get(replayState)).projections.get(threadId);- if (projection === undefined)- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- return projection.plans.find((plan) => plan.id === planId);- }),- hasUnpairedRunInterruptRequest: (threadId, requestId, resultId) =>- Effect.gen(function* () {+ },+ ),+ getPlan: Effect.fn("ProjectionStore.getPlan")(function* (threadId, planId) {+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);+ if (projection === undefined)+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ return projection.plans.find((plan) => plan.id === planId);+ }),+ hasUnpairedRunInterruptRequest: Effect.fn("ProjectionStore.hasUnpairedRunInterruptRequest")(+ function* (threadId, requestId, resultId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);return (projection !== undefined &&projection.turnItems.some((item) => item.id === requestId) &&!projection.turnItems.some((item) => item.id === resultId));- }),+ },+ ),isNodeStored: (node) =>Ref.get(replayState).pipe(Effect.map((state) => {@@ -6594,8 +6639,8 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(]),]),),- getThreadRecords: (threadId, fields, filter) =>- Effect.gen(function* () {+ getThreadRecords: Effect.fn("ProjectionStore.getThreadRecords")(+ function* (threadId, fields, filter) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6630,16 +6675,18 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(["thread", projection.thread],...fields.map((field) => [field, selected[field]]),]) as ProjectionRecords<(typeof fields)[number]>;- }),- getRuntimeRequest: (threadId, requestId) =>- Effect.gen(function* () {+ },+ ),+ getRuntimeRequest: Effect.fn("ProjectionStore.getRuntimeRequest")(+ function* (threadId, requestId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });return projection.runtimeRequests.find((request) => request.id === requestId);- }),- getProviderControlContext: (threadId, target) =>- Effect.gen(function* () {+ },+ ),+ getProviderControlContext: Effect.fn("ProjectionStore.getProviderControlContext")(+ function* (threadId, target) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6664,9 +6711,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(? undefined: projection.runs.find((run) => run.activeAttemptId === providerTurn.runAttemptId),};- }),- getRunningTurnContext: (threadId) =>- Effect.gen(function* () {+ },+ ),+ getRunningTurnContext: Effect.fn("ProjectionStore.getRunningTurnContext")(+ function* (threadId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6684,9 +6732,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(turn.status === "running",),};- }),- getThreadProviderContext: (threadId, targetInstanceId) =>- Effect.gen(function* () {+ },+ ),+ getThreadProviderContext: Effect.fn("ProjectionStore.getThreadProviderContext")(+ function* (threadId, targetInstanceId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6714,9 +6763,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(thread.id === target?.id,),};- }),- getRuntimeResponseContext: (threadId, requestId) =>- Effect.gen(function* () {+ },+ ),+ getRuntimeResponseContext: Effect.fn("ProjectionStore.getRuntimeResponseContext")(+ function* (threadId, requestId) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6736,35 +6786,35 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(session.id === request.responseCapability.providerSessionId,),};- }),- getCheckpointContext: (threadId) =>- Effect.gen(function* () {- const projection = (yield* Ref.get(replayState)).projections.get(threadId);- if (projection === undefined) {- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- }- return {- runs: projection.runs.map(({ id, ordinal, status }) => ({ id, ordinal, status })),- checkpointScopes: projection.checkpointScopes.map(({ id, runId, kind, cwd }) => ({- id,+ },+ ),+ getCheckpointContext: Effect.fn("ProjectionStore.getCheckpointContext")(function* (threadId) {+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);+ if (projection === undefined) {+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ }+ return {+ runs: projection.runs.map(({ id, ordinal, status }) => ({ id, ordinal, status })),+ checkpointScopes: projection.checkpointScopes.map(({ id, runId, kind, cwd }) => ({+ id,+ runId,+ kind,+ cwd,+ })),+ checkpoints: projection.checkpoints.map(+ ({ scopeId, runId, ordinalWithinScope, appRunOrdinal, status, ref }) => ({+ scopeId,runId,- kind,- cwd,- })),- checkpoints: projection.checkpoints.map(- ({ scopeId, runId, ordinalWithinScope, appRunOrdinal, status, ref }) => ({- scopeId,- runId,- ordinalWithinScope,- appRunOrdinal,- status,- ref,- }),- ),- };- }),- getCheckpointCaptureContext: (threadId, target) =>- Effect.gen(function* () {+ ordinalWithinScope,+ appRunOrdinal,+ status,+ ref,+ }),+ ),+ };+ }),+ getCheckpointCaptureContext: Effect.fn("ProjectionStore.getCheckpointCaptureContext")(+ function* (threadId, target) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6782,9 +6832,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect().map((candidate) => candidate.ordinalWithinScope),};- }),- getCheckpointRollbackContext: (threadId, target) =>- Effect.gen(function* () {+ },+ ),+ getCheckpointRollbackContext: Effect.fn("ProjectionStore.getCheckpointRollbackContext")(+ function* (threadId, target) {const projection = (yield* Ref.get(replayState)).projections.get(threadId);if (projection === undefined)return yield* new ProjectionStoreThreadNotFoundError({ threadId });@@ -6868,77 +6919,75 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(candidate.status === "ready",),};- }),- getRunMessage: (threadId, runId) =>- Effect.gen(function* () {- const projection = (yield* Ref.get(replayState)).projections.get(threadId);- if (projection === undefined)- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- const run = projection.runs.find((candidate) => candidate.id === runId);- return projection.messages.find((message) => message.id === run?.userMessageId);- }),- canStartQueuedRun: (threadId) =>- Effect.gen(function* () {- const projection = (yield* Ref.get(replayState)).projections.get(threadId);- if (projection === undefined)- return yield* new ProjectionStoreThreadNotFoundError({ threadId });- return (- projection.thread.archivedAt === null &&- projection.thread.deletedAt === null &&- projection.runs.some((run) => run.status === "queued") &&- !projection.runs.some(- (run) =>- run.status === "preparing" ||- run.status === "starting" ||- run.status === "running" ||- run.status === "waiting" ||- (run.status === "queued" && run.queueHeld === true),- )- );- }),- getThreadProjection: (threadId) =>- Effect.gen(function* () {- const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);- const readProjection = (- targetThreadId: ThreadId,- seenThreadIds: ReadonlySet<ThreadId>,- ): OrchestrationV2ThreadProjection | null => {- const projection = existing.get(targetThreadId);- if (!projection) {- return null;- }- const forkedFrom = projection.thread.forkedFrom;- if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {- return withLocalVisibleTurnItems(projection);- }- const sourceProjection = readProjection(- forkedFrom.threadId,- new Set([...seenThreadIds, targetThreadId]),- );- return {- ...projection,- visibleTurnItems: buildVisibleTurnItems({- projection,- sourceProjection,- }),- };- };- const projection = readProjection(threadId, new Set());+ },+ ),+ getRunMessage: Effect.fn("ProjectionStore.getRunMessage")(function* (threadId, runId) {+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);+ if (projection === undefined)+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ const run = projection.runs.find((candidate) => candidate.id === runId);+ return projection.messages.find((message) => message.id === run?.userMessageId);+ }),+ canStartQueuedRun: Effect.fn("ProjectionStore.canStartQueuedRun")(function* (threadId) {+ const projection = (yield* Ref.get(replayState)).projections.get(threadId);+ if (projection === undefined)+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ return (+ projection.thread.archivedAt === null &&+ projection.thread.deletedAt === null &&+ projection.runs.some((run) => run.status === "queued") &&+ !projection.runs.some(+ (run) =>+ run.status === "preparing" ||+ run.status === "starting" ||+ run.status === "running" ||+ run.status === "waiting" ||+ (run.status === "queued" && run.queueHeld === true),+ )+ );+ }),+ getThreadProjection: Effect.fn("ProjectionStore.getThreadProjection")(function* (threadId) {+ const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);+ const readProjection = (+ targetThreadId: ThreadId,+ seenThreadIds: ReadonlySet<ThreadId>,+ ): OrchestrationV2ThreadProjection | null => {+ const projection = existing.get(targetThreadId);if (!projection) {- return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ return null;+ }+ const forkedFrom = projection.thread.forkedFrom;+ if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {+ return withLocalVisibleTurnItems(projection);}- // Match the SQL shell join, including provider threads stored on child app threads.+ const sourceProjection = readProjection(+ forkedFrom.threadId,+ new Set([...seenThreadIds, targetThreadId]),+ );return {...projection,- turnItems: projection.turnItems.map((item) => {- const owner =- item.type !== "subagent" || item.providerThreadId === null- ? undefined- : providerThreadInstanceIds.get(item.providerThreadId);- return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };+ visibleTurnItems: buildVisibleTurnItems({+ projection,+ sourceProjection,}),};- }),+ };+ const projection = readProjection(threadId, new Set());+ if (!projection) {+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ }+ // Match the SQL shell join, including provider threads stored on child app threads.+ return {+ ...projection,+ turnItems: projection.turnItems.map((item) => {+ const owner =+ item.type !== "subagent" || item.providerThreadId === null+ ? undefined+ : providerThreadInstanceIds.get(item.providerThreadId);+ return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };+ }),+ };+ }),getTurnStartContext: (threadId, runId) =>service.getThreadProjection(threadId).pipe(Effect.map((projection) => ({diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.tsindex 7dd397ecf54..ac63f639178 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts@@ -310,18 +310,19 @@ export const layer: Layer.Layer<const agentScope = yield* AgentScope;const completedTurnAnalytics = new Set<string>();- const makeDomainEvent = (- input: ProviderEventIngestInput,- payloadInput: {- readonly type: OrchestrationV2DomainEvent["type"];- readonly payload: OrchestrationV2DomainEvent["payload"];- readonly threadId?: ThreadId;- readonly runId?: RunId | null;- readonly nodeId?: NodeId | null;- readonly occurredAt?: DateTime.Utc;- },- ) =>- Effect.gen(function* () {+ const makeDomainEvent =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(function* (+ input: ProviderEventIngestInput,+ payloadInput: {+ readonly type: OrchestrationV2DomainEvent["type"];+ readonly payload: OrchestrationV2DomainEvent["payload"];+ readonly threadId?: ThreadId;+ readonly runId?: RunId | null;+ readonly nodeId?: NodeId | null;+ readonly occurredAt?: DateTime.Utc;+ },+ ) {const threadId = payloadInput.threadId ?? input.threadId;const eventId = yield* idAllocator.allocate.event({threadId,@@ -517,339 +518,352 @@ export const layer: Layer.Layer<return events;});- const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>- Effect.gen(function* () {- switch (input.event.type) {- case "app_thread.created": {- const offered = input.event.appThread;- const existing = yield* projections.getThread(offered.id).pipe(- Effect.catchTags({- ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),- }),- );- if (- existing !== null &&- existing.title === offered.title &&- modelSelectionsEqual(existing.modelSelection, offered.modelSelection)- )- return [];- const now = yield* DateTime.now;- return [- yield* makeDomainEvent(input, {- type: existing === null ? "thread.created" : "thread.metadata-updated",- threadId: offered.id,- payload:- existing === null- ? offered- : {- ...existing,- title: offered.title,- modelSelection: offered.modelSelection,- updatedAt: now,- },- occurredAt: now,- }),- ];- }- case "provider_session.updated":- return [- yield* makeDomainEvent(input, {- type: "provider-session.updated",- payload: input.event.providerSession,- }),- ];- case "provider_thread.updated": {- const threadId = input.event.providerThread.appThreadId ?? input.threadId;- const updated = yield* makeDomainEvent(input, {- type: "provider-thread.updated",- threadId,- payload: input.event.providerThread,- });- return input.event.retainedNativeTurnIds === undefined- ? [updated]- : [- updated,- ...(yield* rollBackRewoundRuns(input, {- threadId,- providerThreadId: input.event.providerThread.id,- retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),- })),- ];- }- case "provider_turn.updated":- return [- ...(["completed", "interrupted", "failed", "cancelled"].includes(- input.event.providerTurn.status,+ const normalize: ProviderEventIngestorV2Shape["normalize"] =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(+ function* (input) {+ switch (input.event.type) {+ case "app_thread.created": {+ const offered = input.event.appThread;+ const existing = yield* projections.getThread(offered.id).pipe(+ Effect.catchTags({+ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),+ }),+ );+ if (+ existing !== null &&+ existing.title === offered.title &&+ modelSelectionsEqual(existing.modelSelection, offered.modelSelection))- ? yield* dismissNativeUserInputs(- input,- input.event.providerTurn.id,- input.event.threadId,- )- : []),- yield* makeDomainEvent(input, {- type: "provider-turn.updated",- ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),- payload: input.event.providerTurn,- nodeId: input.event.providerTurn.nodeId,- }),- ];- case "node.updated":- // Adapters send an unchanged node again with each text delta. Compare with the- // stored node, not the last one sent, because the server also writes nodes.- if (yield* projections.isNodeStored(input.event.node)) return [];- return [- yield* makeDomainEvent(input, {- type: "node.updated",- threadId: input.event.node.threadId,- payload: input.event.node,- runId: input.event.node.runId,- nodeId: input.event.node.id,- }),- ];- case "subagent.updated":- return [- yield* makeDomainEvent(input, {- type: "subagent.updated",- threadId: input.event.subagent.threadId,- payload: input.event.subagent,- runId: input.event.subagent.runId,- nodeId: input.event.subagent.id,- }),- ];- case "message.updated":- return [- yield* makeDomainEvent(input, {- type: "message.updated",- threadId: input.event.message.threadId,- payload: input.event.message,- runId: input.event.message.runId,- nodeId: input.event.message.nodeId,- }),- ];- case "turn_item.updated":- return [- yield* makeDomainEvent(input, {- type: "turn-item.updated",- threadId: input.event.turnItem.threadId,- payload: boundFileChangeForStorage(- stripUnservedToolOutputImageBytes(input.event.turnItem),- ),- runId: input.event.turnItem.runId,- nodeId: input.event.turnItem.nodeId,- }),- ];- case "runtime_request.updated":- return [- yield* makeDomainEvent(input, {- type: "runtime-request.updated",- ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),- payload: input.event.runtimeRequest,- nodeId: input.event.runtimeRequest.nodeId,- }),- ];- case "plan.updated": {- const occurredAt = yield* DateTime.now;- const plan = input.event.plan;- const previous =- plan.kind === "todo_list"- ? yield* projections.getPlan(plan.threadId, plan.id)- : undefined;- const payload =- plan.kind === "todo_list"- ? withPlanStepDurations(- plan,- previous?.kind === "todo_list" ? previous : undefined,+ return [];+ const now = yield* DateTime.now;+ return [+ yield* makeDomainEvent(input, {+ type: existing === null ? "thread.created" : "thread.metadata-updated",+ threadId: offered.id,+ payload:+ existing === null+ ? offered+ : {+ ...existing,+ title: offered.title,+ modelSelection: offered.modelSelection,+ updatedAt: now,+ },+ occurredAt: now,+ }),+ ];+ }+ case "provider_session.updated":+ return [+ yield* makeDomainEvent(input, {+ type: "provider-session.updated",+ payload: input.event.providerSession,+ }),+ ];+ case "provider_thread.updated": {+ const threadId = input.event.providerThread.appThreadId ?? input.threadId;+ const updated = yield* makeDomainEvent(input, {+ type: "provider-thread.updated",+ threadId,+ payload: input.event.providerThread,+ });+ return input.event.retainedNativeTurnIds === undefined+ ? [updated]+ : [+ updated,+ ...(yield* rollBackRewoundRuns(input, {+ threadId,+ providerThreadId: input.event.providerThread.id,+ retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),+ })),+ ];+ }+ case "provider_turn.updated":+ return [+ ...(["completed", "interrupted", "failed", "cancelled"].includes(+ input.event.providerTurn.status,+ )+ ? yield* dismissNativeUserInputs(+ input,+ input.event.providerTurn.id,+ input.event.threadId,+ )+ : []),+ yield* makeDomainEvent(input, {+ type: "provider-turn.updated",+ ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),+ payload: input.event.providerTurn,+ nodeId: input.event.providerTurn.nodeId,+ }),+ ];+ case "node.updated":+ // Adapters send an unchanged node again with each text delta. Compare with the+ // stored node, not the last one sent, because the server also writes nodes.+ if (yield* projections.isNodeStored(input.event.node)) return [];+ return [+ yield* makeDomainEvent(input, {+ type: "node.updated",+ threadId: input.event.node.threadId,+ payload: input.event.node,+ runId: input.event.node.runId,+ nodeId: input.event.node.id,+ }),+ ];+ case "subagent.updated":+ return [+ yield* makeDomainEvent(input, {+ type: "subagent.updated",+ threadId: input.event.subagent.threadId,+ payload: input.event.subagent,+ runId: input.event.subagent.runId,+ nodeId: input.event.subagent.id,+ }),+ ];+ case "message.updated":+ return [+ yield* makeDomainEvent(input, {+ type: "message.updated",+ threadId: input.event.message.threadId,+ payload: input.event.message,+ runId: input.event.message.runId,+ nodeId: input.event.message.nodeId,+ }),+ ];+ case "turn_item.updated":+ return [+ yield* makeDomainEvent(input, {+ type: "turn-item.updated",+ threadId: input.event.turnItem.threadId,+ payload: boundFileChangeForStorage(+ stripUnservedToolOutputImageBytes(input.event.turnItem),+ ),+ runId: input.event.turnItem.runId,+ nodeId: input.event.turnItem.nodeId,+ }),+ ];+ case "runtime_request.updated":+ return [+ yield* makeDomainEvent(input, {+ type: "runtime-request.updated",+ ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),+ payload: input.event.runtimeRequest,+ nodeId: input.event.runtimeRequest.nodeId,+ }),+ ];+ case "plan.updated": {+ const occurredAt = yield* DateTime.now;+ const plan = input.event.plan;+ const previous =+ plan.kind === "todo_list"+ ? yield* projections.getPlan(plan.threadId, plan.id)+ : undefined;+ const payload =+ plan.kind === "todo_list"+ ? withPlanStepDurations(+ plan,+ previous?.kind === "todo_list" ? previous : undefined,+ occurredAt,+ )+ : plan;+ return [+ yield* makeDomainEvent(input, {+ type: "plan.updated",+ threadId: plan.threadId,+ payload,+ runId: plan.runId,+ nodeId: plan.nodeId,+ occurredAt,+ }),+ ];+ }+ case "command_output.delta":+ // Live output is routed to the command output hub before ingestion.+ return [];+ case "turn.terminal":+ const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);+ if (input.event.status !== "failed") {+ return dismissed;+ }+ const occurredAt = yield* DateTime.now;+ const failure = (yield* agentScope.oomKilled(input.threadId))+ ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }+ : input.event.failure;+ return [+ ...dismissed,+ yield* makeDomainEvent(input, {+ type: "turn-item.updated",+ payload: makeProviderFailureTurnItem({+ driver: input.event.driver,+ threadId: input.threadId,+ runId: input.runId ?? null,+ nodeId: input.nodeId ?? null,+ providerThreadId: input.event.providerThreadId,+ providerTurnId: input.event.providerTurnId,+ itemOrdinal: input.event.failureItemOrdinal,+ failure,+ ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),+ ...(input.event.retryStartedAt === undefined+ ? {}+ : { retryStartedAt: input.event.retryStartedAt }),occurredAt,- )- : plan;- return [- yield* makeDomainEvent(input, {- type: "plan.updated",- threadId: plan.threadId,- payload,- runId: plan.runId,- nodeId: plan.nodeId,- occurredAt,- }),- ];+ }),+ }),+ ];}- case "command_output.delta":- // Live output is routed to the command output hub before ingestion.- return [];- case "turn.terminal":- const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);- if (input.event.status !== "failed") {- return dismissed;- }- const occurredAt = yield* DateTime.now;- const failure = (yield* agentScope.oomKilled(input.threadId))- ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }- : input.event.failure;- return [- ...dismissed,- yield* makeDomainEvent(input, {- type: "turn-item.updated",- payload: makeProviderFailureTurnItem({- driver: input.event.driver,+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderEventNormalizeError({+ providerSessionId: input.providerSessionId,threadId: input.threadId,- runId: input.runId ?? null,- nodeId: input.nodeId ?? null,- providerThreadId: input.event.providerThreadId,- providerTurnId: input.event.providerTurnId,- itemOrdinal: input.event.failureItemOrdinal,- failure,- ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),- ...(input.event.retryStartedAt === undefined- ? {}- : { retryStartedAt: input.event.retryStartedAt }),- occurredAt,+ providerEvent: input.event,+ cause,}),- }),- ];- }- }).pipe(- Effect.mapError(- (cause) =>- new ProviderEventNormalizeError({- providerSessionId: input.providerSessionId,- threadId: input.threadId,- providerEvent: input.event,- cause,- }),- ),+ ),+ ),);return ProviderEventIngestorV2.of({normalize,- ingestNormalized: (input) =>- Effect.gen(function* () {- const events = yield* normalize(input);- if (events.length === 0) {- return [];- }- const mapWriteError = (cause: unknown) =>- new ProviderEventPublishError({- providerSessionId: input.providerSessionId,- eventCount: events.length,- cause,- });- if (input.writeIfProviderThreadOwner !== undefined) {- const ownerResult = yield* eventSink- .writeIfProviderThreadOwner({- guardPendingUserInputCancellations: true,- ...(input.commandId === undefined ? {} : { commandId: input.commandId }),- ...input.writeIfProviderThreadOwner,- events,- })- .pipe(Effect.mapError(mapWriteError));- return ownerResult.storedEvents;- }- if (input.writeIfRunCurrent === undefined) {- return yield* eventSink- .write({+ ingestNormalized:+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(+ function* (input) {+ const events = yield* normalize(input);+ if (events.length === 0) {+ return [];+ }+ const mapWriteError = (cause: unknown) =>+ new ProviderEventPublishError({+ providerSessionId: input.providerSessionId,+ eventCount: events.length,+ cause,+ });+ if (input.writeIfProviderThreadOwner !== undefined) {+ const ownerResult = yield* eventSink+ .writeIfProviderThreadOwner({+ guardPendingUserInputCancellations: true,+ ...(input.commandId === undefined ? {} : { commandId: input.commandId }),+ ...input.writeIfProviderThreadOwner,+ events,+ })+ .pipe(Effect.mapError(mapWriteError));+ return ownerResult.storedEvents;+ }+ if (input.writeIfRunCurrent === undefined) {+ return yield* eventSink+ .write({+ guardPendingUserInputCancellations: true,+ ...(input.commandId === undefined ? {} : { commandId: input.commandId }),+ events,+ })+ .pipe(Effect.mapError(mapWriteError));+ }+ const result = yield* eventSink+ .writeIfRunCurrent({guardPendingUserInputCancellations: true,...(input.commandId === undefined ? {} : { commandId: input.commandId }),+ threadId: input.threadId,+ ...input.writeIfRunCurrent,events,}).pipe(Effect.mapError(mapWriteError));- }- const result = yield* eventSink- .writeIfRunCurrent({- guardPendingUserInputCancellations: true,- ...(input.commandId === undefined ? {} : { commandId: input.commandId }),- threadId: input.threadId,- ...input.writeIfRunCurrent,- events,- })- .pipe(Effect.mapError(mapWriteError));- return result.storedEvents;- }).pipe(- Effect.flatMap((storedEvents) =>- Effect.gen(function* () {- if (input.event.type !== "app_thread.created") return storedEvents;- const created = storedEvents.find((stored) => stored.event.type === "thread.created");- if (created?.event.type !== "thread.created") return storedEvents;- const child = created.event.payload;- if (- child.worktreePath === null ||- child.branch === null ||- !isTemporaryWorktreeBranch(child.branch)- )- return storedEvents;- // Git renames before scanning committed threads. If that scan missed this- // creation, HEAD already has the new name, even if the parent moved away.- const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");- if (branch === null || branch === child.branch) return storedEvents;- const now = yield* DateTime.now;- const event = yield* makeDomainEvent(input, {- type: "thread.metadata-updated",- threadId: child.id,- payload: { ...child, branch, updatedAt: now },- occurredAt: now,- });- const synced = yield* eventSink.write({ events: [event] });- return [...storedEvents, ...synced];- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning("Native thread worktree branch recheck failed", {- threadId:- input.event.type === "app_thread.created"- ? input.event.appThread.id- : input.threadId,- cause,- }).pipe(Effect.as(storedEvents)),- ),- ),- ),- Effect.flatMap((storedEvents) =>- storedEvents.length === 0 || input.event.type !== "subagent.updated"- ? Effect.succeed(storedEvents)- : syncSubagentThreadModel(input, input.event.subagent).pipe(- Effect.map((synced) => [...storedEvents, ...synced]),- Effect.mapError(- (cause) =>- new ProviderEventPublishError({- providerSessionId: input.providerSessionId,- eventCount: 1,- cause,- }),+ return result.storedEvents;+ },+ (effect, input) =>+ effect.pipe(+ Effect.flatMap((storedEvents) =>+ Effect.gen(function* () {+ if (input.event.type !== "app_thread.created") return storedEvents;+ const created = storedEvents.find(+ (stored) => stored.event.type === "thread.created",+ );+ if (created?.event.type !== "thread.created") return storedEvents;+ const child = created.event.payload;+ if (+ child.worktreePath === null ||+ child.branch === null ||+ !isTemporaryWorktreeBranch(child.branch)+ )+ return storedEvents;+ // Git renames before scanning committed threads. If that scan missed this+ // creation, HEAD already has the new name, even if the parent moved away.+ const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");+ if (branch === null || branch === child.branch) return storedEvents;+ const now = yield* DateTime.now;+ const event = yield* makeDomainEvent(input, {+ type: "thread.metadata-updated",+ threadId: child.id,+ payload: { ...child, branch, updatedAt: now },+ occurredAt: now,+ });+ const synced = yield* eventSink.write({ events: [event] });+ return [...storedEvents, ...synced];+ }).pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Native thread worktree branch recheck failed", {+ threadId:+ input.event.type === "app_thread.created"+ ? input.event.appThread.id+ : input.threadId,+ cause,+ }).pipe(Effect.as(storedEvents)),),),- ),- Effect.tap((storedEvents) =>- Effect.gen(function* () {- if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;- const providerTurn = input.event.providerTurn;- if (- providerTurn.status !== "completed" &&- providerTurn.status !== "failed" &&- providerTurn.status !== "interrupted" &&- providerTurn.status !== "cancelled"- )- return;- const key = `${input.providerInstanceId}:${providerTurn.id}`;- if (completedTurnAnalytics.has(key)) return;- completedTurnAnalytics.add(key);- if (completedTurnAnalytics.size > 4096) {- const oldest = completedTurnAnalytics.values().next().value;- if (oldest !== undefined) completedTurnAnalytics.delete(oldest);- }- yield* analytics.record(- providerTurnAnalyticsProperties({- driver: input.event.driver,- providerTurn,- ...(input.analyticsContext === undefined- ? {}- : { context: input.analyticsContext }),+ ),+ Effect.flatMap((storedEvents) =>+ storedEvents.length === 0 || input.event.type !== "subagent.updated"+ ? Effect.succeed(storedEvents)+ : syncSubagentThreadModel(input, input.event.subagent).pipe(+ Effect.map((synced) => [...storedEvents, ...synced]),+ Effect.mapError(+ (cause) =>+ new ProviderEventPublishError({+ providerSessionId: input.providerSessionId,+ eventCount: 1,+ cause,+ }),+ ),+ ),+ ),+ Effect.tap((storedEvents) =>+ Effect.gen(function* () {+ if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated")+ return;+ const providerTurn = input.event.providerTurn;+ if (+ providerTurn.status !== "completed" &&+ providerTurn.status !== "failed" &&+ providerTurn.status !== "interrupted" &&+ providerTurn.status !== "cancelled"+ )+ return;+ const key = `${input.providerInstanceId}:${providerTurn.id}`;+ if (completedTurnAnalytics.has(key)) return;+ completedTurnAnalytics.add(key);+ if (completedTurnAnalytics.size > 4096) {+ const oldest = completedTurnAnalytics.values().next().value;+ if (oldest !== undefined) completedTurnAnalytics.delete(oldest);+ }+ yield* analytics.record(+ providerTurnAnalyticsProperties({+ driver: input.event.driver,+ providerTurn,+ ...(input.analyticsContext === undefined+ ? {}+ : { context: input.analyticsContext }),+ }),+ );}),- );- }),- ),- (effect) =>- input.event.type === "app_thread.created"- ? threadCommands.withLock(input.event.appThread.id, effect)- : effect,+ ),+ (effect) =>+ input.event.type === "app_thread.created"+ ? threadCommands.withLock(input.event.appThread.id, effect)+ : effect,+ ),),});}),diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.tsindex c5a80e70281..be8020ac425 100644--- a/apps/server/src/orchestration-v2/ShellStream.ts+++ b/apps/server/src/orchestration-v2/ShellStream.ts@@ -38,28 +38,32 @@ export function buildActiveShellSnapshot(input: {* because the server shares one SQLite connection and decoding a large shell takes longer than* reading it.*/-export const loadShellSnapshotParts = <E1, E2, E3, E4>(input: {+export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <+ E1,+ E2,+ E3,+ E4,+>(input: {readonly sql: SqlClient.SqlClient;readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;readonly latestSequence: Effect.Effect<number, E4>;-}) =>- Effect.gen(function* () {- const read = yield* input.sql- .withTransaction(- Effect.all({- decodeThreads: input.readThreads,- projects: input.listProjects,- snapshotSequence: input.latestSequence,- }),- )- .pipe(NodeSqliteClient.readOnly);- return {- projects: read.projects,- threads: yield* read.decodeThreads,- snapshotSequence: read.snapshotSequence,- };- });+}) {+ const read = yield* input.sql+ .withTransaction(+ Effect.all({+ decodeThreads: input.readThreads,+ projects: input.listProjects,+ snapshotSequence: input.latestSequence,+ }),+ )+ .pipe(NodeSqliteClient.readOnly);+ return {+ projects: read.projects,+ threads: yield* read.decodeThreads,+ snapshotSequence: read.snapshotSequence,+ };+});export type ShellApplicationEvent =| Pick<diff --git a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.tsindex e28deae2072..00340e2e06f 100644--- a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts+++ b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts@@ -80,153 +80,154 @@ export function coalesceLiveToolUpdatedEvents(return survivors;}-export const makeThreadLiveEventCoalescer = <E = never>(options?: {+export const makeThreadLiveEventCoalescer = Effect.fn(+ "ThreadLiveEventCoalescer.makeThreadLiveEventCoalescer",+)(function* <E = never>(options?: {readonly coalesceWindow?: Duration.Input;readonly maxItems?: number;readonly maxSerializedBytes?: number;-}) =>- Effect.gen(function* () {- const coalescerScope = yield* Effect.scope;- const budget = yield* makeLiveStreamBudget(options);- const cleanupComplete = yield* Deferred.make<void>();- const output = yield* Queue.unbounded<- RetainedLiveItem<ThreadLiveInput>,- E | LiveStreamBufferError | Cause.Done- >();- const mutex = yield* Semaphore.make(1);- const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;- let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];- let windowGeneration = 0;- let windowFiber: Fiber.Fiber<void, never> | null = null;- let closed = false;-- const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {- const fiber = windowFiber;- if (!fiber) {- return;- }- windowFiber = null;- yield* Fiber.interrupt(fiber);- });+}) {+ const coalescerScope = yield* Effect.scope;+ const budget = yield* makeLiveStreamBudget(options);+ const cleanupComplete = yield* Deferred.make<void>();+ const output = yield* Queue.unbounded<+ RetainedLiveItem<ThreadLiveInput>,+ E | LiveStreamBufferError | Cause.Done+ >();+ const mutex = yield* Semaphore.make(1);+ const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;+ let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];+ let windowGeneration = 0;+ let windowFiber: Fiber.Fiber<void, never> | null = null;+ let closed = false;++ const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {+ const fiber = windowFiber;+ if (!fiber) {+ return;+ }+ windowFiber = null;+ yield* Fiber.interrupt(fiber);+ });- const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {- if (pendingUpdates.length === 0) {- return;- }- const items = yield* budget.replace(- pendingUpdates,- coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)),- );- pendingUpdates = [];- yield* Queue.offerAll(output, items);- }, Effect.uninterruptible);-- const flushWindow = (generation: number) =>- Effect.sleep(coalesceWindow).pipe(- Effect.andThen(- mutex.withPermits(1)(- Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),- ),- ),- Effect.ensuring(- Effect.sync(() => {- if (generation === windowGeneration) {- windowFiber = null;- }- }),+ const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {+ if (pendingUpdates.length === 0) {+ return;+ }+ const items = yield* budget.replace(+ pendingUpdates,+ coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)),+ );+ pendingUpdates = [];+ yield* Queue.offerAll(output, items);+ }, Effect.uninterruptible);++ const flushWindow = (generation: number) =>+ Effect.sleep(coalesceWindow).pipe(+ Effect.andThen(+ mutex.withPermits(1)(+ Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),),- Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),- );+ ),+ Effect.ensuring(+ Effect.sync(() => {+ if (generation === windowGeneration) {+ windowFiber = null;+ }+ }),+ ),+ Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),+ );- // Keep each source batch together so a synchronization marker cannot pass- // events already pulled from PubSub but still being coalesced.- const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (- inputs: ReadonlyArray<ThreadLiveInput>,- ) {- yield* mutex.withPermits(1)(- Effect.forEach(- inputs,- (input) =>- Effect.gen(function* () {- yield* budget.check;- if (input.kind === "event") {- yield* budget.retain(input).pipe(- Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),- Effect.uninterruptible,- );+ // Keep each source batch together so a synchronization marker cannot pass+ // events already pulled from PubSub but still being coalesced.+ const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (+ inputs: ReadonlyArray<ThreadLiveInput>,+ ) {+ yield* mutex.withPermits(1)(+ Effect.forEach(+ inputs,+ (input) =>+ Effect.gen(function* () {+ yield* budget.check;+ if (input.kind === "event") {+ yield* budget.retain(input).pipe(+ Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),+ Effect.uninterruptible,+ );+ }+ if (input.kind === "event" && isToolUpdated(input)) {+ if (pendingUpdates.length === 1) {+ const generation = ++windowGeneration;+ windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);}- if (input.kind === "event" && isToolUpdated(input)) {- if (pendingUpdates.length === 1) {- const generation = ++windowGeneration;- windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);- }- if (pendingUpdates.length >= MAX_PENDING_UPDATES) {- yield* cancelWindow();- windowGeneration += 1;- yield* flushPending();- }- return;+ if (pendingUpdates.length >= MAX_PENDING_UPDATES) {+ yield* cancelWindow();+ windowGeneration += 1;+ yield* flushPending();}+ return;+ }- yield* cancelWindow();- windowGeneration += 1;- yield* flushPending();- if (input.kind === "synchronized") {- yield* budget.retain({ kind: "synchronized" as const }).pipe(- Effect.flatMap((marker) => Queue.offer(output, marker)),- Effect.uninterruptible,- );- }- }),- { discard: true },- ),- );- });-- const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>- mutex.withPermits(1)(- Effect.gen(function* () {- if (closed) {- return;- }- closed = true;- windowGeneration += 1;- yield* cancelWindow();- budget.release(pendingUpdates);- pendingUpdates = [];- budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));- if (cause) {- yield* Queue.failCause(output, cause);- }- yield* Queue.shutdown(output);- yield* Deferred.succeed(cleanupComplete, undefined);- }),- );+ yield* cancelWindow();+ windowGeneration += 1;+ yield* flushPending();+ if (input.kind === "synchronized") {+ yield* budget.retain({ kind: "synchronized" as const }).pipe(+ Effect.flatMap((marker) => Queue.offer(output, marker)),+ Effect.uninterruptible,+ );+ }+ }),+ { discard: true },+ ),+ );+ });- yield* Effect.addFinalizer(() => close());- yield* budget.failed.pipe(- Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),- Effect.forkScoped,+ const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>+ mutex.withPermits(1)(+ Effect.gen(function* () {+ if (closed) {+ return;+ }+ closed = true;+ windowGeneration += 1;+ yield* cancelWindow();+ budget.release(pendingUpdates);+ pendingUpdates = [];+ budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));+ if (cause) {+ yield* Queue.failCause(output, cause);+ }+ yield* Queue.shutdown(output);+ yield* Deferred.succeed(cleanupComplete, undefined);+ }),);- return {- offer: (input: ThreadLiveInput) => offerAll([input]),- close,- end: mutex.withPermits(1)(- Effect.gen(function* () {- yield* cancelWindow();- windowGeneration += 1;- yield* flushPending();- yield* Queue.end(output);- }),- ),- offerAll,- stream: budget.deliver(Stream.fromQueue(output)),- failed: budget.failed,- closed: Deferred.await(cleanupComplete),- usage: budget.usage,- } as const;- });+ yield* Effect.addFinalizer(() => close());+ yield* budget.failed.pipe(+ Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),+ Effect.forkScoped,+ );++ return {+ offer: (input: ThreadLiveInput) => offerAll([input]),+ close,+ end: mutex.withPermits(1)(+ Effect.gen(function* () {+ yield* cancelWindow();+ windowGeneration += 1;+ yield* flushPending();+ yield* Queue.end(output);+ }),+ ),+ offerAll,+ stream: budget.deliver(Stream.fromQueue(output)),+ failed: budget.failed,+ closed: Deferred.await(cleanupComplete),+ usage: budget.usage,+ } as const;+});export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>Stream.unwrap(diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.tsindex 9e60c0f0fdf..a004191e095 100644--- a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts+++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts@@ -39,34 +39,31 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCliEffect.gen(function* () {const sql = yield* SqlClient.SqlClient;- const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({- threadId,- turnItemId,- runId,- runOrdinal: suppliedRunOrdinal,- }) =>- Effect.gen(function* () {- const existing = yield* sql<{ readonly ordinal: number }>`+ const allocate: TurnItemPositionStoreV2Shape["allocate"] =+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */+ Effect.fnUntraced(+ function* ({ threadId, turnItemId, runId, runOrdinal: suppliedRunOrdinal }) {+ const existing = yield* sql<{ readonly ordinal: number }>`SELECT ordinalFROM orchestration_v2_turn_item_positionsWHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}LIMIT 1`;- if (existing[0] !== undefined) return existing[0].ordinal;+ if (existing[0] !== undefined) return existing[0].ordinal;- const runRows =- runId === null- ? []- : yield* sql<{ readonly ordinal: number }>`+ const runRows =+ runId === null+ ? []+ : yield* sql<{ readonly ordinal: number }>`SELECT ordinalFROM orchestration_v2_projection_runsWHERE thread_id = ${threadId} AND run_id = ${runId}LIMIT 1`;- const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;- const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;- const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;- yield* sql`+ const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;+ const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;+ const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;+ yield* sql`INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)SELECT${threadId},@@ -78,27 +75,30 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCliAND ordinal <= ${upperBound}ON CONFLICT(thread_id, turn_item_id) DO NOTHING`;- const rows = yield* sql<{ readonly ordinal: number }>`+ const rows = yield* sql<{ readonly ordinal: number }>`SELECT ordinalFROM orchestration_v2_turn_item_positionsWHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}LIMIT 1`;- const ordinal = rows[0]?.ordinal;- if (ordinal === undefined) {- return yield* new TurnItemPositionStoreError({- threadId,- turnItemId,- cause: "Position allocation returned no row.",- });- }- return ordinal;- }).pipe(- Effect.mapError((cause) =>- isTurnItemPositionStoreError(cause)- ? cause- : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),- ),+ const ordinal = rows[0]?.ordinal;+ if (ordinal === undefined) {+ return yield* new TurnItemPositionStoreError({+ threadId,+ turnItemId,+ cause: "Position allocation returned no row.",+ });+ }+ return ordinal;+ },+ (effect, { threadId, turnItemId }) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isTurnItemPositionStoreError(cause)+ ? cause+ : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),+ ),+ ),);return TurnItemPositionStoreV2.of({