Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LegacyV1ThreadImporter.test.ts

495 lines17.8 KB

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