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

main
ts 371 lines 13.1 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 import * as DateTime from "effect/DateTime";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as SqlClient from "effect/sql/SqlClient";
7
8 import * as EventStore from "../../orchestration-v2/EventStore.ts";
9 import * as ProjectionReplay from "../../orchestration-v2/testkit/ProjectionReplay.ts";
10 import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
11 import { runMigrations } from "../Migrations.ts";
12 import Migration0066 from "./066_RepairClientSettlementTimestamps.ts";
13
14 const layer = it.layer(
15 ProjectionReplay.layer.pipe(
16 Layer.provideMerge(
17 Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
18 Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })),
19 ),
20 ),
21 ),
22 );
23 const createdAt = "2026-03-01T00:00:00.000Z";
24 const sweptAt = "2026-09-04T13:33:00.000Z";
25 const userMessageAt = "2026-04-01T00:00:00.000Z";
26 const finishedAt = "2026-06-01T00:05:00.000Z";
27 const manualAt = "2026-10-01T00:00:00.000Z";
28 const plusSeconds = (iso: string, seconds: number) =>
29 DateTime.makeUnsafe(iso).pipe(DateTime.add({ seconds }), DateTime.formatIso);
30
31 layer("066_RepairClientSettlementTimestamps", (it) => {
32 it.effect("repairs only sweep stamps, preserves overrides, and survives a V2 rebuild", () =>
33 Effect.gen(function* () {
34 const sql = yield* SqlClient.SqlClient;
35 yield* runMigrations({ toMigrationInclusive: 64 });
36 assert.deepEqual(
37 yield* sql`SELECT name FROM sqlite_master WHERE name = 'projection_turns'`,
38 [],
39 );
40 let eventNumber = 0;
41 const insertEvent = (
42 threadId: string,
43 eventType: string,
44 occurredAt: string,
45 payload: Record<string, unknown>,
46 applicationVersion = 1,
47 actor = "client",
48 appVersion: string | null = "0.0.37",
49 ) => {
50 const version = eventNumber++;
51 return sql`
52 INSERT INTO orchestration_events (
53 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
54 command_id, actor_kind, payload_json, metadata_json, application_event_version
55 ) VALUES (
56 ${`event-${version}`}, 'thread', ${threadId}, ${version}, ${eventType}, ${occurredAt},
57 ${`command-${version}`}, ${actor}, ${JSON.stringify(payload)},
58 ${JSON.stringify({ origin: { appVersion } })}, ${applicationVersion}
59 )
60 `;
61 };
62 const insertSettlement = Effect.fnUntraced(function* (
63 id: string,
64 at: string,
65 appVersion: string | null = "0.0.37",
66 actor = "client",
67 ) {
68 yield* sql`
69 INSERT INTO projection_threads (
70 thread_id, project_id, title, model_selection_json, created_at, updated_at,
71 settled_override, settled_at
72 ) VALUES (
73 ${id}, 'project-1', ${id}, '{"instanceId":"codex","model":"gpt-5.4"}',
74 ${createdAt}, ${at}, 'settled', ${at}
75 )
76 `;
77 yield* insertEvent(
78 id,
79 "thread.settled",
80 at,
81 { threadId: id, settledAt: at, updatedAt: at },
82 1,
83 actor,
84 appVersion,
85 );
86 });
87
88 // A finished turn must come from retained events after 063 drops projection_turns.
89 for (const [at, status, activeTurnId] of [
90 ["2026-06-01T00:00:00.000Z", "running", "turn-1"],
91 [finishedAt, "ready", null],
92 ["2026-06-03T00:00:00.000Z", "stopped", null],
93 ] as const) {
94 yield* insertEvent(
95 "sweep-2",
96 "thread.session-set",
97 at,
98 {
99 threadId: "sweep-2",
100 session: { status, activeTurnId, updatedAt: at },
101 },
102 1,
103 "server",
104 );
105 if (status === "running") {
106 for (let index = 0; index < 500; index++) {
107 yield* insertEvent(
108 "sweep-2",
109 "thread.turn-start-requested",
110 "invalid",
111 {
112 createdAt: "invalid",
113 },
114 1,
115 "server",
116 );
117 }
118 }
119 }
120 for (let index = 0; index < 10; index++) {
121 yield* insertSettlement(
122 `sweep-${index}`,
123 plusSeconds(sweptAt, index * 2),
124 `0.0.${35 + (index % 4)}`,
125 );
126 }
127 // Completed or reverted turns must not be finished again by an idle restart.
128 for (const [id, eventType, at, payload] of [
129 [
130 "sweep-5",
131 "thread.message-sent",
132 userMessageAt,
133 {
134 turnId: "finished",
135 role: "assistant",
136 streaming: true,
137 createdAt: userMessageAt,
138 },
139 ],
140 [
141 "sweep-5",
142 "thread.message-sent",
143 finishedAt,
144 {
145 turnId: "finished",
146 role: "assistant",
147 streaming: false,
148 createdAt: userMessageAt,
149 updatedAt: finishedAt,
150 },
151 ],
152 [
153 "sweep-6",
154 "thread.session-set",
155 "invalid",
156 {
157 session: { status: "running", activeTurnId: "invalid-start", updatedAt: "invalid" },
158 },
159 ],
160 [
161 "sweep-6",
162 "thread.session-set",
163 finishedAt,
164 {
165 session: { status: "ready", activeTurnId: null, updatedAt: "invalid" },
166 },
167 ],
168 [
169 "sweep-7",
170 "thread.session-set",
171 userMessageAt,
172 {
173 session: { status: "running", activeTurnId: "discarded", updatedAt: userMessageAt },
174 },
175 ],
176 ["sweep-7", "thread.reverted", finishedAt, { turnCount: 0 }],
177 ] as const) {
178 yield* insertEvent(id, eventType, at, payload, 1, "server");
179 }
180 for (const id of ["sweep-5", "sweep-6", "sweep-7"]) {
181 yield* insertEvent(
182 id,
183 "thread.session-set",
184 "2026-06-03T00:00:00.000Z",
185 {
186 session: {
187 status: "stopped",
188 activeTurnId: null,
189 updatedAt: "2026-06-03T00:00:00.000Z",
190 },
191 },
192 1,
193 "server",
194 );
195 }
196 yield* sql`
197 INSERT INTO projection_thread_messages (
198 message_id, thread_id, role, text, is_streaming, created_at, updated_at
199 ) VALUES
200 ('before', 'sweep-0', 'user', 'Prompt', 0, ${userMessageAt}, ${userMessageAt}),
201 ('after', 'sweep-0', 'user', 'Later prompt', 0, ${manualAt}, ${manualAt})
202 `;
203 yield* insertEvent(
204 "sweep-2",
205 "thread.turn-start-requested",
206 manualAt,
207 {
208 threadId: "sweep-2",
209 createdAt: manualAt,
210 },
211 1,
212 "server",
213 );
214 yield* sql`UPDATE projection_threads SET settled_at = ${manualAt} WHERE thread_id = 'sweep-3'`;
215 yield* sql`UPDATE projection_threads SET settled_override = 'active', settled_at = NULL WHERE thread_id = 'sweep-4'`;
216
217 // This manual settle is within two minutes, but outside the sweep's 30-second gap.
218 yield* insertSettlement("manual", plusSeconds(sweptAt, 18 + 45));
219 // Ten events for nine distinct threads must not qualify.
220 for (let index = 0; index < 9; index++) {
221 yield* insertSettlement(
222 `small-${index}`,
223 plusSeconds("2026-09-03T00:00:00.000Z", index * 2),
224 );
225 }
226 const repeatedAt = "2026-09-03T00:00:18.000Z";
227 yield* insertEvent("small-8", "thread.settled", repeatedAt, { settledAt: repeatedAt });
228 yield* sql`UPDATE projection_threads SET settled_at = ${repeatedAt} WHERE thread_id = 'small-8'`;
229 for (let index = 0; index < 10; index++) {
230 yield* insertSettlement(
231 `spread-${index}`,
232 plusSeconds("2026-09-03T01:00:00.000Z", index * 15),
233 );
234 yield* insertSettlement(
235 `late-${index}`,
236 plusSeconds("2026-09-05T00:00:00.000Z", index * 2),
237 );
238 }
239 yield* insertSettlement("wrong-version", sweptAt, "0.0.40");
240 yield* insertSettlement("missing-version", sweptAt, null);
241 yield* insertSettlement("server", sweptAt, "0.0.37", "server");
242 yield* insertSettlement("different-stamp", sweptAt);
243 yield* sql`
244 UPDATE orchestration_events SET payload_json = json_set(payload_json, '$.settledAt', ${createdAt})
245 WHERE stream_id = 'different-stamp'
246 `;
247 const untouched = sql`
248 SELECT * FROM projection_threads WHERE thread_id NOT LIKE 'sweep-%' ORDER BY thread_id
249 `;
250 const untouchedBefore = yield* untouched;
251
252 for (const index of [0, 2, 3, 4]) {
253 const id = `sweep-${index}`;
254 const badStamp = plusSeconds(sweptAt, index * 2);
255 const thread = {
256 id,
257 projectId: "project-1",
258 title: id,
259 providerInstanceId: "codex",
260 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
261 runtimeMode: "full-access",
262 interactionMode: "default",
263 createdBy: "user",
264 creationSource: "web",
265 branch: null,
266 worktreePath: null,
267 activeProviderThreadId: null,
268 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
269 forkedFrom: null,
270 createdAt,
271 updatedAt: badStamp,
272 archivedAt: null,
273 deletedAt: null,
274 settledOverride: "settled",
275 settledAt: badStamp,
276 };
277 yield* insertEvent(id, "thread.created", badStamp, thread, 2);
278 const current = {
279 ...thread,
280 settledOverride: index === 4 ? "active" : "settled",
281 settledAt: index === 4 ? null : index === 3 ? manualAt : badStamp,
282 };
283 if (index === 4) {
284 yield* insertEvent(
285 id,
286 "thread.metadata-updated",
287 badStamp,
288 {
289 ...thread,
290 settledOverride: "active",
291 },
292 2,
293 );
294 }
295 if (index !== 2) yield* insertEvent(id, "thread.metadata-updated", manualAt, current, 2);
296 yield* sql`
297 INSERT INTO orchestration_v2_projection_threads (
298 thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
299 created_at, updated_at, payload_json
300 ) VALUES (
301 ${id}, 'project-1', ${id}, 'codex', 'full-access', 'default',
302 ${createdAt}, ${badStamp}, ${JSON.stringify(current)}
303 )
304 `;
305 }
306 const v1History = sql`
307 SELECT * FROM orchestration_events WHERE application_event_version = 1 ORDER BY sequence
308 `;
309 const v1Before = yield* v1History;
310 const overrides = sql`
311 SELECT * FROM orchestration_events
312 WHERE application_event_version = 2 AND event_type = 'thread.metadata-updated'
313 AND stream_id IN ('sweep-3', 'sweep-4') ORDER BY sequence
314 `;
315 const overridesBefore = yield* overrides;
316
317 yield* runMigrations({ toMigrationInclusive: 66 });
318 const legacy = yield* sql`
319 SELECT thread_id, settled_override, settled_at FROM projection_threads
320 WHERE thread_id LIKE 'sweep-%' ORDER BY thread_id
321 `;
322 assert.deepEqual(
323 legacy,
324 Array.from({ length: 10 }, (_, index) => ({
325 thread_id: `sweep-${index}`,
326 settled_override: index === 4 ? "active" : "settled",
327 settled_at:
328 index === 4
329 ? null
330 : ([
331 userMessageAt,
332 createdAt,
333 finishedAt,
334 manualAt,
335 null,
336 finishedAt,
337 finishedAt,
338 userMessageAt,
339 ][index] ?? createdAt),
340 })),
341 );
342 assert.deepEqual(yield* untouched, untouchedBefore);
343 assert.deepEqual(yield* v1History, v1Before);
344 assert.deepEqual(yield* overrides, overridesBefore);
345 const imported = sql`
346 SELECT thread_id,
347 json_extract(payload_json, '$.settledAt') AS settled_at,
348 json_extract(payload_json, '$.settledOverride') AS settled_override,
349 json_extract(payload_json, '$.title') AS title
350 FROM orchestration_v2_projection_threads ORDER BY thread_id
351 `;
352 const expectedImported = legacy
353 .filter((_, index) => [0, 2, 3, 4].includes(index))
354 .map((row) => ({ ...row, title: row.thread_id }));
355 assert.deepEqual(yield* imported, expectedImported);
356 const snapshot = Effect.all([
357 sql`SELECT * FROM projection_threads ORDER BY thread_id`,
358 sql`SELECT * FROM orchestration_v2_projection_threads ORDER BY thread_id`,
359 sql`SELECT * FROM orchestration_events ORDER BY sequence`,
360 ]);
361 const repaired = yield* snapshot;
362 assert.deepEqual(yield* runMigrations({ toMigrationInclusive: 66 }), []);
363 yield* Migration0066;
364 assert.deepEqual(yield* snapshot, repaired);
365
366 const maintenance = yield* ProjectionReplay.ProjectionReplay;
367 assert.isTrue((yield* maintenance.rebuild).valid);
368 assert.deepEqual(yield* imported, expectedImported);
369 }),
370 );
371 });