TypeScript
fix(server): keep attachments until the command commits (#7941)
Theo Browne716069f40f00
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex b0aa2c57d81..3810ee378c4 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -222,6 +222,7 @@ describe("OrchestrationEngine", () => {Layer.succeed(OrchestrationProjectionPipeline, {bootstrap: Effect.void,projectEvent: () => Effect.void,+ projectEventDeferred: () => Effect.succeed(Effect.void),} satisfies OrchestrationProjectionPipelineShape),),Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),@@ -1116,7 +1117,8 @@ describe("OrchestrationEngine", () => {let shouldFailRequestedProjection = true;const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {bootstrap: Effect.void,- projectEvent: (event) => {+ projectEvent: () => Effect.void,+ projectEventDeferred: (event) => {if (shouldFailRequestedProjection &&event.commandId === CommandId.make("cmd-turn-start-atomic") &&@@ -1130,7 +1132,7 @@ describe("OrchestrationEngine", () => {}),);}- return Effect.void;+ return Effect.succeed(Effect.void);},};@@ -1263,7 +1265,8 @@ describe("OrchestrationEngine", () => {let shouldFailProjection = true;const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {bootstrap: Effect.void,- projectEvent: (event) => {+ projectEvent: () => Effect.void,+ projectEventDeferred: (event) => {if (shouldFailProjection &&event.commandId === CommandId.make("cmd-thread-archive-sync-fail")@@ -1276,7 +1279,7 @@ describe("OrchestrationEngine", () => {}),);}- return Effect.void;+ return Effect.succeed(Effect.void);},};diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex f6a928fdc70..741e0fac719 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -224,12 +224,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {.withTransaction(Effect.gen(function* () {const committedEvents: OrchestrationEvent[] = [];+ const attachmentCleanups: Effect.Effect<void>[] = [];let nextCommandReadModel = commandReadModel;for (const nextEvent of eventBases) {const savedEvent = yield* eventStore.append(nextEvent);nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);- yield* projectionPipeline.projectEvent(savedEvent);+ const cleanup = yield* projectionPipeline.projectEventDeferred(savedEvent);+ attachmentCleanups.push(cleanup);committedEvents.push(savedEvent);}@@ -253,6 +255,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {return {committedEvents,+ attachmentCleanups,lastSequence: lastSavedEvent.sequence,nextCommandReadModel,} as const;@@ -267,6 +270,9 @@ const makeOrchestrationEngine = Effect.gen(function* () {);commandReadModel = committedCommand.nextCommandReadModel;+ for (const cleanup of committedCommand.attachmentCleanups) {+ yield* cleanup;+ }for (const [index, event] of committedCommand.committedEvents.entries()) {yield* PubSub.publish(eventPubSub, event);if (index === 0) {@@ -381,6 +387,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {return {readEvents,dispatch,+ subscribeDomainEvents: PubSub.subscribe(eventPubSub).pipe(Effect.map(Stream.fromSubscription)),// Each access creates a fresh PubSub subscription so that multiple// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)// each independently receive all domain events.diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex 080ea263e44..504fa7c5254 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -2,6 +2,7 @@ import {CheckpointRef,CommandId,CorrelationId,+ DEFAULT_PROVIDER_INTERACTION_MODE,EventId,MessageId,ProjectId,@@ -874,12 +875,13 @@ it.layer(it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-overwrite-")),)("OrchestrationProjectionPipeline", (it) => {- it.effect("removes unreferenced attachment files when a thread is reverted", () =>+ it.effect("prunes reverted attachments only after every projector commits", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;const projectionPipeline = yield* OrchestrationProjectionPipeline;const eventStore = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;const { attachmentsDir } = yield* ServerConfig;const now = "2026-01-01T00:00:00.000Z";const threadId = ThreadId.make("Thread Revert.Files");@@ -1067,7 +1069,7 @@ it.layer(assert.isTrue(yield* exists(removePath));assert.isTrue(yield* exists(otherThreadPath));- yield* appendAndProject({+ const revertedEvent = yield* eventStore.append({type: "thread.reverted",eventId: EventId.make("evt-revert-files-7"),aggregateKind: "thread",@@ -1083,9 +1085,75 @@ it.layer(},});+ yield* sql`+ CREATE TRIGGER fail_revert_projection+ BEFORE UPDATE ON projection_state+ WHEN NEW.projector = 'projection.threads'+ BEGIN+ SELECT RAISE(FAIL, 'forced later projector failure');+ END+ `;+ const projectionError = yield* projectionPipeline+ .projectEvent(revertedEvent)+ .pipe(Effect.flip);+ assert.equal(projectionError._tag, "PersistenceSqlError");+ assert.isTrue(yield* exists(removePath));+ const rolledBackMessages = yield* sql<{ readonly messageId: string }>`+ SELECT message_id AS "messageId" FROM projection_thread_messages+ WHERE message_id = 'message-remove'+ `;+ assert.deepEqual(rolledBackMessages, [{ messageId: "message-remove" }]);+ yield* sql`DROP TRIGGER fail_revert_projection`;++ const laterAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000005";+ const laterPath = path.join(attachmentsDir, `${laterAttachmentId}.png`);+ yield* fileSystem.writeFileString(laterPath, "added after revert");+ const cleanup = yield* sql.withTransaction(+ Effect.gen(function* () {+ const cleanup = yield* projectionPipeline.projectEventDeferred(revertedEvent);+ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.make("evt-revert-files-later"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.make("cmd-revert-files-later"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-revert-files-later"),+ metadata: {},+ payload: {+ threadId,+ messageId: MessageId.make("message-later"),+ role: "user",+ text: "Later attachment",+ attachments: [+ {+ type: "image",+ id: laterAttachmentId,+ name: "later.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ });+ assert.isTrue(yield* exists(removePath));+ // Return the cleanup effect so the caller runs it after the outer transaction commits.+ // @effect-diagnostics-next-line returnEffectInGen:off+ return cleanup;+ }),+ );+ assert.isTrue(yield* exists(removePath));+ yield* cleanup;+assert.isTrue(yield* exists(keepPath));assert.isTrue(yield* exists(keepFilePath));assert.isFalse(yield* exists(removePath));+ assert.isTrue(yield* exists(laterPath));assert.isTrue(yield* exists(otherThreadPath));}),);@@ -3522,4 +3590,111 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {assert.isNull(detail.session);}),);++ it.effect("cleans attachments only after the command receipt commits", () =>+ Effect.gen(function* () {+ const engine = yield* OrchestrationEngineService;+ const sql = yield* SqlClient.SqlClient;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const { attachmentsDir } = yield* ServerConfig;+ const createdAt = "2026-01-01T00:00:00.000Z";+ const projectId = ProjectId.make("project-outer-rollback");+ const threadId = ThreadId.make("thread-outer-rollback");+ const cleanupFailureThreadId = ThreadId.make("thread-cleanup-failure");+ const commandId = CommandId.make("cmd-outer-rollback-delete");+ const attachmentPath = path.join(+ attachmentsDir,+ "thread-outer-rollback-00000000-0000-4000-8000-000000000001.png",+ );+ const blockedAttachmentPath = path.join(+ attachmentsDir,+ "thread-cleanup-failure-00000000-0000-4000-8000-000000000001.png",+ );++ yield* engine.dispatch({+ type: "project.create",+ commandId: CommandId.make("cmd-outer-rollback-project"),+ projectId,+ title: "Outer rollback project",+ workspaceRoot: "/tmp/project-outer-rollback",+ createdAt,+ });+ for (const id of [threadId, cleanupFailureThreadId]) {+ yield* engine.dispatch({+ type: "thread.create",+ commandId: CommandId.make(`cmd-create-${id}`),+ threadId: id,+ projectId,+ title: "Attachment cleanup thread",+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5-codex",+ },+ runtimeMode: "full-access",+ branch: null,+ worktreePath: null,+ createdAt,+ });+ }++ yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });+ yield* fileSystem.writeFileString(attachmentPath, "keep this attachment");+ yield* sql`+ CREATE TRIGGER fail_attachment_command_receipt+ BEFORE INSERT ON orchestration_command_receipts+ WHEN NEW.command_id = 'cmd-outer-rollback-delete' AND NEW.status = 'accepted'+ BEGIN+ SELECT RAISE(FAIL, 'forced receipt failure');+ END+ `;+ const deleteCommand = { type: "thread.delete", commandId, threadId } as const;+ const dispatchError = yield* engine.dispatch(deleteCommand).pipe(Effect.flip);+ assert.equal(dispatchError._tag, "PersistenceSqlError");+ assert.equal(yield* fileSystem.readFileString(attachmentPath), "keep this attachment");+ const rolledBackThreads = yield* sql<{ readonly deletedAt: string | null }>`+ SELECT deleted_at AS "deletedAt" FROM projection_threads WHERE thread_id = ${threadId}+ `;+ assert.deepEqual(rolledBackThreads, [{ deletedAt: null }]);+ const rolledBackEvents = yield* sql`+ SELECT sequence FROM orchestration_events WHERE command_id = ${commandId}+ `;+ assert.deepEqual(rolledBackEvents, []);+ const rolledBackReceipts = yield* sql`+ SELECT status FROM orchestration_command_receipts WHERE command_id = ${commandId}+ `;+ assert.deepEqual(rolledBackReceipts, []);+ yield* sql`DROP TRIGGER fail_attachment_command_receipt`;++ const result = yield* engine.dispatch(deleteCommand);+ assert.isFalse(yield* exists(attachmentPath));+ const committedReceipts = yield* sql<{+ readonly status: string;+ readonly resultSequence: number;+ }>`+ SELECT status, result_sequence AS "resultSequence"+ FROM orchestration_command_receipts WHERE command_id = ${commandId}+ `;+ assert.deepEqual(committedReceipts, [+ { status: "accepted", resultSequence: result.sequence },+ ]);++ // Removing a nonempty directory as a file fails after the command commits.+ yield* fileSystem.makeDirectory(blockedAttachmentPath);+ yield* fileSystem.writeFileString(path.join(blockedAttachmentPath, "keep.txt"), "keep");+ const cleanupFailureCommandId = CommandId.make("cmd-cleanup-failure-delete");+ yield* engine.dispatch({+ type: "thread.delete",+ commandId: cleanupFailureCommandId,+ threadId: cleanupFailureThreadId,+ });+ assert.isTrue(yield* exists(blockedAttachmentPath));+ const cleanupFailureReceipts = yield* sql<{ readonly status: string }>`+ SELECT status FROM orchestration_command_receipts+ WHERE command_id = ${cleanupFailureCommandId}+ `;+ assert.deepEqual(cleanupFailureReceipts, [{ status: "accepted" }]);+ }),+ );});diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 3d1dfd9c7e3..e40f0229f44 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -1765,6 +1765,70 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti},];+ const applyAttachmentSideEffects = Effect.fn("applyAttachmentSideEffects")(+ function* (event: OrchestrationEvent, sideEffects: AttachmentSideEffects) {+ if (+ sideEffects.deletedThreadIds.size === 0 &&+ sideEffects.prunedThreadRelativePaths.size === 0+ ) {+ return;+ }++ const deletedThreadIds = new Set<string>();+ for (const threadId of sideEffects.deletedThreadIds) {+ const recreatedLater = yield* eventStore.hasEventAfter({+ aggregateKind: "thread",+ aggregateId: ThreadId.make(threadId),+ type: "thread.created",+ sequenceExclusive: event.sequence,+ });+ if (!recreatedLater) {+ deletedThreadIds.add(threadId);+ }+ }++ // Later events in the same transaction can add attachment references.+ const prunedThreadRelativePaths = new Map<string, Set<string>>();+ for (const threadId of sideEffects.prunedThreadRelativePaths.keys()) {+ const messages = yield* projectionThreadMessageRepository.listByThreadId({+ threadId: ThreadId.make(threadId),+ });+ prunedThreadRelativePaths.set(+ threadId,+ collectThreadAttachmentRelativePaths(threadId, messages),+ );+ }++ yield* runAttachmentSideEffects({ deletedThreadIds, prunedThreadRelativePaths });+ },+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.provideService(ServerConfig, serverConfig),+ (effect, event) =>+ effect.pipe(+ Effect.catch((cause) =>+ Effect.logWarning("failed to apply projected attachment side-effects", {+ sequence: event.sequence,+ eventType: event.type,+ cause,+ }),+ ),+ ),+ );++ const applyProjectorForEvent = Effect.fn("applyProjectorForEvent")(function* (+ projector: ProjectorDefinition,+ event: OrchestrationEvent,+ attachmentSideEffects: AttachmentSideEffects,+ ) {+ yield* projector.apply(event, attachmentSideEffects);+ yield* projectionStateRepository.upsert({+ projector: projector.name,+ lastAppliedSequence: event.sequence,+ updatedAt: event.occurredAt,+ });+ });+const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (projector: ProjectorDefinition,event: OrchestrationEvent,@@ -1774,28 +1838,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiprunedThreadRelativePaths: new Map<string, Set<string>>(),};- yield* sql.withTransaction(- projector.apply(event, attachmentSideEffects).pipe(- Effect.flatMap(() =>- projectionStateRepository.upsert({- projector: projector.name,- lastAppliedSequence: event.sequence,- updatedAt: event.occurredAt,- }),- ),- ),- );-- yield* runAttachmentSideEffects(attachmentSideEffects).pipe(- Effect.catch((cause) =>- Effect.logWarning("failed to apply projected attachment side-effects", {- projector: projector.name,- sequence: event.sequence,- eventType: event.type,- cause,- }),- ),- );+ yield* sql.withTransaction(applyProjectorForEvent(projector, event, attachmentSideEffects));+ yield* applyAttachmentSideEffects(event, attachmentSideEffects);});const bootstrapProjector = (projector: ProjectorDefinition) =>@@ -1815,19 +1859,39 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti),);- const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>- Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {- concurrency: 1,- }).pipe(+ const projectEventDeferred: OrchestrationProjectionPipelineShape["projectEventDeferred"] =+ Effect.fn("projectEventDeferred")(+ function* (event) {+ const attachmentSideEffects: AttachmentSideEffects = {+ deletedThreadIds: new Set<string>(),+ prunedThreadRelativePaths: new Map<string, Set<string>>(),+ };+ yield* sql.withTransaction(+ Effect.forEach(+ projectors,+ (projector) => applyProjectorForEvent(projector, event, attachmentSideEffects),+ { concurrency: 1, discard: true },+ ),+ );+ // Return the cleanup effect so the caller runs it after the outer transaction commits.+ // @effect-diagnostics-next-line returnEffectInGen:off+ return applyAttachmentSideEffects(event, attachmentSideEffects);+ },Effect.provideService(FileSystem.FileSystem, fileSystem),Effect.provideService(Path.Path, path),Effect.provideService(ServerConfig, serverConfig),- Effect.asVoid,Effect.catchTag("SqlError", (sqlError) =>Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),),);+ const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = Effect.fn(+ "projectEvent",+ )(function* (event) {+ const cleanup = yield* projectEventDeferred(event);+ yield* cleanup;+ });+const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(projectors,bootstrapProjector,@@ -1850,6 +1914,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectireturn {bootstrap,projectEvent,+ projectEventDeferred,} satisfies OrchestrationProjectionPipelineShape;},);diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex ff246128c44..cac4ebe4dde 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -61,6 +61,7 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"import * as NodeServices from "@effect/platform-node/NodeServices";import * as Clock from "effect/Clock";import { ServerSettingsService } from "../../serverSettings.ts";+import { ServerActivation } from "../../serverActivation.ts";import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";import * as GitWorkflowService from "../../git/GitWorkflowService.ts";@@ -150,6 +151,7 @@ describe("ProviderCommandReactor", () => {readonly requiresNewThreadForModelChange?: boolean;readonly titleRegenerationCompletionDispatchFailures?: number;readonly titleRegenerationBeforeStart?: "one" | "two";+ readonly serverActivation?: Effect.Effect<void>;readonly interruptTurnEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;readonly stopSessionEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;readonly startSessionEffect?: (@@ -395,6 +397,7 @@ describe("ProviderCommandReactor", () => {get streamDomainEvents() {return engine.streamDomainEvents;},+ subscribeDomainEvents: engine.subscribeDomainEvents,latestSequence: engine.latestSequence,} satisfies OrchestrationEngineService["Service"];}),@@ -500,7 +503,14 @@ describe("ProviderCommandReactor", () => {}scope = await Effect.runPromise(Scope.make("sequential"));- await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));+ await Effect.runPromise(+ reactor+ .start()+ .pipe(+ Scope.provide(scope),+ Effect.provideService(ServerActivation, input?.serverActivation),+ ),+ );const drain = () => Effect.runPromise(reactor.drain);return {@@ -568,6 +578,45 @@ describe("ProviderCommandReactor", () => {expect(thread?.session?.runtimeMode).toBe("approval-required");});+ effectIt.effect("retains a turn dispatched immediately after start until activation", () =>+ Effect.gen(function* () {+ const activation = yield* Deferred.make<void>();+ const started = yield* Deferred.make<ProviderSession>();+ const harness = yield* Effect.promise(() =>+ createHarness({+ serverActivation: Deferred.await(activation),+ startSessionEffect: (session) =>+ Deferred.succeed(started, session).pipe(Effect.as(session)),+ }),+ );++ yield* harness.engine.dispatch({+ type: "thread.turn.start",+ commandId: CommandId.make("cmd-turn-start-before-activation"),+ threadId: ThreadId.make("thread-1"),+ message: {+ messageId: MessageId.make("message-before-activation"),+ role: "user",+ text: "Start after activation",+ attachments: [],+ },+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,+ runtimeMode: "approval-required",+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ expect(yield* Deferred.isDone(started)).toBe(false);++ yield* Deferred.succeed(activation, undefined);+ const session = yield* Deferred.await(started);+ yield* Effect.promise(() => harness.drain());+ expect(session.threadId).toBe(ThreadId.make("thread-1"));+ expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({+ threadId: ThreadId.make("thread-1"),+ input: "Start after activation",+ });+ }),+ );+effectIt.effect("projects starting before a slow provider session finishes", () =>Effect.gen(function* () {const releaseStart = yield* Deferred.make<void>();diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex 84d472089d8..37ed0d344b0 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -1554,7 +1554,9 @@ const make = Effect.gen(function* () {}});- yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent));+ // Subscribe before returning, even while event handling waits for server activation.+ const domainEvents = yield* orchestrationEngine.subscribeDomainEvents;+ yield* forkParked(Stream.runForEach(domainEvents, processEvent));// The domain event stream is hot, so work pending before this reactor// starts cannot be resumed. Correlated completions only clear the requestdiff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.tsindex a32a4568401..08f63c47642 100644--- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts@@ -17,6 +17,7 @@ import type {} from "@t3tools/contracts";import * as Context from "effect/Context";import type * as Effect from "effect/Effect";+import type * as Scope from "effect/Scope";import type * as Stream from "effect/Stream";import type { OrchestrationDispatchError } from "../Errors.ts";@@ -64,6 +65,16 @@ export interface OrchestrationEngineShape {*/readonly streamDomainEvents: Stream.Stream<OrchestrationEvent>;+ /**+ * Acquire a domain-event subscription before starting a consumer.+ * The subscription is ready when this effect returns and closes with the scope.+ */+ readonly subscribeDomainEvents: Effect.Effect<+ Stream.Stream<OrchestrationEvent>,+ never,+ Scope.Scope+ >;+/*** The latest sequence reflected in the engine's authoritative command read* model (0 if none). Used to gauge how far behind a resuming client is beforediff --git a/apps/server/src/orchestration/Services/ProjectionPipeline.ts b/apps/server/src/orchestration/Services/ProjectionPipeline.tsindex bb4736ca57a..0fab7f364f0 100644--- a/apps/server/src/orchestration/Services/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Services/ProjectionPipeline.ts@@ -26,11 +26,20 @@ export interface OrchestrationProjectionPipelineShape {/*** Project a single orchestration event into projection repositories.*- * Projectors are executed sequentially to preserve deterministic ordering.+ * Projectors run sequentially in one transaction. Attachment cleanup runs+ * after that transaction commits.*/readonly projectEvent: (event: OrchestrationEvent,) => Effect.Effect<void, ProjectionRepositoryError>;++ /**+ * Project an event inside a caller's transaction and return its attachment+ * cleanup. Run the returned effect only after the outer transaction commits.+ */+ readonly projectEventDeferred: (+ event: OrchestrationEvent,+ ) => Effect.Effect<Effect.Effect<void>, ProjectionRepositoryError>;}/**diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.tsindex 65aa9949fe1..d36afbc1df3 100644--- a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts@@ -19,6 +19,7 @@ export interface ProviderCommandReactorShape {** The returned effect must be run in a scope so all worker fibers can be* finalized on shutdown.+ * It subscribes before returning. Event handling waits for server activation.** Filters orchestration domain events to provider-intent types before* processing.diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex 74a4de594a1..2465052a33c 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -474,6 +474,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {readEvents: () => Stream.empty,dispatch: () => Effect.succeed({ sequence: 1 }),streamDomainEvents: Stream.fromQueue(events),+ subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),latestSequence: Effect.succeed(0),} satisfies OrchestrationEngineShape;@@ -666,6 +667,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {readEvents: () => Stream.empty,dispatch: () => Effect.succeed({ sequence: 1 }),streamDomainEvents: Stream.fromQueue(events),+ subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),latestSequence: Effect.succeed(0),} satisfies OrchestrationEngineShape),Layer.succeed(ProjectionSnapshotQuery, {diff --git a/apps/server/src/serverRuntimeStartup.reconcile.test.ts b/apps/server/src/serverRuntimeStartup.reconcile.test.tsindex 485cd5bb08a..4cb9cc3b826 100644--- a/apps/server/src/serverRuntimeStartup.reconcile.test.ts+++ b/apps/server/src/serverRuntimeStartup.reconcile.test.ts@@ -84,6 +84,7 @@ const runReconciliation = (input: {readEvents: () => Stream.empty,dispatch: input.dispatch,streamDomainEvents: Stream.empty,+ subscribeDomainEvents: Effect.succeed(Stream.empty),latestSequence: Effect.succeed(0),}),Effect.provide(NodeServices.layer),@@ -289,6 +290,7 @@ it.effect("does not fail startup when the live provider session inventory cannotreadEvents: () => Stream.empty,dispatch: () => Effect.die("unused"),streamDomainEvents: Stream.empty,+ subscribeDomainEvents: Effect.succeed(Stream.empty),latestSequence: Effect.succeed(0),}),Effect.provide(NodeServices.layer),diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.tsindex 83642a956ae..6747bfccc32 100644--- a/apps/server/src/serverRuntimeStartup.test.ts+++ b/apps/server/src/serverRuntimeStartup.test.ts@@ -181,6 +181,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threaEffect.as({ sequence: 1 }),),streamDomainEvents: Stream.empty,+ subscribeDomainEvents: Effect.succeed(Stream.empty),latestSequence: Effect.succeed(0),} satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),Effect.provide(NodeServices.layer),@@ -227,6 +228,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread whenEffect.as({ sequence: 1 }),),streamDomainEvents: Stream.empty,+ subscribeDomainEvents: Effect.succeed(Stream.empty),latestSequence: Effect.succeed(0),} satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),Effect.provide(NodeServices.layer),@@ -279,6 +281,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation faEffect.as({ sequence: 1 }),),streamDomainEvents: Stream.empty,+ subscribeDomainEvents: Effect.succeed(Stream.empty),latestSequence: Effect.succeed(0),} satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),Effect.provideService(Crypto.Crypto, {diff --git a/docs/internals/overview.md b/docs/internals/overview.mdindex 1deef28b355..65b6c1424a5 100644--- a/docs/internals/overview.md+++ b/docs/internals/overview.md@@ -73,7 +73,8 @@ processing is totally ordered. For each envelope `processEnvelope`:3. inside one SQL transaction, appends events to the event store, applies them to the in-memory readmodel via [`projector.ts`][projector], projects them into persisted tables, and writes theaccepted receipt;-4. after commit, swaps in the new read model and publishes committed events to subscribers.+4. after commit, swaps in the new read model, cleans up attachments, and publishes committed events+ to subscribers. Attachment cleanup failures are logged and do not reject committed commands.Because persistence and projection share a transaction, the read model cannot durably disagree withthe event log. On dispatch failure the engine rereads persisted events past the starting sequence and