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 decoded 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 },
39 payload: {
40 projectId: ProjectId.make("project-roundtrip"),
41 title: "Roundtrip Project",
42 workspaceRoot: "/tmp/project-roundtrip",
43 defaultModelSelection: null,
44 scripts: [],
45 createdAt: now,
46 updatedAt: now,
47 },
48 });
49
50 const storedRows = yield* sql<{
51 readonly payloadJson: string;
52 readonly metadataJson: string;
53 }>`
54 SELECT
55 payload_json AS "payloadJson",
56 metadata_json AS "metadataJson"
57 FROM orchestration_events
58 WHERE event_id = ${appended.eventId}
59 `;
60 assert.equal(storedRows.length, 1);
61 assert.equal(typeof storedRows[0]?.payloadJson, "string");
62 assert.equal(typeof storedRows[0]?.metadataJson, "string");
63
64 const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe(
65 Effect.map((chunk) => Array.from(chunk)),
66 );
67 assert.equal(replayed.length, 1);
68 assert.equal(replayed[0]?.type, "project.created");
69 assert.equal(replayed[0]?.metadata.adapterKey, "codex");
70 }),
71 );
72
73 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
74 Effect.gen(function* () {
75 const eventStore = yield* OrchestrationEventStore;
76 const sql = yield* SqlClient.SqlClient;
77 const now = "2026-01-01T00:00:00.000Z";
78
79 yield* sql`
80 INSERT INTO orchestration_events (
81 event_id,
82 aggregate_kind,
83 stream_id,
84 stream_version,
85 event_type,
86 occurred_at,
87 command_id,
88 causation_event_id,
89 correlation_id,
90 actor_kind,
91 payload_json,
92 metadata_json
93 )
94 VALUES (
95 ${EventId.make("evt-store-invalid-json")},
96 ${"project"},
97 ${ProjectId.make("project-invalid-json")},
98 ${0},
99 ${"project.created"},
100 ${now},
101 ${CommandId.make("cmd-store-invalid-json")},
102 ${null},
103 ${null},
104 ${"server"},
105 ${"{"},
106 ${"{}"}
107 )
108 `;
109
110 const replayResult = yield* Effect.result(
111 Stream.runCollect(eventStore.readFromSequence(0, 10)),
112 );
113 assert.equal(replayResult._tag, "Failure");
114 if (replayResult._tag === "Failure") {
115 assert.ok(isPersistenceDecodeError(replayResult.failure));
116 assert.ok(
117 replayResult.failure.operation.includes(
118 "OrchestrationEventStore.readFromSequence:decodeRows",
119 ),
120 );
121 }
122 }),
123 );
124
125 it.effect("orders project and V2 agent events in the retained application event source", () =>
126 Effect.gen(function* () {
127 const eventStore = yield* OrchestrationEventStore;
128 const projectId = ProjectId.make("project-shared-stream");
129 const threadId = ThreadId.make("thread-shared-stream");
130 const providerInstanceId = ProviderInstanceId.make("codex");
131 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
132 const now = DateTime.formatIso(occurredAt);
133 const baselineSequence = yield* eventStore.latestApplicationSequence;
134
135 const projectEvent = yield* eventStore.append({
136 type: "project.created",
137 eventId: EventId.make("event-project-shared-stream"),
138 aggregateKind: "project",
139 aggregateId: projectId,
140 occurredAt: now,
141 commandId: CommandId.make("command-project-shared-stream"),
142 causationEventId: null,
143 correlationId: CommandId.make("command-project-shared-stream"),
144 metadata: {},
145 payload: {
146 projectId,
147 title: "Shared stream",
148 workspaceRoot: "/tmp/shared-stream",
149 defaultModelSelection: null,
150 scripts: [],
151 createdAt: now,
152 updatedAt: now,
153 },
154 });
155 const [threadEvent] = yield* eventStore.appendAgentEvents({
156 commandId: CommandId.make("command-thread-shared-stream"),
157 events: [
158 {
159 id: EventId.make("event-thread-shared-stream"),
160 type: "thread.created",
161 threadId,
162 providerInstanceId,
163 occurredAt,
164 payload: {
165 id: threadId,
166 projectId,
167 title: "Thread",
168 providerInstanceId,
169 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
170 runtimeMode: "full-access",
171 interactionMode: "default",
172 branch: null,
173 worktreePath: null,
174 activeProviderThreadId: null,
175 lineage: {
176 rootThreadId: threadId,
177 parentThreadId: null,
178 relationshipToParent: null,
179 },
180 forkedFrom: null,
181 createdBy: "user",
182 creationSource: "web",
183 createdAt: occurredAt,
184 updatedAt: occurredAt,
185 archivedAt: null,
186 deletedAt: null,
187 },
188 },
189 ],
190 });
191
192 const applicationEvents = yield* eventStore
193 .streamApplicationEvents({ afterSequence: baselineSequence })
194 .pipe(
195 Stream.take(2),
196 Stream.runCollect,
197 Effect.map((chunk) => Array.from(chunk)),
198 );
199 assert.deepEqual(
200 applicationEvents.map((event) => event.sequence),
201 [projectEvent.sequence, threadEvent!.sequence],
202 );
203 assert.isTrue("aggregateKind" in applicationEvents[0]!);
204 assert.isTrue("event" in applicationEvents[1]!);
205
206 const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
207 Stream.runCollect,
208 Effect.map((chunk) => Array.from(chunk)),
209 );
210 assert.deepEqual(
211 legacyReplay.map((event) => event.type),
212 ["project.created"],
213 );
214 }),
215 );
216});