Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import { EventId, ThreadId } from "@t3tools/contracts";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Tracer from "effect/Tracer";
7import * as SqlClient from "effect/unstable/sql/SqlClient";
8
9import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
10import { listLinkedPullRequestThreads } from "../pullRequest/linkedThreads.ts";
11import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
12import { layer as eventStoreLayer } from "./EventStore.ts";
13import {
14 LegacyV1ThreadImporter,
15 layer as legacyV1ThreadImporterLayer,
16} from "./LegacyV1ThreadImporter.ts";
17import {
18 ProjectionMaintenanceV2,
19 layer as projectionMaintenanceLayer,
20} from "./ProjectionMaintenance.ts";
21import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
22
23const databaseLayer = SqlitePersistenceMemory;
24const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
25const projectionStoreProvided = projectionStoreLayer.pipe(Layer.provideMerge(databaseLayer));
26const storesProvided = Layer.mergeAll(databaseLayer, eventStoreProvided, projectionStoreProvided);
27const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
28const importerProvided = legacyV1ThreadImporterLayer.pipe(
29 Layer.provide(Layer.mergeAll(storesProvided, eventSinkProvided)),
30);
31const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(
32 Layer.provide(storesProvided),
33);
34const TestLayer = Layer.mergeAll(
35 storesProvided,
36 eventSinkProvided,
37 importerProvided,
38 projectionMaintenanceProvided,
39);
40
41it.layer(TestLayer)("LegacyV1ThreadImporter", (it) => {
42 it.effect("uses the created-thread index for startup migration checks", () =>
43 Effect.gen(function* () {
44 const sql = yield* SqlClient.SqlClient;
45 const importer = yield* LegacyV1ThreadImporter;
46 const statements: string[] = [];
47 const tracer = Tracer.make({
48 span(options) {
49 const span = new Tracer.NativeSpan(options);
50 const end = span.end.bind(span);
51 span.end = (endTime, exit) => {
52 end(endTime, exit);
53 const query = span.attributes.get("db.query.text");
54 if (
55 typeof query === "string" &&
56 query.includes("FROM projection_threads AS thread") &&
57 query.includes("FROM orchestration_events AS event")
58 ) {
59 statements.push(query);
60 }
61 };
62 return span;
63 },
64 });
65
66 assert.equal(yield* importer.pendingThreadCount.pipe(Effect.withTracer(tracer)), 0);
67 assert.deepStrictEqual(yield* importer.reconcileShells.pipe(Effect.withTracer(tracer)), {
68 importedThreadCount: 0,
69 importedMessageCount: 0,
70 });
71 assert.lengthOf(statements, 2);
72 for (const statement of statements) {
73 const plan = yield* sql.unsafe<{ readonly detail: string }>(
74 `EXPLAIN QUERY PLAN ${statement}`,
75 );
76 assert.match(
77 plan.map((row) => row.detail).join("\n"),
78 /SEARCH event USING INDEX orchestration_events_v2_created_threads_idx \(stream_id=\?\)/,
79 );
80 }
81 }),
82 );
83
84 it.effect("imports lightweight shells, hydrates transcripts, and remains idempotent", () =>
85 Effect.gen(function* () {
86 const sql = yield* SqlClient.SqlClient;
87 const importer = yield* LegacyV1ThreadImporter;
88 const maintenance = yield* ProjectionMaintenanceV2;
89 const projections = yield* ProjectionStoreV2;
90 const eventSink = yield* EventSinkV2;
91 const threadId = ThreadId.make("thread:legacy-import");
92
93 yield* sql`
94 INSERT INTO projection_projects (
95 project_id,
96 title,
97 workspace_root,
98 default_model_selection_json,
99 scripts_json,
100 created_at,
101 updated_at,
102 deleted_at
103 ) VALUES (
104 'project:legacy-import',
105 'Legacy project',
106 '/tmp/legacy-project',
107 '{"instanceId":"codex","model":"gpt-5.4"}',
108 '[]',
109 '2026-01-01T00:00:00.000Z',
110 '2026-01-04T00:00:00.000Z',
111 NULL
112 )
113 `;
114 yield* sql`
115 INSERT INTO projection_threads (
116 thread_id,
117 project_id,
118 title,
119 model_selection_json,
120 runtime_mode,
121 interaction_mode,
122 branch,
123 worktree_path,
124 latest_turn_id,
125 created_at,
126 updated_at,
127 archived_at,
128 settled_override,
129 settled_at,
130 unsettled_at,
131 snoozed_until,
132 snoozed_at,
133 pinned_at,
134 pin_order_key,
135 linked_pull_request_json,
136 deleted_at
137 ) VALUES (
138 ${threadId},
139 'project:legacy-import',
140 'Migrated conversation',
141 '{"instanceId":"codex","model":"gpt-5.4"}',
142 'full-access',
143 'default',
144 ' main ',
145 ' /tmp/legacy-project ',
146 NULL,
147 '2026-01-01T00:00:00.000Z',
148 '2026-01-04T00:00:00.000Z',
149 NULL,
150 NULL,
151 NULL,
152 '2026-01-03T12:00:00.000Z',
153 '2026-02-01T00:00:00.000Z',
154 '2026-01-04T00:00:00.000Z',
155 '2026-01-02T00:00:00.000Z',
156 'm',
157 '{"projectId":"project:legacy-import","repository":"pingdotgg/t3code","number":9000,"url":"https://github.com/pingdotgg/t3code/pull/9000"}',
158 NULL
159 )
160 `;
161 yield* sql`
162 INSERT INTO projection_thread_messages (
163 message_id,
164 thread_id,
165 turn_id,
166 role,
167 text,
168 attachments_json,
169 is_streaming,
170 created_at,
171 updated_at
172 ) VALUES
173 (
174 'message:legacy:1',
175 ${threadId},
176 NULL,
177 'user',
178 'First question',
179 '[]',
180 0,
181 '2026-01-01T01:00:00.000Z',
182 '2026-01-01T01:00:00.000Z'
183 ),
184 (
185 'message:legacy:2',
186 ${threadId},
187 NULL,
188 'assistant',
189 'First answer',
190 '[]',
191 0,
192 '2026-01-02T01:00:00.000Z',
193 '2026-01-02T01:00:00.000Z'
194 ),
195 (
196 'message:legacy:3',
197 ${threadId},
198 NULL,
199 'user',
200 'Follow-up question',
201 '[]',
202 0,
203 '2026-01-03T01:00:00.000Z',
204 '2026-01-03T01:00:00.000Z'
205 ),
206 (
207 'message:legacy:4',
208 ${threadId},
209 NULL,
210 'assistant',
211 'Partial answer',
212 '[]',
213 1,
214 '2026-01-04T01:00:00.000Z',
215 '2026-01-04T01:00:00.000Z'
216 )
217 `;
218
219 yield* sql`
220 INSERT INTO projection_thread_pull_requests (
221 thread_id, host, repository, number, url, source, linked_at, snapshot_json
222 ) VALUES
223 (${threadId}, 'github.com', 'pingdotgg/t3code', 9002,
224 'https://github.com/pingdotgg/t3code/pull/9002', 'created',
225 '2026-01-03T00:00:00.000Z',
226 '{"state":"open","title":"Second PR","headBranch":"feature-two","baseBranch":"main","isDraft":false,"updatedAt":"2026-01-03T00:00:00.000Z","syncedAt":"2026-01-03T00:00:00.000Z"}'),
227 (${threadId}, 'github.com', 'pingdotgg/t3code', 9003,
228 'https://github.com/pingdotgg/t3code/pull/9003', 'manual',
229 '2026-01-04T00:00:00.000Z', NULL)
230 `;
231
232 assert.equal(yield* importer.pendingThreadCount, 1);
233 const shellImport = yield* importer.reconcileShells;
234 assert.equal(yield* importer.pendingThreadCount, 1);
235 assert.deepStrictEqual(shellImport, {
236 importedThreadCount: 1,
237 importedMessageCount: 2,
238 });
239 const shellEventCount = yield* sql<{ readonly count: number }>`
240 SELECT COUNT(*) AS count
241 FROM orchestration_events
242 WHERE application_event_version = 2
243 AND aggregate_kind = 'thread'
244 AND stream_id = ${threadId}
245 `;
246 assert.equal(shellEventCount[0]?.count, 6);
247
248 assert.isTrue((yield* maintenance.verify).valid);
249 const shellProjection = yield* projections.getThreadProjection(threadId);
250 assert.equal(shellProjection.thread.historyOrigin, "v1_import");
251 assert.equal(shellProjection.thread.branch, "main");
252 assert.equal(shellProjection.thread.worktreePath, "/tmp/legacy-project");
253 assert.deepEqual(
254 shellProjection.thread.pinnedAt,
255 DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"),
256 );
257 assert.equal(shellProjection.thread.pinOrderKey, "m");
258 assert.deepEqual(
259 shellProjection.thread.snoozedUntil,
260 DateTime.makeUnsafe("2026-02-01T00:00:00.000Z"),
261 );
262 assert.deepEqual(
263 shellProjection.thread.unsettledAt,
264 DateTime.makeUnsafe("2026-01-03T12:00:00.000Z"),
265 );
266 assert.equal(shellProjection.thread.linkedPullRequest?.number, 9000);
267 assert.deepStrictEqual(
268 (shellProjection.thread.pullRequests ?? []).map((link) => link.number),
269 [9002, 9003, 9000],
270 );
271 assert.equal(shellProjection.thread.pullRequests?.[0]?.snapshot?.title, "Second PR");
272 assert.deepStrictEqual(
273 (yield* listLinkedPullRequestThreads({
274 host: "github.com",
275 repository: "pingdotgg/t3code",
276 number: 9002,
277 })).threads.map((thread) => thread.id),
278 [threadId],
279 );
280 const shellSnapshot = yield* projections.getShellSnapshot();
281 assert.equal(
282 shellSnapshot.threads.find((thread) => thread.id === threadId)?.historyOrigin,
283 "v1_import",
284 );
285 assert.deepStrictEqual(
286 shellProjection.messages.map((message) => message.id),
287 ["message:legacy:3", "message:legacy:4"],
288 );
289
290 const renamedAt = DateTime.makeUnsafe("2026-01-05T00:00:00.000Z");
291 yield* eventSink.write({
292 events: [
293 {
294 id: EventId.make("event:legacy-import:metadata-after-shell"),
295 type: "thread.metadata-updated",
296 threadId,
297 providerInstanceId: shellProjection.thread.providerInstanceId,
298 occurredAt: renamedAt,
299 payload: {
300 ...shellProjection.thread,
301 title: "Renamed after shell import",
302 runtimeMode: "approval-required",
303 interactionMode: "plan",
304 archivedAt: renamedAt,
305 settledOverride: "settled",
306 settledAt: renamedAt,
307 updatedAt: renamedAt,
308 },
309 },
310 ],
311 });
312
313 const transcriptImport = yield* importer.ensureTranscript(threadId);
314 assert.equal(yield* importer.pendingThreadCount, 0);
315 assert.deepStrictEqual(transcriptImport, {
316 importedThreadCount: 1,
317 importedMessageCount: 2,
318 });
319 const projection = yield* projections.getThreadProjection(threadId);
320 assert.equal(projection.thread.title, "Renamed after shell import");
321 assert.equal(projection.thread.runtimeMode, "approval-required");
322 assert.equal(projection.thread.interactionMode, "plan");
323 assert.deepEqual(projection.thread.archivedAt, renamedAt);
324 assert.equal(projection.thread.settledOverride, "settled");
325 assert.deepEqual(projection.thread.settledAt, renamedAt);
326 assert.deepStrictEqual(
327 projection.messages.map((message) => message.id),
328 ["message:legacy:1", "message:legacy:2", "message:legacy:3", "message:legacy:4"],
329 );
330 assert.deepStrictEqual(
331 projection.turnItems
332 .filter(
333 (
334 item,
335 ): item is Extract<
336 (typeof projection.turnItems)[number],
337 { readonly type: "user_message" | "assistant_message" }
338 > => item.type === "user_message" || item.type === "assistant_message",
339 )
340 .map((item) => [item.messageId, item.ordinal, item.status]),
341 [
342 ["message:legacy:1", 1, "completed"],
343 ["message:legacy:2", 2, "completed"],
344 ["message:legacy:3", 3, "completed"],
345 ["message:legacy:4", 4, "interrupted"],
346 ],
347 );
348
349 yield* eventSink.write({
350 events: [
351 {
352 id: EventId.make("event:legacy-import:explicit-unpin"),
353 type: "thread.unpinned",
354 threadId,
355 providerInstanceId: projection.thread.providerInstanceId,
356 occurredAt: renamedAt,
357 payload: { ...projection.thread, pinnedAt: null, pinOrderKey: null },
358 },
359 ],
360 });
361 yield* sql`
362 UPDATE orchestration_v2_projection_threads
363 SET payload_json = json_remove(
364 payload_json,
365 '$.snoozedUntil',
366 '$.snoozedAt',
367 '$.unsettledAt',
368 '$.linkedPullRequest',
369 '$.pullRequests'
370 )
371 WHERE thread_id = ${threadId}
372 `;
373 assert.deepStrictEqual(yield* importer.reconcileShells, {
374 importedThreadCount: 1,
375 importedMessageCount: 0,
376 });
377 const repaired = yield* projections.getThreadProjection(threadId);
378 assert.isNull(repaired.thread.pinnedAt);
379 assert.isNull(repaired.thread.pinOrderKey);
380 assert.deepEqual(
381 repaired.thread.snoozedUntil,
382 DateTime.makeUnsafe("2026-02-01T00:00:00.000Z"),
383 );
384 assert.deepEqual(
385 repaired.thread.unsettledAt,
386 DateTime.makeUnsafe("2026-01-03T12:00:00.000Z"),
387 );
388 assert.equal(repaired.thread.linkedPullRequest?.number, 9000);
389 assert.deepStrictEqual(
390 (repaired.thread.pullRequests ?? []).map((link) => link.number),
391 [9002, 9003, 9000],
392 );
393 assert.equal(repaired.thread.pullRequests?.[0]?.snapshot?.title, "Second PR");
394 const eventCountBeforeRetry = yield* sql<{ readonly count: number }>`
395 SELECT COUNT(*) AS count
396 FROM orchestration_events
397 WHERE application_event_version = 2
398 AND aggregate_kind = 'thread'
399 AND stream_id = ${threadId}
400 `;
401 assert.deepStrictEqual(yield* importer.reconcileShells, {
402 importedThreadCount: 0,
403 importedMessageCount: 0,
404 });
405 assert.deepStrictEqual(yield* importer.ensureTranscript(threadId), {
406 importedThreadCount: 0,
407 importedMessageCount: 0,
408 });
409 const eventCountAfterRetry = yield* sql<{ readonly count: number }>`
410 SELECT COUNT(*) AS count
411 FROM orchestration_events
412 WHERE application_event_version = 2
413 AND aggregate_kind = 'thread'
414 AND stream_id = ${threadId}
415 `;
416 assert.equal(eventCountAfterRetry[0]?.count, eventCountBeforeRetry[0]?.count);
417 }),
418 );
419
420 it.effect("repairs newly added metadata after an earlier metadata repair", () =>
421 Effect.gen(function* () {
422 const sql = yield* SqlClient.SqlClient;
423 const importer = yield* LegacyV1ThreadImporter;
424 const maintenance = yield* ProjectionMaintenanceV2;
425 const projections = yield* ProjectionStoreV2;
426 const eventSink = yield* EventSinkV2;
427 const threadId = ThreadId.make("thread:legacy-metadata-upgrade");
428 const previousRepairId = EventId.make(`migration:v1:thread:${threadId}:metadata-repair`);
429
430 yield* sql`
431 INSERT INTO projection_projects (
432 project_id, title, workspace_root, scripts_json, created_at, updated_at
433 ) VALUES (
434 'project:legacy-metadata-upgrade',
435 'Legacy project',
436 '/tmp/legacy-metadata-upgrade',
437 '[]',
438 '2026-01-01T00:00:00.000Z',
439 '2026-01-01T00:00:00.000Z'
440 )
441 `;
442 yield* sql`
443 INSERT INTO projection_threads (
444 thread_id, project_id, title, model_selection_json, runtime_mode,
445 interaction_mode, created_at, updated_at, pinned_at, pin_order_key,
446 linked_pull_request_json, branch_pull_request_json, active_order_key
447 ) VALUES (
448 ${threadId},
449 'project:legacy-metadata-upgrade',
450 'Original v1 title',
451 '{"instanceId":"codex","model":"gpt-5.4"}',
452 'full-access',
453 'default',
454 '2026-01-01T00:00:00.000Z',
455 '2026-01-01T00:00:00.000Z',
456 '2026-01-02T00:00:00.000Z',
457 'm',
458 '{"projectId":"project:legacy-metadata-upgrade","repository":"pingdotgg/t3code","number":9000,"url":"https://github.com/pingdotgg/t3code/pull/9000"}',
459 '{"projectId":"project:legacy-metadata-upgrade","repository":"pingdotgg/t3code","number":9001,"url":"https://github.com/pingdotgg/t3code/pull/9001"}',
460 'az'
461 )
462 `;
463 yield* importer.reconcileShells;
464 yield* maintenance.rebuild;
465 const shellProjection = yield* projections.getThreadProjection(threadId);
466 assert.deepStrictEqual(
467 (shellProjection.thread.pullRequests ?? []).map((link) => link.number),
468 [9000],
469 );
470 const previousRepairThread = {
471 ...shellProjection.thread,
472 title: "Renamed in v2",
473 pinnedAt: null,
474 pinOrderKey: null,
475 linkedPullRequest: null,
476 pullRequests: [],
477 };
478 delete previousRepairThread.branchPullRequest;
479 delete previousRepairThread.activeOrderKey;
480 yield* eventSink.write({
481 events: [
482 {
483 id: previousRepairId,
484 type: "thread.metadata-updated",
485 threadId,
486 providerInstanceId: previousRepairThread.providerInstanceId,
487 occurredAt: DateTime.makeUnsafe("2026-01-03T00:00:00.000Z"),
488 payload: previousRepairThread,
489 },
490 ],
491 });
492
493 assert.deepStrictEqual(yield* importer.reconcileShells, {
494 importedThreadCount: 1,
495 importedMessageCount: 0,
496 });
497 const repaired = yield* projections.getThreadProjection(threadId);
498 assert.equal(repaired.thread.title, "Renamed in v2");
499 assert.isNull(repaired.thread.pinnedAt);
500 assert.isNull(repaired.thread.pinOrderKey);
501 assert.isNull(repaired.thread.linkedPullRequest);
502 assert.deepStrictEqual(repaired.thread.pullRequests, []);
503 assert.equal(repaired.thread.branchPullRequest?.number, 9001);
504 assert.equal(repaired.thread.activeOrderKey, "az");
505
506 const eventsBeforeRetry = yield* sql<{ readonly event_id: string }>`
507 SELECT event_id
508 FROM orchestration_events
509 WHERE application_event_version = 2 AND stream_id = ${threadId}
510 ORDER BY sequence
511 `;
512 assert.equal(eventsBeforeRetry.length, 4);
513 assert.isTrue(eventsBeforeRetry.some((event) => event.event_id === previousRepairId));
514 assert.deepStrictEqual(yield* importer.reconcileShells, {
515 importedThreadCount: 0,
516 importedMessageCount: 0,
517 });
518
519 assert.isTrue((yield* maintenance.rebuild).valid);
520 const replayed = yield* projections.getThreadProjection(threadId);
521 assert.deepStrictEqual(replayed.thread, repaired.thread);
522 assert.deepStrictEqual(
523 yield* Effect.gen(function* () {
524 const restartedImporter = yield* LegacyV1ThreadImporter;
525 return yield* restartedImporter.reconcileShells;
526 }).pipe(Effect.provide(legacyV1ThreadImporterLayer)),
527 { importedThreadCount: 0, importedMessageCount: 0 },
528 );
529 const eventsAfterRestart = yield* sql<{ readonly event_id: string }>`
530 SELECT event_id
531 FROM orchestration_events
532 WHERE application_event_version = 2 AND stream_id = ${threadId}
533 ORDER BY sequence
534 `;
535 assert.deepStrictEqual(eventsAfterRestart, eventsBeforeRetry);
536 }),
537 );
538});