@devries-cameron20 / t3code Mirror · read-only / commits / 236c11962f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

refactor(orchestration): trace storage operations without per-event spans (#21994)

Julius Marminge committed Oct 19, 2026 at 18:30 UTC 236c11962fdca4ae8c742f08e3e76e75ea1d2c39
8 files changed +1399 -1319
apps/server/src/orchestration-v2/EffectOutbox.ts
+66 -54
@@ -370,8 +370,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
370 );
371
372 const service: EffectOutboxV2Shape = {
373 - enqueue: (effects) =>
374 - Effect.gen(function* () {
373 + enqueue: Effect.fn("EffectOutbox.enqueue")(
374 + function* (effects) {
375 const now = yield* DateTime.now;
376 const nowIso = DateTime.formatIso(now);
377 yield* Effect.forEach(
@@ -406,7 +406,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
406 { concurrency: 1, discard: true },
407 );
408 // EventSink owns the corresponding post-commit notification.
409 - }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
409 + },
410 + Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause })),
411 + ),
412 get: (effectId) =>
413 sql<EffectRow>`
414 SELECT *
@@ -438,8 +440,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
440 : new EffectOutboxError({ operation: "list", cause }),
441 ),
442 ),
441 - cancelUnsettled: ({ threadId, effectTypes, reason }) =>
442 - Effect.gen(function* () {
443 + cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
444 + function* ({ threadId, effectTypes, reason }) {
445 if (effectTypes.length === 0) return [];
446 const now = DateTime.formatIso(yield* DateTime.now);
447 const rows = yield* sql<{ readonly effect_id: string }>`
@@ -457,40 +459,36 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
459 RETURNING effect_id
460 `;
461 return rows.map(({ effect_id }) => effect_id);
460 - }).pipe(
461 - Effect.mapError(
462 - (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
463 - ),
464 - ),
465 - signalCancellations: (effectIds) =>
466 - Effect.gen(function* () {
467 - yield* Effect.forEach(
468 - effectIds,
469 - (effectId) => {
470 - const signal = cancellationSignals.get(effectId);
471 - return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
472 - },
473 - { discard: true },
474 - );
475 - yield* signalSettled(effectIds);
476 - if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
477 - }),
462 + },
463 + Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),
464 + ),
465 + signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {
466 + yield* Effect.forEach(
467 + effectIds,
468 + (effectId) => {
469 + const signal = cancellationSignals.get(effectId);
470 + return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
471 + },
472 + { discard: true },
473 + );
474 + yield* signalSettled(effectIds);
475 + if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
476 + }),
477 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
478 clearCancellation: (effectId) =>
479 Effect.sync(() => {
480 cancellationSignals.delete(effectId);
481 }),
483 - awaitSettled: (effectId) =>
484 - Effect.gen(function* () {
485 - // Registered before the read, so a settle right after it still resolves.
486 - const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
487 - settledSignals.set(effectId, signal);
488 - const effect = yield* service.get(effectId);
489 - if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
490 - return yield* Deferred.await(signal);
491 - }
492 - yield* signalSettled([effectId]);
493 - }),
482 + awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {
483 + // Registered before the read, so a settle right after it still resolves.
484 + const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
485 + settledSignals.set(effectId, signal);
486 + const effect = yield* service.get(effectId);
487 + if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
488 + return yield* Deferred.await(signal);
489 + }
490 + yield* signalSettled([effectId]);
491 + }),
492 reconcileAfterProcessLoss: Effect.gen(function* () {
493 const now = DateTime.formatIso(yield* DateTime.now);
494 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
@@ -526,8 +524,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
524 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
525 ),
526 ),
529 - claimNext: ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) =>
530 - Effect.gen(function* () {
527 + // The worker polls for the next effect even when there is no work to claim.
528 + claimNext: Effect.fnUntraced(
529 + function* ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) {
530 const now = yield* DateTime.now;
531 const nowIso = DateTime.formatIso(now);
532 const leaseExpiresAt = DateTime.formatIso(
@@ -560,7 +559,9 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
559 if (row === undefined) return Option.none();
560 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
561 return Option.some(yield* rowToEffect(row));
563 - }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
562 + },
563 + Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })),
564 + ),
565 nextClaimableAt: Effect.gen(function* () {
566 const rows = yield* sql<{ readonly available_at: string | null }>`
567 SELECT MIN(candidate.available_at) AS available_at
@@ -584,8 +585,8 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
585 : new EffectOutboxError({ operation: "next-claimable", cause }),
586 ),
587 ),
587 - succeed: ({ effectId, workerId }) =>
588 - Effect.gen(function* () {
588 + succeed: Effect.fn("EffectOutbox.succeed")(
589 + function* ({ effectId, workerId }) {
590 const now = DateTime.formatIso(yield* DateTime.now);
591 const rows = yield* sql<{ readonly effect_id: string }>`
592 UPDATE orchestration_v2_effect_outbox
@@ -607,13 +608,16 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
608 yield* notifyAvailable();
609 }
610 return rows.length === 1;
610 - }).pipe(
611 - Effect.mapError(
612 - (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
611 + },
612 + (effect, { effectId }) =>
613 + effect.pipe(
614 + Effect.mapError(
615 + (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
616 + ),
617 ),
614 - ),
615 - retry: ({ effectId, workerId, error, delayMs }) =>
616 - Effect.gen(function* () {
618 + ),
619 + retry: Effect.fn("EffectOutbox.retry")(
620 + function* ({ effectId, workerId, error, delayMs }) {
621 const now = yield* DateTime.now;
622 const nowIso = DateTime.formatIso(now);
623 const availableAt = DateTime.formatIso(
@@ -638,13 +642,16 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
642 yield* notifyAvailable();
643 }
644 return rows.length === 1;
641 - }).pipe(
642 - Effect.mapError(
643 - (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
645 + },
646 + (effect, { effectId }) =>
647 + effect.pipe(
648 + Effect.mapError(
649 + (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
650 + ),
651 ),
645 - ),
646 - fail: ({ effectId, workerId, error }) =>
647 - Effect.gen(function* () {
652 + ),
653 + fail: Effect.fn("EffectOutbox.fail")(
654 + function* ({ effectId, workerId, error }) {
655 const now = DateTime.formatIso(yield* DateTime.now);
656 const rows = yield* sql<{ readonly effect_id: string }>`
657 UPDATE orchestration_v2_effect_outbox
@@ -666,9 +673,14 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
673 yield* notifyAvailable();
674 }
675 return rows.length === 1;
669 - }).pipe(
670 - Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
671 - ),
676 + },
677 + (effect, { effectId }) =>
678 + effect.pipe(
679 + Effect.mapError(
680 + (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),
681 + ),
682 + ),
683 + ),
684 pruneSettled: Effect.gen(function* () {
685 const cutoff = DateTime.formatIso(
686 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
apps/server/src/orchestration-v2/EventSink.ts
+12 -8
@@ -227,8 +227,9 @@ const layerBase: Layer.Layer<
227 OrchestrationV2DomainEvent["type"],
228 PubSub.PubSub<OrchestrationV2StoredEvent>
229 >();
230 - const publishLiveEvents = (events: ReadonlyArray<OrchestrationV2StoredEvent>) =>
231 - Effect.gen(function* () {
230 + const publishLiveEvents =
231 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
232 + Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
233 yield* PubSub.publishAll(liveEvents, events);
234 for (const [type, pubsub] of liveEventsByType) {
235 yield* PubSub.publishAll(
@@ -271,8 +272,9 @@ const layerBase: Layer.Layer<
272
273 // A user can answer after terminal normalization reads the pending request.
274 // Recheck inside the write transaction so stale cleanup cannot erase answers.
274 - const guardUserInputCancellations = (events: ReadonlyArray<OrchestrationV2DomainEvent>) =>
275 - Effect.gen(function* () {
275 + const guardUserInputCancellations =
276 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
277 + Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
278 const staleRequests = new Set<RuntimeRequestId>();
279 const staleNodes = new Set<NodeId>();
280 for (const event of events) {
@@ -337,8 +339,9 @@ const layerBase: Layer.Layer<
339 );
340 };
341
340 - const applyStoredEvents = (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) =>
341 - Effect.gen(function* () {
342 + const applyStoredEvents =
343 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
344 + Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {
345 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
346 concurrency: 1,
347 });
@@ -564,8 +567,9 @@ const layerBase: Layer.Layer<
567 );
568 });
569
567 - const existingCommandResult = (commandId: CommandId) =>
568 - Effect.gen(function* () {
570 + const existingCommandResult =
571 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
572 + Effect.fnUntraced(function* (commandId: CommandId) {
573 const existing = yield* commandReceipts.getByCommandId(commandId);
574 if (Option.isNone(existing)) {
575 return yield* Effect.die(
apps/server/src/orchestration-v2/LiveStreamBudget.ts
+34 -38
@@ -207,45 +207,41 @@ type LiveStreamLimits = {
207 readonly maxSerializedBytes?: number;
208 };
209
210 -const retainLiveStream = <A extends object, E, R>(
211 - source: Stream.Stream<A, E, R>,
212 - budget: LiveStreamBudget,
213 -) =>
214 - Effect.gen(function* () {
215 - const queue = yield* Queue.unbounded<
216 - RetainedLiveItem<A>,
217 - E | LiveStreamBufferError | Cause.Done
218 - >();
219 - let closed = false;
220 - const close = (error?: LiveStreamBufferError) =>
221 - Effect.gen(function* () {
222 - if (closed) return;
223 - closed = true;
224 - budget.release(yield* Queue.clear(queue).pipe(Effect.orElseSucceed(() => [])));
225 - if (error) yield* Queue.fail(queue, error);
226 - yield* Queue.shutdown(queue);
227 - });
228 - yield* Effect.addFinalizer(() => close());
229 - yield* budget.failed.pipe(
230 - Effect.catchTags({ LiveStreamBufferError: close }),
231 - Effect.forkScoped,
232 - );
233 - yield* source.pipe(
234 - Stream.runForEach((value) =>
235 - budget.retain(value).pipe(
236 - Effect.flatMap((item) => Queue.offer(queue, item)),
237 - Effect.uninterruptible,
238 - ),
239 - ),
240 - Effect.raceFirst(budget.failed),
241 - Effect.exit,
242 - Effect.flatMap((exit) =>
243 - Exit.isFailure(exit) ? Queue.failCause(queue, exit.cause) : Queue.end(queue),
244 - ),
245 - Effect.forkScoped({ startImmediately: true }),
246 - );
247 - return Stream.fromQueue(queue);
210 +const retainLiveStream = Effect.fn("LiveStreamBudget.retainLiveStream")(function* <
211 + A extends object,
212 + E,
213 + R,
214 +>(source: Stream.Stream<A, E, R>, budget: LiveStreamBudget) {
215 + const queue = yield* Queue.unbounded<
216 + RetainedLiveItem<A>,
217 + E | LiveStreamBufferError | Cause.Done
218 + >();
219 + let closed = false;
220 + const close = Effect.fn("LiveStreamBudget.close")(function* (error?: LiveStreamBufferError) {
221 + if (closed) return;
222 + closed = true;
223 + budget.release(yield* Queue.clear(queue).pipe(Effect.orElseSucceed(() => [])));
224 + if (error) yield* Queue.fail(queue, error);
225 + yield* Queue.shutdown(queue);
226 });
227 + yield* Effect.addFinalizer(() => close());
228 + yield* budget.failed.pipe(Effect.catchTags({ LiveStreamBufferError: close }), Effect.forkScoped);
229 + yield* source.pipe(
230 + Stream.runForEach((value) =>
231 + budget.retain(value).pipe(
232 + Effect.flatMap((item) => Queue.offer(queue, item)),
233 + Effect.uninterruptible,
234 + ),
235 + ),
236 + Effect.raceFirst(budget.failed),
237 + Effect.exit,
238 + Effect.flatMap((exit) =>
239 + Exit.isFailure(exit) ? Queue.failCause(queue, exit.cause) : Queue.end(queue),
240 + ),
241 + Effect.forkScoped({ startImmediately: true }),
242 + );
243 + return Stream.fromQueue(queue);
244 +});
245
246 export const bufferLiveStream = <A extends object, E, R>(
247 source: Stream.Stream<A, E, R>,
apps/server/src/orchestration-v2/ProjectionStore.ts
+754 -705
@@ -1886,42 +1886,44 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
1886 END
1887 `;
1888
1889 - const apply: ProjectionStoreV2Shape["apply"] = (event) =>
1890 - Effect.gen(function* () {
1891 - switch (event.type) {
1892 - case "thread.pull-request-link-updated": {
1893 - const thread = yield* getThread(event.threadId);
1894 - yield* apply({
1895 - ...event,
1896 - type: "thread.pull-request-synced",
1897 - payload: applyThreadPullRequestLinkUpdate(thread, event.payload),
1898 - });
1899 - break;
1900 - }
1901 - case "thread.created":
1902 - case "thread.archived":
1903 - case "thread.unarchived":
1904 - case "thread.deleted":
1905 - case "thread.settled":
1906 - case "thread.unsettled":
1907 - case "thread.snoozed":
1908 - case "thread.unsnoozed":
1909 - case "thread.auto-settle-set":
1910 - case "thread.pinned":
1911 - case "thread.unpinned":
1912 - case "thread.pin-reordered":
1913 - case "thread.active-reordered":
1914 - case "thread.visited":
1915 - case "thread.marked-unread":
1916 - case "thread.metadata-updated":
1917 - case "thread.pull-request-synced":
1918 - case "thread.runtime-mode-updated":
1919 - case "thread.interaction-mode-updated":
1920 - case "thread.model-selection-updated":
1921 - case "thread.provider-switched": {
1922 - const payloadJson = yield* encodeThreadPayload(event.payload);
1923 - const payload = parseEncodedPayload(payloadJson);
1924 - yield* sql`
1889 + const apply: ProjectionStoreV2Shape["apply"] =
1890 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1891 + Effect.fnUntraced(
1892 + function* (event) {
1893 + switch (event.type) {
1894 + case "thread.pull-request-link-updated": {
1895 + const thread = yield* getThread(event.threadId);
1896 + yield* apply({
1897 + ...event,
1898 + type: "thread.pull-request-synced",
1899 + payload: applyThreadPullRequestLinkUpdate(thread, event.payload),
1900 + });
1901 + break;
1902 + }
1903 + case "thread.created":
1904 + case "thread.archived":
1905 + case "thread.unarchived":
1906 + case "thread.deleted":
1907 + case "thread.settled":
1908 + case "thread.unsettled":
1909 + case "thread.snoozed":
1910 + case "thread.unsnoozed":
1911 + case "thread.auto-settle-set":
1912 + case "thread.pinned":
1913 + case "thread.unpinned":
1914 + case "thread.pin-reordered":
1915 + case "thread.active-reordered":
1916 + case "thread.visited":
1917 + case "thread.marked-unread":
1918 + case "thread.metadata-updated":
1919 + case "thread.pull-request-synced":
1920 + case "thread.runtime-mode-updated":
1921 + case "thread.interaction-mode-updated":
1922 + case "thread.model-selection-updated":
1923 + case "thread.provider-switched": {
1924 + const payloadJson = yield* encodeThreadPayload(event.payload);
1925 + const payload = parseEncodedPayload(payloadJson);
1926 + yield* sql`
1927 INSERT INTO orchestration_v2_projection_threads (
1928 thread_id,
1929 project_id,
@@ -1967,13 +1969,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
1969 deleted_at = excluded.deleted_at,
1970 payload_json = excluded.payload_json
1971 `;
1970 - break;
1971 - }
1972 - case "run.created":
1973 - case "run.updated": {
1974 - const payloadJson = yield* encodeRunPayload(event.payload);
1975 - const payload = parseEncodedPayload(payloadJson);
1976 - yield* sql`
1972 + break;
1973 + }
1974 + case "run.created":
1975 + case "run.updated": {
1976 + const payloadJson = yield* encodeRunPayload(event.payload);
1977 + const payload = parseEncodedPayload(payloadJson);
1978 + yield* sql`
1979 INSERT INTO orchestration_v2_projection_runs (
1980 run_id,
1981 thread_id,
@@ -2013,14 +2015,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2015 "$.restartCancelledBackgroundWork",
2016 )}
2017 `;
2016 - break;
2017 - }
2018 - case "run.background-work-cancelled": {
2019 - // Only this field changes, so a concurrent lifecycle write is never regressed.
2020 - const workJson = yield* encodeRestartCancelledBackgroundWork(
2021 - event.payload.restartCancelledBackgroundWork,
2022 - );
2023 - yield* sql`
2018 + break;
2019 + }
2020 + case "run.background-work-cancelled": {
2021 + // Only this field changes, so a concurrent lifecycle write is never regressed.
2022 + const workJson = yield* encodeRestartCancelledBackgroundWork(
2023 + event.payload.restartCancelledBackgroundWork,
2024 + );
2025 + yield* sql`
2026 UPDATE orchestration_v2_projection_runs
2027 SET payload_json = json_set(
2028 payload_json,
@@ -2029,12 +2031,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2031 )
2032 WHERE run_id = ${event.payload.runId} AND thread_id = ${event.threadId}
2033 `;
2032 - break;
2033 - }
2034 - case "run-attempt.created":
2035 - case "run-attempt.updated": {
2036 - const payloadJson = yield* encodeRunAttemptPayload(event.payload);
2037 - yield* sql`
2034 + break;
2035 + }
2036 + case "run-attempt.created":
2037 + case "run-attempt.updated": {
2038 + const payloadJson = yield* encodeRunAttemptPayload(event.payload);
2039 + yield* sql`
2040 INSERT INTO orchestration_v2_projection_run_attempts (
2041 attempt_id,
2042 thread_id,
@@ -2074,12 +2076,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2076 status = excluded.status,
2077 payload_json = excluded.payload_json
2078 `;
2077 - break;
2078 - }
2079 - case "node.updated": {
2080 - const payloadJson = yield* encodeNodePayload(event.payload);
2081 - const payload = parseEncodedPayload(payloadJson);
2082 - yield* sql`
2079 + break;
2080 + }
2081 + case "node.updated": {
2082 + const payloadJson = yield* encodeNodePayload(event.payload);
2083 + const payload = parseEncodedPayload(payloadJson);
2084 + yield* sql`
2085 INSERT INTO orchestration_v2_projection_nodes (
2086 node_id,
2087 thread_id,
@@ -2128,12 +2130,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2130 completed_at = excluded.completed_at,
2131 payload_json = excluded.payload_json
2132 `;
2131 - break;
2132 - }
2133 - case "subagent.updated": {
2134 - const payloadJson = yield* encodeSubagentPayload(event.payload);
2135 - const payload = parseEncodedPayload(payloadJson);
2136 - yield* sql`
2133 + break;
2134 + }
2135 + case "subagent.updated": {
2136 + const payloadJson = yield* encodeSubagentPayload(event.payload);
2137 + const payload = parseEncodedPayload(payloadJson);
2138 + yield* sql`
2139 INSERT INTO orchestration_v2_projection_subagents (
2140 subagent_id,
2141 thread_id,
@@ -2197,13 +2199,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2199 ELSE excluded.payload_json
2200 END
2201 `;
2200 - break;
2201 - }
2202 - case "provider-session.attached":
2203 - case "provider-session.updated": {
2204 - const payloadJson = yield* encodeProviderSessionPayload(event.payload);
2205 - const payload = parseEncodedPayload(payloadJson);
2206 - yield* sql`
2202 + break;
2203 + }
2204 + case "provider-session.attached":
2205 + case "provider-session.updated": {
2206 + const payloadJson = yield* encodeProviderSessionPayload(event.payload);
2207 + const payload = parseEncodedPayload(payloadJson);
2208 + yield* sql`
2209 INSERT INTO orchestration_v2_projection_provider_sessions (
2210 provider_session_id,
2211 thread_id,
@@ -2237,29 +2239,29 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2239 updated_at = excluded.updated_at,
2240 payload_json = excluded.payload_json
2241 `;
2240 - if (event.type === "provider-session.attached") {
2241 - yield* sql`
2242 + if (event.type === "provider-session.attached") {
2243 + yield* sql`
2244 INSERT OR IGNORE INTO orchestration_v2_projection_provider_session_bindings (
2245 provider_session_id,
2246 thread_id
2247 )
2248 VALUES (${event.payload.id}, ${event.threadId})
2249 `;
2250 + }
2251 + break;
2252 }
2249 - break;
2250 - }
2251 - case "provider-session.detached": {
2252 - yield* sql`
2253 + case "provider-session.detached": {
2254 + yield* sql`
2255 DELETE FROM orchestration_v2_projection_provider_session_bindings
2256 WHERE provider_session_id = ${event.payload.providerSessionId}
2257 AND thread_id = ${event.threadId}
2258 `;
2257 - break;
2258 - }
2259 - case "provider-thread.updated": {
2260 - const payloadJson = yield* encodeProviderThreadPayload(event.payload);
2261 - const payload = parseEncodedPayload(payloadJson);
2262 - yield* sql`
2259 + break;
2260 + }
2261 + case "provider-thread.updated": {
2262 + const payloadJson = yield* encodeProviderThreadPayload(event.payload);
2263 + const payload = parseEncodedPayload(payloadJson);
2264 + yield* sql`
2265 INSERT INTO orchestration_v2_projection_provider_threads (
2266 provider_thread_id,
2267 thread_id,
@@ -2302,26 +2304,26 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2304 updated_at = excluded.updated_at,
2305 payload_json = excluded.payload_json
2306 `;
2305 - if (
2306 - event.payload.appThreadId !== null &&
2307 - !isQueuedProviderThreadPlaceholder(event.payload)
2308 - ) {
2309 - const threadRows = yield* sql<PayloadRow>`
2307 + if (
2308 + event.payload.appThreadId !== null &&
2309 + !isQueuedProviderThreadPlaceholder(event.payload)
2310 + ) {
2311 + const threadRows = yield* sql<PayloadRow>`
2312 SELECT payload_json
2313 FROM orchestration_v2_projection_threads
2314 WHERE thread_id = ${event.payload.appThreadId}
2315 LIMIT 1
2316 `;
2315 - const threadRow = threadRows[0];
2316 - if (threadRow !== undefined) {
2317 - const thread = yield* decodeThreadPayload(threadRow.payload_json);
2318 - const updatedThread = {
2319 - ...thread,
2320 - activeProviderThreadId: event.payload.id,
2321 - updatedAt: event.payload.updatedAt,
2322 - };
2323 - const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread);
2324 - yield* sql`
2317 + const threadRow = threadRows[0];
2318 + if (threadRow !== undefined) {
2319 + const thread = yield* decodeThreadPayload(threadRow.payload_json);
2320 + const updatedThread = {
2321 + ...thread,
2322 + activeProviderThreadId: event.payload.id,
2323 + updatedAt: event.payload.updatedAt,
2324 + };
2325 + const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread);
2326 + yield* sql`
2327 UPDATE orchestration_v2_projection_threads
2328 SET
2329 active_provider_thread_id = ${event.payload.id},
@@ -2329,31 +2331,31 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2331 payload_json = ${updatedThreadPayloadJson}
2332 WHERE thread_id = ${event.payload.appThreadId}
2333 `;
2334 + }
2335 }
2336 + break;
2337 }
2334 - break;
2335 - }
2336 - case "provider-turn.updated": {
2337 - const existingRows =
2338 - event.payload.tokenUsage === undefined
2339 - ? yield* sql<PayloadRow>`
2338 + case "provider-turn.updated": {
2339 + const existingRows =
2340 + event.payload.tokenUsage === undefined
2341 + ? yield* sql<PayloadRow>`
2342 SELECT payload_json
2343 FROM orchestration_v2_projection_provider_turns
2344 WHERE provider_turn_id = ${event.payload.id}
2345 LIMIT 1
2346 `
2345 - : [];
2346 - const existing = existingRows[0];
2347 - const providerTurn =
2348 - existing === undefined
2349 - ? event.payload
2350 - : upsertProviderTurn(
2351 - [yield* decodeProviderTurnPayload(existing.payload_json)],
2352 - event.payload,
2353 - )[0]!;
2354 - const payloadJson = yield* encodeProviderTurnPayload(providerTurn);
2355 - const payload = parseEncodedPayload(payloadJson);
2356 - yield* sql`
2347 + : [];
2348 + const existing = existingRows[0];
2349 + const providerTurn =
2350 + existing === undefined
2351 + ? event.payload
2352 + : upsertProviderTurn(
2353 + [yield* decodeProviderTurnPayload(existing.payload_json)],
2354 + event.payload,
2355 + )[0]!;
2356 + const payloadJson = yield* encodeProviderTurnPayload(providerTurn);
2357 + const payload = parseEncodedPayload(payloadJson);
2358 + yield* sql`
2359 INSERT INTO orchestration_v2_projection_provider_turns (
2360 provider_turn_id,
2361 thread_id,
@@ -2390,12 +2392,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2392 completed_at = excluded.completed_at,
2393 payload_json = excluded.payload_json
2394 `;
2393 - break;
2394 - }
2395 - case "runtime-request.updated": {
2396 - const payloadJson = yield* encodeRuntimeRequestPayload(event.payload);
2397 - const payload = parseEncodedPayload(payloadJson);
2398 - yield* sql`
2395 + break;
2396 + }
2397 + case "runtime-request.updated": {
2398 + const payloadJson = yield* encodeRuntimeRequestPayload(event.payload);
2399 + const payload = parseEncodedPayload(payloadJson);
2400 + yield* sql`
2401 INSERT INTO orchestration_v2_projection_runtime_requests (
2402 runtime_request_id,
2403 thread_id,
@@ -2429,12 +2431,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2431 resolved_at = excluded.resolved_at,
2432 payload_json = excluded.payload_json
2433 `;
2432 - break;
2433 - }
2434 - case "message.updated": {
2435 - const payloadJson = yield* encodeMessagePayload(event.payload);
2436 - const payload = parseEncodedPayload(payloadJson);
2437 - yield* sql`
2434 + break;
2435 + }
2436 + case "message.updated": {
2437 + const payloadJson = yield* encodeMessagePayload(event.payload);
2438 + const payload = parseEncodedPayload(payloadJson);
2439 + yield* sql`
2440 INSERT INTO orchestration_v2_projection_messages (
2441 message_id,
2442 thread_id,
@@ -2468,11 +2470,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2470 updated_at = excluded.updated_at,
2471 payload_json = excluded.payload_json
2472 `;
2471 - break;
2472 - }
2473 - case "plan.updated": {
2474 - const payloadJson = yield* encodePlanPayload(event.payload);
2475 - yield* sql`
2473 + break;
2474 + }
2475 + case "plan.updated": {
2476 + const payloadJson = yield* encodePlanPayload(event.payload);
2477 + yield* sql`
2478 INSERT INTO orchestration_v2_projection_plans (
2479 plan_id,
2480 thread_id,
@@ -2500,12 +2502,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2502 status = excluded.status,
2503 payload_json = excluded.payload_json
2504 `;
2503 - break;
2504 - }
2505 - case "turn-item.updated": {
2506 - const payloadJson = yield* encodeTurnItemPayload(event.payload);
2507 - const payload = parseEncodedPayload(payloadJson);
2508 - yield* sql`
2505 + break;
2506 + }
2507 + case "turn-item.updated": {
2508 + const payloadJson = yield* encodeTurnItemPayload(event.payload);
2509 + const payload = parseEncodedPayload(payloadJson);
2510 + yield* sql`
2511 INSERT INTO orchestration_v2_projection_turn_items (
2512 turn_item_id,
2513 thread_id,
@@ -2548,12 +2550,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2550 updated_at = excluded.updated_at,
2551 payload_json = excluded.payload_json
2552 `;
2551 - break;
2552 - }
2553 - case "checkpoint-scope.created": {
2554 - const payloadJson = yield* encodeCheckpointScopePayload(event.payload);
2555 - const payload = parseEncodedPayload(payloadJson);
2556 - yield* sql`
2553 + break;
2554 + }
2555 + case "checkpoint-scope.created": {
2556 + const payloadJson = yield* encodeCheckpointScopePayload(event.payload);
2557 + const payload = parseEncodedPayload(payloadJson);
2558 + yield* sql`
2559 INSERT INTO orchestration_v2_projection_checkpoint_scopes (
2560 scope_id,
2561 thread_id,
@@ -2593,12 +2595,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2595 created_at = excluded.created_at,
2596 payload_json = excluded.payload_json
2597 `;
2596 - break;
2597 - }
2598 - case "checkpoint.captured": {
2599 - const payloadJson = yield* encodeCheckpointPayload(event.payload);
2600 - const payload = parseEncodedPayload(payloadJson);
2601 - yield* sql`
2598 + break;
2599 + }
2600 + case "checkpoint.captured": {
2601 + const payloadJson = yield* encodeCheckpointPayload(event.payload);
2602 + const payload = parseEncodedPayload(payloadJson);
2603 + yield* sql`
2604 INSERT INTO orchestration_v2_projection_checkpoints (
2605 checkpoint_id,
2606 thread_id,
@@ -2638,14 +2640,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2640 captured_at = excluded.captured_at,
2641 payload_json = excluded.payload_json
2642 `;
2641 - break;
2642 - }
2643 - case "checkpoint.rollback-requested":
2644 - break;
2645 - case "context-handoff.updated": {
2646 - const payloadJson = yield* encodeContextHandoffPayload(event.payload);
2647 - const payload = parseEncodedPayload(payloadJson);
2648 - yield* sql`
2643 + break;
2644 + }
2645 + case "checkpoint.rollback-requested":
2646 + break;
2647 + case "context-handoff.updated": {
2648 + const payloadJson = yield* encodeContextHandoffPayload(event.payload);
2649 + const payload = parseEncodedPayload(payloadJson);
2650 + yield* sql`
2651 INSERT INTO orchestration_v2_projection_context_handoffs (
2652 context_handoff_id,
2653 thread_id,
@@ -2676,13 +2678,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2678 updated_at = excluded.updated_at,
2679 payload_json = excluded.payload_json
2680 `;
2679 - break;
2680 - }
2681 - case "context-transfer.created":
2682 - case "context-transfer.updated": {
2683 - const payloadJson = yield* encodeContextTransferPayload(event.payload);
2684 - const payload = parseEncodedPayload(payloadJson);
2685 - yield* sql`
2681 + break;
2682 + }
2683 + case "context-transfer.created":
2684 + case "context-transfer.updated": {
2685 + const payloadJson = yield* encodeContextTransferPayload(event.payload);
2686 + const payload = parseEncodedPayload(payloadJson);
2687 + yield* sql`
2688 INSERT INTO orchestration_v2_projection_context_transfers (
2689 context_transfer_id,
2690 source_thread_id,
@@ -2725,66 +2727,69 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2727 updated_at = excluded.updated_at,
2728 payload_json = excluded.payload_json
2729 `;
2728 - break;
2730 + break;
2731 + }
2732 }
2730 - }
2733
2732 - if (
2733 - event.type !== "thread.created" &&
2734 - event.type !== "thread.archived" &&
2735 - event.type !== "thread.unarchived" &&
2736 - event.type !== "thread.deleted" &&
2737 - event.type !== "thread.settled" &&
2738 - event.type !== "thread.unsettled" &&
2739 - event.type !== "thread.snoozed" &&
2740 - event.type !== "thread.unsnoozed" &&
2741 - event.type !== "thread.auto-settle-set" &&
2742 - event.type !== "thread.pinned" &&
2743 - event.type !== "thread.unpinned" &&
2744 - event.type !== "thread.pin-reordered" &&
2745 - event.type !== "thread.active-reordered" &&
2746 - event.type !== "thread.visited" &&
2747 - event.type !== "thread.marked-unread" &&
2748 - event.type !== "thread.metadata-updated" &&
2749 - event.type !== "thread.pull-request-synced" &&
2750 - event.type !== "thread.pull-request-link-updated" &&
2751 - event.type !== "thread.runtime-mode-updated" &&
2752 - event.type !== "thread.interaction-mode-updated" &&
2753 - event.type !== "thread.model-selection-updated" &&
2754 - event.type !== "thread.provider-switched"
2755 - ) {
2756 - const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);
2757 - yield* sql`
2734 + if (
2735 + event.type !== "thread.created" &&
2736 + event.type !== "thread.archived" &&
2737 + event.type !== "thread.unarchived" &&
2738 + event.type !== "thread.deleted" &&
2739 + event.type !== "thread.settled" &&
2740 + event.type !== "thread.unsettled" &&
2741 + event.type !== "thread.snoozed" &&
2742 + event.type !== "thread.unsnoozed" &&
2743 + event.type !== "thread.auto-settle-set" &&
2744 + event.type !== "thread.pinned" &&
2745 + event.type !== "thread.unpinned" &&
2746 + event.type !== "thread.pin-reordered" &&
2747 + event.type !== "thread.active-reordered" &&
2748 + event.type !== "thread.visited" &&
2749 + event.type !== "thread.marked-unread" &&
2750 + event.type !== "thread.metadata-updated" &&
2751 + event.type !== "thread.pull-request-synced" &&
2752 + event.type !== "thread.pull-request-link-updated" &&
2753 + event.type !== "thread.runtime-mode-updated" &&
2754 + event.type !== "thread.interaction-mode-updated" &&
2755 + event.type !== "thread.model-selection-updated" &&
2756 + event.type !== "thread.provider-switched"
2757 + ) {
2758 + const updatedAt = yield* encodeThreadUpdatedAt(event.occurredAt);
2759 + yield* sql`
2760 UPDATE orchestration_v2_projection_threads
2761 SET
2762 updated_at = ${updatedAt},
2763 payload_json = json_set(payload_json, '$.updatedAt', ${updatedAt})
2764 WHERE thread_id = ${event.threadId}
2765 `;
2764 - }
2765 - }).pipe(
2766 - Effect.mapError(
2767 - (cause) =>
2768 - new ProjectionStoreApplyEventError({
2769 - eventType: event.type,
2770 - cause,
2771 - }),
2772 - ),
2766 + }
2767 + },
2768 + (effect, event) =>
2769 + effect.pipe(
2770 + Effect.mapError(
2771 + (cause) =>
2772 + new ProjectionStoreApplyEventError({
2773 + eventType: event.type,
2774 + cause,
2775 + }),
2776 + ),
2777 + ),
2778 );
2779
2775 - const readCanonicalProjection = (
2776 - threadId: ThreadId,
2777 - window?: {
2778 - readonly rowLimit: number;
2779 - readonly userTurnLimit?: number | undefined;
2780 - readonly anchorItemId?: TurnItemId | undefined;
2781 - readonly requiredRunId?: RunId | undefined;
2782 - readonly suppressLocal?: boolean | undefined;
2783 - },
2784 - fields?: ReadonlyArray<ProjectionRecordField>,
2785 - filter?: ProjectionRecordFilter,
2786 - ) =>
2787 - Effect.gen(function* () {
2780 + const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")(
2781 + function* (
2782 + threadId: ThreadId,
2783 + window?: {
2784 + readonly rowLimit: number;
2785 + readonly userTurnLimit?: number | undefined;
2786 + readonly anchorItemId?: TurnItemId | undefined;
2787 + readonly requiredRunId?: RunId | undefined;
2788 + readonly suppressLocal?: boolean | undefined;
2789 + },
2790 + fields?: ReadonlyArray<ProjectionRecordField>,
2791 + filter?: ProjectionRecordFilter,
2792 + ) {
2793 const threadRows = yield* sql<PayloadRow>`
2794 SELECT payload_json
2795 FROM orchestration_v2_projection_threads
@@ -3425,18 +3430,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3430 updatedAt: thread.updatedAt,
3431 } satisfies OrchestrationV2ThreadProjection;
3432 return projection;
3428 - }).pipe(
3429 - Effect.mapError((cause) =>
3430 - isProjectionStoreThreadNotFoundError(cause)
3431 - ? cause
3432 - : new ProjectionStoreReadError({
3433 - threadId,
3434 - cause,
3435 - }),
3433 + },
3434 + (effect, threadId, _window?, _fields?, _filter?) =>
3435 + effect.pipe(
3436 + Effect.mapError((cause) =>
3437 + isProjectionStoreThreadNotFoundError(cause)
3438 + ? cause
3439 + : new ProjectionStoreReadError({
3440 + threadId,
3441 + cause,
3442 + }),
3443 + ),
3444 ),
3437 - );
3445 + );
3446
3439 - const readProjection = (
3447 + const readProjection: (
3448 threadId: ThreadId,
3449 seenThreadIds: ReadonlySet<ThreadId>,
3450 window?: {
@@ -3449,8 +3457,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3457 | { readonly threadId: ThreadId; readonly itemId: TurnItemId }
3458 | undefined;
3459 },
3452 - ): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>
3453 - Effect.gen(function* () {
3460 + ) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> = Effect.fn(
3461 + "ProjectionStore.readProjection",
3462 + )(
3463 + function* (
3464 + threadId: ThreadId,
3465 + seenThreadIds: ReadonlySet<ThreadId>,
3466 + window?: {
3467 + readonly rowLimit: number;
3468 + readonly userTurnLimit?: number | undefined;
3469 + readonly anchorItemId?: TurnItemId | undefined;
3470 + readonly requiredRunId?: RunId | undefined;
3471 + readonly suppressLocal?: boolean | undefined;
3472 + readonly historyAnchor?:
3473 + | { readonly threadId: ThreadId; readonly itemId: TurnItemId }
3474 + | undefined;
3475 + },
3476 + ) {
3477 const localWindow =
3478 window?.suppressLocal === true ||
3479 (window?.historyAnchor !== undefined && window.historyAnchor.threadId !== threadId)
@@ -3579,13 +3602,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3602 sourceProjection,
3603 }),
3604 };
3582 - }).pipe(
3583 - Effect.mapError((cause) =>
3584 - isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)
3585 - ? cause
3586 - : new ProjectionStoreReadError({ threadId, cause }),
3605 + },
3606 + (effect, threadId, _seenThreadIds, _window?) =>
3607 + effect.pipe(
3608 + Effect.mapError((cause) =>
3609 + isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)
3610 + ? cause
3611 + : new ProjectionStoreReadError({ threadId, cause }),
3612 + ),
3613 ),
3588 - );
3614 + );
3615
3616 const getLimitRecoveryCandidates = Effect.fn("ProjectionStore.getLimitRecoveryCandidates")(
3617 function* (options: Parameters<ProjectionStoreV2Shape["getLimitRecoveryCandidates"]>[0]) {
@@ -4106,8 +4132,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4132 ),
4133 );
4134
4109 - const getTurnStartHistory: ProjectionStoreV2Shape["getTurnStartHistory"] = (threadId, runIds) =>
4110 - Effect.gen(function* () {
4135 + const getTurnStartHistory: ProjectionStoreV2Shape["getTurnStartHistory"] = Effect.fn(
4136 + "ProjectionStore.getTurnStartHistory",
4137 + )(
4138 + function* (threadId, runIds) {
4139 const rows = yield* sql<PayloadRow>`
4140 SELECT payload_json FROM orchestration_v2_projection_turn_items
4141 WHERE thread_id = ${threadId}
@@ -4117,37 +4145,39 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4145 ORDER BY ordinal ASC, turn_item_id ASC
4146 `;
4147 return yield* decodeRows(decodeTurnItemPayload, threadId)(rows);
4120 - }).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
4148 + },
4149 + (effect, threadId, _runIds) =>
4150 + effect.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))),
4151 + );
4152
4153 const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
4154 readProjection(threadId, new Set());
4155
4125 - const getRuntimeRecoveryProjection: ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] = (
4126 - threadId,
4127 - ) =>
4128 - Effect.gen(function* () {
4129 - const threadRows = yield* sql<PayloadRow>`
4156 + const getRuntimeRecoveryProjection: ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] =
4157 + Effect.fn("ProjectionStore.getRuntimeRecoveryProjection")(
4158 + function* (threadId) {
4159 + const threadRows = yield* sql<PayloadRow>`
4160 SELECT payload_json FROM orchestration_v2_projection_threads
4161 WHERE thread_id = ${threadId}
4162 `;
4133 - if (threadRows[0] === undefined) {
4134 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
4135 - }
4136 - const [
4137 - thread,
4138 - runRows,
4139 - attemptRows,
4140 - nodeRows,
4141 - subagentRows,
4142 - providerSessionRows,
4143 - providerThreadRows,
4144 - providerTurnRows,
4145 - runtimeRequestRows,
4146 - messageRows,
4147 - turnItemRows,
4148 - ] = yield* Effect.all([
4149 - decodeThreadPayload(threadRows[0].payload_json),
4150 - sql<PayloadRow>`
4163 + if (threadRows[0] === undefined) {
4164 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
4165 + }
4166 + const [
4167 + thread,
4168 + runRows,
4169 + attemptRows,
4170 + nodeRows,
4171 + subagentRows,
4172 + providerSessionRows,
4173 + providerThreadRows,
4174 + providerTurnRows,
4175 + runtimeRequestRows,
4176 + messageRows,
4177 + turnItemRows,
4178 + ] = yield* Effect.all([
4179 + decodeThreadPayload(threadRows[0].payload_json),
4180 + sql<PayloadRow>`
4181 SELECT payload_json FROM orchestration_v2_projection_runs AS run
4182 WHERE run.thread_id = ${threadId}
4183 AND (
@@ -4190,7 +4220,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4220 )
4221 ORDER BY run.ordinal ASC
4222 `,
4193 - sql<PayloadRow>`
4223 + sql<PayloadRow>`
4224 SELECT attempt.payload_json
4225 FROM orchestration_v2_projection_run_attempts AS attempt
4226 WHERE attempt.thread_id = ${threadId}
@@ -4201,7 +4231,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4231 )
4232 ORDER BY attempt.run_id ASC, attempt.attempt_ordinal ASC
4233 `,
4204 - sql<PayloadRow>`
4234 + sql<PayloadRow>`
4235 SELECT node.payload_json FROM orchestration_v2_projection_nodes AS node
4236 WHERE node.thread_id = ${threadId}
4237 AND node.status IN ('pending', 'starting', 'running', 'waiting')
@@ -4232,7 +4262,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4262 )
4263 ORDER BY COALESCE(node.started_at, ''), node.node_id ASC
4264 `,
4235 - sql<PayloadRow>`
4265 + sql<PayloadRow>`
4266 SELECT subagent.payload_json FROM orchestration_v2_projection_subagents AS subagent
4267 WHERE subagent.thread_id = ${threadId}
4268 AND subagent.status IN ('pending', 'starting', 'running', 'waiting')
@@ -4252,7 +4282,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4282 )
4283 ORDER BY COALESCE(subagent.started_at, ''), subagent.subagent_id ASC
4284 `,
4255 - sql<PayloadRow>`
4285 + sql<PayloadRow>`
4286 SELECT session.payload_json
4287 FROM orchestration_v2_projection_provider_sessions AS session
4288 WHERE (
@@ -4287,7 +4317,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4317 )
4318 ORDER BY session.updated_at ASC, session.provider_session_id ASC
4319 `,
4290 - sql<PayloadRow>`
4320 + sql<PayloadRow>`
4321 SELECT provider_thread.payload_json
4322 FROM orchestration_v2_projection_provider_threads AS provider_thread
4323 WHERE (
@@ -4331,7 +4361,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4361 )
4362 ORDER BY COALESCE(provider_thread.first_run_ordinal, 0), provider_thread.provider_thread_id ASC
4363 `,
4334 - sql<PayloadRow>`
4364 + sql<PayloadRow>`
4365 SELECT provider_turn.payload_json
4366 FROM orchestration_v2_projection_provider_turns AS provider_turn
4367 WHERE provider_turn.thread_id = ${threadId}
@@ -4347,12 +4377,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4377 )
4378 ORDER BY provider_turn.provider_thread_id ASC, provider_turn.ordinal ASC
4379 `,
4350 - sql<PayloadRow>`
4380 + sql<PayloadRow>`
4381 SELECT payload_json FROM orchestration_v2_projection_runtime_requests
4382 WHERE thread_id = ${threadId} AND status = 'pending'
4383 ORDER BY created_at ASC, runtime_request_id ASC
4384 `,
4355 - sql<PayloadRow>`
4385 + sql<PayloadRow>`
4386 SELECT message.payload_json FROM orchestration_v2_projection_messages AS message
4387 WHERE message.thread_id = ${threadId} AND message.streaming = 1
4388 AND message.run_id IN (
@@ -4362,7 +4392,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4392 )
4393 ORDER BY message.created_at ASC, message.message_id ASC
4394 `,
4365 - sql<PayloadRow>`
4395 + sql<PayloadRow>`
4396 SELECT item.payload_json FROM orchestration_v2_projection_turn_items AS item
4397 WHERE item.thread_id = ${threadId}
4398 AND item.status IN ('pending', 'running', 'waiting')
@@ -4386,53 +4416,56 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4416 )
4417 ORDER BY item.ordinal ASC, item.turn_item_id ASC
4418 `,
4389 - ]);
4390 - const [
4391 - runs,
4392 - attempts,
4393 - nodes,
4394 - subagents,
4395 - providerSessions,
4396 - providerThreads,
4397 - providerTurns,
4398 - runtimeRequests,
4399 - messages,
4400 - turnItems,
4401 - ] = yield* Effect.all([
4402 - decodeRows(decodeRunPayload, threadId)(runRows),
4403 - decodeRows(decodeRunAttemptPayload, threadId)(attemptRows),
4404 - decodeRows(decodeNodePayload, threadId)(nodeRows),
4405 - decodeRows(decodeSubagentPayload, threadId)(subagentRows),
4406 - decodeRows(decodeProviderSessionPayload, threadId)(providerSessionRows),
4407 - decodeRows(decodeProviderThreadPayload, threadId)(providerThreadRows),
4408 - decodeRows(decodeProviderTurnPayload, threadId)(providerTurnRows),
4409 - decodeRows(decodeRuntimeRequestPayload, threadId)(runtimeRequestRows),
4410 - decodeRows(decodeMessagePayload, threadId)(messageRows),
4411 - decodeRows(decodeTurnItemPayload, threadId)(turnItemRows),
4412 - ]);
4413 - return {
4414 - thread,
4415 - runs,
4416 - attempts,
4417 - nodes,
4418 - subagents,
4419 - providerSessions,
4420 - providerThreads,
4421 - providerTurns,
4422 - runtimeRequests,
4423 - messages,
4424 - turnItems,
4425 - } satisfies ProjectionRuntimeRecoveryState;
4426 - }).pipe(
4427 - Effect.mapError((cause) =>
4428 - isProjectionStoreThreadNotFoundError(cause)
4429 - ? cause
4430 - : new ProjectionStoreReadError({ threadId, cause }),
4431 - ),
4419 + ]);
4420 + const [
4421 + runs,
4422 + attempts,
4423 + nodes,
4424 + subagents,
4425 + providerSessions,
4426 + providerThreads,
4427 + providerTurns,
4428 + runtimeRequests,
4429 + messages,
4430 + turnItems,
4431 + ] = yield* Effect.all([
4432 + decodeRows(decodeRunPayload, threadId)(runRows),
4433 + decodeRows(decodeRunAttemptPayload, threadId)(attemptRows),
4434 + decodeRows(decodeNodePayload, threadId)(nodeRows),
4435 + decodeRows(decodeSubagentPayload, threadId)(subagentRows),
4436 + decodeRows(decodeProviderSessionPayload, threadId)(providerSessionRows),
4437 + decodeRows(decodeProviderThreadPayload, threadId)(providerThreadRows),
4438 + decodeRows(decodeProviderTurnPayload, threadId)(providerTurnRows),
4439 + decodeRows(decodeRuntimeRequestPayload, threadId)(runtimeRequestRows),
4440 + decodeRows(decodeMessagePayload, threadId)(messageRows),
4441 + decodeRows(decodeTurnItemPayload, threadId)(turnItemRows),
4442 + ]);
4443 + return {
4444 + thread,
4445 + runs,
4446 + attempts,
4447 + nodes,
4448 + subagents,
4449 + providerSessions,
4450 + providerThreads,
4451 + providerTurns,
4452 + runtimeRequests,
4453 + messages,
4454 + turnItems,
4455 + } satisfies ProjectionRuntimeRecoveryState;
4456 + },
4457 + (effect, threadId) =>
4458 + effect.pipe(
4459 + Effect.mapError((cause) =>
4460 + isProjectionStoreThreadNotFoundError(cause)
4461 + ? cause
4462 + : new ProjectionStoreReadError({ threadId, cause }),
4463 + ),
4464 + ),
4465 );
4466
4434 - const getThread: ProjectionStoreV2Shape["getThread"] = (threadId) =>
4435 - Effect.gen(function* () {
4467 + const getThread: ProjectionStoreV2Shape["getThread"] = Effect.fn("ProjectionStore.getThread")(
4468 + function* (threadId) {
4469 const rows = yield* sql<PayloadRow>`
4470 SELECT payload_json FROM orchestration_v2_projection_threads
4471 WHERE thread_id = ${threadId}
@@ -4441,21 +4474,25 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4474 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
4475 }
4476 return yield* decodeThreadPayload(rows[0].payload_json);
4444 - }).pipe(
4445 - Effect.mapError((cause) =>
4446 - isProjectionStoreThreadNotFoundError(cause)
4447 - ? cause
4448 - : new ProjectionStoreReadError({ threadId, cause }),
4477 + },
4478 + (effect, threadId) =>
4479 + effect.pipe(
4480 + Effect.mapError((cause) =>
4481 + isProjectionStoreThreadNotFoundError(cause)
4482 + ? cause
4483 + : new ProjectionStoreReadError({ threadId, cause }),
4484 + ),
4485 ),
4450 - );
4486 + );
4487
4452 - const requireThread = (threadId: ThreadId) =>
4453 - Effect.gen(function* () {
4454 - const rows = yield* sql<{ readonly thread_id: string }>`
4488 + const requireThread = Effect.fn("ProjectionStore.requireThread")(function* (
4489 + threadId: ThreadId,
4490 + ) {
4491 + const rows = yield* sql<{ readonly thread_id: string }>`
4492 SELECT thread_id FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId} LIMIT 1
4493 `;
4457 - if (rows.length === 0) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
4458 - });
4494 + if (rows.length === 0) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
4495 + });
4496 const controlReadError = (threadId: ThreadId) => (cause: unknown) =>
4497 isProjectionStoreThreadNotFoundError(cause)
4498 ? cause
@@ -4518,8 +4555,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4555 .pipe(Effect.mapError(controlReadError(threadId)));
4556
4557 const hasUnpairedRunInterruptRequest: ProjectionStoreV2Shape["hasUnpairedRunInterruptRequest"] =
4521 - (threadId, requestId, resultId) =>
4522 - Effect.gen(function* () {
4558 + Effect.fn("ProjectionStore.hasUnpairedRunInterruptRequest")(
4559 + function* (threadId, requestId, resultId) {
4560 const rows = yield* sql<{ pending: number }>`
4561 SELECT EXISTS (
4562 SELECT 1 FROM orchestration_v2_projection_turn_items
@@ -4530,16 +4567,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4567 ) AS pending
4568 `;
4569 return rows[0]?.pending === 1;
4533 - }).pipe(Effect.mapError(controlReadError(threadId)));
4570 + },
4571 + (effect, threadId, _requestId, _resultId) =>
4572 + effect.pipe(Effect.mapError(controlReadError(threadId))),
4573 + );
4574
4535 - const isNodeStored: ProjectionStoreV2Shape["isNodeStored"] = (node) =>
4536 - Effect.gen(function* () {
4575 + const isNodeStored: ProjectionStoreV2Shape["isNodeStored"] = Effect.fn(
4576 + "ProjectionStore.isNodeStored",
4577 + )(
4578 + function* (node) {
4579 const payloadJson = yield* encodeNodePayload(node);
4580 const rows = yield* sql<PayloadRow>`
4581 SELECT payload_json FROM orchestration_v2_projection_nodes WHERE node_id = ${node.id}
4582 `;
4583 return rows[0]?.payload_json === payloadJson;
4542 - }).pipe(Effect.mapError(controlReadError(node.threadId)));
4584 + },
4585 + (effect, node) => effect.pipe(Effect.mapError(controlReadError(node.threadId))),
4586 + );
4587
4588 const getRuntimeRequest: ProjectionStoreV2Shape["getRuntimeRequest"] = (threadId, requestId) =>
4589 sql
@@ -5107,18 +5151,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5151 readonly item: TimelineIndexItem;
5152 readonly synthetic?: OrchestrationV2TurnItem;
5153 };
5110 - const readTimelineIndex = (
5154 + const readTimelineIndex: (
5155 threadId: ThreadId,
5156 seen: ReadonlySet<ThreadId>,
5113 - ): Effect.Effect<
5157 + ) => Effect.Effect<
5158 {
5159 readonly records: ProjectionRecords<"runs" | "attempts">;
5160 readonly local: ReadonlyArray<TimelineIndexRow>;
5161 readonly visible: ReadonlyArray<TimelineIndexRow>;
5162 },
5163 ProjectionStoreV2Error
5120 - > =>
5121 - Effect.gen(function* () {
5164 + > = Effect.fn("ProjectionStore.readTimelineIndex")(
5165 + function* (threadId: ThreadId, seen: ReadonlySet<ThreadId>) {
5166 const records = yield* getThreadRecords(threadId, ["runs", "attempts"]);
5167 const rows = yield* sql<{
5168 turn_item_id: string;
@@ -5204,13 +5248,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5248 ...visible,
5249 ],
5250 };
5207 - }).pipe(
5208 - Effect.mapError((cause) =>
5209 - isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)
5210 - ? cause
5211 - : new ProjectionStoreReadError({ threadId, cause }),
5251 + },
5252 + (effect, threadId, _seen) =>
5253 + effect.pipe(
5254 + Effect.mapError((cause) =>
5255 + isProjectionStoreThreadNotFoundError(cause) || isProjectionStoreReadError(cause)
5256 + ? cause
5257 + : new ProjectionStoreReadError({ threadId, cause }),
5258 + ),
5259 ),
5213 - );
5260 + );
5261
5262 const { searchThread, searchThreadStream } = yield* makeThreadFind((threadId) =>
5263 readTimelineIndex(threadId, new Set()).pipe(Effect.map((index) => index.visible)),
@@ -5720,47 +5767,46 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5767 return { runOrdinalsByThreadId, itemCountsByThreadId };
5768 };
5769
5723 - const pendingBackgroundDataByThreadId = (input: {
5770 + const pendingBackgroundDataByThreadId = Effect.fn(
5771 + "ProjectionStore.pendingBackgroundDataByThreadId",
5772 + )(function* (input: {
5773 readonly providerThreadRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;
5774 readonly pendingTurnItemRows: ReadonlyArray<ShellPendingTurnItemRow>;
5726 - }) =>
5727 - Effect.gen(function* () {
5728 - const providerThreadsByThreadId = new Map<
5729 - ThreadId,
5730 - Array<OrchestrationV2ThreadProjection["providerThreads"][number]>
5731 - >();
5732 - for (const row of input.providerThreadRows) {
5733 - const providerThread = yield* decodeProviderThreadPayload(row.payload_json);
5734 - const threadId =
5735 - row.thread_id.length > 0 ? ThreadId.make(row.thread_id) : providerThread.appThreadId;
5736 - if (threadId === null) {
5737 - continue;
5738 - }
5739 - const existing = providerThreadsByThreadId.get(threadId) ?? [];
5740 - existing.push(providerThread);
5741 - providerThreadsByThreadId.set(threadId, existing);
5775 + }) {
5776 + const providerThreadsByThreadId = new Map<
5777 + ThreadId,
5778 + Array<OrchestrationV2ThreadProjection["providerThreads"][number]>
5779 + >();
5780 + for (const row of input.providerThreadRows) {
5781 + const providerThread = yield* decodeProviderThreadPayload(row.payload_json);
5782 + const threadId =
5783 + row.thread_id.length > 0 ? ThreadId.make(row.thread_id) : providerThread.appThreadId;
5784 + if (threadId === null) {
5785 + continue;
5786 }
5787 + const existing = providerThreadsByThreadId.get(threadId) ?? [];
5788 + existing.push(providerThread);
5789 + providerThreadsByThreadId.set(threadId, existing);
5790 + }
5791
5744 - const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();
5745 - for (const row of input.pendingTurnItemRows) {
5746 - const turnItem = {
5747 - ...(yield* decodeTurnItemPayload(row.payload_json)),
5748 - ...(row.owning_provider_instance_id === null
5749 - ? {}
5750 - : {
5751 - owningProviderInstanceId: ProviderInstanceId.make(
5752 - row.owning_provider_instance_id,
5753 - ),
5754 - }),
5755 - };
5756 - const threadId = ThreadId.make(row.thread_id);
5757 - const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];
5758 - existing.push(turnItem);
5759 - pendingTurnItemsByThreadId.set(threadId, existing);
5760 - }
5792 + const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();
5793 + for (const row of input.pendingTurnItemRows) {
5794 + const turnItem = {
5795 + ...(yield* decodeTurnItemPayload(row.payload_json)),
5796 + ...(row.owning_provider_instance_id === null
5797 + ? {}
5798 + : {
5799 + owningProviderInstanceId: ProviderInstanceId.make(row.owning_provider_instance_id),
5800 + }),
5801 + };
5802 + const threadId = ThreadId.make(row.thread_id);
5803 + const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];
5804 + existing.push(turnItem);
5805 + pendingTurnItemsByThreadId.set(threadId, existing);
5806 + }
5807
5762 - return { providerThreadsByThreadId, pendingTurnItemsByThreadId };
5763 - });
5808 + return { providerThreadsByThreadId, pendingTurnItemsByThreadId };
5809 + });
5810
5811 const getSettlementCandidates: ProjectionStoreV2Shape["getSettlementCandidates"] = (threadId) =>
5812 sql
@@ -5874,11 +5920,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5920 )
5921 .pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));
5922
5877 - const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = (
5878 - threadId,
5879 - ) =>
5880 - Effect.gen(function* () {
5881 - const rows = yield* sql<PayloadRow>`
5923 + const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] =
5924 + Effect.fn("ProjectionStore.getThreadsWithPullRequests")(
5925 + function* (threadId) {
5926 + const rows = yield* sql<PayloadRow>`
5927 SELECT payload_json
5928 FROM orchestration_v2_projection_threads
5929 WHERE 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> =
5931 AND json_array_length(payload_json, '$.pullRequests') > 0
5932 ORDER BY updated_at ASC, thread_id ASC
5933 `;
5889 - return yield* Effect.forEach(rows, (row) =>
5890 - decodeThreadPayload(row.payload_json).pipe(
5891 - Effect.map((thread): ProjectionThreadPullRequests => ({
5892 - id: thread.id,
5893 - projectId: thread.projectId,
5894 - lineage: thread.lineage,
5895 - settledOverride: thread.settledOverride,
5896 - settledAt: thread.settledAt,
5897 - pullRequests: thread.pullRequests ?? [],
5898 - })),
5899 - ),
5900 - );
5901 - }).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));
5934 + return yield* Effect.forEach(rows, (row) =>
5935 + decodeThreadPayload(row.payload_json).pipe(
5936 + Effect.map((thread): ProjectionThreadPullRequests => ({
5937 + id: thread.id,
5938 + projectId: thread.projectId,
5939 + lineage: thread.lineage,
5940 + settledOverride: thread.settledOverride,
5941 + settledAt: thread.settledAt,
5942 + pullRequests: thread.pullRequests ?? [],
5943 + })),
5944 + ),
5945 + );
5946 + },
5947 + Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
5948 + );
5949
5950 const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = (options) =>
5951 sql<{ readonly thread_id: string; readonly worktree_path: string }>`
@@ -5917,20 +5964,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5964 Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
5965 );
5966
5920 - const shellThreadStateFromRow = (input: {
5921 - readonly row: ShellThreadRow;
5922 - readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
5923 - readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
5924 - readonly providerThreadsByThreadId: ReadonlyMap<
5925 - ThreadId,
5926 - ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>
5927 - >;
5928 - readonly pendingTurnItemsByThreadId: ReadonlyMap<
5929 - ThreadId,
5930 - ReadonlyArray<OrchestrationV2TurnItem>
5931 - >;
5932 - }) =>
5933 - Effect.gen(function* () {
5967 + const shellThreadStateFromRow =
5968 + /* Runs once per shell row; the enclosing snapshot or thread read owns the span. */
5969 + Effect.fnUntraced(function* (input: {
5970 + readonly row: ShellThreadRow;
5971 + readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
5972 + readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
5973 + readonly providerThreadsByThreadId: ReadonlyMap<
5974 + ThreadId,
5975 + ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>
5976 + >;
5977 + readonly pendingTurnItemsByThreadId: ReadonlyMap<
5978 + ThreadId,
5979 + ReadonlyArray<OrchestrationV2TurnItem>
5980 + >;
5981 + }) {
5982 const {
5983 row,
5984 runOrdinalsByThreadId,
@@ -6069,62 +6117,61 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6117 const shellSnapshotReadError = (cause: unknown) =>
6118 new ProjectionStoreReadError({ threadId: ThreadId.make("thread:shell"), cause });
6119
6072 - const readShellSnapshotRows = (options: ShellSnapshotOptions | undefined) =>
6073 - Effect.gen(function* () {
6074 - const targetThreadRows = yield* selectShellThreadRows(undefined, options);
6075 - const targetThreadIds = new Set(
6076 - targetThreadRows.map((row) => ThreadId.make(row.thread_id)),
6077 - );
6078 - const rowsByThreadId = new Map(
6079 - targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const),
6080 - );
6081 - const pendingSourceIds = targetThreadRows.flatMap((row) =>
6082 - row.forked_from_run_source_thread_id === null
6083 - ? []
6084 - : [ThreadId.make(row.forked_from_run_source_thread_id)],
6085 - );
6086 - while (pendingSourceIds.length > 0) {
6087 - const sourceId = pendingSourceIds.pop();
6088 - if (sourceId === undefined || rowsByThreadId.has(sourceId)) continue;
6089 - const source = (yield* selectShellThreadRows(sourceId))[0];
6090 - if (source === undefined) continue;
6091 - rowsByThreadId.set(sourceId, source);
6092 - if (source.forked_from_run_source_thread_id !== null) {
6093 - pendingSourceIds.push(ThreadId.make(source.forked_from_run_source_thread_id));
6094 - }
6120 + const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* (
6121 + options: ShellSnapshotOptions | undefined,
6122 + ) {
6123 + const targetThreadRows = yield* selectShellThreadRows(undefined, options);
6124 + const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id)));
6125 + const rowsByThreadId = new Map(
6126 + targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const),
6127 + );
6128 + const pendingSourceIds = targetThreadRows.flatMap((row) =>
6129 + row.forked_from_run_source_thread_id === null
6130 + ? []
6131 + : [ThreadId.make(row.forked_from_run_source_thread_id)],
6132 + );
6133 + while (pendingSourceIds.length > 0) {
6134 + const sourceId = pendingSourceIds.pop();
6135 + if (sourceId === undefined || rowsByThreadId.has(sourceId)) continue;
6136 + const source = (yield* selectShellThreadRows(sourceId))[0];
6137 + if (source === undefined) continue;
6138 + rowsByThreadId.set(sourceId, source);
6139 + if (source.forked_from_run_source_thread_id !== null) {
6140 + pendingSourceIds.push(ThreadId.make(source.forked_from_run_source_thread_id));
6141 }
6096 - const threadRows = [...rowsByThreadId.values()];
6097 - const threadIds = [...rowsByThreadId.keys()];
6098 - const forkSourceIds = shellForkSourceIds(threadRows);
6099 - const readForThreadIds = <A>(
6100 - read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,
6101 - ids: ReadonlyArray<ThreadId> = threadIds,
6102 - ) => (ids.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : read(ids));
6103 - const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] =
6104 - yield* Effect.all([
6105 - readForThreadIds(selectShellRunRows, forkSourceIds),
6106 - readForThreadIds(selectShellRunItemCounts, forkSourceIds),
6107 - sql<{ readonly snapshot_sequence: number | null }>`
6142 + }
6143 + const threadRows = [...rowsByThreadId.values()];
6144 + const threadIds = [...rowsByThreadId.keys()];
6145 + const forkSourceIds = shellForkSourceIds(threadRows);
6146 + const readForThreadIds = <A>(
6147 + read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,
6148 + ids: ReadonlyArray<ThreadId> = threadIds,
6149 + ) => (ids.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : read(ids));
6150 + const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] =
6151 + yield* Effect.all([
6152 + readForThreadIds(selectShellRunRows, forkSourceIds),
6153 + readForThreadIds(selectShellRunItemCounts, forkSourceIds),
6154 + sql<{ readonly snapshot_sequence: number | null }>`
6155 SELECT MAX(sequence) AS snapshot_sequence
6156 FROM orchestration_events
6157 WHERE application_event_version = 2
6158 AND aggregate_kind = 'thread'
6159 `,
6113 - readForThreadIds(selectShellProviderThreadRows),
6114 - readForThreadIds(selectShellPendingTurnItemRows),
6115 - ]);
6116 - return {
6117 - targetThreadIds,
6118 - threadRows,
6119 - runRows,
6120 - itemCountRows,
6121 - sequenceRows,
6122 - providerThreadRows,
6123 - pendingTurnItemRows,
6124 - };
6125 - });
6160 + readForThreadIds(selectShellProviderThreadRows),
6161 + readForThreadIds(selectShellPendingTurnItemRows),
6162 + ]);
6163 + return {
6164 + targetThreadIds,
6165 + threadRows,
6166 + runRows,
6167 + itemCountRows,
6168 + sequenceRows,
6169 + providerThreadRows,
6170 + pendingTurnItemRows,
6171 + };
6172 + });
6173
6127 - const decodeShellSnapshot = ({
6174 + const decodeShellSnapshot = Effect.fn("ProjectionStore.decodeShellSnapshot")(function* ({
6175 targetThreadIds,
6176 threadRows,
6177 runRows,
@@ -6132,44 +6179,43 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6179 sequenceRows,
6180 providerThreadRows,
6181 pendingTurnItemRows,
6135 - }: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) =>
6136 - Effect.gen(function* () {
6137 - const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
6138 - runRows,
6139 - itemCountRows,
6140 - });
6141 - const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =
6142 - yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });
6143 - const states = yield* Effect.forEach(threadRows, (row) =>
6144 - shellThreadStateFromRow({
6145 - row,
6146 - runOrdinalsByThreadId,
6147 - itemCountsByThreadId,
6148 - providerThreadsByThreadId,
6149 - pendingTurnItemsByThreadId,
6182 + }: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) {
6183 + const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
6184 + runRows,
6185 + itemCountRows,
6186 + });
6187 + const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =
6188 + yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });
6189 + const states = yield* Effect.forEach(threadRows, (row) =>
6190 + shellThreadStateFromRow({
6191 + row,
6192 + runOrdinalsByThreadId,
6193 + itemCountsByThreadId,
6194 + providerThreadsByThreadId,
6195 + pendingTurnItemsByThreadId,
6196 + }),
6197 + );
6198 + const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
6199 +
6200 + const shells = states
6201 + .filter((state) => targetThreadIds.has(state.thread.id))
6202 + .map((state) =>
6203 + shellFromState({
6204 + state,
6205 + visibleItemCount: visibleItemCountForShell({
6206 + threadId: state.thread.id,
6207 + statesByThreadId,
6208 + }),
6209 }),
6210 );
6152 - const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
6211
6154 - const shells = states
6155 - .filter((state) => targetThreadIds.has(state.thread.id))
6156 - .map((state) =>
6157 - shellFromState({
6158 - state,
6159 - visibleItemCount: visibleItemCountForShell({
6160 - threadId: state.thread.id,
6161 - statesByThreadId,
6162 - }),
6163 - }),
6164 - );
6165 -
6166 - return {
6167 - schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
6168 - snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,
6169 - threads: shells.filter((thread) => thread.archivedAt === null),
6170 - archivedThreads: shells.filter((thread) => thread.archivedAt !== null),
6171 - };
6172 - }).pipe(Effect.mapError(shellSnapshotReadError));
6212 + return {
6213 + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
6214 + snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,
6215 + threads: shells.filter((thread) => thread.archivedAt === null),
6216 + archivedThreads: shells.filter((thread) => thread.archivedAt !== null),
6217 + };
6218 + }, Effect.mapError(shellSnapshotReadError));
6219
6220 const readShellSnapshot: ProjectionStoreV2Shape["readShellSnapshot"] = (options) =>
6221 readShellSnapshotRows(options).pipe(
@@ -6301,8 +6347,9 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6347 const sequence = yield* Ref.make(0);
6348
6349 const service: ProjectionStoreV2Shape = {
6304 - apply: (event) =>
6305 - Effect.gen(function* () {
6350 + apply:
6351 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
6352 + Effect.fnUntraced(function* (event) {
6353 const result = yield* Ref.modify(replayState, (existing) => {
6354 const next: ProjectionReplayState = {
6355 projections: new Map(existing.projections),
@@ -6323,65 +6370,62 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6370 }
6371 yield* Ref.update(sequence, (current) => current + 1);
6372 }),
6326 - getShellSnapshot: (options) =>
6327 - Effect.gen(function* () {
6328 - const existing = (yield* Ref.get(replayState)).projections;
6329 - const selectedThreadIds = [...existing.entries()]
6330 - .filter(([, projection]) => {
6331 - if (
6332 - options?.projectId !== undefined &&
6333 - projection.thread.projectId !== options.projectId
6334 - ) {
6335 - return false;
6336 - }
6337 - if (
6338 - options?.unsettledOnly &&
6339 - (projection.thread.settledAt !== null ||
6340 - projection.thread.settledOverride === "settled")
6341 - ) {
6342 - return false;
6343 - }
6344 - if (options?.location === "active") return projection.thread.archivedAt === null;
6345 - if (options?.location === "archive") return projection.thread.archivedAt !== null;
6346 - return true;
6347 - })
6348 - .map(([threadId]) => threadId);
6349 - const shells = yield* Effect.forEach(
6350 - selectedThreadIds.toSorted((left, right) => String(left).localeCompare(String(right))),
6351 - (threadId) =>
6352 - service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),
6353 - );
6354 - const visible = shells.filter((thread) => thread.deletedAt === null);
6355 - return {
6356 - schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
6357 - snapshotSequence: yield* Ref.get(sequence),
6358 - threads: visible.filter((thread) => thread.archivedAt === null),
6359 - archivedThreads: visible.filter((thread) => thread.archivedAt !== null),
6360 - };
6361 - }),
6373 + getShellSnapshot: Effect.fn("ProjectionStore.getShellSnapshot")(function* (options) {
6374 + const existing = (yield* Ref.get(replayState)).projections;
6375 + const selectedThreadIds = [...existing.entries()]
6376 + .filter(([, projection]) => {
6377 + if (
6378 + options?.projectId !== undefined &&
6379 + projection.thread.projectId !== options.projectId
6380 + ) {
6381 + return false;
6382 + }
6383 + if (
6384 + options?.unsettledOnly &&
6385 + (projection.thread.settledAt !== null ||
6386 + projection.thread.settledOverride === "settled")
6387 + ) {
6388 + return false;
6389 + }
6390 + if (options?.location === "active") return projection.thread.archivedAt === null;
6391 + if (options?.location === "archive") return projection.thread.archivedAt !== null;
6392 + return true;
6393 + })
6394 + .map(([threadId]) => threadId);
6395 + const shells = yield* Effect.forEach(
6396 + selectedThreadIds.toSorted((left, right) => String(left).localeCompare(String(right))),
6397 + (threadId) =>
6398 + service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),
6399 + );
6400 + const visible = shells.filter((thread) => thread.deletedAt === null);
6401 + return {
6402 + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
6403 + snapshotSequence: yield* Ref.get(sequence),
6404 + threads: visible.filter((thread) => thread.archivedAt === null),
6405 + archivedThreads: visible.filter((thread) => thread.archivedAt !== null),
6406 + };
6407 + }),
6408 readShellSnapshot: (options) =>
6409 service.getShellSnapshot(options).pipe(Effect.map(Effect.succeed)),
6364 - getThreadShell: (threadId) =>
6365 - Effect.gen(function* () {
6366 - const existing = (yield* Ref.get(replayState)).projections;
6367 - if (!existing.has(threadId)) {
6368 - return null;
6369 - }
6370 - const shell = yield* service
6371 - .getThreadProjection(threadId)
6372 - .pipe(Effect.map(threadShellFromProjection));
6373 - return shell.deletedAt === null ? shell : null;
6374 - }),
6375 - getThread: (threadId) =>
6376 - Effect.gen(function* () {
6377 - const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6378 - if (projection === undefined) {
6379 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6380 - }
6381 - return projection.thread;
6382 - }),
6383 - getSettlementCandidates: (threadId) =>
6384 - Effect.gen(function* () {
6410 + getThreadShell: Effect.fn("ProjectionStore.getThreadShell")(function* (threadId) {
6411 + const existing = (yield* Ref.get(replayState)).projections;
6412 + if (!existing.has(threadId)) {
6413 + return null;
6414 + }
6415 + const shell = yield* service
6416 + .getThreadProjection(threadId)
6417 + .pipe(Effect.map(threadShellFromProjection));
6418 + return shell.deletedAt === null ? shell : null;
6419 + }),
6420 + getThread: Effect.fn("ProjectionStore.getThread")(function* (threadId) {
6421 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6422 + if (projection === undefined) {
6423 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6424 + }
6425 + return projection.thread;
6426 + }),
6427 + getSettlementCandidates: Effect.fn("ProjectionStore.getSettlementCandidates")(
6428 + function* (threadId) {
6429 const projections = (yield* Ref.get(replayState)).projections;
6430 return [...projections.values()]
6431 .filter(
@@ -6408,7 +6452,8 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6452 DateTime.toEpochMillis(left.updatedAt) - DateTime.toEpochMillis(right.updatedAt) ||
6453 left.id.localeCompare(right.id),
6454 );
6411 - }),
6455 + },
6456 + ),
6457 getThreadWorktreePaths: (options) =>
6458 Ref.get(replayState).pipe(
6459 Effect.map((state) =>
@@ -6490,30 +6535,29 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6535 .toSorted((left, right) => left.id.localeCompare(right.id)),
6536 ),
6537 ),
6493 - getRecoveryThreadIds: (kind) =>
6494 - Effect.gen(function* () {
6495 - const projections = (yield* Ref.get(replayState)).projections;
6496 - return [...projections.values()]
6497 - .filter((projection) =>
6498 - needsRecovery(
6499 - projection,
6500 - kind,
6501 - projection.thread.lineage.parentThreadId === null
6502 - ? undefined
6503 - : projections.get(projection.thread.lineage.parentThreadId),
6504 - ),
6505 - )
6506 - .toSorted(
6507 - (left, right) =>
6508 - DateTime.toEpochMillis(left.thread.updatedAt) -
6509 - DateTime.toEpochMillis(right.thread.updatedAt) ||
6510 - left.thread.id.localeCompare(right.thread.id),
6511 - )
6512 - .map((projection) => projection.thread.id);
6513 - }),
6538 + getRecoveryThreadIds: Effect.fn("ProjectionStore.getRecoveryThreadIds")(function* (kind) {
6539 + const projections = (yield* Ref.get(replayState)).projections;
6540 + return [...projections.values()]
6541 + .filter((projection) =>
6542 + needsRecovery(
6543 + projection,
6544 + kind,
6545 + projection.thread.lineage.parentThreadId === null
6546 + ? undefined
6547 + : projections.get(projection.thread.lineage.parentThreadId),
6548 + ),
6549 + )
6550 + .toSorted(
6551 + (left, right) =>
6552 + DateTime.toEpochMillis(left.thread.updatedAt) -
6553 + DateTime.toEpochMillis(right.thread.updatedAt) ||
6554 + left.thread.id.localeCompare(right.thread.id),
6555 + )
6556 + .map((projection) => projection.thread.id);
6557 + }),
6558 getUnreadableThreadIds: () => Effect.succeed([]),
6515 - getPendingNativeUserInputs: (threadId, providerTurnId) =>
6516 - Effect.gen(function* () {
6559 + getPendingNativeUserInputs: Effect.fn("ProjectionStore.getPendingNativeUserInputs")(
6560 + function* (threadId, providerTurnId) {
6561 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6562 if (projection === undefined) return { runtimeRequests: [], nodes: [], turnItems: [] };
6563 const runtimeRequests = projection.runtimeRequests.filter(
@@ -6532,23 +6576,24 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6576 (item) => item.type === "user_input_request" && requestIds.has(item.requestId),
6577 ),
6578 };
6535 - }),
6536 - getPlan: (threadId, planId) =>
6537 - Effect.gen(function* () {
6538 - const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6539 - if (projection === undefined)
6540 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6541 - return projection.plans.find((plan) => plan.id === planId);
6542 - }),
6543 - hasUnpairedRunInterruptRequest: (threadId, requestId, resultId) =>
6544 - Effect.gen(function* () {
6579 + },
6580 + ),
6581 + getPlan: Effect.fn("ProjectionStore.getPlan")(function* (threadId, planId) {
6582 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6583 + if (projection === undefined)
6584 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6585 + return projection.plans.find((plan) => plan.id === planId);
6586 + }),
6587 + hasUnpairedRunInterruptRequest: Effect.fn("ProjectionStore.hasUnpairedRunInterruptRequest")(
6588 + function* (threadId, requestId, resultId) {
6589 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6590 return (
6591 projection !== undefined &&
6592 projection.turnItems.some((item) => item.id === requestId) &&
6593 !projection.turnItems.some((item) => item.id === resultId)
6594 );
6551 - }),
6595 + },
6596 + ),
6597 isNodeStored: (node) =>
6598 Ref.get(replayState).pipe(
6599 Effect.map((state) => {
@@ -6594,8 +6639,8 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6639 ]),
6640 ]),
6641 ),
6597 - getThreadRecords: (threadId, fields, filter) =>
6598 - Effect.gen(function* () {
6642 + getThreadRecords: Effect.fn("ProjectionStore.getThreadRecords")(
6643 + function* (threadId, fields, filter) {
6644 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6645 if (projection === undefined)
6646 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6630,16 +6675,18 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6675 ["thread", projection.thread],
6676 ...fields.map((field) => [field, selected[field]]),
6677 ]) as ProjectionRecords<(typeof fields)[number]>;
6633 - }),
6634 - getRuntimeRequest: (threadId, requestId) =>
6635 - Effect.gen(function* () {
6678 + },
6679 + ),
6680 + getRuntimeRequest: Effect.fn("ProjectionStore.getRuntimeRequest")(
6681 + function* (threadId, requestId) {
6682 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6683 if (projection === undefined)
6684 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6685 return projection.runtimeRequests.find((request) => request.id === requestId);
6640 - }),
6641 - getProviderControlContext: (threadId, target) =>
6642 - Effect.gen(function* () {
6686 + },
6687 + ),
6688 + getProviderControlContext: Effect.fn("ProjectionStore.getProviderControlContext")(
6689 + function* (threadId, target) {
6690 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6691 if (projection === undefined)
6692 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6664,9 +6711,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6711 ? undefined
6712 : projection.runs.find((run) => run.activeAttemptId === providerTurn.runAttemptId),
6713 };
6667 - }),
6668 - getRunningTurnContext: (threadId) =>
6669 - Effect.gen(function* () {
6714 + },
6715 + ),
6716 + getRunningTurnContext: Effect.fn("ProjectionStore.getRunningTurnContext")(
6717 + function* (threadId) {
6718 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6719 if (projection === undefined)
6720 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6684,9 +6732,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6732 turn.status === "running",
6733 ),
6734 };
6687 - }),
6688 - getThreadProviderContext: (threadId, targetInstanceId) =>
6689 - Effect.gen(function* () {
6735 + },
6736 + ),
6737 + getThreadProviderContext: Effect.fn("ProjectionStore.getThreadProviderContext")(
6738 + function* (threadId, targetInstanceId) {
6739 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6740 if (projection === undefined)
6741 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6714,9 +6763,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6763 thread.id === target?.id,
6764 ),
6765 };
6717 - }),
6718 - getRuntimeResponseContext: (threadId, requestId) =>
6719 - Effect.gen(function* () {
6766 + },
6767 + ),
6768 + getRuntimeResponseContext: Effect.fn("ProjectionStore.getRuntimeResponseContext")(
6769 + function* (threadId, requestId) {
6770 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6771 if (projection === undefined)
6772 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6736,35 +6786,35 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6786 session.id === request.responseCapability.providerSessionId,
6787 ),
6788 };
6739 - }),
6740 - getCheckpointContext: (threadId) =>
6741 - Effect.gen(function* () {
6742 - const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6743 - if (projection === undefined) {
6744 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6745 - }
6746 - return {
6747 - runs: projection.runs.map(({ id, ordinal, status }) => ({ id, ordinal, status })),
6748 - checkpointScopes: projection.checkpointScopes.map(({ id, runId, kind, cwd }) => ({
6749 - id,
6789 + },
6790 + ),
6791 + getCheckpointContext: Effect.fn("ProjectionStore.getCheckpointContext")(function* (threadId) {
6792 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6793 + if (projection === undefined) {
6794 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6795 + }
6796 + return {
6797 + runs: projection.runs.map(({ id, ordinal, status }) => ({ id, ordinal, status })),
6798 + checkpointScopes: projection.checkpointScopes.map(({ id, runId, kind, cwd }) => ({
6799 + id,
6800 + runId,
6801 + kind,
6802 + cwd,
6803 + })),
6804 + checkpoints: projection.checkpoints.map(
6805 + ({ scopeId, runId, ordinalWithinScope, appRunOrdinal, status, ref }) => ({
6806 + scopeId,
6807 runId,
6751 - kind,
6752 - cwd,
6753 - })),
6754 - checkpoints: projection.checkpoints.map(
6755 - ({ scopeId, runId, ordinalWithinScope, appRunOrdinal, status, ref }) => ({
6756 - scopeId,
6757 - runId,
6758 - ordinalWithinScope,
6759 - appRunOrdinal,
6760 - status,
6761 - ref,
6762 - }),
6763 - ),
6764 - };
6765 - }),
6766 - getCheckpointCaptureContext: (threadId, target) =>
6767 - Effect.gen(function* () {
6808 + ordinalWithinScope,
6809 + appRunOrdinal,
6810 + status,
6811 + ref,
6812 + }),
6813 + ),
6814 + };
6815 + }),
6816 + getCheckpointCaptureContext: Effect.fn("ProjectionStore.getCheckpointCaptureContext")(
6817 + function* (threadId, target) {
6818 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6819 if (projection === undefined)
6820 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6782,9 +6832,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6832 )
6833 .map((candidate) => candidate.ordinalWithinScope),
6834 };
6785 - }),
6786 - getCheckpointRollbackContext: (threadId, target) =>
6787 - Effect.gen(function* () {
6835 + },
6836 + ),
6837 + getCheckpointRollbackContext: Effect.fn("ProjectionStore.getCheckpointRollbackContext")(
6838 + function* (threadId, target) {
6839 const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6840 if (projection === undefined)
6841 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
@@ -6868,77 +6919,75 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6919 candidate.status === "ready",
6920 ),
6921 };
6871 - }),
6872 - getRunMessage: (threadId, runId) =>
6873 - Effect.gen(function* () {
6874 - const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6875 - if (projection === undefined)
6876 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6877 - const run = projection.runs.find((candidate) => candidate.id === runId);
6878 - return projection.messages.find((message) => message.id === run?.userMessageId);
6879 - }),
6880 - canStartQueuedRun: (threadId) =>
6881 - Effect.gen(function* () {
6882 - const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6883 - if (projection === undefined)
6884 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6885 - return (
6886 - projection.thread.archivedAt === null &&
6887 - projection.thread.deletedAt === null &&
6888 - projection.runs.some((run) => run.status === "queued") &&
6889 - !projection.runs.some(
6890 - (run) =>
6891 - run.status === "preparing" ||
6892 - run.status === "starting" ||
6893 - run.status === "running" ||
6894 - run.status === "waiting" ||
6895 - (run.status === "queued" && run.queueHeld === true),
6896 - )
6897 - );
6898 - }),
6899 - getThreadProjection: (threadId) =>
6900 - Effect.gen(function* () {
6901 - const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);
6902 - const readProjection = (
6903 - targetThreadId: ThreadId,
6904 - seenThreadIds: ReadonlySet<ThreadId>,
6905 - ): OrchestrationV2ThreadProjection | null => {
6906 - const projection = existing.get(targetThreadId);
6907 - if (!projection) {
6908 - return null;
6909 - }
6910 - const forkedFrom = projection.thread.forkedFrom;
6911 - if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
6912 - return withLocalVisibleTurnItems(projection);
6913 - }
6914 - const sourceProjection = readProjection(
6915 - forkedFrom.threadId,
6916 - new Set([...seenThreadIds, targetThreadId]),
6917 - );
6918 - return {
6919 - ...projection,
6920 - visibleTurnItems: buildVisibleTurnItems({
6921 - projection,
6922 - sourceProjection,
6923 - }),
6924 - };
6925 - };
6926 - const projection = readProjection(threadId, new Set());
6922 + },
6923 + ),
6924 + getRunMessage: Effect.fn("ProjectionStore.getRunMessage")(function* (threadId, runId) {
6925 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6926 + if (projection === undefined)
6927 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6928 + const run = projection.runs.find((candidate) => candidate.id === runId);
6929 + return projection.messages.find((message) => message.id === run?.userMessageId);
6930 + }),
6931 + canStartQueuedRun: Effect.fn("ProjectionStore.canStartQueuedRun")(function* (threadId) {
6932 + const projection = (yield* Ref.get(replayState)).projections.get(threadId);
6933 + if (projection === undefined)
6934 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6935 + return (
6936 + projection.thread.archivedAt === null &&
6937 + projection.thread.deletedAt === null &&
6938 + projection.runs.some((run) => run.status === "queued") &&
6939 + !projection.runs.some(
6940 + (run) =>
6941 + run.status === "preparing" ||
6942 + run.status === "starting" ||
6943 + run.status === "running" ||
6944 + run.status === "waiting" ||
6945 + (run.status === "queued" && run.queueHeld === true),
6946 + )
6947 + );
6948 + }),
6949 + getThreadProjection: Effect.fn("ProjectionStore.getThreadProjection")(function* (threadId) {
6950 + const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);
6951 + const readProjection = (
6952 + targetThreadId: ThreadId,
6953 + seenThreadIds: ReadonlySet<ThreadId>,
6954 + ): OrchestrationV2ThreadProjection | null => {
6955 + const projection = existing.get(targetThreadId);
6956 if (!projection) {
6928 - return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6957 + return null;
6958 + }
6959 + const forkedFrom = projection.thread.forkedFrom;
6960 + if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) {
6961 + return withLocalVisibleTurnItems(projection);
6962 }
6930 - // Match the SQL shell join, including provider threads stored on child app threads.
6963 + const sourceProjection = readProjection(
6964 + forkedFrom.threadId,
6965 + new Set([...seenThreadIds, targetThreadId]),
6966 + );
6967 return {
6968 ...projection,
6933 - turnItems: projection.turnItems.map((item) => {
6934 - const owner =
6935 - item.type !== "subagent" || item.providerThreadId === null
6936 - ? undefined
6937 - : providerThreadInstanceIds.get(item.providerThreadId);
6938 - return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };
6969 + visibleTurnItems: buildVisibleTurnItems({
6970 + projection,
6971 + sourceProjection,
6972 }),
6973 };
6941 - }),
6974 + };
6975 + const projection = readProjection(threadId, new Set());
6976 + if (!projection) {
6977 + return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6978 + }
6979 + // Match the SQL shell join, including provider threads stored on child app threads.
6980 + return {
6981 + ...projection,
6982 + turnItems: projection.turnItems.map((item) => {
6983 + const owner =
6984 + item.type !== "subagent" || item.providerThreadId === null
6985 + ? undefined
6986 + : providerThreadInstanceIds.get(item.providerThreadId);
6987 + return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };
6988 + }),
6989 + };
6990 + }),
6991 getTurnStartContext: (threadId, runId) =>
6992 service.getThreadProjection(threadId).pipe(
6993 Effect.map((projection) => ({
apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+342 -328
@@ -310,18 +310,19 @@ export const layer: Layer.Layer<
310 const agentScope = yield* AgentScope;
311 const completedTurnAnalytics = new Set<string>();
312
313 - const makeDomainEvent = (
314 - input: ProviderEventIngestInput,
315 - payloadInput: {
316 - readonly type: OrchestrationV2DomainEvent["type"];
317 - readonly payload: OrchestrationV2DomainEvent["payload"];
318 - readonly threadId?: ThreadId;
319 - readonly runId?: RunId | null;
320 - readonly nodeId?: NodeId | null;
321 - readonly occurredAt?: DateTime.Utc;
322 - },
323 - ) =>
324 - Effect.gen(function* () {
313 + const makeDomainEvent =
314 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
315 + Effect.fnUntraced(function* (
316 + input: ProviderEventIngestInput,
317 + payloadInput: {
318 + readonly type: OrchestrationV2DomainEvent["type"];
319 + readonly payload: OrchestrationV2DomainEvent["payload"];
320 + readonly threadId?: ThreadId;
321 + readonly runId?: RunId | null;
322 + readonly nodeId?: NodeId | null;
323 + readonly occurredAt?: DateTime.Utc;
324 + },
325 + ) {
326 const threadId = payloadInput.threadId ?? input.threadId;
327 const eventId = yield* idAllocator.allocate.event({
328 threadId,
@@ -517,339 +518,352 @@ export const layer: Layer.Layer<
518 return events;
519 });
520
520 - const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
521 - Effect.gen(function* () {
522 - switch (input.event.type) {
523 - case "app_thread.created": {
524 - const offered = input.event.appThread;
525 - const existing = yield* projections.getThread(offered.id).pipe(
526 - Effect.catchTags({
527 - ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
528 - }),
529 - );
530 - if (
531 - existing !== null &&
532 - existing.title === offered.title &&
533 - modelSelectionsEqual(existing.modelSelection, offered.modelSelection)
534 - )
535 - return [];
536 - const now = yield* DateTime.now;
537 - return [
538 - yield* makeDomainEvent(input, {
539 - type: existing === null ? "thread.created" : "thread.metadata-updated",
540 - threadId: offered.id,
541 - payload:
542 - existing === null
543 - ? offered
544 - : {
545 - ...existing,
546 - title: offered.title,
547 - modelSelection: offered.modelSelection,
548 - updatedAt: now,
549 - },
550 - occurredAt: now,
551 - }),
552 - ];
553 - }
554 - case "provider_session.updated":
555 - return [
556 - yield* makeDomainEvent(input, {
557 - type: "provider-session.updated",
558 - payload: input.event.providerSession,
559 - }),
560 - ];
561 - case "provider_thread.updated": {
562 - const threadId = input.event.providerThread.appThreadId ?? input.threadId;
563 - const updated = yield* makeDomainEvent(input, {
564 - type: "provider-thread.updated",
565 - threadId,
566 - payload: input.event.providerThread,
567 - });
568 - return input.event.retainedNativeTurnIds === undefined
569 - ? [updated]
570 - : [
571 - updated,
572 - ...(yield* rollBackRewoundRuns(input, {
573 - threadId,
574 - providerThreadId: input.event.providerThread.id,
575 - retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
576 - })),
577 - ];
578 - }
579 - case "provider_turn.updated":
580 - return [
581 - ...(["completed", "interrupted", "failed", "cancelled"].includes(
582 - input.event.providerTurn.status,
521 + const normalize: ProviderEventIngestorV2Shape["normalize"] =
522 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
523 + Effect.fnUntraced(
524 + function* (input) {
525 + switch (input.event.type) {
526 + case "app_thread.created": {
527 + const offered = input.event.appThread;
528 + const existing = yield* projections.getThread(offered.id).pipe(
529 + Effect.catchTags({
530 + ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
531 + }),
532 + );
533 + if (
534 + existing !== null &&
535 + existing.title === offered.title &&
536 + modelSelectionsEqual(existing.modelSelection, offered.modelSelection)
537 )
584 - ? yield* dismissNativeUserInputs(
585 - input,
586 - input.event.providerTurn.id,
587 - input.event.threadId,
588 - )
589 - : []),
590 - yield* makeDomainEvent(input, {
591 - type: "provider-turn.updated",
592 - ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
593 - payload: input.event.providerTurn,
594 - nodeId: input.event.providerTurn.nodeId,
595 - }),
596 - ];
597 - case "node.updated":
598 - // Adapters send an unchanged node again with each text delta. Compare with the
599 - // stored node, not the last one sent, because the server also writes nodes.
600 - if (yield* projections.isNodeStored(input.event.node)) return [];
601 - return [
602 - yield* makeDomainEvent(input, {
603 - type: "node.updated",
604 - threadId: input.event.node.threadId,
605 - payload: input.event.node,
606 - runId: input.event.node.runId,
607 - nodeId: input.event.node.id,
608 - }),
609 - ];
610 - case "subagent.updated":
611 - return [
612 - yield* makeDomainEvent(input, {
613 - type: "subagent.updated",
614 - threadId: input.event.subagent.threadId,
615 - payload: input.event.subagent,
616 - runId: input.event.subagent.runId,
617 - nodeId: input.event.subagent.id,
618 - }),
619 - ];
620 - case "message.updated":
621 - return [
622 - yield* makeDomainEvent(input, {
623 - type: "message.updated",
624 - threadId: input.event.message.threadId,
625 - payload: input.event.message,
626 - runId: input.event.message.runId,
627 - nodeId: input.event.message.nodeId,
628 - }),
629 - ];
630 - case "turn_item.updated":
631 - return [
632 - yield* makeDomainEvent(input, {
633 - type: "turn-item.updated",
634 - threadId: input.event.turnItem.threadId,
635 - payload: boundFileChangeForStorage(
636 - stripUnservedToolOutputImageBytes(input.event.turnItem),
637 - ),
638 - runId: input.event.turnItem.runId,
639 - nodeId: input.event.turnItem.nodeId,
640 - }),
641 - ];
642 - case "runtime_request.updated":
643 - return [
644 - yield* makeDomainEvent(input, {
645 - type: "runtime-request.updated",
646 - ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
647 - payload: input.event.runtimeRequest,
648 - nodeId: input.event.runtimeRequest.nodeId,
649 - }),
650 - ];
651 - case "plan.updated": {
652 - const occurredAt = yield* DateTime.now;
653 - const plan = input.event.plan;
654 - const previous =
655 - plan.kind === "todo_list"
656 - ? yield* projections.getPlan(plan.threadId, plan.id)
657 - : undefined;
658 - const payload =
659 - plan.kind === "todo_list"
660 - ? withPlanStepDurations(
661 - plan,
662 - previous?.kind === "todo_list" ? previous : undefined,
538 + return [];
539 + const now = yield* DateTime.now;
540 + return [
541 + yield* makeDomainEvent(input, {
542 + type: existing === null ? "thread.created" : "thread.metadata-updated",
543 + threadId: offered.id,
544 + payload:
545 + existing === null
546 + ? offered
547 + : {
548 + ...existing,
549 + title: offered.title,
550 + modelSelection: offered.modelSelection,
551 + updatedAt: now,
552 + },
553 + occurredAt: now,
554 + }),
555 + ];
556 + }
557 + case "provider_session.updated":
558 + return [
559 + yield* makeDomainEvent(input, {
560 + type: "provider-session.updated",
561 + payload: input.event.providerSession,
562 + }),
563 + ];
564 + case "provider_thread.updated": {
565 + const threadId = input.event.providerThread.appThreadId ?? input.threadId;
566 + const updated = yield* makeDomainEvent(input, {
567 + type: "provider-thread.updated",
568 + threadId,
569 + payload: input.event.providerThread,
570 + });
571 + return input.event.retainedNativeTurnIds === undefined
572 + ? [updated]
573 + : [
574 + updated,
575 + ...(yield* rollBackRewoundRuns(input, {
576 + threadId,
577 + providerThreadId: input.event.providerThread.id,
578 + retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
579 + })),
580 + ];
581 + }
582 + case "provider_turn.updated":
583 + return [
584 + ...(["completed", "interrupted", "failed", "cancelled"].includes(
585 + input.event.providerTurn.status,
586 + )
587 + ? yield* dismissNativeUserInputs(
588 + input,
589 + input.event.providerTurn.id,
590 + input.event.threadId,
591 + )
592 + : []),
593 + yield* makeDomainEvent(input, {
594 + type: "provider-turn.updated",
595 + ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
596 + payload: input.event.providerTurn,
597 + nodeId: input.event.providerTurn.nodeId,
598 + }),
599 + ];
600 + case "node.updated":
601 + // Adapters send an unchanged node again with each text delta. Compare with the
602 + // stored node, not the last one sent, because the server also writes nodes.
603 + if (yield* projections.isNodeStored(input.event.node)) return [];
604 + return [
605 + yield* makeDomainEvent(input, {
606 + type: "node.updated",
607 + threadId: input.event.node.threadId,
608 + payload: input.event.node,
609 + runId: input.event.node.runId,
610 + nodeId: input.event.node.id,
611 + }),
612 + ];
613 + case "subagent.updated":
614 + return [
615 + yield* makeDomainEvent(input, {
616 + type: "subagent.updated",
617 + threadId: input.event.subagent.threadId,
618 + payload: input.event.subagent,
619 + runId: input.event.subagent.runId,
620 + nodeId: input.event.subagent.id,
621 + }),
622 + ];
623 + case "message.updated":
624 + return [
625 + yield* makeDomainEvent(input, {
626 + type: "message.updated",
627 + threadId: input.event.message.threadId,
628 + payload: input.event.message,
629 + runId: input.event.message.runId,
630 + nodeId: input.event.message.nodeId,
631 + }),
632 + ];
633 + case "turn_item.updated":
634 + return [
635 + yield* makeDomainEvent(input, {
636 + type: "turn-item.updated",
637 + threadId: input.event.turnItem.threadId,
638 + payload: boundFileChangeForStorage(
639 + stripUnservedToolOutputImageBytes(input.event.turnItem),
640 + ),
641 + runId: input.event.turnItem.runId,
642 + nodeId: input.event.turnItem.nodeId,
643 + }),
644 + ];
645 + case "runtime_request.updated":
646 + return [
647 + yield* makeDomainEvent(input, {
648 + type: "runtime-request.updated",
649 + ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
650 + payload: input.event.runtimeRequest,
651 + nodeId: input.event.runtimeRequest.nodeId,
652 + }),
653 + ];
654 + case "plan.updated": {
655 + const occurredAt = yield* DateTime.now;
656 + const plan = input.event.plan;
657 + const previous =
658 + plan.kind === "todo_list"
659 + ? yield* projections.getPlan(plan.threadId, plan.id)
660 + : undefined;
661 + const payload =
662 + plan.kind === "todo_list"
663 + ? withPlanStepDurations(
664 + plan,
665 + previous?.kind === "todo_list" ? previous : undefined,
666 + occurredAt,
667 + )
668 + : plan;
669 + return [
670 + yield* makeDomainEvent(input, {
671 + type: "plan.updated",
672 + threadId: plan.threadId,
673 + payload,
674 + runId: plan.runId,
675 + nodeId: plan.nodeId,
676 + occurredAt,
677 + }),
678 + ];
679 + }
680 + case "command_output.delta":
681 + // Live output is routed to the command output hub before ingestion.
682 + return [];
683 + case "turn.terminal":
684 + const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
685 + if (input.event.status !== "failed") {
686 + return dismissed;
687 + }
688 + const occurredAt = yield* DateTime.now;
689 + const failure = (yield* agentScope.oomKilled(input.threadId))
690 + ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
691 + : input.event.failure;
692 + return [
693 + ...dismissed,
694 + yield* makeDomainEvent(input, {
695 + type: "turn-item.updated",
696 + payload: makeProviderFailureTurnItem({
697 + driver: input.event.driver,
698 + threadId: input.threadId,
699 + runId: input.runId ?? null,
700 + nodeId: input.nodeId ?? null,
701 + providerThreadId: input.event.providerThreadId,
702 + providerTurnId: input.event.providerTurnId,
703 + itemOrdinal: input.event.failureItemOrdinal,
704 + failure,
705 + ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
706 + ...(input.event.retryStartedAt === undefined
707 + ? {}
708 + : { retryStartedAt: input.event.retryStartedAt }),
709 occurredAt,
664 - )
665 - : plan;
666 - return [
667 - yield* makeDomainEvent(input, {
668 - type: "plan.updated",
669 - threadId: plan.threadId,
670 - payload,
671 - runId: plan.runId,
672 - nodeId: plan.nodeId,
673 - occurredAt,
674 - }),
675 - ];
710 + }),
711 + }),
712 + ];
713 }
677 - case "command_output.delta":
678 - // Live output is routed to the command output hub before ingestion.
679 - return [];
680 - case "turn.terminal":
681 - const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
682 - if (input.event.status !== "failed") {
683 - return dismissed;
684 - }
685 - const occurredAt = yield* DateTime.now;
686 - const failure = (yield* agentScope.oomKilled(input.threadId))
687 - ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
688 - : input.event.failure;
689 - return [
690 - ...dismissed,
691 - yield* makeDomainEvent(input, {
692 - type: "turn-item.updated",
693 - payload: makeProviderFailureTurnItem({
694 - driver: input.event.driver,
714 + },
715 + (effect, input) =>
716 + effect.pipe(
717 + Effect.mapError(
718 + (cause) =>
719 + new ProviderEventNormalizeError({
720 + providerSessionId: input.providerSessionId,
721 threadId: input.threadId,
696 - runId: input.runId ?? null,
697 - nodeId: input.nodeId ?? null,
698 - providerThreadId: input.event.providerThreadId,
699 - providerTurnId: input.event.providerTurnId,
700 - itemOrdinal: input.event.failureItemOrdinal,
701 - failure,
702 - ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
703 - ...(input.event.retryStartedAt === undefined
704 - ? {}
705 - : { retryStartedAt: input.event.retryStartedAt }),
706 - occurredAt,
722 + providerEvent: input.event,
723 + cause,
724 }),
708 - }),
709 - ];
710 - }
711 - }).pipe(
712 - Effect.mapError(
713 - (cause) =>
714 - new ProviderEventNormalizeError({
715 - providerSessionId: input.providerSessionId,
716 - threadId: input.threadId,
717 - providerEvent: input.event,
718 - cause,
719 - }),
720 - ),
725 + ),
726 + ),
727 );
728
729 return ProviderEventIngestorV2.of({
730 normalize,
725 - ingestNormalized: (input) =>
726 - Effect.gen(function* () {
727 - const events = yield* normalize(input);
728 - if (events.length === 0) {
729 - return [];
730 - }
731 - const mapWriteError = (cause: unknown) =>
732 - new ProviderEventPublishError({
733 - providerSessionId: input.providerSessionId,
734 - eventCount: events.length,
735 - cause,
736 - });
737 - if (input.writeIfProviderThreadOwner !== undefined) {
738 - const ownerResult = yield* eventSink
739 - .writeIfProviderThreadOwner({
740 - guardPendingUserInputCancellations: true,
741 - ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
742 - ...input.writeIfProviderThreadOwner,
743 - events,
744 - })
745 - .pipe(Effect.mapError(mapWriteError));
746 - return ownerResult.storedEvents;
747 - }
748 - if (input.writeIfRunCurrent === undefined) {
749 - return yield* eventSink
750 - .write({
731 + ingestNormalized:
732 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
733 + Effect.fnUntraced(
734 + function* (input) {
735 + const events = yield* normalize(input);
736 + if (events.length === 0) {
737 + return [];
738 + }
739 + const mapWriteError = (cause: unknown) =>
740 + new ProviderEventPublishError({
741 + providerSessionId: input.providerSessionId,
742 + eventCount: events.length,
743 + cause,
744 + });
745 + if (input.writeIfProviderThreadOwner !== undefined) {
746 + const ownerResult = yield* eventSink
747 + .writeIfProviderThreadOwner({
748 + guardPendingUserInputCancellations: true,
749 + ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
750 + ...input.writeIfProviderThreadOwner,
751 + events,
752 + })
753 + .pipe(Effect.mapError(mapWriteError));
754 + return ownerResult.storedEvents;
755 + }
756 + if (input.writeIfRunCurrent === undefined) {
757 + return yield* eventSink
758 + .write({
759 + guardPendingUserInputCancellations: true,
760 + ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
761 + events,
762 + })
763 + .pipe(Effect.mapError(mapWriteError));
764 + }
765 + const result = yield* eventSink
766 + .writeIfRunCurrent({
767 guardPendingUserInputCancellations: true,
768 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
769 + threadId: input.threadId,
770 + ...input.writeIfRunCurrent,
771 events,
772 })
773 .pipe(Effect.mapError(mapWriteError));
756 - }
757 - const result = yield* eventSink
758 - .writeIfRunCurrent({
759 - guardPendingUserInputCancellations: true,
760 - ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
761 - threadId: input.threadId,
762 - ...input.writeIfRunCurrent,
763 - events,
764 - })
765 - .pipe(Effect.mapError(mapWriteError));
766 - return result.storedEvents;
767 - }).pipe(
768 - Effect.flatMap((storedEvents) =>
769 - Effect.gen(function* () {
770 - if (input.event.type !== "app_thread.created") return storedEvents;
771 - const created = storedEvents.find((stored) => stored.event.type === "thread.created");
772 - if (created?.event.type !== "thread.created") return storedEvents;
773 - const child = created.event.payload;
774 - if (
775 - child.worktreePath === null ||
776 - child.branch === null ||
777 - !isTemporaryWorktreeBranch(child.branch)
778 - )
779 - return storedEvents;
780 - // Git renames before scanning committed threads. If that scan missed this
781 - // creation, HEAD already has the new name, even if the parent moved away.
782 - const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
783 - if (branch === null || branch === child.branch) return storedEvents;
784 - const now = yield* DateTime.now;
785 - const event = yield* makeDomainEvent(input, {
786 - type: "thread.metadata-updated",
787 - threadId: child.id,
788 - payload: { ...child, branch, updatedAt: now },
789 - occurredAt: now,
790 - });
791 - const synced = yield* eventSink.write({ events: [event] });
792 - return [...storedEvents, ...synced];
793 - }).pipe(
794 - Effect.catchCause((cause) =>
795 - Effect.logWarning("Native thread worktree branch recheck failed", {
796 - threadId:
797 - input.event.type === "app_thread.created"
798 - ? input.event.appThread.id
799 - : input.threadId,
800 - cause,
801 - }).pipe(Effect.as(storedEvents)),
802 - ),
803 - ),
804 - ),
805 - Effect.flatMap((storedEvents) =>
806 - storedEvents.length === 0 || input.event.type !== "subagent.updated"
807 - ? Effect.succeed(storedEvents)
808 - : syncSubagentThreadModel(input, input.event.subagent).pipe(
809 - Effect.map((synced) => [...storedEvents, ...synced]),
810 - Effect.mapError(
811 - (cause) =>
812 - new ProviderEventPublishError({
813 - providerSessionId: input.providerSessionId,
814 - eventCount: 1,
815 - cause,
816 - }),
774 + return result.storedEvents;
775 + },
776 + (effect, input) =>
777 + effect.pipe(
778 + Effect.flatMap((storedEvents) =>
779 + Effect.gen(function* () {
780 + if (input.event.type !== "app_thread.created") return storedEvents;
781 + const created = storedEvents.find(
782 + (stored) => stored.event.type === "thread.created",
783 + );
784 + if (created?.event.type !== "thread.created") return storedEvents;
785 + const child = created.event.payload;
786 + if (
787 + child.worktreePath === null ||
788 + child.branch === null ||
789 + !isTemporaryWorktreeBranch(child.branch)
790 + )
791 + return storedEvents;
792 + // Git renames before scanning committed threads. If that scan missed this
793 + // creation, HEAD already has the new name, even if the parent moved away.
794 + const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
795 + if (branch === null || branch === child.branch) return storedEvents;
796 + const now = yield* DateTime.now;
797 + const event = yield* makeDomainEvent(input, {
798 + type: "thread.metadata-updated",
799 + threadId: child.id,
800 + payload: { ...child, branch, updatedAt: now },
801 + occurredAt: now,
802 + });
803 + const synced = yield* eventSink.write({ events: [event] });
804 + return [...storedEvents, ...synced];
805 + }).pipe(
806 + Effect.catchCause((cause) =>
807 + Effect.logWarning("Native thread worktree branch recheck failed", {
808 + threadId:
809 + input.event.type === "app_thread.created"
810 + ? input.event.appThread.id
811 + : input.threadId,
812 + cause,
813 + }).pipe(Effect.as(storedEvents)),
814 ),
815 ),
819 - ),
820 - Effect.tap((storedEvents) =>
821 - Effect.gen(function* () {
822 - if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;
823 - const providerTurn = input.event.providerTurn;
824 - if (
825 - providerTurn.status !== "completed" &&
826 - providerTurn.status !== "failed" &&
827 - providerTurn.status !== "interrupted" &&
828 - providerTurn.status !== "cancelled"
829 - )
830 - return;
831 - const key = `${input.providerInstanceId}:${providerTurn.id}`;
832 - if (completedTurnAnalytics.has(key)) return;
833 - completedTurnAnalytics.add(key);
834 - if (completedTurnAnalytics.size > 4096) {
835 - const oldest = completedTurnAnalytics.values().next().value;
836 - if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
837 - }
838 - yield* analytics.record(
839 - providerTurnAnalyticsProperties({
840 - driver: input.event.driver,
841 - providerTurn,
842 - ...(input.analyticsContext === undefined
843 - ? {}
844 - : { context: input.analyticsContext }),
816 + ),
817 + Effect.flatMap((storedEvents) =>
818 + storedEvents.length === 0 || input.event.type !== "subagent.updated"
819 + ? Effect.succeed(storedEvents)
820 + : syncSubagentThreadModel(input, input.event.subagent).pipe(
821 + Effect.map((synced) => [...storedEvents, ...synced]),
822 + Effect.mapError(
823 + (cause) =>
824 + new ProviderEventPublishError({
825 + providerSessionId: input.providerSessionId,
826 + eventCount: 1,
827 + cause,
828 + }),
829 + ),
830 + ),
831 + ),
832 + Effect.tap((storedEvents) =>
833 + Effect.gen(function* () {
834 + if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated")
835 + return;
836 + const providerTurn = input.event.providerTurn;
837 + if (
838 + providerTurn.status !== "completed" &&
839 + providerTurn.status !== "failed" &&
840 + providerTurn.status !== "interrupted" &&
841 + providerTurn.status !== "cancelled"
842 + )
843 + return;
844 + const key = `${input.providerInstanceId}:${providerTurn.id}`;
845 + if (completedTurnAnalytics.has(key)) return;
846 + completedTurnAnalytics.add(key);
847 + if (completedTurnAnalytics.size > 4096) {
848 + const oldest = completedTurnAnalytics.values().next().value;
849 + if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
850 + }
851 + yield* analytics.record(
852 + providerTurnAnalyticsProperties({
853 + driver: input.event.driver,
854 + providerTurn,
855 + ...(input.analyticsContext === undefined
856 + ? {}
857 + : { context: input.analyticsContext }),
858 + }),
859 + );
860 }),
846 - );
847 - }),
848 - ),
849 - (effect) =>
850 - input.event.type === "app_thread.created"
851 - ? threadCommands.withLock(input.event.appThread.id, effect)
852 - : effect,
861 + ),
862 + (effect) =>
863 + input.event.type === "app_thread.created"
864 + ? threadCommands.withLock(input.event.appThread.id, effect)
865 + : effect,
866 + ),
867 ),
868 });
869 }),
apps/server/src/orchestration-v2/ShellStream.ts
+22 -18
@@ -38,28 +38,32 @@ export function buildActiveShellSnapshot(input: {
38 * because the server shares one SQLite connection and decoding a large shell takes longer than
39 * reading it.
40 */
41 -export const loadShellSnapshotParts = <E1, E2, E3, E4>(input: {
41 +export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <
42 + E1,
43 + E2,
44 + E3,
45 + E4,
46 +>(input: {
47 readonly sql: SqlClient.SqlClient;
48 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
49 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
50 readonly latestSequence: Effect.Effect<number, E4>;
46 -}) =>
47 - Effect.gen(function* () {
48 - const read = yield* input.sql
49 - .withTransaction(
50 - Effect.all({
51 - decodeThreads: input.readThreads,
52 - projects: input.listProjects,
53 - snapshotSequence: input.latestSequence,
54 - }),
55 - )
56 - .pipe(NodeSqliteClient.readOnly);
57 - return {
58 - projects: read.projects,
59 - threads: yield* read.decodeThreads,
60 - snapshotSequence: read.snapshotSequence,
61 - };
62 - });
51 +}) {
52 + const read = yield* input.sql
53 + .withTransaction(
54 + Effect.all({
55 + decodeThreads: input.readThreads,
56 + projects: input.listProjects,
57 + snapshotSequence: input.latestSequence,
58 + }),
59 + )
60 + .pipe(NodeSqliteClient.readOnly);
61 + return {
62 + projects: read.projects,
63 + threads: yield* read.decodeThreads,
64 + snapshotSequence: read.snapshotSequence,
65 + };
66 +});
67
68 export type ShellApplicationEvent =
69 | Pick<
apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts
+136 -135
@@ -80,153 +80,154 @@ export function coalesceLiveToolUpdatedEvents(
80 return survivors;
81 }
82
83 -export const makeThreadLiveEventCoalescer = <E = never>(options?: {
83 +export const makeThreadLiveEventCoalescer = Effect.fn(
84 + "ThreadLiveEventCoalescer.makeThreadLiveEventCoalescer",
85 +)(function* <E = never>(options?: {
86 readonly coalesceWindow?: Duration.Input;
87 readonly maxItems?: number;
88 readonly maxSerializedBytes?: number;
87 -}) =>
88 - Effect.gen(function* () {
89 - const coalescerScope = yield* Effect.scope;
90 - const budget = yield* makeLiveStreamBudget(options);
91 - const cleanupComplete = yield* Deferred.make<void>();
92 - const output = yield* Queue.unbounded<
93 - RetainedLiveItem<ThreadLiveInput>,
94 - E | LiveStreamBufferError | Cause.Done
95 - >();
96 - const mutex = yield* Semaphore.make(1);
97 - const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
98 - let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
99 - let windowGeneration = 0;
100 - let windowFiber: Fiber.Fiber<void, never> | null = null;
101 - let closed = false;
102 -
103 - const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
104 - const fiber = windowFiber;
105 - if (!fiber) {
106 - return;
107 - }
108 - windowFiber = null;
109 - yield* Fiber.interrupt(fiber);
110 - });
89 +}) {
90 + const coalescerScope = yield* Effect.scope;
91 + const budget = yield* makeLiveStreamBudget(options);
92 + const cleanupComplete = yield* Deferred.make<void>();
93 + const output = yield* Queue.unbounded<
94 + RetainedLiveItem<ThreadLiveInput>,
95 + E | LiveStreamBufferError | Cause.Done
96 + >();
97 + const mutex = yield* Semaphore.make(1);
98 + const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
99 + let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
100 + let windowGeneration = 0;
101 + let windowFiber: Fiber.Fiber<void, never> | null = null;
102 + let closed = false;
103 +
104 + const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
105 + const fiber = windowFiber;
106 + if (!fiber) {
107 + return;
108 + }
109 + windowFiber = null;
110 + yield* Fiber.interrupt(fiber);
111 + });
112
112 - const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
113 - if (pendingUpdates.length === 0) {
114 - return;
115 - }
116 - const items = yield* budget.replace(
117 - pendingUpdates,
118 - coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)),
119 - );
120 - pendingUpdates = [];
121 - yield* Queue.offerAll(output, items);
122 - }, Effect.uninterruptible);
123 -
124 - const flushWindow = (generation: number) =>
125 - Effect.sleep(coalesceWindow).pipe(
126 - Effect.andThen(
127 - mutex.withPermits(1)(
128 - Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
129 - ),
130 - ),
131 - Effect.ensuring(
132 - Effect.sync(() => {
133 - if (generation === windowGeneration) {
134 - windowFiber = null;
135 - }
136 - }),
113 + const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
114 + if (pendingUpdates.length === 0) {
115 + return;
116 + }
117 + const items = yield* budget.replace(
118 + pendingUpdates,
119 + coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)),
120 + );
121 + pendingUpdates = [];
122 + yield* Queue.offerAll(output, items);
123 + }, Effect.uninterruptible);
124 +
125 + const flushWindow = (generation: number) =>
126 + Effect.sleep(coalesceWindow).pipe(
127 + Effect.andThen(
128 + mutex.withPermits(1)(
129 + Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
130 ),
138 - Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
139 - );
131 + ),
132 + Effect.ensuring(
133 + Effect.sync(() => {
134 + if (generation === windowGeneration) {
135 + windowFiber = null;
136 + }
137 + }),
138 + ),
139 + Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
140 + );
141
141 - // Keep each source batch together so a synchronization marker cannot pass
142 - // events already pulled from PubSub but still being coalesced.
143 - const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
144 - inputs: ReadonlyArray<ThreadLiveInput>,
145 - ) {
146 - yield* mutex.withPermits(1)(
147 - Effect.forEach(
148 - inputs,
149 - (input) =>
150 - Effect.gen(function* () {
151 - yield* budget.check;
152 - if (input.kind === "event") {
153 - yield* budget.retain(input).pipe(
154 - Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
155 - Effect.uninterruptible,
156 - );
142 + // Keep each source batch together so a synchronization marker cannot pass
143 + // events already pulled from PubSub but still being coalesced.
144 + const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
145 + inputs: ReadonlyArray<ThreadLiveInput>,
146 + ) {
147 + yield* mutex.withPermits(1)(
148 + Effect.forEach(
149 + inputs,
150 + (input) =>
151 + Effect.gen(function* () {
152 + yield* budget.check;
153 + if (input.kind === "event") {
154 + yield* budget.retain(input).pipe(
155 + Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
156 + Effect.uninterruptible,
157 + );
158 + }
159 + if (input.kind === "event" && isToolUpdated(input)) {
160 + if (pendingUpdates.length === 1) {
161 + const generation = ++windowGeneration;
162 + windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
163 }
158 - if (input.kind === "event" && isToolUpdated(input)) {
159 - if (pendingUpdates.length === 1) {
160 - const generation = ++windowGeneration;
161 - windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
162 - }
163 - if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
164 - yield* cancelWindow();
165 - windowGeneration += 1;
166 - yield* flushPending();
167 - }
168 - return;
164 + if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
165 + yield* cancelWindow();
166 + windowGeneration += 1;
167 + yield* flushPending();
168 }
169 + return;
170 + }
171
171 - yield* cancelWindow();
172 - windowGeneration += 1;
173 - yield* flushPending();
174 - if (input.kind === "synchronized") {
175 - yield* budget.retain({ kind: "synchronized" as const }).pipe(
176 - Effect.flatMap((marker) => Queue.offer(output, marker)),
177 - Effect.uninterruptible,
178 - );
179 - }
180 - }),
181 - { discard: true },
182 - ),
183 - );
184 - });
185 -
186 - const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
187 - mutex.withPermits(1)(
188 - Effect.gen(function* () {
189 - if (closed) {
190 - return;
191 - }
192 - closed = true;
193 - windowGeneration += 1;
194 - yield* cancelWindow();
195 - budget.release(pendingUpdates);
196 - pendingUpdates = [];
197 - budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
198 - if (cause) {
199 - yield* Queue.failCause(output, cause);
200 - }
201 - yield* Queue.shutdown(output);
202 - yield* Deferred.succeed(cleanupComplete, undefined);
203 - }),
204 - );
172 + yield* cancelWindow();
173 + windowGeneration += 1;
174 + yield* flushPending();
175 + if (input.kind === "synchronized") {
176 + yield* budget.retain({ kind: "synchronized" as const }).pipe(
177 + Effect.flatMap((marker) => Queue.offer(output, marker)),
178 + Effect.uninterruptible,
179 + );
180 + }
181 + }),
182 + { discard: true },
183 + ),
184 + );
185 + });
186
206 - yield* Effect.addFinalizer(() => close());
207 - yield* budget.failed.pipe(
208 - Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
209 - Effect.forkScoped,
187 + const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
188 + mutex.withPermits(1)(
189 + Effect.gen(function* () {
190 + if (closed) {
191 + return;
192 + }
193 + closed = true;
194 + windowGeneration += 1;
195 + yield* cancelWindow();
196 + budget.release(pendingUpdates);
197 + pendingUpdates = [];
198 + budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
199 + if (cause) {
200 + yield* Queue.failCause(output, cause);
201 + }
202 + yield* Queue.shutdown(output);
203 + yield* Deferred.succeed(cleanupComplete, undefined);
204 + }),
205 );
206
212 - return {
213 - offer: (input: ThreadLiveInput) => offerAll([input]),
214 - close,
215 - end: mutex.withPermits(1)(
216 - Effect.gen(function* () {
217 - yield* cancelWindow();
218 - windowGeneration += 1;
219 - yield* flushPending();
220 - yield* Queue.end(output);
221 - }),
222 - ),
223 - offerAll,
224 - stream: budget.deliver(Stream.fromQueue(output)),
225 - failed: budget.failed,
226 - closed: Deferred.await(cleanupComplete),
227 - usage: budget.usage,
228 - } as const;
229 - });
207 + yield* Effect.addFinalizer(() => close());
208 + yield* budget.failed.pipe(
209 + Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
210 + Effect.forkScoped,
211 + );
212 +
213 + return {
214 + offer: (input: ThreadLiveInput) => offerAll([input]),
215 + close,
216 + end: mutex.withPermits(1)(
217 + Effect.gen(function* () {
218 + yield* cancelWindow();
219 + windowGeneration += 1;
220 + yield* flushPending();
221 + yield* Queue.end(output);
222 + }),
223 + ),
224 + offerAll,
225 + stream: budget.deliver(Stream.fromQueue(output)),
226 + failed: budget.failed,
227 + closed: Deferred.await(cleanupComplete),
228 + usage: budget.usage,
229 + } as const;
230 +});
231
232 export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>
233 Stream.unwrap(
apps/server/src/orchestration-v2/TurnItemPositionStore.ts
+33 -33
@@ -39,34 +39,31 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
39 Effect.gen(function* () {
40 const sql = yield* SqlClient.SqlClient;
41
42 - const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({
43 - threadId,
44 - turnItemId,
45 - runId,
46 - runOrdinal: suppliedRunOrdinal,
47 - }) =>
48 - Effect.gen(function* () {
49 - const existing = yield* sql<{ readonly ordinal: number }>`
42 + const allocate: TurnItemPositionStoreV2Shape["allocate"] =
43 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
44 + Effect.fnUntraced(
45 + function* ({ threadId, turnItemId, runId, runOrdinal: suppliedRunOrdinal }) {
46 + const existing = yield* sql<{ readonly ordinal: number }>`
47 SELECT ordinal
48 FROM orchestration_v2_turn_item_positions
49 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
50 LIMIT 1
51 `;
55 - if (existing[0] !== undefined) return existing[0].ordinal;
52 + if (existing[0] !== undefined) return existing[0].ordinal;
53
57 - const runRows =
58 - runId === null
59 - ? []
60 - : yield* sql<{ readonly ordinal: number }>`
54 + const runRows =
55 + runId === null
56 + ? []
57 + : yield* sql<{ readonly ordinal: number }>`
58 SELECT ordinal
59 FROM orchestration_v2_projection_runs
60 WHERE thread_id = ${threadId} AND run_id = ${runId}
61 LIMIT 1
62 `;
66 - const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
67 - const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
68 - const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
69 - yield* sql`
63 + const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
64 + const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
65 + const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
66 + yield* sql`
67 INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
68 SELECT
69 ${threadId},
@@ -78,27 +75,30 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
75 AND ordinal <= ${upperBound}
76 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
77 `;
81 - const rows = yield* sql<{ readonly ordinal: number }>`
78 + const rows = yield* sql<{ readonly ordinal: number }>`
79 SELECT ordinal
80 FROM orchestration_v2_turn_item_positions
81 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
82 LIMIT 1
83 `;
87 - const ordinal = rows[0]?.ordinal;
88 - if (ordinal === undefined) {
89 - return yield* new TurnItemPositionStoreError({
90 - threadId,
91 - turnItemId,
92 - cause: "Position allocation returned no row.",
93 - });
94 - }
95 - return ordinal;
96 - }).pipe(
97 - Effect.mapError((cause) =>
98 - isTurnItemPositionStoreError(cause)
99 - ? cause
100 - : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
101 - ),
84 + const ordinal = rows[0]?.ordinal;
85 + if (ordinal === undefined) {
86 + return yield* new TurnItemPositionStoreError({
87 + threadId,
88 + turnItemId,
89 + cause: "Position allocation returned no row.",
90 + });
91 + }
92 + return ordinal;
93 + },
94 + (effect, { threadId, turnItemId }) =>
95 + effect.pipe(
96 + Effect.mapError((cause) =>
97 + isTurnItemPositionStoreError(cause)
98 + ? cause
99 + : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
100 + ),
101 + ),
102 );
103
104 return TurnItemPositionStoreV2.of({