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

LegacyV1ThreadImporter.ts

822 lines28.4 KB

1import {
2 threadPullRequestKeysEqual,
3 threadPullRequestsOf,
4} from "@t3tools/shared/threadPullRequests";
5import {
6 ChatAttachment,
7 OrchestrationMessageContext,
8 DEFAULT_MODEL,
9 EventId,
10 MessageId,
11 ModelSelection,
12 type OrchestrationV2AppThread,
13 OrchestrationV2AppThreadJson,
14 type OrchestrationV2ConversationMessage,
15 type OrchestrationV2DomainEvent,
16 type OrchestrationV2TurnItem,
17 ProjectId,
18 ProviderInstanceId,
19 ThreadId,
20 ThreadLinkedPullRequest,
21 ThreadPullRequestLink,
22 TurnItemId,
23} from "@t3tools/contracts";
24import * as Context from "effect/Context";
25import * as DateTime from "effect/DateTime";
26import * as Effect from "effect/Effect";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as Schema from "effect/Schema";
30import * as SqlClient from "effect/unstable/sql/SqlClient";
31​
32import { EventSinkV2 } from "./EventSink.ts";
33import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts";
34import { randomUuidV4 } from "./RandomUuid.ts";
35​
36const IMPORT_EVENT_PREFIX = "migration:v1";
37const TRANSCRIPT_EVENT_BATCH_SIZE = 100;
38​
39interface LegacyThreadRow {
40 readonly thread_id: string;
41 readonly project_id: string;
42 readonly title: string;
43 readonly model_selection_json: string | null;
44 readonly runtime_mode: string;
45 readonly interaction_mode: string;
46 readonly branch: string | null;
47 readonly worktree_path: string | null;
48 readonly created_at: string;
49 readonly updated_at: string;
50 readonly archived_at: string | null;
51 readonly settled_override: string | null;
52 readonly settled_at: string | null;
53 readonly unsettled_at: string | null;
54 readonly snoozed_until: string | null;
55 readonly snoozed_at: string | null;
56 readonly pinned_at: string | null;
57 readonly pin_order_key: string | null;
58 readonly pull_requests_json: string;
59 readonly linked_pull_request_json: string | null;
60 readonly branch_pull_request_json: string | null;
61 readonly active_order_key: string | null;
62 readonly deleted_at: string | null;
64​
65interface LegacyRepairRow extends LegacyThreadRow {
66 readonly payload_json: string;
68​
69interface LegacyMessageRow {
70 readonly message_id: string;
71 readonly thread_id: string;
72 readonly role: "user" | "assistant";
73 readonly text: string;
74 readonly attachments_json: string | null;
75 readonly context_json?: string | null;
76 readonly is_streaming: number;
77 readonly created_at: string;
78 readonly updated_at: string;
79 readonly ordinal: number;
81​
82interface LegacyImportRow {
83 readonly thread_id: string;
84 readonly transcript_imported_at: string | null;
86​
87export interface LegacyV1ImportSummary {
88 readonly importedThreadCount: number;
89 readonly importedMessageCount: number;
91​
92export class LegacyV1ThreadImportError extends Schema.TaggedError<LegacyV1ThreadImportError>()(
93 "LegacyV1ThreadImportError",
94 {
95 operation: Schema.String,
96 threadId: Schema.optional(ThreadId),
97 cause: Schema.optional(Schema.Defect()),
98 },
99) {
100 override get message(): string {
101 return this.threadId === undefined
102 ? `Failed to ${this.operation} legacy v1 threads.`
103 : `Failed to ${this.operation} legacy v1 thread ${this.threadId}.`;
104 }
106​
107export interface LegacyV1ThreadImporterShape {
108 readonly pendingThreadCount: Effect.Effect<number, LegacyV1ThreadImportError>;
109 readonly reconcileShells: Effect.Effect<LegacyV1ImportSummary, LegacyV1ThreadImportError>;
110 readonly ensureTranscript: (
111 threadId: ThreadId,
112 ) => Effect.Effect<LegacyV1ImportSummary, LegacyV1ThreadImportError>;
113 readonly importPendingTranscripts: Effect.Effect<LegacyV1ImportSummary, never>;
115​
116export class LegacyV1ThreadImporter extends Context.Service<
117 LegacyV1ThreadImporter,
118 LegacyV1ThreadImporterShape
119>()("t3/orchestration-v2/LegacyV1ThreadImporter") {}
120​
121const decodeModelSelection = Schema.decodeUnknownOption(ModelSelection);
122const decodeAttachments = Schema.decodeUnknownOption(Schema.Array(ChatAttachment));
123const decodePullRequests = Schema.decodeUnknownOption(Schema.Array(ThreadPullRequestLink));
124const decodeLinkedPullRequest = Schema.decodeUnknownOption(ThreadLinkedPullRequest);
125const decodeStoredThread = Schema.decodeUnknownOption(
126 Schema.fromJsonString(OrchestrationV2AppThreadJson),
127);
128​
129function parseJson(json: string): unknown {
130 try {
131 return JSON.parse(json);
132 } catch {
133 return undefined;
134 }
136​
137function modelSelectionFor(row: LegacyThreadRow) {
138 const decoded =
139 row.model_selection_json === null
140 ? Option.none()
141 : decodeModelSelection(parseJson(row.model_selection_json));
142 return Option.getOrElse(decoded, () => ({
143 instanceId: ProviderInstanceId.make("codex"),
144 model: DEFAULT_MODEL,
145 }));
147​
148function attachmentsFor(row: LegacyMessageRow) {
149 if (row.attachments_json === null) return [];
150 return Option.getOrElse(decodeAttachments(parseJson(row.attachments_json)), () => []);
152​
153function linkedPullRequestFor(row: LegacyThreadRow) {
154 if (row.linked_pull_request_json === null) return null;
155 return Option.getOrNull(decodeLinkedPullRequest(parseJson(row.linked_pull_request_json)));
157​
158function branchPullRequestFor(row: LegacyThreadRow) {
159 if (row.branch_pull_request_json === null) return null;
160 return Option.getOrNull(decodeLinkedPullRequest(parseJson(row.branch_pull_request_json)));
162​
163function runtimeModeFor(value: string): OrchestrationV2AppThread["runtimeMode"] {
164 return value === "approval-required" ||
165 value === "auto-accept-edits" ||
166 value === "auto" ||
167 value === "full-access"
168 ? value
169 : "full-access";
171​
172function interactionModeFor(value: string): OrchestrationV2AppThread["interactionMode"] {
173 return value === "plan" ? "plan" : "default";
175​
176function settledOverrideFor(value: string | null): OrchestrationV2AppThread["settledOverride"] {
177 return value === "settled" || value === "active" ? value : null;
179​
180function dateTime(value: string): DateTime.Utc {
181 return DateTime.makeUnsafe(value);
183​
184function nullableDateTime(value: string | null): DateTime.Utc | null {
185 return value === null ? null : dateTime(value);
187​
188function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
189 const threadId = ThreadId.make(row.thread_id);
190 const modelSelection = modelSelectionFor(row);
191 const branch = row.branch?.trim() || null;
192 const worktreePath = row.worktree_path?.trim() || null;
193 const pullRequests = Option.getOrElse(
194 decodePullRequests(parseJson(row.pull_requests_json)),
195 () => [],
196 );
197 const linkedPullRequest = linkedPullRequestFor(row);
198 const legacyLink = threadPullRequestsOf({ linkedPullRequest })[0];
199 const importedPullRequests =
200 legacyLink !== undefined &&
201 !pullRequests.some((link) => threadPullRequestKeysEqual(link, legacyLink))
202 ? [...pullRequests, legacyLink]
203 : pullRequests;
204 return {
205 createdBy: "system",
206 creationSource: "server",
207 id: threadId,
208 projectId: ProjectId.make(row.project_id),
209 title: row.title.trim() === "" ? "Untitled thread" : row.title,
210 providerInstanceId: modelSelection.instanceId,
211 modelSelection,
212 runtimeMode: runtimeModeFor(row.runtime_mode),
213 interactionMode: interactionModeFor(row.interaction_mode),
214 branch,
215 worktreePath,
216 linkedPullRequest,
217 pullRequests: importedPullRequests,
218 branchPullRequest: branchPullRequestFor(row),
219 activeOrderKey: row.active_order_key?.trim() || null,
220 activeProviderThreadId: null,
221 historyOrigin: "v1_import",
222 lineage: {
223 parentThreadId: null,
224 relationshipToParent: null,
225 rootThreadId: threadId,
226 },
227 forkedFrom: null,
228 createdAt: dateTime(row.created_at),
229 updatedAt: dateTime(row.updated_at),
230 archivedAt: nullableDateTime(row.archived_at),
231 settledOverride: settledOverrideFor(row.settled_override),
232 settledAt: nullableDateTime(row.settled_at),
233 unsettledAt: nullableDateTime(row.unsettled_at),
234 snoozedUntil: nullableDateTime(row.snoozed_until),
235 snoozedAt: nullableDateTime(row.snoozed_at),
236 pinnedAt: nullableDateTime(row.pinned_at),
237 pinOrderKey: row.pin_order_key?.trim() || null,
238 lastVisitedAt: null,
239 deletedAt: nullableDateTime(row.deleted_at),
240 };
242​
243function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2DomainEvent> {
244 const threadId = ThreadId.make(row.thread_id);
245 const messageId = MessageId.make(row.message_id);
246 const createdAt = dateTime(row.created_at);
247 const updatedAt = dateTime(row.updated_at);
248 const attachments = attachmentsFor(row);
249 const message: OrchestrationV2ConversationMessage = {
250 createdBy: row.role === "user" ? "user" : "agent",
251 creationSource: "server",
252 id: messageId,
253 threadId,
254 runId: null,
255 nodeId: null,
256 role: row.role,
257 text: row.text,
258 ...(row.context_json
259 ? {
260 context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
261 parseJson(row.context_json),
262 ),
263 }
264 : {}),
265 attachments,
266 streaming: false,
267 createdAt,
268 updatedAt,
269 };
270 const baseTurnItem = {
271 id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${row.message_id}`),
272 threadId,
273 runId: null,
274 nodeId: null,
275 providerThreadId: null,
276 providerTurnId: null,
277 nativeItemRef: null,
278 parentItemId: null,
279 ordinal: row.ordinal,
280 status: row.is_streaming === 1 ? ("interrupted" as const) : ("completed" as const),
281 title: null,
282 startedAt: createdAt,
283 completedAt: updatedAt,
284 updatedAt,
285 };
286 const turnItem: OrchestrationV2TurnItem =
287 row.role === "user"
288 ? {
289 ...baseTurnItem,
290 createdBy: "user",
291 creationSource: "server",
292 type: "user_message",
293 messageId,
294 inputIntent: "turn_start",
295 text: row.text,
296 ...(row.context_json
297 ? {
298 context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
299 parseJson(row.context_json),
300 ),
301 }
302 : {}),
303 attachments,
304 }
305 : {
306 ...baseTurnItem,
307 type: "assistant_message",
308 messageId,
309 text: row.text,
310 ...(row.context_json
311 ? {
312 context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
313 parseJson(row.context_json),
314 ),
315 }
316 : {}),
317 streaming: false,
318 };
319 return [
320 {
321 id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${row.message_id}`),
322 type: "message.updated",
323 threadId,
324 occurredAt: updatedAt,
325 payload: message,
326 },
327 {
328 id: EventId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${row.message_id}`),
329 type: "turn-item.updated",
330 threadId,
331 occurredAt: updatedAt,
332 payload: turnItem,
333 },
334 ];
336​
337function chunks<A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> {
338 const result: Array<ReadonlyArray<A>> = [];
339 for (let index = 0; index < items.length; index += size) {
340 result.push(items.slice(index, index + size));
341 }
342 return result;
344​
345const make = Effect.gen(function* () {
346 const sql = yield* SqlClient.SqlClient;
347 const eventSink = yield* EventSinkV2;
348 const transcriptImports = yield* makeKeyedSerialExecutor<ThreadId>();
349​
350 const listMessages = (threadId: ThreadId) =>
351 sql<LegacyMessageRow>`
352 SELECT
353 message_id,
354 thread_id,
355 role,
356 text,
357 attachments_json,
358 context_json,
359 is_streaming,
360 created_at,
361 updated_at,
362 ROW_NUMBER() OVER (
363 PARTITION BY thread_id
364 ORDER BY created_at ASC, message_id ASC
365 ) AS ordinal
366 FROM projection_thread_messages
367 WHERE thread_id = ${threadId}
368 AND role IN ('user', 'assistant')
369 ORDER BY created_at ASC, message_id ASC
370 `;
371​
372 const listShellMessages = (threadId: ThreadId) =>
373 Effect.gen(function* () {
374 const latest = yield* sql<LegacyMessageRow>`
375 SELECT
376 message.message_id,
377 message.thread_id,
378 message.role,
379 message.text,
380 message.attachments_json,
381 message.context_json,
382 message.is_streaming,
383 message.created_at,
384 message.updated_at,
385 (
386 SELECT COUNT(*)
387 FROM projection_thread_messages AS earlier
388 WHERE earlier.thread_id = message.thread_id
389 AND earlier.role IN ('user', 'assistant')
390 AND (
391 earlier.created_at < message.created_at
392 OR (
393 earlier.created_at = message.created_at
394 AND earlier.message_id <= message.message_id
395 )
396 )
397 ) AS ordinal
398 FROM projection_thread_messages AS message
399 WHERE message.thread_id = ${threadId}
400 AND message.role IN ('user', 'assistant')
401 ORDER BY message.created_at DESC, message.message_id DESC
402 LIMIT 1
403 `;
404 const latestUser = yield* sql<LegacyMessageRow>`
405 SELECT
406 message.message_id,
407 message.thread_id,
408 message.role,
409 message.text,
410 message.attachments_json,
411 message.context_json,
412 message.is_streaming,
413 message.created_at,
414 message.updated_at,
415 (
416 SELECT COUNT(*)
417 FROM projection_thread_messages AS earlier
418 WHERE earlier.thread_id = message.thread_id
419 AND earlier.role IN ('user', 'assistant')
420 AND (
421 earlier.created_at < message.created_at
422 OR (
423 earlier.created_at = message.created_at
424 AND earlier.message_id <= message.message_id
425 )
426 )
427 ) AS ordinal
428 FROM projection_thread_messages AS message
429 WHERE message.thread_id = ${threadId}
430 AND message.role = 'user'
431 ORDER BY message.created_at DESC, message.message_id DESC
432 LIMIT 1
433 `;
434 return [latestUser[0], latest[0]].filter(
435 (message, index, selected): message is LegacyMessageRow =>
436 message !== undefined &&
437 selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
438 );
439 });
440​
441 const reconcileShellsBase = Effect.gen(function* () {
442 const now = DateTime.formatIso(yield* DateTime.now);
443 const repairRows = yield* sql<LegacyRepairRow>`
444 SELECT
445 thread.thread_id,
446 thread.project_id,
447 thread.title,
448 thread.model_selection_json,
449 thread.runtime_mode,
450 thread.interaction_mode,
451 thread.branch,
452 thread.worktree_path,
453 thread.created_at,
454 thread.updated_at,
455 thread.archived_at,
456 thread.settled_override,
457 thread.settled_at,
458 thread.unsettled_at,
459 thread.snoozed_until,
460 thread.snoozed_at,
461 thread.pinned_at,
462 thread.pin_order_key,
463 (SELECT json_group_array(json_object('host', pr.host, 'repository', pr.repository, 'number', pr.number, 'url', pr.url, 'source', pr.source, 'linkedAt', pr.linked_at, 'snapshot', json(pr.snapshot_json), 'stack', json(pr.stack_json))) FROM projection_thread_pull_requests pr WHERE pr.thread_id = thread.thread_id) AS pull_requests_json,
464 thread.linked_pull_request_json,
465 thread.branch_pull_request_json,
466 thread.active_order_key,
467 thread.deleted_at,
468 projection.payload_json
469 FROM orchestration_v2_legacy_imports AS legacy_import
470 INNER JOIN projection_threads AS thread
471 ON thread.thread_id = legacy_import.thread_id
472 INNER JOIN orchestration_v2_projection_threads AS projection
473 ON projection.thread_id = legacy_import.thread_id
474 WHERE json_type(projection.payload_json, '$.pinnedAt') IS NULL
475 OR json_type(projection.payload_json, '$.pinOrderKey') IS NULL
476 OR json_type(projection.payload_json, '$.snoozedUntil') IS NULL
477 OR json_type(projection.payload_json, '$.snoozedAt') IS NULL
478 OR json_type(projection.payload_json, '$.unsettledAt') IS NULL
479 OR json_type(projection.payload_json, '$.linkedPullRequest') IS NULL
480 OR json_type(projection.payload_json, '$.pullRequests') IS NULL
481 OR json_type(projection.payload_json, '$.branchPullRequest') IS NULL
482 OR json_type(projection.payload_json, '$.activeOrderKey') IS NULL
483 ORDER BY thread.created_at ASC, thread.thread_id ASC
484 `;
485 let repairedThreadCount = 0;
486 for (const row of repairRows) {
487 const decoded = decodeStoredThread(row.payload_json);
488 if (Option.isNone(decoded)) continue;
489 const current = decoded.value;
490 const legacy = importedThread(row);
491 const legacyPullRequests = legacy.pullRequests ?? [];
492 const repaired: OrchestrationV2AppThread = {
493 ...current,
494 pinnedAt: current.pinnedAt === undefined ? legacy.pinnedAt : current.pinnedAt,
495 pinOrderKey: current.pinOrderKey === undefined ? legacy.pinOrderKey : current.pinOrderKey,
496 snoozedUntil:
497 current.snoozedUntil === undefined ? legacy.snoozedUntil : current.snoozedUntil,
498 snoozedAt: current.snoozedAt === undefined ? legacy.snoozedAt : current.snoozedAt,
499 unsettledAt: current.unsettledAt === undefined ? legacy.unsettledAt : current.unsettledAt,
500 linkedPullRequest:
501 current.linkedPullRequest === undefined
502 ? legacy.linkedPullRequest
503 : current.linkedPullRequest,
504 pullRequests:
505 current.pullRequests === undefined
506 ? current.linkedPullRequest === null
507 ? []
508 : legacyPullRequests.length > 0
509 ? legacyPullRequests
510 : threadPullRequestsOf({
511 linkedPullRequest:
512 current.linkedPullRequest === undefined
513 ? legacy.linkedPullRequest
514 : current.linkedPullRequest,
515 })
516 : current.pullRequests,
517 branchPullRequest:
518 current.branchPullRequest === undefined
519 ? legacy.branchPullRequest
520 : current.branchPullRequest,
521 activeOrderKey:
522 current.activeOrderKey === undefined ? legacy.activeOrderKey : current.activeOrderKey,
523 };
524 // Later schema additions can require another repair for the same thread.
525 const repairId = yield* randomUuidV4;
526 yield* eventSink.write({
527 events: [
528 {
529 id: EventId.make(
530 `${IMPORT_EVENT_PREFIX}:thread:${row.thread_id}:metadata-repair:${repairId}`,
531 ),
532 type: "thread.metadata-updated",
533 threadId: repaired.id,
534 providerInstanceId: repaired.providerInstanceId,
535 occurredAt: dateTime(now),
536 payload: repaired,
537 },
538 ],
539 });
540 repairedThreadCount += 1;
541 }
542 const rows = yield* sql<LegacyThreadRow>`
543 SELECT
544 thread.thread_id,
545 thread.project_id,
546 thread.title,
547 thread.model_selection_json,
548 thread.runtime_mode,
549 thread.interaction_mode,
550 thread.branch,
551 thread.worktree_path,
552 thread.created_at,
553 thread.updated_at,
554 thread.archived_at,
555 thread.settled_override,
556 thread.settled_at,
557 thread.unsettled_at,
558 thread.snoozed_until,
559 thread.snoozed_at,
560 thread.pinned_at,
561 thread.pin_order_key,
562 (SELECT json_group_array(json_object('host', pr.host, 'repository', pr.repository, 'number', pr.number, 'url', pr.url, 'source', pr.source, 'linkedAt', pr.linked_at, 'snapshot', json(pr.snapshot_json), 'stack', json(pr.stack_json))) FROM projection_thread_pull_requests pr WHERE pr.thread_id = thread.thread_id) AS pull_requests_json,
563 thread.linked_pull_request_json,
564 thread.branch_pull_request_json,
565 thread.active_order_key,
566 thread.deleted_at
567 FROM projection_threads AS thread
568 WHERE NOT EXISTS (
569 SELECT 1
570 FROM orchestration_events AS event
571 WHERE event.application_event_version = 2
572 AND event.aggregate_kind = 'thread'
573 AND event.stream_id = thread.thread_id
574 AND event.event_type = 'thread.created'
575 )
576 ORDER BY thread.created_at ASC, thread.thread_id ASC
577 `;
578 let importedThreadCount = repairedThreadCount;
579 let importedMessageCount = 0;
580 for (const row of rows) {
581 const thread = importedThread(row);
582 const previews = yield* listShellMessages(thread.id);
583 const events: Array<OrchestrationV2DomainEvent> = [
584 {
585 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${row.thread_id}:created`),
586 type: "thread.created",
587 threadId: thread.id,
588 providerInstanceId: thread.providerInstanceId,
589 occurredAt: thread.createdAt,
590 payload: thread,
591 },
592 ...previews.flatMap(messageEvents),
593 {
594 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${row.thread_id}:shell`),
595 type: "thread.metadata-updated",
596 threadId: thread.id,
597 providerInstanceId: thread.providerInstanceId,
598 occurredAt: thread.updatedAt,
599 payload: thread,
600 },
601 ];
602 yield* sql.withTransaction(
603 Effect.gen(function* () {
604 yield* Effect.forEach(
605 previews,
606 (message) =>
607 sql`
608 INSERT INTO orchestration_v2_turn_item_positions (
609 thread_id,
610 turn_item_id,
611 ordinal
612 )
613 VALUES (
614 ${thread.id},
615 ${TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${message.message_id}`)},
616 ${message.ordinal}
617 )
618 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
619 `,
620 { discard: true },
621 );
622 yield* eventSink.write({ events });
623 yield* sql`
624 INSERT INTO orchestration_v2_legacy_imports (
625 thread_id,
626 source_updated_at,
627 shell_imported_at,
628 transcript_imported_at,
629 imported_message_count,
630 last_error
631 )
632 VALUES (
633 ${thread.id},
634 ${row.updated_at},
635 ${now},
636 NULL,
637 ${previews.length},
638 NULL
639 )
640 ON CONFLICT(thread_id) DO NOTHING
641 `;
642 }),
643 );
644 importedThreadCount += 1;
645 importedMessageCount += previews.length;
646 }
647 return { importedThreadCount, importedMessageCount };
648 });
649​
650 const reconcileShells = reconcileShellsBase.pipe(
651 Effect.mapError((cause) => new LegacyV1ThreadImportError({ operation: "import", cause })),
652 );
653​
654 const pendingThreadCount = sql<{ readonly count: number }>`
655 SELECT COUNT(*) AS count
656 FROM (
657 SELECT thread.thread_id
658 FROM projection_threads AS thread
659 WHERE NOT EXISTS (
660 SELECT 1
661 FROM orchestration_events AS event
662 WHERE event.application_event_version = 2
663 AND event.aggregate_kind = 'thread'
664 AND event.stream_id = thread.thread_id
665 AND event.event_type = 'thread.created'
666 )
667 UNION
668 SELECT legacy_import.thread_id
669 FROM orchestration_v2_legacy_imports AS legacy_import
670 WHERE legacy_import.transcript_imported_at IS NULL
671 )
672 `.pipe(
673 Effect.map((rows) => rows[0]?.count ?? 0),
674 Effect.mapError(
675 (cause) => new LegacyV1ThreadImportError({ operation: "inspect pending", cause }),
676 ),
677 );
678​
679 // Threads whose transcript import this process has already confirmed.
680 // `transcript_imported_at` is never reset to NULL, so a positive answer
681 // stays valid for the process lifetime; ensureTranscript runs on most
682 // thread reads and command dispatches, so skipping the lock + lookup here
683 // keeps that path off the database entirely after first confirmation.
684 const confirmedTranscriptThreadIds = new Set<ThreadId>();
685​
686 const ensureTranscriptBase = (threadId: ThreadId) =>
687 transcriptImports.withLock(
688 threadId,
689 Effect.gen(function* () {
690 const imports = yield* sql<LegacyImportRow>`
691 SELECT thread_id, transcript_imported_at
692 FROM orchestration_v2_legacy_imports
693 WHERE thread_id = ${threadId}
694 LIMIT 1
695 `;
696 const imported = imports[0];
697 if (imported === undefined || imported.transcript_imported_at !== null) {
698 if (imported !== undefined) {
699 confirmedTranscriptThreadIds.add(threadId);
700 }
701 return { importedThreadCount: 0, importedMessageCount: 0 };
702 }
703 const messages = yield* listMessages(threadId);
704 const existingRows = yield* sql<{ readonly event_id: string }>`
705 SELECT event_id
706 FROM orchestration_events
707 WHERE application_event_version = 2
708 AND aggregate_kind = 'thread'
709 AND stream_id = ${threadId}
710 AND event_id LIKE ${`${IMPORT_EVENT_PREFIX}:message:%`}
711 `;
712 const existing = new Set(existingRows.map((row) => row.event_id));
713 const missing = messages.filter(
714 (message) => !existing.has(`${IMPORT_EVENT_PREFIX}:message:${message.message_id}`),
715 );
716 for (const batch of chunks(missing, TRANSCRIPT_EVENT_BATCH_SIZE / 2)) {
717 yield* Effect.forEach(
718 batch,
719 (message) =>
720 sql`
721 INSERT INTO orchestration_v2_turn_item_positions (
722 thread_id,
723 turn_item_id,
724 ordinal
725 )
726 VALUES (
727 ${threadId},
728 ${TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${message.message_id}`)},
729 ${message.ordinal}
730 )
731 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
732 `,
733 { discard: true },
734 );
735 yield* eventSink.write({ events: batch.flatMap(messageEvents) });
736 yield* Effect.yieldNow;
737 }
738 const now = DateTime.formatIso(yield* DateTime.now);
739 yield* sql`
740 UPDATE orchestration_v2_legacy_imports
741 SET
742 transcript_imported_at = ${now},
743 imported_message_count = ${messages.length},
744 last_error = NULL
745 WHERE thread_id = ${threadId}
746 `;
747 confirmedTranscriptThreadIds.add(threadId);
748 return {
749 importedThreadCount: 1,
750 importedMessageCount: missing.length,
751 };
752 }),
753 );
754​
755 const ensureTranscript = (threadId: ThreadId) =>
756 confirmedTranscriptThreadIds.has(threadId)
757 ? Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 })
758 : ensureTranscriptBase(threadId).pipe(
759 Effect.mapError(
760 (cause) =>
761 new LegacyV1ThreadImportError({
762 operation: "hydrate transcript for",
763 threadId,
764 cause,
765 }),
766 ),
767 );
768​
769 const importPendingTranscripts = Effect.gen(function* () {
770 const rows = yield* sql<LegacyImportRow>`
771 SELECT thread_id, transcript_imported_at
772 FROM orchestration_v2_legacy_imports
773 WHERE transcript_imported_at IS NULL
774 ORDER BY shell_imported_at ASC, thread_id ASC
775 `;
776 let importedThreadCount = 0;
777 let importedMessageCount = 0;
778 for (const row of rows) {
779 const result = yield* ensureTranscript(ThreadId.make(row.thread_id)).pipe(
780 Effect.tapError((error) =>
781 Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
782 threadId: row.thread_id,
783 cause: error,
784 }),
785 ),
786 Effect.catch(() =>
787 sql`
788 UPDATE orchestration_v2_legacy_imports
789 SET last_error = 'Transcript hydration failed; retry on next open.'
790 WHERE thread_id = ${row.thread_id}
791 `.pipe(
792 Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
793 Effect.orElseSucceed(() => ({
794 importedThreadCount: 0,
795 importedMessageCount: 0,
796 })),
797 ),
798 ),
799 );
800 importedThreadCount += result.importedThreadCount;
801 importedMessageCount += result.importedMessageCount;
802 yield* Effect.yieldNow;
803 }
804 return { importedThreadCount, importedMessageCount };
805 }).pipe(
806 Effect.catchCause((cause) =>
807 Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
808 Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
809 ),
810 ),
811 );
812​
813 return LegacyV1ThreadImporter.of({
814 pendingThreadCount,
815 reconcileShells,
816 ensureTranscript,
817 importPendingTranscripts,
818 });
819});
820​
821export const layer: Layer.Layer<LegacyV1ThreadImporter, never, EventSinkV2 | SqlClient.SqlClient> =
822 Layer.effect(LegacyV1ThreadImporter, make);