Open History to see the last commit
1import { CommandId, EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8import * as SqlClient from "effect/unstable/sql/SqlClient";
9
10import { PersistenceDecodeError } from "../Errors.ts";
11import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
12import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
13import { SqlitePersistenceMemory } from "./Sqlite.ts";
14const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
15
16const layer = it.layer(
17 OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
18);
19
20layer("OrchestrationEventStore", (it) => {
21 it.effect("stores json columns as strings and replays CLI-origin events", () =>
22 Effect.gen(function* () {
23 const eventStore = yield* OrchestrationEventStore;
24 const sql = yield* SqlClient.SqlClient;
25 const now = "2026-01-01T00:00:00.000Z";
26
27 const appended = yield* eventStore.append({
28 type: "project.created",
29 eventId: EventId.make("evt-store-roundtrip"),
30 aggregateKind: "project",
31 aggregateId: ProjectId.make("project-roundtrip"),
32 occurredAt: now,
33 commandId: CommandId.make("cmd-store-roundtrip"),
34 causationEventId: null,
35 correlationId: CommandId.make("cmd-store-roundtrip"),
36 metadata: {
37 adapterKey: "codex",
38 origin: {
39 surface: "cli",
40 },
41 },
42 payload: {
43 projectId: ProjectId.make("project-roundtrip"),
44 title: "Roundtrip Project",
45 workspaceRoot: "/tmp/project-roundtrip",
46 defaultModelSelection: null,
47 scripts: [],
48 createdAt: now,
49 updatedAt: now,
50 },
51 });
52
53 const storedRows = yield* sql<{
54 readonly payloadJson: string;
55 readonly metadataJson: string;
56 }>`
57 SELECT
58 payload_json AS "payloadJson",
59 metadata_json AS "metadataJson"
60 FROM orchestration_events
61 WHERE event_id = ${appended.eventId}
62 `;
63 assert.equal(storedRows.length, 1);
64 assert.equal(typeof storedRows[0]?.payloadJson, "string");
65 assert.equal(typeof storedRows[0]?.metadataJson, "string");
66
67 const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe(
68 Effect.map((chunk) => Array.from(chunk)),
69 );
70 assert.equal(replayed.length, 1);
71 assert.equal(replayed[0]?.type, "project.created");
72 assert.equal(replayed[0]?.metadata.adapterKey, "codex");
73 assert.deepEqual(replayed[0]?.metadata.origin, { surface: "cli" });
74 }),
75 );
76
77 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
78 Effect.gen(function* () {
79 const eventStore = yield* OrchestrationEventStore;
80 const sql = yield* SqlClient.SqlClient;
81 const now = "2026-01-01T00:00:00.000Z";
82
83 yield* sql`
84 INSERT INTO orchestration_events (
85 event_id,
86 aggregate_kind,
87 stream_id,
88 stream_version,
89 event_type,
90 occurred_at,
91 command_id,
92 causation_event_id,
93 correlation_id,
94 actor_kind,
95 payload_json,
96 metadata_json
97 )
98 VALUES (
99 ${EventId.make("evt-store-invalid-json")},
100 ${"project"},
101 ${ProjectId.make("project-invalid-json")},
102 ${0},
103 ${"project.created"},
104 ${now},
105 ${CommandId.make("cmd-store-invalid-json")},
106 ${null},
107 ${null},
108 ${"server"},
109 ${"{"},
110 ${"{}"}
111 )
112 `;
113
114 const replayResult = yield* Effect.result(
115 Stream.runCollect(eventStore.readFromSequence(0, 10)),
116 );
117 assert.equal(replayResult._tag, "Failure");
118 if (replayResult._tag === "Failure") {
119 assert.ok(isPersistenceDecodeError(replayResult.failure));
120 assert.ok(
121 replayResult.failure.operation.includes(
122 "OrchestrationEventStore.readFromSequence:decodeRows",
123 ),
124 );
125 }
126 }),
127 );
128
129 it.effect("orders project and V2 agent events in the retained application event source", () =>
130 Effect.gen(function* () {
131 const eventStore = yield* OrchestrationEventStore;
132 const projectId = ProjectId.make("project-shared-stream");
133 const threadId = ThreadId.make("thread-shared-stream");
134 const providerInstanceId = ProviderInstanceId.make("codex");
135 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
136 const now = DateTime.formatIso(occurredAt);
137 const baselineSequence = yield* eventStore.latestApplicationSequence;
138
139 const projectEvent = yield* eventStore.append({
140 type: "project.created",
141 eventId: EventId.make("event-project-shared-stream"),
142 aggregateKind: "project",
143 aggregateId: projectId,
144 occurredAt: now,
145 commandId: CommandId.make("command-project-shared-stream"),
146 causationEventId: null,
147 correlationId: CommandId.make("command-project-shared-stream"),
148 metadata: {},
149 payload: {
150 projectId,
151 title: "Shared stream",
152 workspaceRoot: "/tmp/shared-stream",
153 defaultModelSelection: null,
154 scripts: [],
155 createdAt: now,
156 updatedAt: now,
157 },
158 });
159 const [threadEvent] = yield* eventStore.appendAgentEvents({
160 commandId: CommandId.make("command-thread-shared-stream"),
161 events: [
162 {
163 id: EventId.make("event-thread-shared-stream"),
164 type: "thread.created",
165 threadId,
166 providerInstanceId,
167 occurredAt,
168 payload: {
169 id: threadId,
170 projectId,
171 title: "Thread",
172 providerInstanceId,
173 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
174 runtimeMode: "full-access",
175 interactionMode: "default",
176 branch: null,
177 worktreePath: null,
178 activeProviderThreadId: null,
179 lineage: {
180 rootThreadId: threadId,
181 parentThreadId: null,
182 relationshipToParent: null,
183 },
184 forkedFrom: null,
185 createdBy: "user",
186 creationSource: "web",
187 createdAt: occurredAt,
188 updatedAt: occurredAt,
189 archivedAt: null,
190 settledOverride: null,
191 settledAt: null,
192 lastVisitedAt: null,
193 deletedAt: null,
194 },
195 },
196 ],
197 });
198
199 const applicationEvents = yield* eventStore
200 .streamApplicationEvents({ afterSequence: baselineSequence })
201 .pipe(
202 Stream.take(2),
203 Stream.runCollect,
204 Effect.map((chunk) => Array.from(chunk)),
205 );
206 assert.deepEqual(
207 applicationEvents.map((event) => event.sequence),
208 [projectEvent.sequence, threadEvent!.sequence],
209 );
210 assert.isTrue("aggregateKind" in applicationEvents[0]!);
211 assert.isTrue("event" in applicationEvents[1]!);
212
213 const finiteReplay = yield* eventStore
214 .readApplicationEvents({
215 afterSequence: baselineSequence,
216 throughSequence: threadEvent!.sequence,
217 })
218 .pipe(
219 Stream.runCollect,
220 Effect.map((chunk) => Array.from(chunk)),
221 );
222 assert.deepEqual(
223 finiteReplay.map((event) => event.sequence),
224 [projectEvent.sequence, threadEvent!.sequence],
225 );
226
227 const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
228 Stream.runCollect,
229 Effect.map((chunk) => Array.from(chunk)),
230 );
231 assert.deepEqual(
232 legacyReplay.map((event) => event.type),
233 ["project.created"],
234 );
235 }),
236 );
237});