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