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 25, 17:15 UTC
es terminology
Julius Marminge committed
Feb 23, 2026 at 10:33 UTC
7934639aa1379f745af7db7c05c964bf6d7a7cc8
15 files changed
+880
-234
.plans/14-server-authoritative-event-sourcing-cleanup.md
new
+206
@@ -0,0 +1,206 @@
1
+# Server-Authoritative Event-Sourcing Cleanup Plan
2
+
3
+Goal:
4
+- Move to a cleaner service architecture with:
5
+ - durable, server-authoritative event sourcing
6
+ - strict command routing/validation
7
+ - pluggable provider adapters
8
+ - explicit separation between transport, domain orchestration, provider runtime, and persistence
9
+
10
+## Target Service Graph (ASCII)
11
+
12
+```text
13
+ +---------------------------+
14
+ | wsServer |
15
+ | transport |
16
+ +---------------------------+
17
+ | orchestration.dispatchCommand
18
+ v
19
+ +-------------------------------------------+
20
+ | OrchestrationCommandRouter |
21
+ +-------------------------------------------+
22
+ |
23
+ v
24
+ +-------------------------------------------+
25
+ | OrchestrationCommandHandlers |
26
+ +-------------------------------------------+
27
+ |
28
+ v
29
+ +-------------------------------------------+
30
+ | OrchestrationEventStore |
31
+ +-------------------------------------------+
32
+ |
33
+ v
34
+ +-------------------------------------------+
35
+ | OrchestrationProjectionService |
36
+ +-------------------------------------------+
37
+ | snapshot/replay
38
+ +---------------------------> wsServer
39
+
40
+
41
+wsServer -- providers.* RPC --> +---------------------------+
42
+ | ProviderService |
43
+ +---------------------------+
44
+ | |
45
+ v v
46
+ +-------------------+ +-------------------------+
47
+ | ProviderSession | | ProviderAdapterRegistry |
48
+ | Registry (durable)| +-------------------------+
49
+ +-------------------+ |
50
+ ^ v
51
+ | +-------------------------+
52
+ | | ProviderAdapter(s) |
53
+ | +-------------------------+
54
+ | |
55
+ | runtime events v
56
+ | +---------------------------+
57
+ +----------| ProviderRuntimeIngestion |
58
+ +---------------------------+
59
+ | | |
60
+ v v v
61
+ Router Session Checkpoint
62
+ Registry Service
63
+
64
+ +-------------------------------------------+
65
+ | CheckpointService |
66
+ +-------------------------------------------+
67
+ | | |
68
+ v v v
69
+ +--------------------+ +-------------+ +-------------------+
70
+ | CheckpointCatalog | | Checkpoint | | ProviderAdapter(s)|
71
+ | (durable) | | Store (git) | | (read/rollback) |
72
+ +--------------------+ +-------------+ +-------------------+
73
+ |
74
+ v
75
+ +------+
76
+ |SQLite|
77
+ +------+
78
+
79
+OrchestrationEventStore ------> SQLite
80
+OrchestrationProjectionService -> SQLite
81
+ProviderSessionRegistry ------> SQLite
82
+CheckpointCatalog ------> SQLite
83
+```
84
+
85
+## Commit Series
86
+
87
+### Commit 1: Split public vs system orchestration command contracts
88
+- Create separate schemas/types:
89
+ - `ClientOrchestrationCommandSchema`
90
+ - `SystemOrchestrationCommandSchema`
91
+ - `OrchestrationCommandSchema = union(client, system)`
92
+- Ensure client transport can only submit client commands.
93
+- Keep system commands for server-internal workflows only.
94
+- Expected files:
95
+ - `packages/contracts/src/orchestration.ts`
96
+ - `apps/server/src/wsServer.ts`
97
+ - orchestration/service tests
98
+- Tests:
99
+ - reject system-only command via WS dispatch path
100
+ - preserve internal dispatch functionality for system commands
101
+
102
+### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
103
+- Add dedicated router service to validate, authorize, and route commands.
104
+- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
105
+- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
106
+- Expected files:
107
+ - `apps/server/src/orchestration/Services/CommandRouter.ts` (new)
108
+ - `apps/server/src/orchestration/Layers/CommandRouter.ts` (new)
109
+ - `apps/server/src/orchestration/Layer.ts`
110
+ - `apps/server/src/orchestration/reducer.ts` (only if needed for event payload changes)
111
+- Tests:
112
+ - router validation and invariant failures
113
+ - handler happy-path tests per command type
114
+
115
+### Commit 3: Harden event store for idempotency + optimistic append metadata
116
+- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
117
+- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
118
+- Add optional aggregate version metadata for future optimistic concurrency.
119
+- Expected files:
120
+ - `apps/server/src/persistence/Migrations/00x_*.ts` (new migration)
121
+ - `apps/server/src/persistence/Services/OrchestrationEvents.ts`
122
+ - `apps/server/src/persistence/Layers/OrchestrationEvents.ts`
123
+- Tests:
124
+ - duplicate command ID append returns same event/sequence (or explicit idempotent behavior)
125
+ - concurrent append behavior stays ordered and deterministic
126
+
127
+### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
128
+- Create `ProviderRuntimeIngestionService` that:
129
+ - subscribes to `ProviderService.streamEvents`
130
+ - translates runtime events into orchestration commands
131
+ - dispatches through router/engine
132
+- Remove provider-to-orchestration state mutation logic from `wsServer`.
133
+- Expected files:
134
+ - `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts` (new)
135
+ - `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (new)
136
+ - `apps/server/src/wsServer.ts`
137
+- Tests:
138
+ - ingestion service mapping tests (turn started/completed, message delta/completed, runtime error)
139
+ - ws integration confirms same external push behavior
140
+
141
+### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
142
+- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
143
+- Keep in-memory cache optional, but source of truth must be persistent.
144
+- Add startup reconciliation to prune dead sessions / keep known thread mapping.
145
+- Expected files:
146
+ - `apps/server/src/provider/Services/ProviderSessionDirectory.ts` (or new SessionRegistry service)
147
+ - `apps/server/src/provider/Layers/ProviderSessionDirectory.ts`
148
+ - `apps/server/src/persistence/Migrations/00x_*.ts` (new table/indexes)
149
+ - provider persistence tests
150
+- Tests:
151
+ - survives server restart with correct mapping
152
+ - stale session cleanup semantics
153
+
154
+### Commit 6: Re-key checkpoint metadata from session to thread identity
155
+- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
156
+- Keep `session_id` as nullable metadata only.
157
+- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
158
+- Expected files:
159
+ - `apps/server/src/persistence/Migrations/00x_*.ts` (checkpoint schema migration)
160
+ - `apps/server/src/persistence/Services/Checkpoints.ts`
161
+ - `apps/server/src/persistence/Layers/Checkpoints.ts`
162
+ - `apps/server/src/checkpointing/Layers/CheckpointService.ts`
163
+- Tests:
164
+ - resume/new session over same thread sees same checkpoint history
165
+ - revert/diff still work after session churn
166
+
167
+### Commit 7: Add durable projection persistence for orchestration read models
168
+- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
169
+- Keep event stream as source of truth; projection rebuild stays deterministic.
170
+- `getSnapshot` reads from projection store (memory cache optional).
171
+- Expected files:
172
+ - `apps/server/src/persistence/Migrations/00x_*.ts` (projection tables)
173
+ - `apps/server/src/orchestration/*` projection service/layer
174
+ - `apps/server/src/wsServer.ts` (snapshot/replay path wiring)
175
+- Tests:
176
+ - cold boot snapshot load without replaying full history in process
177
+ - projection rebuild from events yields same result as previous reducer semantics
178
+
179
+### Commit 8: Narrow `ProviderService` responsibilities
180
+- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
181
+- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
182
+- Preserve adapter pluggability and provider-neutral contracts.
183
+- Expected files:
184
+ - `apps/server/src/provider/Layers/ProviderService.ts`
185
+ - new orchestration/checkpoint runtime coordinator service(s)
186
+- Tests:
187
+ - provider service routing stays intact
188
+ - checkpoint capture still triggered by turn completion through new coordinator
189
+
190
+### Commit 9: Remove dead legacy path and finalize docs
191
+- Remove unused legacy manager/store path from active architecture:
192
+ - `providerManager.ts`
193
+ - `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
194
+- Update architecture docs with final service boundaries and boot/runtime graph.
195
+- Expected files:
196
+ - legacy files + references
197
+ - `AGENTS.md`/docs as needed
198
+ - `.plans` docs linkage
199
+- Tests:
200
+ - full server integration suite passes on Effect-only path
201
+ - no regressions in WS protocol behavior
202
+
203
+## Risk Controls
204
+- Keep WS method names and payload contracts stable throughout.
205
+- Gate each commit with targeted integration tests before moving forward.
206
+- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
apps/server/src/orchestration/Errors.ts
+23
-9
@@ -1,6 +1,6 @@
1
import { SchemaIssue, Schema } from "effect";
2
3
-import type { OrchestrationEventRepositoryError } from "../persistence/Errors.ts";
3
+import type { OrchestrationEventStoreError } from "../persistence/Errors.ts";
4
5
export class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<OrchestrationCommandJsonParseError>()(
6
"OrchestrationCommandJsonParseError",
@@ -26,8 +26,21 @@ export class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<Orc
26
}
27
}
28
29
-export class OrchestrationReducerDecodeError extends Schema.TaggedErrorClass<OrchestrationReducerDecodeError>()(
30
- "OrchestrationReducerDecodeError",
29
+export class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass<OrchestrationCommandInvariantError>()(
30
+ "OrchestrationCommandInvariantError",
31
+ {
32
+ commandType: Schema.String,
33
+ detail: Schema.String,
34
+ cause: Schema.optional(Schema.Defect),
35
+ },
36
+) {
37
+ override get message(): string {
38
+ return `Orchestration command invariant failed (${this.commandType}): ${this.detail}`;
39
+ }
40
+}
41
+
42
+export class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass<OrchestrationProjectorDecodeError>()(
43
+ "OrchestrationProjectorDecodeError",
44
{
45
eventType: Schema.String,
46
issue: Schema.String,
@@ -35,7 +48,7 @@ export class OrchestrationReducerDecodeError extends Schema.TaggedErrorClass<Orc
48
},
49
) {
50
override get message(): string {
38
- return `Reducer decode failed for ${this.eventType}: ${this.issue}`;
51
+ return `Projector decode failed for ${this.eventType}: ${this.issue}`;
52
}
53
}
54
@@ -53,8 +66,9 @@ export class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<
66
}
67
68
export type OrchestrationDispatchError =
56
- | OrchestrationEventRepositoryError
57
- | OrchestrationReducerDecodeError
69
+ | OrchestrationEventStoreError
70
+ | OrchestrationCommandInvariantError
71
+ | OrchestrationProjectorDecodeError
72
| OrchestrationListenerCallbackError;
73
74
export type OrchestrationEngineError =
@@ -69,9 +83,9 @@ export function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {
83
});
84
}
85
72
-export function toReducerDecodeError(eventType: string) {
73
- return (error: Schema.SchemaError): OrchestrationReducerDecodeError =>
74
- new OrchestrationReducerDecodeError({
86
+export function toProjectorDecodeError(eventType: string) {
87
+ return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>
88
+ new OrchestrationProjectorDecodeError({
89
eventType,
90
issue: SchemaIssue.makeFormatterDefault()(error.issue),
91
cause: error,
apps/server/src/orchestration/Layer.test.ts
+88
-23
@@ -3,18 +3,18 @@ import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
3
import { describe, expect, it } from "vitest";
4
5
import {
6
- OrchestrationEventRepository,
7
- type OrchestrationEventRepositoryShape,
8
-} from "../persistence/Services/OrchestrationEvents.ts";
6
+ OrchestrationEventStore,
7
+ type OrchestrationEventStoreShape,
8
+} from "../persistence/Services/OrchestrationEventStore.ts";
9
import { PersistenceSqlError } from "../persistence/Errors.ts";
10
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
11
-import { OrchestrationEngineLive } from "./Layer.ts";
12
-import { OrchestrationEngineService } from "./Service.ts";
13
-import { OrchestrationEventRepositoryLive } from "../persistence/Layers/OrchestrationEvents.ts";
11
+import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
12
+import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
13
+import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
14
15
export async function createOrchestrationSystem() {
16
const orchestrationLayer = OrchestrationEngineLive.pipe(
17
- Layer.provide(OrchestrationEventRepositoryLive),
17
+ Layer.provide(OrchestrationEventStoreLive),
18
Layer.provide(SqlitePersistenceMemory),
19
);
20
const runtime = ManagedRuntime.make(orchestrationLayer);
@@ -27,7 +27,7 @@ export async function createOrchestrationSystem() {
27
}
28
29
describe("OrchestrationEngine", () => {
30
- it("returns deterministic snapshots for repeated reads", async () => {
30
+ it("returns deterministic read models for repeated reads", async () => {
31
const createdAt = new Date().toISOString();
32
const projectId = "project-1";
33
const threadId = "thread-1";
@@ -59,9 +59,9 @@ describe("OrchestrationEngine", () => {
59
createdAt,
60
}),
61
);
62
- const snapshotA = await system.run(engine.getSnapshot());
63
- const snapshotB = await system.run(engine.getSnapshot());
64
- expect(snapshotB).toEqual(snapshotA);
62
+ const readModelA = await system.run(engine.getReadModel());
63
+ const readModelB = await system.run(engine.getReadModel());
64
+ expect(readModelB).toEqual(readModelA);
65
await system.dispose();
66
});
67
@@ -89,7 +89,11 @@ describe("OrchestrationEngine", () => {
89
createdAt: new Date().toISOString(),
90
}),
91
);
92
- const events = await system.run(engine.replayEvents(0));
92
+ const events = await system.run(
93
+ Stream.runCollect(engine.readEvents(0)).pipe(
94
+ Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
95
+ ),
96
+ );
97
expect(events.length).toBe(2);
98
expect(events[0]?.type).toBe("thread.created");
99
expect(events[1]?.type).toBe("thread.deleted");
@@ -167,7 +171,7 @@ describe("OrchestrationEngine", () => {
171
}),
172
);
173
170
- const firstThread = (await system.run(engine.getSnapshot())).threads.find(
174
+ const firstThread = (await system.run(engine.getReadModel())).threads.find(
175
(thread) => thread.id === "thread-turn-diff",
176
);
177
expect(firstThread?.turnDiffSummaries).toEqual([
@@ -289,7 +293,7 @@ describe("OrchestrationEngine", () => {
293
}),
294
);
295
292
- const thread = (await system.run(engine.getSnapshot())).threads.find(
296
+ const thread = (await system.run(engine.getReadModel())).threads.find(
297
(entry) => entry.id === "thread-revert",
298
);
299
expect(thread?.messages.map((message) => message.id)).toEqual(["user-1", "assistant:turn-1"]);
@@ -299,20 +303,20 @@ describe("OrchestrationEngine", () => {
303
});
304
305
it("allows stop to be called multiple times", async () => {
302
- const inMemoryStore: OrchestrationEventRepositoryShape = {
306
+ const inMemoryStore: OrchestrationEventStoreShape = {
307
append(event) {
308
return Effect.succeed({ ...event, sequence: 1 });
309
},
310
readFromSequence() {
307
- return Effect.succeed([]);
311
+ return Stream.empty;
312
},
313
readAll() {
310
- return Effect.succeed([]);
314
+ return Stream.empty;
315
},
316
};
317
const runtime = ManagedRuntime.make(
318
OrchestrationEngineLive.pipe(
315
- Layer.provide(Layer.succeed(OrchestrationEventRepository, inMemoryStore)),
319
+ Layer.provide(Layer.succeed(OrchestrationEventStore, inMemoryStore)),
320
),
321
);
322
await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -325,7 +329,7 @@ describe("OrchestrationEngine", () => {
329
let nextSequence = 1;
330
let shouldFailFirstAppend = true;
331
328
- const flakyStore: OrchestrationEventRepositoryShape = {
332
+ const flakyStore: OrchestrationEventStoreShape = {
333
append(event) {
334
if (shouldFailFirstAppend) {
335
shouldFailFirstAppend = false;
@@ -345,16 +349,16 @@ describe("OrchestrationEngine", () => {
349
return Effect.succeed(savedEvent);
350
},
351
readFromSequence(sequenceExclusive) {
348
- return Effect.succeed(events.filter((event) => event.sequence > sequenceExclusive));
352
+ return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
353
},
354
readAll() {
351
- return Effect.succeed(events);
355
+ return Stream.fromIterable(events);
356
},
357
};
358
359
const runtime = ManagedRuntime.make(
360
OrchestrationEngineLive.pipe(
357
- Layer.provide(Layer.succeed(OrchestrationEventRepository, flakyStore)),
361
+ Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
362
),
363
);
364
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -391,8 +395,69 @@ describe("OrchestrationEngine", () => {
395
);
396
397
expect(result.sequence).toBe(1);
394
- expect((await runtime.runPromise(engine.getSnapshot())).sequence).toBe(1);
398
+ expect((await runtime.runPromise(engine.getReadModel())).sequence).toBe(1);
399
400
await runtime.dispose();
401
});
402
+
403
+ it("fails command dispatch when command invariants are violated", async () => {
404
+ const system = await createOrchestrationSystem();
405
+ const engine = system.engine;
406
+ const createdAt = new Date().toISOString();
407
+
408
+ await expect(
409
+ system.run(
410
+ engine.dispatch({
411
+ type: "message.send",
412
+ commandId: "cmd-invariant-missing-thread",
413
+ threadId: "thread-missing",
414
+ messageId: "msg-missing",
415
+ role: "user",
416
+ text: "hello",
417
+ streaming: false,
418
+ createdAt,
419
+ }),
420
+ ),
421
+ ).rejects.toThrow("Thread 'thread-missing' does not exist");
422
+
423
+ await system.dispose();
424
+ });
425
+
426
+ it("rejects duplicate thread creation", async () => {
427
+ const system = await createOrchestrationSystem();
428
+ const engine = system.engine;
429
+ const createdAt = new Date().toISOString();
430
+
431
+ await system.run(
432
+ engine.dispatch({
433
+ type: "thread.create",
434
+ commandId: "cmd-thread-duplicate-1",
435
+ threadId: "thread-duplicate",
436
+ projectId: "project-duplicate",
437
+ title: "duplicate",
438
+ model: "gpt-5-codex",
439
+ branch: null,
440
+ worktreePath: null,
441
+ createdAt,
442
+ }),
443
+ );
444
+
445
+ await expect(
446
+ system.run(
447
+ engine.dispatch({
448
+ type: "thread.create",
449
+ commandId: "cmd-thread-duplicate-2",
450
+ threadId: "thread-duplicate",
451
+ projectId: "project-duplicate",
452
+ title: "duplicate",
453
+ model: "gpt-5-codex",
454
+ branch: null,
455
+ worktreePath: null,
456
+ createdAt,
457
+ }),
458
+ ),
459
+ ).rejects.toThrow("already exists");
460
+
461
+ await system.dispose();
462
+ });
463
});
apps/server/src/orchestration/Layers/OrchestrationEngine.ts
new
+110
@@ -0,0 +1,110 @@
1
+import type {
2
+ OrchestrationCommand,
3
+ OrchestrationEvent,
4
+ OrchestrationReadModel,
5
+} from "@t3tools/contracts";
6
+import { OrchestrationCommandSchema } from "@t3tools/contracts";
7
+import { Deferred, Effect, Layer, PubSub, Queue, Schema, Stream } from "effect";
8
+
9
+import { createLogger } from "../../logger.ts";
10
+import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
11
+import {
12
+ toOrchestrationCommandDecodeError,
13
+ toOrchestrationJsonParseError,
14
+ type OrchestrationDispatchError,
15
+} from "../Errors.ts";
16
+import { decideOrchestrationCommand } from "../decider.ts";
17
+import { createEmptyReadModel, projectEvent } from "../projector.ts";
18
+import {
19
+ OrchestrationEngineService,
20
+ type OrchestrationEngineShape,
21
+} from "../Services/OrchestrationEngine.ts";
22
+
23
+interface CommandEnvelope {
24
+ command: OrchestrationCommand;
25
+ result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
26
+}
27
+
28
+const decodeUnknownCommand = Schema.decodeUnknownEffect(OrchestrationCommandSchema);
29
+
30
+const makeOrchestrationEngine = Effect.gen(function* () {
31
+ const logger = createLogger("orchestration");
32
+ const eventStore = yield* OrchestrationEventStore;
33
+
34
+ let readModel = createEmptyReadModel(new Date().toISOString());
35
+
36
+ const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
37
+ const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
38
+
39
+ const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
40
+ Effect.gen(function* () {
41
+ const eventBase = yield* decideOrchestrationCommand({
42
+ command: envelope.command,
43
+ readModel,
44
+ });
45
+ const savedEvent = yield* eventStore.append(eventBase);
46
+ readModel = yield* projectEvent(readModel, savedEvent);
47
+ yield* PubSub.publish(eventPubSub, savedEvent);
48
+
49
+ yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
50
+ }).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)));
51
+
52
+ // bootstrap read model from event store
53
+ yield* Stream.runForEach(eventStore.readAll(), (event) =>
54
+ Effect.gen(function* () {
55
+ readModel = yield* projectEvent(readModel, event);
56
+ }),
57
+ );
58
+
59
+ const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
60
+ yield* Effect.forkScoped(worker);
61
+ logger.info("orchestration engine started", {
62
+ sequence: readModel.sequence,
63
+ });
64
+
65
+ const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
66
+ Effect.sync((): OrchestrationReadModel => readModel);
67
+
68
+ const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
69
+ eventStore.readFromSequence(fromSequenceExclusive);
70
+
71
+ const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
72
+ Effect.gen(function* () {
73
+ const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
74
+ yield* Queue.offer(commandQueue, { command, result });
75
+ return yield* Deferred.await(result);
76
+ });
77
+
78
+ const dispatchUnknownCommand: OrchestrationEngineShape["dispatchUnknownCommand"] = (command) =>
79
+ Effect.gen(function* () {
80
+ const payload =
81
+ typeof command === "string"
82
+ ? yield* Effect.try({
83
+ try: () => JSON.parse(command) as unknown,
84
+ catch: toOrchestrationJsonParseError,
85
+ })
86
+ : command;
87
+
88
+ const decoded = yield* decodeUnknownCommand(payload).pipe(
89
+ Effect.mapError(toOrchestrationCommandDecodeError),
90
+ );
91
+
92
+ return yield* dispatch(decoded);
93
+ });
94
+
95
+ const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
96
+ Stream.fromPubSub(eventPubSub);
97
+
98
+ return {
99
+ getReadModel,
100
+ readEvents,
101
+ dispatchUnknownCommand,
102
+ dispatch,
103
+ streamDomainEvents,
104
+ } satisfies OrchestrationEngineShape;
105
+});
106
+
107
+export const OrchestrationEngineLive = Layer.effect(
108
+ OrchestrationEngineService,
109
+ makeOrchestrationEngine,
110
+);
apps/server/src/orchestration/Services/OrchestrationEngine.ts
renamed
+10
-10
@@ -2,7 +2,7 @@
2
* OrchestrationEngineService - Service interface for orchestration command handling.
3
*
4
* Owns command validation/dispatch and in-memory read-model updates backed by
5
- * `OrchestrationEventRepository` persistence. It does not own provider process
5
+ * `OrchestrationEventStore` persistence. It does not own provider process
6
* management or transport concerns (e.g. websocket request parsing).
7
*
8
* Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch,
@@ -18,26 +18,26 @@ import type {
18
import { ServiceMap } from "effect";
19
import type { Effect, Stream } from "effect";
20
21
-import type { OrchestrationDispatchError, OrchestrationEngineError } from "./Errors.ts";
22
-import type { OrchestrationEventRepositoryError } from "../persistence/Errors.ts";
21
+import type { OrchestrationDispatchError, OrchestrationEngineError } from "../Errors.ts";
22
+import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
23
24
export interface OrchestrationEngineShape {
25
/**
26
- * Read the current in-memory orchestration snapshot.
26
+ * Read the current in-memory orchestration read model.
27
*
28
* @returns Effect containing the latest read model.
29
*/
30
- readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, never, never>;
30
+ readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
31
32
/**
33
* Replay persisted orchestration events from an exclusive sequence cursor.
34
*
35
* @param fromSequenceExclusive - Sequence cursor (exclusive).
36
- * @returns Effect containing ordered events.
36
+ * @returns Stream containing ordered events.
37
*/
38
- readonly replayEvents: (
38
+ readonly readEvents: (
39
fromSequenceExclusive: number,
40
- ) => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError, never>;
40
+ ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
41
42
/**
43
* Validate and dispatch an unknown command payload.
@@ -47,7 +47,7 @@ export interface OrchestrationEngineShape {
47
* @param command - Unknown command payload.
48
* @returns Effect containing the sequence of the persisted event.
49
*/
50
- readonly dispatchUnknown: (
50
+ readonly dispatchUnknownCommand: (
51
command: unknown,
52
) => Effect.Effect<{ sequence: number }, OrchestrationEngineError, never>;
53
@@ -74,7 +74,7 @@ export interface OrchestrationEngineShape {
74
* ```ts
75
* const program = Effect.gen(function* () {
76
* const engine = yield* OrchestrationEngineService
77
- * return yield* engine.getSnapshot()
77
+ * return yield* engine.getReadModel()
78
* })
79
* ```
80
*/
apps/server/src/orchestration/commandInvariants.test.ts
new
+161
@@ -0,0 +1,161 @@
1
+import { describe, expect, it } from "vitest";
2
+import type { OrchestrationCommand, OrchestrationReadModel } from "@t3tools/contracts";
3
+import { Effect } from "effect";
4
+
5
+import {
6
+ findThreadById,
7
+ listThreadsByProjectId,
8
+ requireNonNegativeInteger,
9
+ requireThread,
10
+ requireThreadAbsent,
11
+} from "./commandInvariants.ts";
12
+
13
+const now = new Date().toISOString();
14
+
15
+const readModel: OrchestrationReadModel = {
16
+ sequence: 2,
17
+ updatedAt: now,
18
+ gitByProjectId: {},
19
+ threads: [
20
+ {
21
+ id: "thread-1",
22
+ projectId: "project-a",
23
+ title: "Thread A",
24
+ model: "gpt-5-codex",
25
+ branch: null,
26
+ worktreePath: null,
27
+ createdAt: now,
28
+ updatedAt: now,
29
+ latestTurnId: null,
30
+ latestTurnStartedAt: null,
31
+ latestTurnCompletedAt: null,
32
+ latestTurnDurationMs: null,
33
+ messages: [],
34
+ session: null,
35
+ turnDiffSummaries: [],
36
+ activities: [],
37
+ error: null,
38
+ },
39
+ {
40
+ id: "thread-2",
41
+ projectId: "project-b",
42
+ title: "Thread B",
43
+ model: "gpt-5-codex",
44
+ branch: null,
45
+ worktreePath: null,
46
+ createdAt: now,
47
+ updatedAt: now,
48
+ latestTurnId: null,
49
+ latestTurnStartedAt: null,
50
+ latestTurnCompletedAt: null,
51
+ latestTurnDurationMs: null,
52
+ messages: [],
53
+ session: null,
54
+ turnDiffSummaries: [],
55
+ activities: [],
56
+ error: null,
57
+ },
58
+ ],
59
+};
60
+
61
+const messageSendCommand: OrchestrationCommand = {
62
+ type: "message.send",
63
+ commandId: "cmd-1",
64
+ threadId: "thread-1",
65
+ messageId: "msg-1",
66
+ role: "user",
67
+ text: "hello",
68
+ streaming: false,
69
+ createdAt: now,
70
+};
71
+
72
+describe("commandInvariants", () => {
73
+ it("finds threads by id and project", () => {
74
+ expect(findThreadById(readModel, "thread-1")?.projectId).toBe("project-a");
75
+ expect(findThreadById(readModel, "missing")).toBeUndefined();
76
+ expect(listThreadsByProjectId(readModel, "project-b").map((thread) => thread.id)).toEqual([
77
+ "thread-2",
78
+ ]);
79
+ });
80
+
81
+ it("requires existing thread", async () => {
82
+ const thread = await Effect.runPromise(
83
+ requireThread({
84
+ readModel,
85
+ command: messageSendCommand,
86
+ threadId: "thread-1",
87
+ }),
88
+ );
89
+ expect(thread.id).toBe("thread-1");
90
+
91
+ await expect(
92
+ Effect.runPromise(
93
+ requireThread({
94
+ readModel,
95
+ command: messageSendCommand,
96
+ threadId: "missing",
97
+ }),
98
+ ),
99
+ ).rejects.toThrow("does not exist");
100
+ });
101
+
102
+ it("requires missing thread for create flows", async () => {
103
+ await Effect.runPromise(
104
+ requireThreadAbsent({
105
+ readModel,
106
+ command: {
107
+ type: "thread.create",
108
+ commandId: "cmd-2",
109
+ threadId: "thread-3",
110
+ projectId: "project-a",
111
+ title: "new",
112
+ model: "gpt-5-codex",
113
+ branch: null,
114
+ worktreePath: null,
115
+ createdAt: now,
116
+ },
117
+ threadId: "thread-3",
118
+ }),
119
+ );
120
+
121
+ await expect(
122
+ Effect.runPromise(
123
+ requireThreadAbsent({
124
+ readModel,
125
+ command: {
126
+ type: "thread.create",
127
+ commandId: "cmd-3",
128
+ threadId: "thread-1",
129
+ projectId: "project-a",
130
+ title: "dup",
131
+ model: "gpt-5-codex",
132
+ branch: null,
133
+ worktreePath: null,
134
+ createdAt: now,
135
+ },
136
+ threadId: "thread-1",
137
+ }),
138
+ ),
139
+ ).rejects.toThrow("already exists");
140
+ });
141
+
142
+ it("requires non-negative integers", async () => {
143
+ await Effect.runPromise(
144
+ requireNonNegativeInteger({
145
+ commandType: "thread.revert",
146
+ field: "turnCount",
147
+ value: 0,
148
+ }),
149
+ );
150
+
151
+ await expect(
152
+ Effect.runPromise(
153
+ requireNonNegativeInteger({
154
+ commandType: "thread.revert",
155
+ field: "turnCount",
156
+ value: -1,
157
+ }),
158
+ ),
159
+ ).rejects.toThrow("greater than or equal to 0");
160
+ });
161
+});
apps/server/src/orchestration/commandInvariants.ts
new
+80
@@ -0,0 +1,80 @@
1
+import type { OrchestrationCommand, OrchestrationReadModel, OrchestrationThread } from "@t3tools/contracts";
2
+import { Effect } from "effect";
3
+
4
+import { OrchestrationCommandInvariantError } from "./Errors.ts";
5
+
6
+function invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError {
7
+ return new OrchestrationCommandInvariantError({
8
+ commandType,
9
+ detail,
10
+ });
11
+}
12
+
13
+export function findThreadById(
14
+ readModel: OrchestrationReadModel,
15
+ threadId: string,
16
+): OrchestrationThread | undefined {
17
+ return readModel.threads.find((thread) => thread.id === threadId);
18
+}
19
+
20
+export function listThreadsByProjectId(
21
+ readModel: OrchestrationReadModel,
22
+ projectId: string,
23
+): ReadonlyArray<OrchestrationThread> {
24
+ return readModel.threads.filter((thread) => thread.projectId === projectId);
25
+}
26
+
27
+export function requireThread(
28
+ input: {
29
+ readonly readModel: OrchestrationReadModel;
30
+ readonly command: OrchestrationCommand;
31
+ readonly threadId: string;
32
+ },
33
+): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
34
+ const thread = findThreadById(input.readModel, input.threadId);
35
+ if (thread) {
36
+ return Effect.succeed(thread);
37
+ }
38
+ return Effect.fail(
39
+ invariantError(
40
+ input.command.type,
41
+ `Thread '${input.threadId}' does not exist for command '${input.command.type}'.`,
42
+ ),
43
+ );
44
+}
45
+
46
+export function requireThreadAbsent(
47
+ input: {
48
+ readonly readModel: OrchestrationReadModel;
49
+ readonly command: OrchestrationCommand;
50
+ readonly threadId: string;
51
+ },
52
+): Effect.Effect<void, OrchestrationCommandInvariantError> {
53
+ if (!findThreadById(input.readModel, input.threadId)) {
54
+ return Effect.void;
55
+ }
56
+ return Effect.fail(
57
+ invariantError(
58
+ input.command.type,
59
+ `Thread '${input.threadId}' already exists and cannot be created twice.`,
60
+ ),
61
+ );
62
+}
63
+
64
+export function requireNonNegativeInteger(
65
+ input: {
66
+ readonly commandType: OrchestrationCommand["type"];
67
+ readonly field: string;
68
+ readonly value: number;
69
+ },
70
+): Effect.Effect<void, OrchestrationCommandInvariantError> {
71
+ if (Number.isInteger(input.value) && input.value >= 0) {
72
+ return Effect.void;
73
+ }
74
+ return Effect.fail(
75
+ invariantError(
76
+ input.commandType,
77
+ `${input.field} must be an integer greater than or equal to 0.`,
78
+ ),
79
+ );
80
+}
apps/server/src/orchestration/decider.ts
renamed
+73
-102
@@ -3,28 +3,31 @@ import type {
3
OrchestrationEvent,
4
OrchestrationReadModel,
5
} from "@t3tools/contracts";
6
-import { OrchestrationCommandSchema } from "@t3tools/contracts";
7
-import { Deferred, Effect, Layer, PubSub, Queue, Schema, Stream } from "effect";
6
+import { Effect } from "effect";
7
9
-import { createLogger } from "../logger.ts";
10
-import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents.ts";
8
+import { OrchestrationCommandInvariantError } from "./Errors.ts";
9
import {
12
- toOrchestrationCommandDecodeError,
13
- toOrchestrationJsonParseError,
14
- type OrchestrationDispatchError,
15
-} from "./Errors.ts";
16
-import { createEmptyReadModel, reduceEvent } from "./reducer.ts";
17
-import { OrchestrationEngineService, type OrchestrationEngineShape } from "./Service.ts";
18
-
19
-interface CommandEnvelope {
20
- command: OrchestrationCommand;
21
- result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
22
-}
23
-
24
-function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEvent, "sequence"> {
10
+ requireNonNegativeInteger,
11
+ requireThread,
12
+ requireThreadAbsent,
13
+} from "./commandInvariants.ts";
14
+
15
+export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
16
+ command,
17
+ readModel,
18
+}: {
19
+ readonly command: OrchestrationCommand;
20
+ readonly readModel: OrchestrationReadModel;
21
+}): Effect.fn.Return<Omit<OrchestrationEvent, "sequence">, OrchestrationCommandInvariantError> {
22
const eventId = crypto.randomUUID();
23
+
24
switch (command.type) {
25
case "thread.create":
26
+ yield* requireThreadAbsent({
27
+ readModel,
28
+ command,
29
+ threadId: command.threadId,
30
+ });
31
return {
32
eventId,
33
type: "thread.created",
@@ -44,6 +47,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
47
},
48
};
49
case "thread.delete":
50
+ yield* requireThread({
51
+ readModel,
52
+ command,
53
+ threadId: command.threadId,
54
+ });
55
return {
56
eventId,
57
type: "thread.deleted",
@@ -57,6 +65,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
65
},
66
};
67
case "thread.meta.update":
68
+ yield* requireThread({
69
+ readModel,
70
+ command,
71
+ threadId: command.threadId,
72
+ });
73
return {
74
eventId,
75
type: "thread.meta-updated",
@@ -74,6 +87,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
87
},
88
};
89
case "message.send":
90
+ yield* requireThread({
91
+ readModel,
92
+ command,
93
+ threadId: command.threadId,
94
+ });
95
return {
96
eventId,
97
type: "message.sent",
@@ -91,6 +109,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
109
},
110
};
111
case "thread.session":
112
+ yield* requireThread({
113
+ readModel,
114
+ command,
115
+ threadId: command.threadId,
116
+ });
117
return {
118
eventId,
119
type: "thread.session-set",
@@ -121,6 +144,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
144
},
145
};
146
case "thread.turnDiff.complete":
147
+ yield* requireThread({
148
+ readModel,
149
+ command,
150
+ threadId: command.threadId,
151
+ });
152
return {
153
eventId,
154
type: "thread.turn-diff-completed",
@@ -143,6 +171,11 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
171
},
172
};
173
case "thread.activity.append":
174
+ yield* requireThread({
175
+ readModel,
176
+ command,
177
+ threadId: command.threadId,
178
+ });
179
return {
180
eventId,
181
type: "thread.activity-appended",
@@ -156,6 +189,21 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
189
},
190
};
191
case "thread.revert":
192
+ yield* requireThread({
193
+ readModel,
194
+ command,
195
+ threadId: command.threadId,
196
+ });
197
+ yield* requireNonNegativeInteger({
198
+ commandType: command.type,
199
+ field: "turnCount",
200
+ value: command.turnCount,
201
+ });
202
+ yield* requireNonNegativeInteger({
203
+ commandType: command.type,
204
+ field: "messageCount",
205
+ value: command.messageCount,
206
+ });
207
return {
208
eventId,
209
type: "thread.reverted",
@@ -169,90 +217,13 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
217
messageCount: command.messageCount,
218
},
219
};
220
+ default: {
221
+ command satisfies never;
222
+ const fallback = command as any;
223
+ return yield* new OrchestrationCommandInvariantError({
224
+ commandType: fallback.type,
225
+ detail: `Unknown command type: ${fallback.type}`,
226
+ });
227
+ }
228
}
173
-}
174
-
175
-const decodeUnknownCommand = Schema.decodeUnknownEffect(OrchestrationCommandSchema);
176
-
177
-const makeOrchestrationEngine = Effect.gen(function* () {
178
- const logger = createLogger("orchestration");
179
- const eventStore = yield* OrchestrationEventRepository;
180
-
181
- let readModel = createEmptyReadModel(new Date().toISOString());
182
-
183
- const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
184
- const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
185
-
186
- const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
187
- Effect.gen(function* () {
188
- const eventBase = mapCommandToEvent(envelope.command);
189
- const savedEvent = yield* eventStore.append(eventBase);
190
- readModel = yield* reduceEvent(readModel, savedEvent);
191
- yield* PubSub.publish(eventPubSub, savedEvent);
192
-
193
- yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
194
- }).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)));
195
-
196
- const bootstrapReadModel: Effect.Effect<void, OrchestrationDispatchError> = Effect.gen(
197
- function* () {
198
- const existingEvents = yield* eventStore.readAll();
199
- for (const event of existingEvents) {
200
- readModel = yield* reduceEvent(readModel, event);
201
- }
202
- },
203
- );
204
-
205
- yield* bootstrapReadModel;
206
-
207
- const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
208
- yield* Effect.forkScoped(worker);
209
- logger.info("orchestration engine started", {
210
- sequence: readModel.sequence,
211
- });
212
-
213
- const getSnapshot: OrchestrationEngineShape["getSnapshot"] = () =>
214
- Effect.sync((): OrchestrationReadModel => readModel);
215
-
216
- const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) =>
217
- eventStore.readFromSequence(fromSequenceExclusive);
218
-
219
- const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
220
- Effect.gen(function* () {
221
- const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
222
- yield* Queue.offer(commandQueue, { command, result });
223
- return yield* Deferred.await(result);
224
- });
225
-
226
- const dispatchUnknown: OrchestrationEngineShape["dispatchUnknown"] = (command) =>
227
- Effect.gen(function* () {
228
- const payload =
229
- typeof command === "string"
230
- ? yield* Effect.try({
231
- try: () => JSON.parse(command) as unknown,
232
- catch: toOrchestrationJsonParseError,
233
- })
234
- : command;
235
-
236
- const decoded = yield* decodeUnknownCommand(payload).pipe(
237
- Effect.mapError(toOrchestrationCommandDecodeError),
238
- );
239
-
240
- return yield* dispatch(decoded);
241
- });
242
-
243
- const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
244
- Stream.fromPubSub(eventPubSub);
245
-
246
- return {
247
- getSnapshot,
248
- replayEvents,
249
- dispatchUnknown,
250
- dispatch,
251
- streamDomainEvents,
252
- } satisfies OrchestrationEngineShape;
229
});
254
-
255
-export const OrchestrationEngineLive = Layer.effect(
256
- OrchestrationEngineService,
257
- makeOrchestrationEngine,
258
-);
apps/server/src/orchestration/projector.test.ts
renamed
+12
-12
@@ -2,9 +2,9 @@ import type { OrchestrationEvent } from "@t3tools/contracts";
2
import { Effect } from "effect";
3
import { describe, expect, it } from "vitest";
4
5
-import { createEmptyReadModel, reduceEvent } from "./reducer.ts";
5
+import { createEmptyReadModel, projectEvent } from "./projector.ts";
6
7
-describe("orchestration reducer", () => {
7
+describe("orchestration projector", () => {
8
it("applies thread.created events using runtime schema decoding", async () => {
9
const now = new Date().toISOString();
10
const model = createEmptyReadModel(now);
@@ -28,7 +28,7 @@ describe("orchestration reducer", () => {
28
},
29
};
30
31
- const next = await Effect.runPromise(reduceEvent(model, event));
31
+ const next = await Effect.runPromise(projectEvent(model, event));
32
expect(next.sequence).toBe(1);
33
expect(next.threads).toEqual([
34
{
@@ -73,10 +73,10 @@ describe("orchestration reducer", () => {
73
},
74
};
75
76
- await expect(Effect.runPromise(reduceEvent(model, event))).rejects.toBeDefined();
76
+ await expect(Effect.runPromise(projectEvent(model, event))).rejects.toBeDefined();
77
});
78
79
- it("keeps reducer forward-compatible for unknown event types", async () => {
79
+ it("keeps projector forward-compatible for unknown event types", async () => {
80
const now = new Date().toISOString();
81
const model = createEmptyReadModel(now);
82
const event: OrchestrationEvent = {
@@ -90,7 +90,7 @@ describe("orchestration reducer", () => {
90
payload: { test: true },
91
};
92
93
- const next = await Effect.runPromise(reduceEvent(model, event));
93
+ const next = await Effect.runPromise(projectEvent(model, event));
94
expect(next.sequence).toBe(7);
95
expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
96
expect(next.threads).toEqual([]);
@@ -168,9 +168,9 @@ describe("orchestration reducer", () => {
168
},
169
};
170
171
- const afterCreate = await Effect.runPromise(reduceEvent(model, createdEvent));
172
- const afterRunning = await Effect.runPromise(reduceEvent(afterCreate, runningSessionEvent));
173
- const afterReady = await Effect.runPromise(reduceEvent(afterRunning, readySessionEvent));
171
+ const afterCreate = await Effect.runPromise(projectEvent(model, createdEvent));
172
+ const afterRunning = await Effect.runPromise(projectEvent(afterCreate, runningSessionEvent));
173
+ const afterReady = await Effect.runPromise(projectEvent(afterRunning, readySessionEvent));
174
const thread = afterReady.threads[0];
175
176
expect(thread?.latestTurnId).toBe("turn-1");
@@ -241,9 +241,9 @@ describe("orchestration reducer", () => {
241
},
242
};
243
244
- const afterCreate = await Effect.runPromise(reduceEvent(model, createdEvent));
245
- const afterDelta = await Effect.runPromise(reduceEvent(afterCreate, deltaEvent));
246
- const afterComplete = await Effect.runPromise(reduceEvent(afterDelta, completionEvent));
244
+ const afterCreate = await Effect.runPromise(projectEvent(model, createdEvent));
245
+ const afterDelta = await Effect.runPromise(projectEvent(afterCreate, deltaEvent));
246
+ const afterComplete = await Effect.runPromise(projectEvent(afterDelta, completionEvent));
247
const message = afterComplete.threads[0]?.messages[0];
248
249
expect(message).toEqual({
apps/server/src/orchestration/projector.ts
renamed
+6
-6
@@ -17,7 +17,7 @@ import {
17
} from "@t3tools/contracts";
18
import { Effect, Schema } from "effect";
19
20
-import { toReducerDecodeError, type OrchestrationReducerDecodeError } from "./Errors.ts";
20
+import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
21
22
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
23
@@ -34,10 +34,10 @@ function decodeForEvent<A>(
34
value: unknown,
35
eventType: string,
36
field: string,
37
-): Effect.Effect<A, OrchestrationReducerDecodeError> {
37
+): Effect.Effect<A, OrchestrationProjectorDecodeError> {
38
return Schema.decodeUnknownEffect(schema)(value).pipe(
39
- Effect.mapError(toReducerDecodeError(`${eventType}:${field}`)),
40
- ) as Effect.Effect<A, OrchestrationReducerDecodeError>;
39
+ Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
40
+ ) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
41
}
42
43
const ThreadCreatedPayloadSchema = Schema.Struct({
@@ -104,10 +104,10 @@ export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
104
};
105
}
106
107
-export function reduceEvent(
107
+export function projectEvent(
108
model: OrchestrationReadModel,
109
event: OrchestrationEvent,
110
-): Effect.Effect<OrchestrationReadModel, OrchestrationReducerDecodeError> {
110
+): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {
111
const nextBase: OrchestrationReadModel = {
112
...model,
113
sequence: event.sequence,
apps/server/src/persistence/Errors.ts
+1
-1
@@ -158,7 +158,7 @@ export type ProjectRepositoryError =
158
| ProjectPathMissingError
159
| ProjectNotFoundError;
160
161
-export type OrchestrationEventRepositoryError =
161
+export type OrchestrationEventStoreError =
162
| PersistenceSqlError
163
| PersistenceDecodeError
164
| PersistenceSerializationError;
apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts
renamed
+10
-8
@@ -1,25 +1,25 @@
1
-import { Effect, Layer } from "effect";
1
+import { Effect, Layer, Stream } from "effect";
2
import { assert, it } from "@effect/vitest";
3
4
-import { OrchestrationEventRepository } from "../Services/OrchestrationEvents.ts";
4
+import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
5
import { SqlitePersistenceMemory } from "./Sqlite.ts";
6
-import { OrchestrationEventRepositoryLive } from "./OrchestrationEvents.ts";
6
+import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
7
import { NodeServices } from "@effect/platform-node";
8
9
const layer = it.layer(
10
Layer.mergeAll(
11
- Layer.provide(OrchestrationEventRepositoryLive, SqlitePersistenceMemory),
11
+ Layer.provide(OrchestrationEventStoreLive, SqlitePersistenceMemory),
12
NodeServices.layer,
13
),
14
);
15
16
-layer("OrchestrationEventRepository", (it) => {
16
+layer("OrchestrationEventStore", (it) => {
17
it.effect("stores and replays events", () =>
18
Effect.gen(function* () {
19
const createdAt = new Date().toISOString();
20
21
- const repository = yield* OrchestrationEventRepository;
22
- const saved = yield* repository.append({
21
+ const eventStore = yield* OrchestrationEventStore;
22
+ const saved = yield* eventStore.append({
23
eventId: "event-1",
24
type: "thread.created",
25
aggregateType: "thread",
@@ -30,7 +30,9 @@ layer("OrchestrationEventRepository", (it) => {
30
});
31
assert.equal(saved.sequence, 1);
32
33
- const replayed = yield* repository.readFromSequence(0);
33
+ const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0)).pipe(
34
+ Effect.map(Array.from),
35
+ );
36
assert.deepEqual(replayed, [saved]);
37
}),
38
);
apps/server/src/persistence/Layers/OrchestrationEventStore.ts
renamed
+59
-27
@@ -2,19 +2,19 @@ import type { OrchestrationEvent } from "@t3tools/contracts";
2
import { OrchestrationEventSchema } from "@t3tools/contracts";
3
import * as SqlClient from "effect/unstable/sql/SqlClient";
4
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
5
-import { Effect, Layer, Schema } from "effect";
5
+import { Effect, Layer, Schema, Stream } from "effect";
6
7
import {
8
toPersistenceDecodeCauseError,
9
toPersistenceDecodeError,
10
toPersistenceSerializationError,
11
toPersistenceSqlError,
12
- type OrchestrationEventRepositoryError,
12
+ type OrchestrationEventStoreError,
13
} from "../Errors.ts";
14
import {
15
- OrchestrationEventRepository,
16
- type OrchestrationEventRepositoryShape,
17
-} from "../Services/OrchestrationEvents.ts";
15
+ OrchestrationEventStore,
16
+ type OrchestrationEventStoreShape,
17
+} from "../Services/OrchestrationEventStore.ts";
18
19
const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEventSchema);
20
@@ -43,11 +43,13 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
43
sequenceExclusive: Schema.Number,
44
limit: Schema.Number,
45
});
46
+const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
47
+const READ_PAGE_SIZE = 500;
48
49
function eventRowToOrchestrationEvent(
50
row: Schema.Schema.Type<typeof EventRowSchema>,
51
operation: string,
50
-): Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError> {
52
+): Effect.Effect<OrchestrationEvent, OrchestrationEventStoreError> {
53
return Effect.try({
54
try: () => JSON.parse(row.payloadJson) as unknown,
55
catch: toPersistenceDecodeCauseError(`${operation}:parsePayloadJson`),
@@ -67,7 +69,7 @@ function eventRowToOrchestrationEvent(
69
);
70
}
71
70
-const makeRepository = Effect.gen(function* () {
72
+const makeEventStore = Effect.gen(function* () {
73
const sql = yield* SqlClient.SqlClient;
74
75
const appendEventRow = SqlSchema.findOne({
@@ -126,10 +128,10 @@ const makeRepository = Effect.gen(function* () {
128
`,
129
});
130
129
- const append: OrchestrationEventRepositoryShape["append"] = (event) =>
131
+ const append: OrchestrationEventStoreShape["append"] = (event) =>
132
Effect.try({
133
try: () => JSON.stringify(event.payload),
132
- catch: toPersistenceSerializationError("OrchestrationEventRepository.append:encodePayload"),
134
+ catch: toPersistenceSerializationError("OrchestrationEventStore.append:encodePayload"),
135
}).pipe(
136
Effect.flatMap((payloadJson) =>
137
appendEventRow({
@@ -141,38 +143,68 @@ const makeRepository = Effect.gen(function* () {
143
commandId: event.commandId,
144
payloadJson,
145
}).pipe(
144
- Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.append:insert")),
146
+ Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.append:insert")),
147
Effect.flatMap((row) =>
146
- eventRowToOrchestrationEvent(row, "OrchestrationEventRepository.append:rowToEvent"),
148
+ eventRowToOrchestrationEvent(row, "OrchestrationEventStore.append:rowToEvent"),
149
),
150
),
151
),
152
);
153
152
- const readFromSequence: OrchestrationEventRepositoryShape["readFromSequence"] = (
154
+ const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
155
sequenceExclusive,
154
- limit = 1_000,
155
- ) =>
156
- readEventRowsFromSequence({ sequenceExclusive, limit }).pipe(
157
- Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.readFromSequence:query")),
158
- Effect.flatMap((rows) =>
159
- Effect.forEach(rows, (row) =>
160
- eventRowToOrchestrationEvent(
161
- row,
162
- "OrchestrationEventRepository.readFromSequence:rowToEvent",
156
+ limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
157
+ ) => {
158
+ const normalizedLimit = Math.max(0, Math.floor(limit));
159
+ if (normalizedLimit === 0) {
160
+ return Stream.empty;
161
+ }
162
+ const readPage = (cursor: number, remaining: number): Stream.Stream<
163
+ OrchestrationEvent,
164
+ OrchestrationEventStoreError
165
+ > =>
166
+ Stream.fromEffect(
167
+ readEventRowsFromSequence({
168
+ sequenceExclusive: cursor,
169
+ limit: Math.min(remaining, READ_PAGE_SIZE),
170
+ }).pipe(
171
+ Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readFromSequence:query")),
172
+ Effect.flatMap((rows) =>
173
+ Effect.forEach(rows, (row) =>
174
+ eventRowToOrchestrationEvent(
175
+ row,
176
+ "OrchestrationEventStore.readFromSequence:rowToEvent",
177
+ ),
178
+ ),
179
),
180
),
165
- ),
166
- );
181
+ ).pipe(
182
+ Stream.flatMap((events) => {
183
+ if (events.length === 0) {
184
+ return Stream.empty;
185
+ }
186
+ const nextRemaining = remaining - events.length;
187
+ if (nextRemaining <= 0) {
188
+ return Stream.fromIterable(events);
189
+ }
190
+ return Stream.concat(
191
+ Stream.fromIterable(events),
192
+ readPage(events[events.length - 1]!.sequence, nextRemaining),
193
+ );
194
+ }),
195
+ );
196
+
197
+ return readPage(sequenceExclusive, normalizedLimit);
198
+ };
199
200
return {
201
append,
202
readFromSequence,
203
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
172
- } satisfies OrchestrationEventRepositoryShape;
204
+ } satisfies OrchestrationEventStoreShape;
205
});
206
175
-export const OrchestrationEventRepositoryLive = Layer.effect(
176
- OrchestrationEventRepository,
177
- makeRepository,
207
+export const OrchestrationEventStoreLive = Layer.effect(
208
+ OrchestrationEventStore,
209
+ makeEventStore,
210
);
apps/server/src/persistence/Services/OrchestrationEventStore.ts
renamed
+18
-18
@@ -1,5 +1,5 @@
1
/**
2
- * OrchestrationEventRepository - Repository interface for orchestration events.
2
+ * OrchestrationEventStore - Event store interface for orchestration events.
3
*
4
* Owns durable append/replay access to the orchestration event stream. It does
5
* not reduce events into read models or apply command validation rules.
@@ -7,15 +7,15 @@
7
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
8
* persistence/decode errors for event append and replay operations.
9
*
10
- * @module OrchestrationEventRepository
10
+ * @module OrchestrationEventStore
11
*/
12
import type { OrchestrationEvent } from "@t3tools/contracts";
13
import { ServiceMap } from "effect";
14
-import type { Effect } from "effect";
14
+import type { Effect, Stream } from "effect";
15
16
-import type { OrchestrationEventRepositoryError } from "../Errors.ts";
16
+import type { OrchestrationEventStoreError } from "../Errors.ts";
17
18
-export interface OrchestrationEventRepositoryShape {
18
+export interface OrchestrationEventStoreShape {
19
/**
20
* Persist a new orchestration event.
21
*
@@ -24,40 +24,40 @@ export interface OrchestrationEventRepositoryShape {
24
*/
25
readonly append: (
26
event: Omit<OrchestrationEvent, "sequence">,
27
- ) => Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError>;
27
+ ) => Effect.Effect<OrchestrationEvent, OrchestrationEventStoreError>;
28
29
/**
30
* Replay events after the provided sequence.
31
*
32
* @param sequenceExclusive - Sequence cursor (exclusive).
33
- * @param limit - Maximum number of events to return.
34
- * @returns Effect containing ordered events.
33
+ * @param limit - Maximum number of events to emit.
34
+ * @returns Stream containing ordered events.
35
*/
36
readonly readFromSequence: (
37
sequenceExclusive: number,
38
limit?: number,
39
- ) => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
39
+ ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
40
41
/**
42
* Read all events from the beginning of the stream.
43
*
44
- * @returns Effect containing all stored events.
44
+ * @returns Stream containing all stored events.
45
*/
46
- readonly readAll: () => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
46
+ readonly readAll: () => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
47
}
48
49
/**
50
- * OrchestrationEventRepository - Service tag for orchestration event persistence.
50
+ * OrchestrationEventStore - Service tag for orchestration event persistence.
51
*
52
* @example
53
* ```ts
54
* const program = Effect.gen(function* () {
55
- * const events = yield* OrchestrationEventRepository
56
- * return yield* events.readAll()
55
+ * const events = yield* OrchestrationEventStore
56
+ * return yield* Stream.runCollect(events.readAll())
57
* })
58
* ```
59
*/
60
-export class OrchestrationEventRepository extends ServiceMap.Service<
61
- OrchestrationEventRepository,
62
- OrchestrationEventRepositoryShape
63
->()("orchestration/EventRepository") {}
60
+export class OrchestrationEventStore extends ServiceMap.Service<
61
+ OrchestrationEventStore,
62
+ OrchestrationEventStoreShape
63
+>()("orchestration/EventStore") {}
apps/server/src/wsServer.ts
+23
-18
@@ -36,13 +36,16 @@ import {
36
import { TerminalManager } from "./terminalManager";
37
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
38
import { searchWorkspaceEntries } from "./workspaceEntries";
39
-import { OrchestrationEngineLive } from "./orchestration/Layer";
40
-import { OrchestrationEngineService, type OrchestrationEngineShape } from "./orchestration/Service";
39
+import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine";
40
+import {
41
+ OrchestrationEngineService,
42
+ type OrchestrationEngineShape,
43
+} from "./orchestration/Services/OrchestrationEngine";
44
import { ProjectRepositoryLive } from "./persistence/Layers/Projects";
45
import { makeSqlitePersistenceLive } from "./persistence/Layers/Sqlite";
46
import { ProjectRepository, type ProjectRepositoryShape } from "./persistence/Services/Projects";
47
import assert from "node:assert";
45
-import { OrchestrationEventRepositoryLive } from "./persistence/Layers/OrchestrationEvents";
48
+import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore";
49
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
50
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
51
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -358,8 +361,8 @@ export function createServer(options: ServerOptions) {
361
362
const processEvent = (event: ProviderRuntimeEvent) =>
363
Effect.gen(function* () {
361
- const snapshot = yield* orchestrationEngine.getSnapshot();
362
- const thread = snapshot.threads.find(
364
+ const readModel = yield* orchestrationEngine.getReadModel();
365
+ const thread = readModel.threads.find(
366
(entry) => entry.session?.sessionId === event.sessionId,
367
);
368
if (!thread) return;
@@ -735,8 +738,8 @@ export function createServer(options: ServerOptions) {
738
const params = request.params as { sessionId?: string };
739
const sessionId = params.sessionId;
740
if (typeof sessionId === "string") {
738
- const snapshot = await effectRuntime.runPromise(orchestrationEngine.getSnapshot());
739
- const thread = snapshot.threads.find((entry) => entry.session?.sessionId === sessionId);
741
+ const readModel = await effectRuntime.runPromise(orchestrationEngine.getReadModel());
742
+ const thread = readModel.threads.find((entry) => entry.session?.sessionId === sessionId);
743
if (thread) {
744
const now = new Date().toISOString();
745
await effectRuntime.runPromise(
@@ -909,7 +912,7 @@ export function createServer(options: ServerOptions) {
912
};
913
914
case ORCHESTRATION_WS_METHODS.getSnapshot:
912
- return effectRuntime.runPromise(orchestrationEngine.getSnapshot());
915
+ return effectRuntime.runPromise(orchestrationEngine.getReadModel());
916
917
case ORCHESTRATION_WS_METHODS.dispatchCommand:
918
orchestrationCommandLogger?.write({
@@ -917,21 +920,23 @@ export function createServer(options: ServerOptions) {
920
requestId: request.id,
921
command: request.params,
922
});
920
- return effectRuntime.runPromise(orchestrationEngine.dispatchUnknown(request.params));
923
+ return effectRuntime.runPromise(orchestrationEngine.dispatchUnknownCommand(request.params));
924
925
case ORCHESTRATION_WS_METHODS.replayEvents:
926
return effectRuntime.runPromise(
924
- orchestrationEngine.replayEvents(
925
- Math.max(
926
- 0,
927
- Math.floor(
928
- Number(
929
- (request.params as { fromSequenceExclusive?: number } | undefined)
930
- ?.fromSequenceExclusive ?? 0,
927
+ Stream.runCollect(
928
+ orchestrationEngine.readEvents(
929
+ Math.max(
930
+ 0,
931
+ Math.floor(
932
+ Number(
933
+ (request.params as { fromSequenceExclusive?: number } | undefined)
934
+ ?.fromSequenceExclusive ?? 0,
935
+ ),
936
),
937
),
938
),
934
- ),
939
+ ).pipe(Effect.map((events) => Array.from(events))),
940
);
941
942
default:
@@ -952,7 +957,7 @@ export function createServer(options: ServerOptions) {
957
const persistenceLayer = customPersistenceLayer ?? makeSqlitePersistenceLive(dbPath);
958
const orchestrationLayer = Layer.provide(
959
OrchestrationEngineLive,
955
- OrchestrationEventRepositoryLive,
960
+ OrchestrationEventStoreLive,
961
);
962
const codexAdapterLayer = makeCodexAdapterLive({
963
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),