@myrialabs/clopen 0.2.23 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +1 -1
  2. package/backend/chat/helpers.ts +2 -20
  3. package/backend/chat/stream-manager.ts +556 -547
  4. package/backend/database/migrations/027_create_opencode_providers_table.ts +27 -0
  5. package/backend/database/migrations/028_create_opencode_accounts_table.ts +25 -0
  6. package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/engine-queries.ts +195 -36
  9. package/backend/database/queries/message-queries.ts +84 -139
  10. package/backend/database/queries/session-queries.ts +167 -21
  11. package/backend/database/queries/snapshot-queries.ts +5 -4
  12. package/backend/database/queries/utils-queries.ts +2 -2
  13. package/backend/engine/adapters/claude/environment.ts +4 -5
  14. package/backend/engine/adapters/claude/message-converter.ts +501 -0
  15. package/backend/engine/adapters/claude/stream.ts +52 -47
  16. package/backend/engine/adapters/opencode/config.ts +156 -0
  17. package/backend/engine/adapters/opencode/message-converter.ts +266 -326
  18. package/backend/engine/adapters/opencode/server.ts +54 -12
  19. package/backend/engine/adapters/opencode/stream.ts +84 -101
  20. package/backend/engine/types.ts +17 -11
  21. package/backend/project/status-manager.ts +10 -13
  22. package/backend/snapshot/helpers.ts +46 -90
  23. package/backend/snapshot/snapshot-service.ts +1 -1
  24. package/backend/utils/paths.ts +22 -1
  25. package/backend/ws/chat/index.ts +1 -11
  26. package/backend/ws/chat/stream.ts +101 -61
  27. package/backend/ws/engine/claude/accounts.ts +27 -7
  28. package/backend/ws/engine/claude/status.ts +3 -2
  29. package/backend/ws/engine/opencode/index.ts +3 -1
  30. package/backend/ws/engine/opencode/providers.ts +300 -0
  31. package/backend/ws/git/commit-message.ts +6 -8
  32. package/backend/ws/messages/crud.ts +4 -59
  33. package/backend/ws/sessions/crud.ts +78 -130
  34. package/backend/ws/sessions/index.ts +1 -9
  35. package/backend/ws/settings/crud.ts +14 -11
  36. package/backend/ws/snapshot/restore.ts +23 -26
  37. package/backend/ws/snapshot/timeline.ts +5 -5
  38. package/dist/assets/{index-BFFIy7ZX.js → index-B95VOHJY.js} +2 -2
  39. package/dist/assets/main-D1QNkcRL.js +257 -0
  40. package/dist/assets/main-rtLiuU_x.css +1 -0
  41. package/dist/index.html +2 -2
  42. package/package.json +4 -4
  43. package/shared/constants/engines.ts +141 -56
  44. package/shared/types/database/schema.ts +39 -40
  45. package/shared/types/stores/settings.ts +8 -4
  46. package/shared/types/unified/common.ts +21 -0
  47. package/shared/types/unified/display.ts +25 -0
  48. package/shared/types/unified/engine.ts +61 -0
  49. package/shared/types/unified/index.ts +108 -0
  50. package/shared/types/unified/message.ts +151 -0
  51. package/shared/types/unified/stream.ts +157 -0
  52. package/shared/types/unified/tool.ts +268 -0
  53. package/shared/utils/message-formatter.ts +9 -73
  54. package/shared/utils/path.ts +3 -2
  55. package/tsconfig.json +1 -1
  56. package/backend/engine/adapters/claude/path-utils.ts +0 -38
  57. package/backend/ws/chat/background.ts +0 -201
  58. package/dist/assets/main-CtNvgvwE.js +0 -249
  59. package/dist/assets/main-DmshCkFM.css +0 -1
  60. package/shared/types/engine/index.ts +0 -45
  61. package/shared/types/messaging/index.ts +0 -242
  62. package/shared/types/messaging/tool.ts +0 -374
@@ -0,0 +1,1108 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Deep-convert messages to unified format, enrich both engines, rename columns, drop sender columns, rename session columns, and unify engine providers/accounts tables';
5
+
6
+ // ============================================================
7
+ // Row Types (before and after column rename)
8
+ // ============================================================
9
+
10
+ interface OldRow {
11
+ id: string;
12
+ session_id: string;
13
+ timestamp: string;
14
+ sdk_message: string;
15
+ sender_id: string | null;
16
+ sender_name: string | null;
17
+ parent_message_id: string | null;
18
+ }
19
+
20
+ interface NewRow {
21
+ id: string;
22
+ session_id: string;
23
+ data: string;
24
+ parent_message_id: string | null;
25
+ }
26
+
27
+ // ============================================================
28
+ // Shared Helpers
29
+ // ============================================================
30
+
31
+ function snakeToCamel(str: string): string {
32
+ return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
33
+ }
34
+
35
+ // ============================================================
36
+ // Claude Code Helpers
37
+ // ============================================================
38
+
39
+ /** Map Claude SDK stop_reason → unified StopReason */
40
+ function mapClaudeStopReason(sdkStop: string | null | undefined): string | null {
41
+ switch (sdkStop) {
42
+ case 'end_turn': return 'end_turn';
43
+ case 'tool_use': return 'tool_use';
44
+ case 'max_tokens': return 'max_tokens';
45
+ case 'interrupted': return 'interrupted';
46
+ default: return sdkStop ? 'end_turn' : null;
47
+ }
48
+ }
49
+
50
+ const GREP_OPTION_MAP: Record<string, string> = {
51
+ '-i': 'caseInsensitive',
52
+ '-n': 'lineNumbers',
53
+ '-A': 'afterContext',
54
+ '-B': 'beforeContext',
55
+ '-C': 'context',
56
+ };
57
+
58
+ /** Normalize Claude SDK tool input: snake_case → camelCase, Grep dash options */
59
+ function convertClaudeToolInput(toolName: string, raw: Record<string, unknown>): Record<string, unknown> {
60
+ const converted: Record<string, unknown> = {};
61
+ for (const [key, value] of Object.entries(raw)) {
62
+ if (toolName === 'Grep' && key in GREP_OPTION_MAP) {
63
+ converted[GREP_OPTION_MAP[key]] = value;
64
+ } else {
65
+ converted[snakeToCamel(key)] = value;
66
+ }
67
+ }
68
+ return converted;
69
+ }
70
+
71
+ /** Normalize Claude tool name: Task → Agent */
72
+ function normalizeClaudeToolName(name: string): string {
73
+ if (name === 'Task') return 'Agent';
74
+ return name;
75
+ }
76
+
77
+ // ============================================================
78
+ // OpenCode Helpers
79
+ // ============================================================
80
+
81
+ /** Map OpenCode finish reason → unified StopReason */
82
+ function mapOpenCodeStopReason(finish: string | null | undefined): string | null {
83
+ switch (finish) {
84
+ case 'tool-calls': return 'tool_use';
85
+ case 'stop': return 'end_turn';
86
+ case 'length': return 'max_tokens';
87
+ default: return finish ? 'end_turn' : null;
88
+ }
89
+ }
90
+
91
+ /** OpenCode tool name → unified tool name */
92
+ const OC_TOOL_NAME_MAP: Record<string, string> = {
93
+ 'bash': 'Bash',
94
+ 'view': 'Read',
95
+ 'read': 'Read',
96
+ 'write': 'Write',
97
+ 'edit': 'Edit',
98
+ 'patch': 'Patch',
99
+ 'glob': 'Glob',
100
+ 'grep': 'Grep',
101
+ 'list': 'List',
102
+ 'fetch': 'WebFetch',
103
+ 'web_fetch': 'WebFetch',
104
+ 'webfetch': 'WebFetch',
105
+ 'web_search': 'WebSearch',
106
+ 'websearch': 'WebSearch',
107
+ 'todo_write': 'TodoWrite',
108
+ 'todowrite': 'TodoWrite',
109
+ 'todoread': 'TodoWrite',
110
+ 'task': 'Agent',
111
+ 'question': 'AskUserQuestion',
112
+ 'skill': 'Skill',
113
+ 'lsp': 'Lsp',
114
+ 'list_mcp_resources': 'ListMcpResources',
115
+ 'read_mcp_resource': 'ReadMcpResource',
116
+ };
117
+
118
+ /** Normalize OpenCode tool name → unified PascalCase */
119
+ function normalizeOpenCodeToolName(name: string): string {
120
+ const lower = name.toLowerCase();
121
+ return OC_TOOL_NAME_MAP[lower] || OC_TOOL_NAME_MAP[name] || name;
122
+ }
123
+
124
+ /** Normalize OpenCode tool input: snake_case → camelCase, Grep dash options */
125
+ function convertOpenCodeToolInput(toolName: string, raw: Record<string, unknown>): Record<string, unknown> {
126
+ // MCP tools pass through as-is
127
+ if (toolName.startsWith('mcp__')) return raw;
128
+ const converted: Record<string, unknown> = {};
129
+ for (const [key, value] of Object.entries(raw)) {
130
+ if (toolName === 'Grep' && key in GREP_OPTION_MAP) {
131
+ converted[GREP_OPTION_MAP[key]] = value;
132
+ } else {
133
+ converted[snakeToCamel(key)] = value;
134
+ }
135
+ }
136
+ return converted;
137
+ }
138
+
139
+ // ============================================================
140
+ // Format Detection
141
+ // ============================================================
142
+
143
+ /** Old SDK format lacks `parent` object at root; unified always has it */
144
+ function isOldSdkFormat(raw: Record<string, unknown>): boolean {
145
+ return !('parent' in raw);
146
+ }
147
+
148
+ // ============================================================
149
+ // Phase 1: Convert Old ClaudeCode SDK Format → Unified
150
+ // ============================================================
151
+
152
+ function convertClaudeAssistantContent(message: Record<string, unknown> | undefined): unknown[] {
153
+ if (!message) return [{ type: 'text', text: '' }];
154
+ const rawContent = message.content;
155
+ if (typeof rawContent === 'string') return [{ type: 'text', text: rawContent }];
156
+ if (!Array.isArray(rawContent)) return [{ type: 'text', text: '' }];
157
+
158
+ const blocks: unknown[] = [];
159
+ for (const block of rawContent as Record<string, unknown>[]) {
160
+ switch (block.type) {
161
+ case 'text':
162
+ blocks.push({ type: 'text', text: (block.text as string) || '' });
163
+ break;
164
+ case 'tool_use': {
165
+ const rawName = (block.name as string) || '';
166
+ const name = normalizeClaudeToolName(rawName);
167
+ const rawInput = (block.input as Record<string, unknown>) || {};
168
+ blocks.push({
169
+ type: 'tool_use',
170
+ id: (block.id as string) || '',
171
+ name,
172
+ input: convertClaudeToolInput(rawName, rawInput),
173
+ result: null,
174
+ subActivities: [],
175
+ skillPrompt: null,
176
+ interrupted: false,
177
+ });
178
+ break;
179
+ }
180
+ // Skip thinking/redacted_thinking — extracted separately
181
+ }
182
+ }
183
+ if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
184
+ return blocks;
185
+ }
186
+
187
+ function convertClaudeUserContent(message: Record<string, unknown> | undefined): unknown[] {
188
+ if (!message) return [{ type: 'text', text: '' }];
189
+ const rawContent = message.content;
190
+ if (typeof rawContent === 'string') return [{ type: 'text', text: rawContent }];
191
+ if (!Array.isArray(rawContent)) return [{ type: 'text', text: '' }];
192
+
193
+ const blocks: unknown[] = [];
194
+ for (const block of rawContent as Record<string, unknown>[]) {
195
+ switch (block.type) {
196
+ case 'text':
197
+ blocks.push({ type: 'text', text: (block.text as string) || '' });
198
+ break;
199
+ case 'tool_result':
200
+ blocks.push({
201
+ type: 'tool_result',
202
+ toolUseId: (block.tool_use_id as string) || '',
203
+ content: typeof block.content === 'string'
204
+ ? block.content
205
+ : JSON.stringify(block.content ?? ''),
206
+ isError: !!(block.is_error),
207
+ });
208
+ break;
209
+ case 'image': {
210
+ const source = block.source as Record<string, unknown> | undefined;
211
+ blocks.push({
212
+ type: 'image',
213
+ mediaType: (source?.media_type as string) || 'image/png',
214
+ data: (source?.data as string) || '',
215
+ });
216
+ break;
217
+ }
218
+ case 'document': {
219
+ const source = block.source as Record<string, unknown> | undefined;
220
+ blocks.push({
221
+ type: 'document',
222
+ mediaType: (source?.media_type as string) || '',
223
+ data: (source?.data as string) || '',
224
+ title: (block.title as string) || null,
225
+ });
226
+ break;
227
+ }
228
+ }
229
+ }
230
+ if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
231
+ return blocks;
232
+ }
233
+
234
+ function convertClaudeUsage(raw: Record<string, unknown>): Record<string, number> | null {
235
+ const usage = (raw.message as Record<string, unknown>)?.usage as Record<string, unknown> | undefined;
236
+ if (!usage) return null;
237
+ return {
238
+ inputTokens: (usage.input_tokens as number) || 0,
239
+ outputTokens: (usage.output_tokens as number) || 0,
240
+ cacheCreationInputTokens: (usage.cache_creation_input_tokens as number) || 0,
241
+ cacheReadInputTokens: (usage.cache_read_input_tokens as number) || 0,
242
+ };
243
+ }
244
+
245
+ function extractThinkingText(message: Record<string, unknown> | undefined): string {
246
+ if (!message) return '';
247
+ const content = message.content;
248
+ if (!Array.isArray(content)) return '';
249
+ return (content as Record<string, unknown>[])
250
+ .filter(b => b.type === 'thinking')
251
+ .map(b => (b.thinking as string) || '')
252
+ .join('\n');
253
+ }
254
+
255
+ function hasThinkingBlocks(message: Record<string, unknown> | undefined): boolean {
256
+ if (!message) return false;
257
+ const content = message.content;
258
+ if (!Array.isArray(content)) return false;
259
+ return (content as Record<string, unknown>[]).some(b => b.type === 'thinking');
260
+ }
261
+
262
+ function extractText(message: Record<string, unknown> | undefined): string {
263
+ if (!message) return '';
264
+ const content = message.content;
265
+ if (typeof content === 'string') return content;
266
+ if (Array.isArray(content)) {
267
+ return (content as Record<string, unknown>[])
268
+ .filter(b => b.type === 'text')
269
+ .map(b => (b.text as string) || '')
270
+ .join('\n');
271
+ }
272
+ return '';
273
+ }
274
+
275
+ /** Convert old SDK format → unified messages (may produce multiple) */
276
+ function convertOldFormat(raw: Record<string, unknown>, row: OldRow, sessionEngine: string): Record<string, unknown>[] {
277
+ const metadata = raw.metadata as Record<string, unknown> | undefined;
278
+ const engine = (metadata?.engine as string) || sessionEngine;
279
+ const model = ((raw.message as Record<string, unknown>)?.model as string) || null;
280
+
281
+ const base = {
282
+ createdAt: row.timestamp,
283
+ messageId: row.id,
284
+ sessionId: (raw.session_id as string) || null,
285
+ parent: {
286
+ messageId: row.parent_message_id || null,
287
+ sessionId: null,
288
+ toolUseId: null,
289
+ },
290
+ engine: { type: engine, provider: '', model: { id: model || '', name: '' }, account: { id: 0, name: '' } },
291
+ sender: {
292
+ id: row.sender_id || '',
293
+ name: row.sender_name || '',
294
+ },
295
+ };
296
+
297
+ const sdkType = raw.type as string;
298
+ const message = raw.message as Record<string, unknown> | undefined;
299
+
300
+ // Reasoning (explicit metadata flag)
301
+ if (metadata?.reasoning === true && sdkType === 'assistant') {
302
+ return [{ ...base, type: 'reasoning', text: extractText(message) }];
303
+ }
304
+
305
+ // Compact boundary
306
+ if (sdkType === 'system') {
307
+ const cb = raw.compactBoundary as Record<string, unknown> | undefined;
308
+ return [{
309
+ ...base,
310
+ type: 'compact_boundary',
311
+ trigger: (cb?.trigger as string) || 'auto',
312
+ preTokens: (cb?.preTokens as number) || 0,
313
+ }];
314
+ }
315
+
316
+ // User message
317
+ if (sdkType === 'user') {
318
+ return [{
319
+ ...base,
320
+ parent: {
321
+ messageId: row.parent_message_id || null,
322
+ sessionId: null,
323
+ toolUseId: (raw.parent_tool_use_id as string) || null,
324
+ },
325
+ type: 'user',
326
+ content: convertClaudeUserContent(message),
327
+ synthetic: (raw.isSynthetic as boolean) || false,
328
+ }];
329
+ }
330
+
331
+ // Assistant message — extract thinking blocks if present
332
+ if (sdkType === 'assistant') {
333
+ const results: Record<string, unknown>[] = [];
334
+
335
+ if (hasThinkingBlocks(message)) {
336
+ const thinkingText = extractThinkingText(message);
337
+ if (thinkingText) {
338
+ results.push({
339
+ ...base,
340
+ messageId: crypto.randomUUID(),
341
+ type: 'reasoning',
342
+ text: thinkingText,
343
+ });
344
+ }
345
+ }
346
+
347
+ results.push({
348
+ ...base,
349
+ parent: {
350
+ messageId: row.parent_message_id || null,
351
+ sessionId: null,
352
+ toolUseId: (raw.parent_tool_use_id as string) || null,
353
+ },
354
+ type: 'assistant',
355
+ content: convertClaudeAssistantContent(message),
356
+ stopReason: mapClaudeStopReason(message?.stop_reason as string | undefined),
357
+ usage: convertClaudeUsage(raw),
358
+ });
359
+
360
+ return results;
361
+ }
362
+
363
+ // Fallback
364
+ return [{
365
+ ...base,
366
+ type: 'assistant',
367
+ content: [{ type: 'text', text: '' }],
368
+ stopReason: null,
369
+ usage: null,
370
+ }];
371
+ }
372
+
373
+ /** Sync unified format metadata with DB columns (for already-unified rows) */
374
+ function syncMetadata(raw: Record<string, unknown>, row: OldRow, sessionEngine: string): Record<string, unknown> {
375
+ raw.messageId = row.id;
376
+ raw.createdAt = row.timestamp;
377
+ // sessionId is the SDK session ID — do NOT overwrite with chat session_id
378
+
379
+ const parent = raw.parent as Record<string, unknown>;
380
+ parent.messageId = row.parent_message_id || null;
381
+
382
+ raw.sender = {
383
+ id: row.sender_id || (raw.sender as Record<string, unknown>)?.id || '',
384
+ name: row.sender_name || (raw.sender as Record<string, unknown>)?.name || '',
385
+ };
386
+
387
+ // Migrate flat engine/model/account → nested engine: { type, model, account }
388
+ if (raw.engine && typeof raw.engine === 'string') {
389
+ // Old flat format → restructure
390
+ const oldEngine = raw.engine as string;
391
+ const oldModel = raw.model as string | null;
392
+ const rawAccount = (raw.account as Record<string, unknown>) || {};
393
+ const oldAccount = { id: (rawAccount.id as number) || 0, name: (rawAccount.name as string) || '' };
394
+ raw.engine = { type: oldEngine, provider: '', model: { id: oldModel || '', name: '' }, account: oldAccount };
395
+ delete raw.model;
396
+ delete raw.account;
397
+ } else if (!raw.engine) {
398
+ raw.engine = { type: sessionEngine, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
399
+ }
400
+ // Ensure engine.provider exists
401
+ const engineObj = raw.engine as Record<string, unknown>;
402
+ if (!('provider' in engineObj)) engineObj.provider = '';
403
+ // Ensure engine.account exists
404
+ if (!engineObj.account) engineObj.account = { id: 0, name: '' };
405
+
406
+ return raw;
407
+ }
408
+
409
+ // ============================================================
410
+ // Phase 2: Deep-Enrich Already-Unified Messages (Both Engines)
411
+ // ============================================================
412
+
413
+ function hasSnakeCaseKeys(input: Record<string, unknown>): boolean {
414
+ return Object.keys(input).some(k => k.includes('_') || k.startsWith('-'));
415
+ }
416
+
417
+ /** Check if a tool name is in lowercase OpenCode format */
418
+ function isOpenCodeToolName(name: string): boolean {
419
+ const lower = name.toLowerCase();
420
+ return lower in OC_TOOL_NAME_MAP;
421
+ }
422
+
423
+ /** Enrich assistant content — engine-aware tool name/input normalization */
424
+ function enrichAssistantContent(content: unknown[], engine: string): { changed: boolean; content: unknown[] } {
425
+ let changed = false;
426
+ const isOpenCode = engine === 'opencode';
427
+
428
+ const enriched = content.map((block: unknown) => {
429
+ const b = block as Record<string, unknown>;
430
+ if (b.type !== 'tool_use') return b;
431
+
432
+ const updates: Record<string, unknown> = {};
433
+
434
+ // Add missing enrichment fields
435
+ if (!('result' in b)) { updates.result = null; changed = true; }
436
+ if (!('subActivities' in b)) { updates.subActivities = []; changed = true; }
437
+ if (!('skillPrompt' in b)) { updates.skillPrompt = null; changed = true; }
438
+ if (!('interrupted' in b)) { updates.interrupted = false; changed = true; }
439
+
440
+ // Normalize tool name
441
+ const rawName = (b.name as string) || '';
442
+ if (isOpenCode) {
443
+ if (isOpenCodeToolName(rawName)) {
444
+ const normalizedName = normalizeOpenCodeToolName(rawName);
445
+ if (normalizedName !== rawName) { updates.name = normalizedName; changed = true; }
446
+ }
447
+ } else {
448
+ const normalizedName = normalizeClaudeToolName(rawName);
449
+ if (normalizedName !== rawName) { updates.name = normalizedName; changed = true; }
450
+ }
451
+
452
+ // Normalize tool input (only if has snake_case/dash keys)
453
+ const input = (b.input as Record<string, unknown>) || {};
454
+ if (hasSnakeCaseKeys(input)) {
455
+ const effectiveName = (updates.name as string) || rawName;
456
+ updates.input = isOpenCode
457
+ ? convertOpenCodeToolInput(effectiveName, input)
458
+ : convertClaudeToolInput(rawName, input);
459
+ changed = true;
460
+ }
461
+
462
+ return { ...b, ...updates };
463
+ });
464
+ return { changed, content: enriched };
465
+ }
466
+
467
+ /** Enrich user content — fix snake_case fields and nested source blocks */
468
+ function enrichUserContent(content: unknown[]): { changed: boolean; content: unknown[] } {
469
+ let changed = false;
470
+ const enriched = content.map((block: unknown) => {
471
+ const b = block as Record<string, unknown>;
472
+
473
+ // Fix tool_result with snake_case tool_use_id → camelCase toolUseId
474
+ if (b.type === 'tool_result' && 'tool_use_id' in b && !('toolUseId' in b)) {
475
+ changed = true;
476
+ return {
477
+ type: 'tool_result',
478
+ toolUseId: b.tool_use_id as string,
479
+ content: typeof b.content === 'string'
480
+ ? b.content
481
+ : JSON.stringify(b.content ?? ''),
482
+ isError: !!((b.is_error ?? b.isError)),
483
+ };
484
+ }
485
+
486
+ // Fix image with nested source → flat mediaType/data
487
+ if (b.type === 'image' && 'source' in b && !('mediaType' in b)) {
488
+ changed = true;
489
+ const source = b.source as Record<string, unknown> | undefined;
490
+ return {
491
+ type: 'image',
492
+ mediaType: (source?.media_type as string) || 'image/png',
493
+ data: (source?.data as string) || '',
494
+ };
495
+ }
496
+
497
+ // Fix document with nested source → flat mediaType/data
498
+ if (b.type === 'document' && 'source' in b && !('mediaType' in b)) {
499
+ changed = true;
500
+ const source = b.source as Record<string, unknown> | undefined;
501
+ return {
502
+ type: 'document',
503
+ mediaType: (source?.media_type as string) || '',
504
+ data: (source?.data as string) || '',
505
+ title: (b.title as string) || null,
506
+ };
507
+ }
508
+
509
+ return b;
510
+ });
511
+ return { changed, content: enriched };
512
+ }
513
+
514
+ /** Map stop reason based on engine — OpenCode uses different values */
515
+ function normalizeStopReason(raw: string | null | undefined, engine: string): string | null {
516
+ if (!raw) return null;
517
+ if (engine === 'opencode') return mapOpenCodeStopReason(raw);
518
+ return mapClaudeStopReason(raw);
519
+ }
520
+
521
+ /** Deep-enrich an already-unified message */
522
+ function deepEnrich(msg: Record<string, unknown>, sessionEngine: string): boolean {
523
+ let changed = false;
524
+
525
+ // Migrate flat engine/model → nested format if still in old format
526
+ if (msg.engine && typeof msg.engine === 'string') {
527
+ const oldEngine = msg.engine as string;
528
+ const oldModel = msg.model as string | null;
529
+ const rawAccount = (msg.account as Record<string, unknown>) || {};
530
+ const oldAccount = { id: (rawAccount.id as number) || 0, name: (rawAccount.name as string) || '' };
531
+ msg.engine = { type: oldEngine, provider: '', model: { id: oldModel || '', name: '' }, account: oldAccount };
532
+ delete msg.model;
533
+ delete msg.account;
534
+ changed = true;
535
+ }
536
+
537
+ // Ensure engine object exists
538
+ if (!msg.engine) {
539
+ msg.engine = { type: sessionEngine, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
540
+ changed = true;
541
+ }
542
+
543
+ // Ensure engine.provider exists
544
+ const engineForProviderCheck = msg.engine as Record<string, unknown>;
545
+ if (!('provider' in engineForProviderCheck)) {
546
+ engineForProviderCheck.provider = '';
547
+ changed = true;
548
+ }
549
+
550
+ // Migrate engine.model from flat string to object format
551
+ if (engineForProviderCheck.model && typeof engineForProviderCheck.model === 'string') {
552
+ engineForProviderCheck.model = { id: engineForProviderCheck.model, name: '' };
553
+ changed = true;
554
+ } else if (!engineForProviderCheck.model) {
555
+ engineForProviderCheck.model = { id: '', name: '' };
556
+ changed = true;
557
+ }
558
+
559
+ const engineObj = msg.engine as Record<string, unknown>;
560
+ const engine = (engineObj.type as string) || sessionEngine;
561
+
562
+ // Ensure engine.account exists
563
+ if (!engineObj.account) {
564
+ engineObj.account = { id: 0, name: '' };
565
+ changed = true;
566
+ }
567
+
568
+ const msgType = msg.type as string;
569
+
570
+ if (msgType === 'assistant') {
571
+ // Normalize stop reason
572
+ const rawStop = msg.stopReason as string | null | undefined;
573
+ const normalized = normalizeStopReason(rawStop, engine);
574
+ if (rawStop !== normalized) {
575
+ msg.stopReason = normalized;
576
+ changed = true;
577
+ }
578
+
579
+ // Enrich content blocks (engine-aware)
580
+ const content = msg.content as unknown[];
581
+ if (Array.isArray(content)) {
582
+ const result = enrichAssistantContent(content, engine);
583
+ if (result.changed) {
584
+ msg.content = result.content;
585
+ changed = true;
586
+ }
587
+ }
588
+ }
589
+
590
+ if (msgType === 'user') {
591
+ const content = msg.content as unknown[];
592
+ if (Array.isArray(content)) {
593
+ const result = enrichUserContent(content);
594
+ if (result.changed) {
595
+ msg.content = result.content;
596
+ changed = true;
597
+ }
598
+ }
599
+ }
600
+
601
+ return changed;
602
+ }
603
+
604
+ // ============================================================
605
+ // Text Extraction (for backfill)
606
+ // ============================================================
607
+
608
+ /** Extract first text content from a unified message data blob */
609
+ function extractTextFromData(msg: Record<string, unknown>): string {
610
+ if (msg.type === 'reasoning') return (msg.text as string) || '';
611
+ if (msg.type === 'compact_boundary') return '';
612
+ const content = msg.content;
613
+ if (!Array.isArray(content)) return '';
614
+ for (const block of content as Record<string, unknown>[]) {
615
+ if (block.type === 'text' && block.text) return (block.text as string);
616
+ }
617
+ return '';
618
+ }
619
+
620
+ // ============================================================
621
+ // Migration Entry Points
622
+ // ============================================================
623
+
624
+ export const up = (db: DatabaseConnection): void => {
625
+ // ── Build session_id → engine map from chat_sessions ──
626
+ const sessionEngineMap = new Map<string, string>();
627
+ const sessions = db.prepare('SELECT id, engine FROM chat_sessions').all() as { id: string; engine: string | null }[];
628
+ for (const s of sessions) {
629
+ sessionEngineMap.set(s.id, s.engine || 'claude-code');
630
+ }
631
+
632
+ // ── Phase 1: Deep-convert old format + sync already-unified ──
633
+ debug.log('migration', 'Phase 1: Deep-converting sdk_message JSON to unified format...');
634
+
635
+ const rows = db.prepare('SELECT id, session_id, timestamp, sdk_message, sender_id, sender_name, parent_message_id FROM messages').all() as OldRow[];
636
+ const updateStmt = db.prepare('UPDATE messages SET sdk_message = ? WHERE id = ?');
637
+ const insertStmt = db.prepare('INSERT OR IGNORE INTO messages (id, session_id, timestamp, sdk_message, sender_id, sender_name, parent_message_id) VALUES (?, ?, ?, ?, ?, ?, ?)');
638
+
639
+ let convertedCount = 0;
640
+ let syncedCount = 0;
641
+ let extraCount = 0;
642
+
643
+ for (const row of rows) {
644
+ const raw = JSON.parse(row.sdk_message) as Record<string, unknown>;
645
+ const sessionEngine = sessionEngineMap.get(row.session_id) || 'claude-code';
646
+
647
+ if (isOldSdkFormat(raw)) {
648
+ const results = convertOldFormat(raw, row, sessionEngine);
649
+ updateStmt.run(JSON.stringify(results[0]), row.id);
650
+ for (let i = 1; i < results.length; i++) {
651
+ const extra = results[i];
652
+ insertStmt.run(
653
+ extra.messageId as string,
654
+ row.session_id,
655
+ row.timestamp,
656
+ JSON.stringify(extra),
657
+ row.sender_id,
658
+ row.sender_name,
659
+ row.parent_message_id,
660
+ );
661
+ extraCount++;
662
+ }
663
+ convertedCount++;
664
+ } else {
665
+ const synced = syncMetadata(raw, row, sessionEngine);
666
+ updateStmt.run(JSON.stringify(synced), row.id);
667
+ syncedCount++;
668
+ }
669
+ }
670
+
671
+ debug.log('migration', `Phase 1 complete: ${convertedCount} converted, ${syncedCount} synced, ${extraCount} extra (${rows.length} total)`);
672
+
673
+ // ── Phase 2: Schema changes ──
674
+ debug.log('migration', 'Phase 2: Renaming columns and dropping sender columns...');
675
+
676
+ db.exec(`ALTER TABLE messages RENAME COLUMN sdk_message TO data`);
677
+
678
+ db.exec(`DROP INDEX IF EXISTS idx_messages_timestamp`);
679
+ db.exec(`ALTER TABLE messages RENAME COLUMN timestamp TO created_at`);
680
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at)`);
681
+
682
+ db.exec(`DROP INDEX IF EXISTS idx_messages_sender_id`);
683
+ db.exec(`ALTER TABLE messages DROP COLUMN sender_id`);
684
+ db.exec(`ALTER TABLE messages DROP COLUMN sender_name`);
685
+
686
+ debug.log('migration', 'Phase 2 complete: columns renamed, sender columns dropped');
687
+
688
+ // ── Phase 3: Deep-enrich all unified messages (both engines) ──
689
+ debug.log('migration', 'Phase 3: Deep-enriching unified messages for both engines...');
690
+
691
+ const newRows = db.prepare('SELECT id, session_id, data, parent_message_id FROM messages').all() as NewRow[];
692
+
693
+ // Build messageId → sessionId map for parent.sessionId resolution
694
+ // Build session_id → model map from assistant/reasoning messages (real SDK model ID)
695
+ const sessionIdMap = new Map<string, string>();
696
+ const realModelMap = new Map<string, string>();
697
+ for (const row of newRows) {
698
+ const msg = JSON.parse(row.data) as Record<string, unknown>;
699
+ if (msg.sessionId) {
700
+ sessionIdMap.set(row.id, msg.sessionId as string);
701
+ }
702
+ // Extract model from engine object (new format) or flat field (old format)
703
+ const msgEngine = msg.engine as Record<string, unknown> | string | null;
704
+ let msgModelId: string | null = null;
705
+ if (typeof msgEngine === 'object' && msgEngine) {
706
+ const modelField = msgEngine.model;
707
+ if (typeof modelField === 'object' && modelField) {
708
+ msgModelId = (modelField as Record<string, unknown>).id as string | null;
709
+ } else if (typeof modelField === 'string') {
710
+ msgModelId = modelField;
711
+ }
712
+ } else {
713
+ msgModelId = (msg.model as string | null);
714
+ }
715
+ if (msgModelId && (msg.type === 'assistant' || msg.type === 'reasoning')) {
716
+ realModelMap.set(row.session_id, msgModelId);
717
+ }
718
+ }
719
+
720
+ const enrichStmt = db.prepare('UPDATE messages SET data = ? WHERE id = ?');
721
+ let enrichedCount = 0;
722
+
723
+ for (const row of newRows) {
724
+ const msg = JSON.parse(row.data) as Record<string, unknown>;
725
+ const sessionEngine = sessionEngineMap.get(row.session_id) || 'claude-code';
726
+ let changed = deepEnrich(msg, sessionEngine);
727
+
728
+ // Fill model from assistant/reasoning messages in same session (real SDK model ID)
729
+ const enrichedEngine = msg.engine as Record<string, unknown>;
730
+ const modelObj = enrichedEngine.model as Record<string, unknown> | null;
731
+ if (!modelObj || !modelObj.id) {
732
+ const realModel = realModelMap.get(row.session_id);
733
+ if (realModel) {
734
+ enrichedEngine.model = { id: realModel, name: '' };
735
+ changed = true;
736
+ }
737
+ }
738
+
739
+ // Resolve parent.sessionId from parent message's sessionId (SDK session)
740
+ const parent = msg.parent as Record<string, unknown> | undefined;
741
+ if (parent && row.parent_message_id && !parent.sessionId) {
742
+ const parentSessionId = sessionIdMap.get(row.parent_message_id);
743
+ if (parentSessionId) {
744
+ parent.sessionId = parentSessionId;
745
+ changed = true;
746
+ }
747
+ }
748
+
749
+ if (changed) {
750
+ enrichStmt.run(JSON.stringify(msg), row.id);
751
+ enrichedCount++;
752
+ }
753
+ }
754
+
755
+ debug.log('migration', `Phase 3 complete: ${enrichedCount} messages enriched (${newRows.length} total)`);
756
+
757
+ // ── Phase 4: Rename session columns to engine-agnostic names ──
758
+ debug.log('migration', 'Phase 4: Renaming chat_sessions columns...');
759
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN claude_account_id TO account_id`);
760
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN latest_sdk_session_id TO head_session_id`);
761
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN current_head_message_id TO head_message_id`);
762
+
763
+ // Rename model → model_id and add model_name, provider
764
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN model TO model_id`);
765
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN model_name TEXT`);
766
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN provider TEXT`);
767
+
768
+ // Strip compound ID prefix (e.g., 'claude-code:sonnet' → 'sonnet')
769
+ db.exec(`
770
+ UPDATE chat_sessions
771
+ SET model_id = CASE
772
+ WHEN model_id LIKE '%:%' THEN SUBSTR(model_id, INSTR(model_id, ':') + 1)
773
+ ELSE model_id
774
+ END
775
+ WHERE model_id IS NOT NULL
776
+ `);
777
+
778
+ debug.log('migration', 'Phase 4 complete: chat_sessions columns renamed');
779
+
780
+ // ── Phase 5: Enrich chat_sessions with HEAD snapshot, counts, sender ──
781
+ debug.log('migration', 'Phase 5: Adding session metadata columns and backfilling...');
782
+
783
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN account_name TEXT`);
784
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN sender_id TEXT`);
785
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN sender_name TEXT`);
786
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN head_title TEXT`);
787
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN head_summary TEXT`);
788
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN message_count INTEGER DEFAULT 0`);
789
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN user_count INTEGER DEFAULT 0`);
790
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN last_message_at TEXT`);
791
+
792
+ // Backfill from existing messages
793
+ const backfillSessions = db.prepare('SELECT id, head_message_id FROM chat_sessions').all() as {
794
+ id: string;
795
+ head_message_id: string | null;
796
+ }[];
797
+
798
+ const backfillUpdate = db.prepare(`
799
+ UPDATE chat_sessions
800
+ SET title = ?, head_title = ?, head_summary = ?,
801
+ message_count = ?, user_count = ?,
802
+ sender_id = ?, sender_name = ?,
803
+ last_message_at = ?
804
+ WHERE id = ?
805
+ `);
806
+
807
+ let backfilledCount = 0;
808
+
809
+ for (const session of backfillSessions) {
810
+ // Get counts
811
+ const counts = db.prepare(`
812
+ SELECT
813
+ COUNT(*) AS total,
814
+ SUM(CASE WHEN json_extract(data, '$.type') = 'user' THEN 1 ELSE 0 END) AS user_count
815
+ FROM messages WHERE session_id = ?
816
+ `).get(session.id) as { total: number; user_count: number } | null;
817
+
818
+ if (!counts || counts.total === 0) continue;
819
+
820
+ // Get first user message for title
821
+ const firstUser = db.prepare(`
822
+ SELECT data FROM messages
823
+ WHERE session_id = ? AND json_extract(data, '$.type') = 'user'
824
+ ORDER BY created_at ASC LIMIT 1
825
+ `).get(session.id) as { data: string } | null;
826
+
827
+ let title: string | null = null;
828
+ if (firstUser) {
829
+ const msg = JSON.parse(firstUser.data) as Record<string, unknown>;
830
+ const text = extractTextFromData(msg);
831
+ if (text) {
832
+ title = text.slice(0, 80) + (text.length > 80 ? '...' : '');
833
+ }
834
+ }
835
+
836
+ // Walk HEAD chain for head_title and head_summary
837
+ let headTitle: string | null = null;
838
+ let headSummary: string | null = null;
839
+
840
+ if (session.head_message_id) {
841
+ const msgLookup = new Map<string, { data: string; parent_message_id: string | null }>();
842
+ const allMsgs = db.prepare(
843
+ 'SELECT id, data, parent_message_id FROM messages WHERE session_id = ?'
844
+ ).all(session.id) as { id: string; data: string; parent_message_id: string | null }[];
845
+ for (const m of allMsgs) {
846
+ msgLookup.set(m.id, m);
847
+ }
848
+
849
+ let walkId: string | null = session.head_message_id;
850
+ while (walkId) {
851
+ const row = msgLookup.get(walkId);
852
+ if (!row) break;
853
+ const msg = JSON.parse(row.data) as Record<string, unknown>;
854
+ const msgType = msg.type as string;
855
+
856
+ if (!headSummary && msgType === 'assistant') {
857
+ const text = extractTextFromData(msg);
858
+ const clean = text.replace(/```[\s\S]*?```/g, '').trim();
859
+ if (clean) {
860
+ headSummary = clean.slice(0, 200) + (clean.length > 200 ? '...' : '');
861
+ }
862
+ }
863
+ if (!headTitle && msgType === 'user') {
864
+ const text = extractTextFromData(msg);
865
+ if (text) {
866
+ headTitle = text.slice(0, 80) + (text.length > 80 ? '...' : '');
867
+ }
868
+ }
869
+ if (headTitle && headSummary) break;
870
+ walkId = row.parent_message_id;
871
+ }
872
+ }
873
+
874
+ // Get last message sender and timestamp
875
+ const lastMsg = db.prepare(`
876
+ SELECT data, created_at FROM messages
877
+ WHERE session_id = ?
878
+ ORDER BY created_at DESC LIMIT 1
879
+ `).get(session.id) as { data: string; created_at: string } | null;
880
+
881
+ let senderId: string | null = null;
882
+ let senderName: string | null = null;
883
+ let lastMessageAt: string | null = null;
884
+
885
+ if (lastMsg) {
886
+ const msg = JSON.parse(lastMsg.data) as Record<string, unknown>;
887
+ const sender = msg.sender as Record<string, unknown> | undefined;
888
+ senderId = (sender?.id as string) || null;
889
+ senderName = (sender?.name as string) || null;
890
+ lastMessageAt = lastMsg.created_at;
891
+ }
892
+
893
+ backfillUpdate.run(
894
+ title, headTitle, headSummary,
895
+ counts.total, counts.user_count,
896
+ senderId, senderName,
897
+ lastMessageAt,
898
+ session.id
899
+ );
900
+ backfilledCount++;
901
+ }
902
+
903
+ debug.log('migration', `Phase 5 complete: ${backfilledCount} sessions backfilled (${backfillSessions.length} total)`);
904
+
905
+ // ── Phase 6: Create unified engine_providers / engine_accounts tables ──
906
+ debug.log('migration', 'Phase 6: Creating unified engine_providers / engine_accounts tables...');
907
+
908
+ // engine_providers: one row per (engine_type, slug).
909
+ // - slug = machine id (e.g. 'anthropic', 'openai'). Always lowercase.
910
+ // - name = display name (e.g. 'Anthropic', 'OpenAI').
911
+ // - npm = npm package for opencode providers (null for claude-code).
912
+ // - api_url = optional custom API endpoint.
913
+ // - options = provider-specific JSON (extra env vars, flags, etc).
914
+ // - is_enabled = whether the provider shows up to the user.
915
+ db.exec(`
916
+ CREATE TABLE IF NOT EXISTS engine_providers (
917
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
918
+ engine_type TEXT NOT NULL,
919
+ slug TEXT NOT NULL,
920
+ name TEXT NOT NULL,
921
+ npm TEXT,
922
+ api_url TEXT,
923
+ options TEXT NOT NULL DEFAULT '{}',
924
+ is_enabled INTEGER NOT NULL DEFAULT 1,
925
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
926
+ UNIQUE (engine_type, slug)
927
+ )
928
+ `);
929
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_engine_providers_engine_type ON engine_providers(engine_type)`);
930
+
931
+ // engine_accounts: credentials under a provider.
932
+ // - credential = generic secret (OAuth token for claude-code, API key for opencode).
933
+ db.exec(`
934
+ CREATE TABLE IF NOT EXISTS engine_accounts (
935
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
936
+ provider_id INTEGER NOT NULL,
937
+ name TEXT NOT NULL,
938
+ credential TEXT NOT NULL,
939
+ is_active INTEGER NOT NULL DEFAULT 0,
940
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
941
+ FOREIGN KEY (provider_id) REFERENCES engine_providers(id) ON DELETE CASCADE
942
+ )
943
+ `);
944
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_engine_accounts_provider_id ON engine_accounts(provider_id)`);
945
+
946
+ debug.log('migration', 'Phase 6 complete: unified tables created');
947
+
948
+ // ── Phase 7: Migrate data into unified tables ──
949
+ debug.log('migration', 'Phase 7: Migrating data into engine_providers / engine_accounts...');
950
+
951
+ // 7a. Seed claude-code / anthropic provider (single row).
952
+ db.prepare(`
953
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
954
+ VALUES ('claude-code', 'anthropic', 'Anthropic', NULL, NULL, '{}', 1)
955
+ `).run();
956
+
957
+ const anthropicProvider = db.prepare(`
958
+ SELECT id FROM engine_providers WHERE engine_type = 'claude-code' AND slug = 'anthropic'
959
+ `).get() as { id: number } | null;
960
+ const anthropicProviderId = anthropicProvider?.id ?? null;
961
+
962
+ // 7b. Migrate claude_accounts → engine_accounts (linked to anthropic).
963
+ const hasClaudeAccounts = db.prepare(
964
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'claude_accounts'`
965
+ ).get() as { name: string } | undefined;
966
+
967
+ let migratedClaudeAccounts = 0;
968
+ if (hasClaudeAccounts && anthropicProviderId !== null) {
969
+ const claudeRows = db.prepare(
970
+ `SELECT id, name, oauth_token, is_active, created_at FROM claude_accounts ORDER BY created_at ASC`
971
+ ).all() as { id: number; name: string; oauth_token: string; is_active: number; created_at: string }[];
972
+
973
+ const insertClaudeAccount = db.prepare(`
974
+ INSERT INTO engine_accounts (provider_id, name, credential, is_active, created_at)
975
+ VALUES (?, ?, ?, ?, ?)
976
+ `);
977
+
978
+ for (const row of claudeRows) {
979
+ insertClaudeAccount.run(anthropicProviderId, row.name, row.oauth_token, row.is_active, row.created_at);
980
+ migratedClaudeAccounts++;
981
+ }
982
+ }
983
+
984
+ // 7c. Migrate opencode_providers → engine_providers.
985
+ // We need a map from old opencode_providers.id → new engine_providers.id
986
+ const hasOpenCodeProviders = db.prepare(
987
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'opencode_providers'`
988
+ ).get() as { name: string } | undefined;
989
+
990
+ const opencodeProviderIdMap = new Map<number, number>();
991
+ let migratedOpenCodeProviders = 0;
992
+ if (hasOpenCodeProviders) {
993
+ const ocProviderRows = db.prepare(
994
+ `SELECT id, provider_id, name, npm, api_url, options, is_enabled, created_at FROM opencode_providers ORDER BY created_at ASC`
995
+ ).all() as {
996
+ id: number;
997
+ provider_id: string;
998
+ name: string;
999
+ npm: string;
1000
+ api_url: string | null;
1001
+ options: string;
1002
+ is_enabled: number;
1003
+ created_at: string;
1004
+ }[];
1005
+
1006
+ const insertOcProvider = db.prepare(`
1007
+ INSERT INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled, created_at)
1008
+ VALUES ('opencode', ?, ?, ?, ?, ?, ?, ?)
1009
+ `);
1010
+
1011
+ for (const row of ocProviderRows) {
1012
+ const result = insertOcProvider.run(
1013
+ row.provider_id,
1014
+ row.name,
1015
+ row.npm || null,
1016
+ row.api_url,
1017
+ row.options || '{}',
1018
+ row.is_enabled,
1019
+ row.created_at,
1020
+ ) as { lastInsertRowid: number | bigint };
1021
+ const newId = Number(result.lastInsertRowid);
1022
+ opencodeProviderIdMap.set(row.id, newId);
1023
+ migratedOpenCodeProviders++;
1024
+ }
1025
+ }
1026
+
1027
+ // 7d. Migrate opencode_accounts → engine_accounts (with remapped provider_id).
1028
+ const hasOpenCodeAccounts = db.prepare(
1029
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'opencode_accounts'`
1030
+ ).get() as { name: string } | undefined;
1031
+
1032
+ let migratedOpenCodeAccounts = 0;
1033
+ if (hasOpenCodeAccounts) {
1034
+ const ocAccountRows = db.prepare(
1035
+ `SELECT id, provider_id, name, api_key, is_active, created_at FROM opencode_accounts ORDER BY created_at ASC`
1036
+ ).all() as {
1037
+ id: number;
1038
+ provider_id: number;
1039
+ name: string;
1040
+ api_key: string;
1041
+ is_active: number;
1042
+ created_at: string;
1043
+ }[];
1044
+
1045
+ const insertOcAccount = db.prepare(`
1046
+ INSERT INTO engine_accounts (provider_id, name, credential, is_active, created_at)
1047
+ VALUES (?, ?, ?, ?, ?)
1048
+ `);
1049
+
1050
+ for (const row of ocAccountRows) {
1051
+ const newProviderId = opencodeProviderIdMap.get(row.provider_id);
1052
+ if (newProviderId === undefined) continue; // orphan — skip
1053
+ insertOcAccount.run(newProviderId, row.name, row.api_key, row.is_active, row.created_at);
1054
+ migratedOpenCodeAccounts++;
1055
+ }
1056
+ }
1057
+
1058
+ debug.log(
1059
+ 'migration',
1060
+ `Phase 7 complete: ${migratedClaudeAccounts} claude accounts, ${migratedOpenCodeProviders} opencode providers, ${migratedOpenCodeAccounts} opencode accounts migrated`
1061
+ );
1062
+
1063
+ // ── Phase 8: Drop legacy tables ──
1064
+ debug.log('migration', 'Phase 8: Dropping legacy claude_accounts / opencode_* tables...');
1065
+ db.exec(`DROP TABLE IF EXISTS opencode_accounts`);
1066
+ db.exec(`DROP TABLE IF EXISTS opencode_providers`);
1067
+ db.exec(`DROP TABLE IF EXISTS claude_accounts`);
1068
+ debug.log('migration', 'Phase 8 complete: legacy tables dropped');
1069
+ };
1070
+
1071
+ export const down = (db: DatabaseConnection): void => {
1072
+ debug.log('migration', 'Reverting column renames...');
1073
+ db.exec(`ALTER TABLE messages RENAME COLUMN data TO sdk_message`);
1074
+
1075
+ db.exec(`DROP INDEX IF EXISTS idx_messages_created_at`);
1076
+ db.exec(`ALTER TABLE messages RENAME COLUMN created_at TO timestamp`);
1077
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp)`);
1078
+
1079
+ db.exec(`ALTER TABLE messages ADD COLUMN sender_id TEXT`);
1080
+ db.exec(`ALTER TABLE messages ADD COLUMN sender_name TEXT`);
1081
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id)`);
1082
+
1083
+ // Revert Phase 5: drop session metadata columns
1084
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN account_name`);
1085
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN sender_id`);
1086
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN sender_name`);
1087
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN head_title`);
1088
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN head_summary`);
1089
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN message_count`);
1090
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN user_count`);
1091
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN last_message_at`);
1092
+
1093
+ // Revert session column renames
1094
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN account_id TO claude_account_id`);
1095
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN head_session_id TO latest_sdk_session_id`);
1096
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN head_message_id TO current_head_message_id`);
1097
+ db.exec(`ALTER TABLE chat_sessions RENAME COLUMN model_id TO model`);
1098
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN model_name`);
1099
+ db.exec(`ALTER TABLE chat_sessions DROP COLUMN provider`);
1100
+
1101
+ debug.log('migration', 'Columns reverted (data conversion is irreversible)');
1102
+
1103
+ // Revert Phase 6-8: drop unified tables (data loss — cannot safely rebuild
1104
+ // the original split tables from the merged data).
1105
+ db.exec(`DROP TABLE IF EXISTS engine_accounts`);
1106
+ db.exec(`DROP TABLE IF EXISTS engine_providers`);
1107
+ debug.log('migration', 'Unified engine tables dropped (original split tables are not restored)');
1108
+ };