dsh-plugin-external-session-sync 0.0.0-stage → 1.2.1

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.
package/engine.js ADDED
@@ -0,0 +1,576 @@
1
+ // Import Codex / Claude conversations into DSH's native session store.
2
+ //
3
+ // Design rules this engine keeps:
4
+ // - Source history is READ ONLY. Nothing under ~/.codex or ~/.claude is written.
5
+ // - A durable import goes through DSH's own Session/Persistence/Controller/Workspace
6
+ // APIs. No hand-written session log or workspace index.
7
+ // - An import is an immutable snapshot keyed by (source, id, revision, cwd).
8
+ // - "Synced" means: the body is readable AND the original session id was resumed AND
9
+ // it is registered in its project. Re-running a sync repairs a missing registration
10
+ // without rewriting history.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import {
14
+ listClaudeSessionsAsync,
15
+ readCodexThreadConversation,
16
+ readClaudeConversation,
17
+ CODEX_ROOT,
18
+ CLAUDE_ROOT,
19
+ } from './readers.js';
20
+ import { nativeEvents, nativeId, canonicalCwd } from './native.js';
21
+ import { discoverCodexThreads } from './discovery.js';
22
+ import { planSessionDeletion, deleteSessionPayload } from './cleanup.js';
23
+
24
+ const visibleMessages = (events) =>
25
+ events.filter((event) => event.type === 'user/message' || event.type === 'assistant/message');
26
+
27
+ export class SyncEngine {
28
+ constructor(ctx, home) {
29
+ this.ctx = ctx;
30
+ this.home = home;
31
+ this.stateFile = path.join(home, 'storages', 'external-session-sync-v1.json');
32
+ this.archiveRoot = path.join(home, 'external-session-sync', 'archives');
33
+ this.state = this.load();
34
+ this.queue = Promise.resolve();
35
+ this.lastReport = null;
36
+ }
37
+
38
+ load() {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(this.stateFile, 'utf8'));
41
+ } catch (error) {
42
+ if (error.code !== 'ENOENT') throw error;
43
+ return { version: 1, entries: {} };
44
+ }
45
+ }
46
+
47
+ save() {
48
+ fs.mkdirSync(path.dirname(this.stateFile), { recursive: true });
49
+ const tmp = `${this.stateFile}.${process.pid}.tmp`;
50
+ fs.writeFileSync(tmp, JSON.stringify(this.state, null, 2));
51
+ fs.renameSync(tmp, this.stateFile);
52
+ }
53
+
54
+ async discover(options = {}) {
55
+ const out = [];
56
+ if (options.source !== 'claude') out.push(...discoverCodexThreads());
57
+ if (options.source !== 'codex') {
58
+ for (const row of await listClaudeSessionsAsync()) {
59
+ // A concurrently rotated file must not break the other source's list.
60
+ try {
61
+ const stat = fs.statSync(row.file);
62
+ out.push({ ...row, source: 'claude', revision: `${stat.size}:${Math.trunc(stat.mtimeMs)}` });
63
+ } catch {
64
+ // the file vanished between listing and stat
65
+ }
66
+ }
67
+ }
68
+ return out
69
+ .filter((row) => options.includeSubagents !== false || !row.isSubagent)
70
+ .map((row) => ({ ...row, cwd: canonicalCwd(row.cwd) }))
71
+ .sort((a, b) => Number(b.updatedAt || 0) - Number(a.updatedAt || 0) || String(a.title || '').localeCompare(String(b.title || '')));
72
+ }
73
+
74
+ async status(options = {}) {
75
+ const discovered = await this.discover(options);
76
+ const query = String(options.q || '').toLowerCase();
77
+ const filtered = discovered.filter(
78
+ (row) => !query || `${row.title || ''} ${row.cwd || ''} ${row.id}`.toLowerCase().includes(query),
79
+ );
80
+ const workspaces = this.ctx.workspaceRegistry.list();
81
+ return {
82
+ version: 1,
83
+ roots: { codex: CODEX_ROOT, claude: CLAUDE_ROOT },
84
+ scannedAt: Date.now(),
85
+ counts: {
86
+ codex: discovered.filter((row) => row.source === 'codex').length,
87
+ claude: discovered.filter((row) => row.source === 'claude').length,
88
+ synced: Object.keys(this.state.entries).length,
89
+ },
90
+ discovered: filtered.map((row) => {
91
+ const entry = this.state.entries[`${row.source}:${row.id}`];
92
+ const workspace = entry?.sessionId
93
+ ? workspaces.find((candidate) => candidate.sessionIds.includes(entry.sessionId))
94
+ : null;
95
+ return {
96
+ id: row.id,
97
+ source: row.source,
98
+ title: row.title || '未命名会话',
99
+ cwd: row.cwd || null,
100
+ bytes: row.bytes,
101
+ updatedAt: row.updatedAt || null,
102
+ rolloutCount: row.rolloutCount || 1,
103
+ synced: !!entry,
104
+ upToDate: entry?.revision === row.revision,
105
+ dshSessionId: entry?.sessionId || null,
106
+ workspaceAttached: !!workspace,
107
+ workspaceId: workspace?.id || null,
108
+ };
109
+ }),
110
+ lastReport: this.lastReport,
111
+ };
112
+ }
113
+
114
+ async descriptor(source, id) {
115
+ if (!['codex', 'claude'].includes(source)) throw new Error('未知会话来源');
116
+ const all = await this.discover({ source, includeSubagents: true });
117
+ const item = all.find((row) => row.id === id);
118
+ if (!item) throw new Error('找不到外部会话,请刷新列表');
119
+ return item;
120
+ }
121
+
122
+ async conversation(source, id, maxMessages = 100) {
123
+ const found = await this.descriptor(source, id);
124
+ const conversation =
125
+ source === 'codex'
126
+ ? await readCodexThreadConversation(id, { maxMessages: 2000 })
127
+ : await readClaudeConversation(found.file);
128
+ conversation.cwd = canonicalCwd(conversation.cwd || found.cwd);
129
+ const limit = Math.max(1, Math.min(2000, Number(maxMessages) || 100));
130
+ return {
131
+ id: found.id,
132
+ title: conversation.title || found.title,
133
+ cwd: conversation.cwd || null,
134
+ totalMessages: conversation.messages.length,
135
+ messages: conversation.messages
136
+ .slice(-limit)
137
+ .map((message) => ({ role: message.role, text: message.text, timestamp: message.timestamp || null })),
138
+ source,
139
+ };
140
+ }
141
+
142
+ sync(options = {}) {
143
+ const work = this.queue.then(() => this.run(options));
144
+ this.queue = work.catch(() => {});
145
+ return work;
146
+ }
147
+
148
+ /**
149
+ * Resume an already-persisted native session and register it in its project.
150
+ * `sessionController.create()` is for NEW conversations: given an existing non-empty
151
+ * id it mints another one, which is exactly how a chat ends up outside its project.
152
+ */
153
+ async attachImportedSession(id, inspected) {
154
+ const cwd = inspected.meta.cwd;
155
+ if (!cwd) throw new Error('导入会话没有工作目录,无法登记到项目');
156
+ const resolved = await this.ctx.sessionController.resolveAgent(id);
157
+ if (resolved.error) throw resolved.error;
158
+ if (!resolved.agent || resolved.agent.id !== id) throw new Error('DSH 恢复了错误的会话身份');
159
+ const workspace = await this.ctx.workspaceRegistry.create(cwd);
160
+ const hadMembership = workspace.sessionIds.includes(id);
161
+ await workspace.attachSession(id);
162
+ if (!workspace.sessionIds.includes(id)) throw new Error('DSH 会话未出现在项目中,同步未完成');
163
+ return {
164
+ workspaceId: workspace.id,
165
+ workspaceTitle: workspace.title,
166
+ workspacePath: workspace.path,
167
+ workspaceAttached: true,
168
+ repaired: !hadMembership,
169
+ };
170
+ }
171
+
172
+ async readSource(row) {
173
+ // A durable import is never capped the way a preview is.
174
+ const conversation =
175
+ row.source === 'codex'
176
+ ? await readCodexThreadConversation(row.id)
177
+ : await readClaudeConversation(row.file);
178
+ conversation.messages = conversation.messages.filter(
179
+ (message) => (message.role === 'user' || message.role === 'assistant') && message.text?.trim(),
180
+ );
181
+ return conversation;
182
+ }
183
+
184
+ /** Read a stored session log without resuming its Agent. */
185
+ async readStoredSession(id) {
186
+ const handle = await this.ctx.sessionPersistence.open(id, 'read');
187
+ try {
188
+ const { events } = await handle.read();
189
+ return { meta: { cwd: handle.header.cwd }, events };
190
+ } finally {
191
+ await handle.close();
192
+ }
193
+ }
194
+
195
+ /** Distinguish "no stored log" from "a stored log this DSH version cannot read". */
196
+ async usableSession(id) {
197
+ try {
198
+ if (!(await this.ctx.sessionPersistence.stat(id))) return { exists: false, corrupt: false };
199
+ await this.readStoredSession(id);
200
+ return { exists: true, corrupt: false };
201
+ } catch (error) {
202
+ if (/corrupt/i.test(String(error && error.message))) return { exists: true, corrupt: true };
203
+ throw error;
204
+ }
205
+ }
206
+
207
+ async run(options = {}) {
208
+ const all = await this.discover({ source: options.source });
209
+ const ids = options.ids ? new Set(options.ids) : null;
210
+ const filtered = all.filter((row) => !ids || ids.has(row.id));
211
+ const selected = options.limit && options.limit > 0 ? filtered.slice(0, Math.min(1000, options.limit)) : filtered;
212
+ const report = {
213
+ scanned: all.length,
214
+ selected: selected.length,
215
+ imported: [],
216
+ skipped: [],
217
+ repaired: [],
218
+ recovered: [],
219
+ archived: [],
220
+ failed: [],
221
+ dryRun: !!options.dryRun,
222
+ };
223
+
224
+ if (options.archiveSessionIds?.length && !report.dryRun) {
225
+ for (const sessionId of [...new Set(options.archiveSessionIds)]) {
226
+ try {
227
+ await this.ctx.workspaceRegistry.archiveSession(sessionId, { stopActivity: false });
228
+ report.archived.push({ id: sessionId });
229
+ } catch (error) {
230
+ report.failed.push({ key: `archive:${sessionId}`, title: '旧空白会话', error: error.message });
231
+ }
232
+ }
233
+ }
234
+
235
+ for (const row of selected) {
236
+ const key = `${row.source}:${row.id}`;
237
+ const previous = this.state.entries[key];
238
+ try {
239
+ let reusable = false;
240
+ if (previous?.revision === row.revision) {
241
+ const state = await this.usableSession(previous.sessionId);
242
+ reusable = state.exists && !state.corrupt;
243
+ // A log left by an older writer can be unreadable; re-import under a fresh
244
+ // identity instead of failing the whole conversation forever.
245
+ if (state.corrupt) report.recovered.push({ key, previous: previous.sessionId, reason: 'corrupt-session-log' });
246
+ }
247
+ if (reusable) {
248
+ const inspected = await this.readStoredSession(previous.sessionId);
249
+ const messages = visibleMessages(inspected.events).length;
250
+ if (!messages) throw new Error('已同步会话没有有效消息,无法标记为同步完成');
251
+ if (report.dryRun) {
252
+ report.skipped.push({ key, id: previous.sessionId, title: row.title, messages, reason: 'already-synced' });
253
+ continue;
254
+ }
255
+ // A matching snapshot still has to prove its project membership.
256
+ const association = await this.attachImportedSession(previous.sessionId, inspected);
257
+ this.state.entries[key] = { ...previous, ...association, messages };
258
+ this.save();
259
+ const item = {
260
+ key,
261
+ id: previous.sessionId,
262
+ title: row.title,
263
+ messages,
264
+ ...association,
265
+ reason: association.repaired ? 'workspace-repaired' : 'already-synced',
266
+ };
267
+ report.skipped.push(item);
268
+ if (association.repaired) report.repaired.push(item);
269
+ continue;
270
+ }
271
+
272
+ const conversation = await this.readSource(row);
273
+ if (!conversation.messages.length) {
274
+ report.skipped.push({ key, reason: 'no-messages' });
275
+ continue;
276
+ }
277
+ let cwd = canonicalCwd(conversation.cwd || row.cwd);
278
+ let warning;
279
+ if (cwd) {
280
+ try {
281
+ if (!fs.statSync(cwd).isDirectory()) throw new Error('not a directory');
282
+ } catch {
283
+ warning = '原工作目录不存在,接手工作区使用同步模块所在工作区';
284
+ cwd = undefined;
285
+ }
286
+ }
287
+ cwd ||= path.resolve(import.meta.dirname, '../..');
288
+ let id = nativeId(row.source, row.id, `${row.revision}|${cwd}`);
289
+ if (report.dryRun) {
290
+ report.imported.push({ key, id, title: conversation.title || row.title, messages: conversation.messages.length, cwd });
291
+ continue;
292
+ }
293
+
294
+ let stored = await this.ctx.sessionPersistence.stat(id);
295
+ if (stored) {
296
+ const state = await this.usableSession(id);
297
+ if (state.corrupt) {
298
+ // Keep the unreadable log untouched and give this snapshot a readable identity.
299
+ const brokenId = id;
300
+ id = nativeId(row.source, row.id, `${row.revision}|${cwd}|recovered`);
301
+ stored = await this.ctx.sessionPersistence.stat(id);
302
+ report.recovered.push({ key, previous: brokenId, sessionId: id, reason: 'corrupt-session-log' });
303
+ }
304
+ }
305
+ if (!stored) {
306
+ const events = nativeEvents(conversation, row.source);
307
+ const meta = {
308
+ createdAt: Number(conversation.startedAt) || Date.now(),
309
+ isSeeded: false,
310
+ delegationDepth: 0,
311
+ agentPreset: 'standard',
312
+ cwd,
313
+ };
314
+ const prepared = this.ctx.sessions.prepare(id, { seed: events, meta });
315
+ const handle = await this.ctx.sessionPersistence.create(prepared.header);
316
+ try {
317
+ await handle.append(events);
318
+ await handle.flush();
319
+ } finally {
320
+ await handle.close();
321
+ }
322
+ }
323
+
324
+ const inspected = await this.readStoredSession(id);
325
+ const count = visibleMessages(inspected.events).length;
326
+ if (count < conversation.messages.length) {
327
+ throw new Error(`DSH 还原消息数不完整 (${count}/${conversation.messages.length})`);
328
+ }
329
+ const association = await this.attachImportedSession(id, inspected);
330
+
331
+ fs.mkdirSync(this.archiveRoot, { recursive: true });
332
+ const archive = path.join(this.archiveRoot, `${id}.json`);
333
+ fs.writeFileSync(
334
+ archive,
335
+ JSON.stringify(
336
+ {
337
+ source: row.source,
338
+ externalId: row.id,
339
+ title: conversation.title,
340
+ cwd: canonicalCwd(conversation.cwd),
341
+ messages: conversation.messages,
342
+ },
343
+ null,
344
+ 2,
345
+ ),
346
+ );
347
+ this.state.entries[key] = {
348
+ revision: row.revision,
349
+ sessionId: id,
350
+ title: conversation.title || row.title,
351
+ importedAt: Date.now(),
352
+ ...association,
353
+ messages: count,
354
+ archive,
355
+ previousSessionIds: [
356
+ ...(previous?.previousSessionIds || []),
357
+ ...(previous?.sessionId && previous.sessionId !== id ? [previous.sessionId] : []),
358
+ ],
359
+ };
360
+ this.save();
361
+ report.imported.push({
362
+ key,
363
+ id,
364
+ title: conversation.title || row.title,
365
+ messages: count,
366
+ cwd,
367
+ ...association,
368
+ ...(warning ? { warning } : {}),
369
+ });
370
+ } catch (error) {
371
+ report.failed.push({ key, title: row.title, error: error.message });
372
+ }
373
+ }
374
+ this.lastReport = report;
375
+ return report;
376
+ }
377
+
378
+ /** Archived sessions whose payload may be deleted: never pinned, live or already deleted. */
379
+ async deletableArchived(options = {}) {
380
+ const sessionsRoot = path.join(this.home, 'sessions');
381
+ const archived = Array.from(this.ctx.workspaceRegistry.archivedSessionIds || [], String);
382
+ const pinned = new Set(Array.from(this.ctx.workspaceRegistry.pinnedSessionIds || [], String));
383
+ const tombstones = this.state.deleted || {};
384
+ const wanted = Array.isArray(options.ids) ? new Set(options.ids.map(String)) : null;
385
+ const rows = [];
386
+ for (const sessionId of archived) {
387
+ if (pinned.has(sessionId) || tombstones[sessionId]) continue;
388
+ if (wanted && !wanted.has(sessionId)) continue;
389
+ // A chat that is currently open is never deleted out from under its agent.
390
+ try {
391
+ if (this.ctx.sessions.get(sessionId)) continue;
392
+ } catch {}
393
+ const plan = planSessionDeletion({ sessionsRoot, archivesRoot: this.archiveRoot, sessionId });
394
+ const entry = Object.values(this.state.entries).find((item) => item.sessionId === sessionId);
395
+ rows.push({ ...plan, title: entry?.title || null });
396
+ }
397
+ return rows;
398
+ }
399
+
400
+ /**
401
+ * Permanently delete archived session payloads. Dry run unless `dryRun:false`.
402
+ * The id stays in the registry's archived list and a tombstone is recorded, so the
403
+ * session never resurfaces as an unreadable chat.
404
+ */
405
+ async deleteArchived(options = {}) {
406
+ const rows = (await this.deletableArchived(options)).sort((a, b) => b.bytes - a.bytes);
407
+ const limit = Math.max(1, Math.min(500, Number(options.limit) || rows.length || 1));
408
+ const batch = rows.slice(0, limit);
409
+ const bytes = batch.reduce((sum, row) => sum + row.bytes, 0);
410
+ if (options.dryRun !== false) {
411
+ return {
412
+ dryRun: true,
413
+ candidates: rows.length,
414
+ batch: batch.length,
415
+ bytes,
416
+ missingPayload: rows.filter((row) => !row.exists).length,
417
+ sample: batch.slice(0, 8).map(({ sessionId, title, bytes }) => ({ sessionId, title, bytes })),
418
+ };
419
+ }
420
+ this.state.deleted ||= {};
421
+ const journal = { startedAt: new Date().toISOString(), rows: [] };
422
+ let freedBytes = 0;
423
+ for (const row of batch) {
424
+ try {
425
+ const result = deleteSessionPayload({ sessionsRoot: path.join(this.home, 'sessions'), archivesRoot: this.archiveRoot, sessionId: row.sessionId });
426
+ freedBytes += result.bytes || 0;
427
+ this.state.deleted[row.sessionId] = { deletedAt: Date.now(), title: row.title, bytes: result.bytes || 0 };
428
+ for (const [key, entry] of Object.entries(this.state.entries)) if (entry.sessionId === row.sessionId) delete this.state.entries[key];
429
+ this.save();
430
+ journal.rows.push({ sessionId: row.sessionId, title: row.title, bytes: result.bytes || 0, ok: true });
431
+ } catch (error) {
432
+ journal.rows.push({ sessionId: row.sessionId, title: row.title, ok: false, error: error.message });
433
+ }
434
+ }
435
+ journal.finishedAt = new Date().toISOString();
436
+ journal.freedBytes = freedBytes;
437
+ fs.mkdirSync(path.join(this.home, 'external-session-sync'), { recursive: true });
438
+ fs.writeFileSync(path.join(this.home, 'external-session-sync', `deletions-${Date.now()}.json`), JSON.stringify(journal, null, 2));
439
+ const remaining = await this.deletableArchived({});
440
+ return {
441
+ dryRun: false,
442
+ deleted: journal.rows.filter((row) => row.ok).length,
443
+ failed: journal.rows.filter((row) => !row.ok),
444
+ freedBytes,
445
+ remaining: remaining.length,
446
+ deletedSessionIds: journal.rows.filter((row) => row.ok).map((row) => row.sessionId),
447
+ };
448
+ }
449
+
450
+ async validateSession(id) {
451
+ const owned = Object.values(this.state.entries).some(
452
+ (entry) => entry.sessionId === id || entry.previousSessionIds?.includes(id),
453
+ );
454
+ if (!owned) throw new Error('这不是同步模块创建的会话');
455
+ const read = await this.readStoredSession(id);
456
+ const messages = visibleMessages(read.events);
457
+ const resolved = await this.ctx.sessionController.resolveAgent(id);
458
+ if (resolved.error) throw resolved.error;
459
+ const session = this.ctx.sessions.get(id);
460
+ const derived = session.deriveMessages();
461
+ const workspace = this.ctx.workspaceRegistry.list().find((row) => row.sessionIds.includes(id));
462
+ return {
463
+ sessionId: id,
464
+ cwd: read.meta.cwd || null,
465
+ eventCount: read.events.length,
466
+ messageCount: messages.length,
467
+ derivedMessages: derived.length,
468
+ agentAvailable: !!resolved.agent,
469
+ workspaceId: workspace?.id || null,
470
+ workspaceTitle: workspace?.title || null,
471
+ workspaceAttached: !!workspace,
472
+ roles: derived.map((message) => message.role),
473
+ lastText: derived
474
+ .at(-1)
475
+ ?.content?.filter((part) => part.type === 'text')
476
+ .map((part) => part.text)
477
+ .join('')
478
+ ?.slice(0, 300),
479
+ };
480
+ }
481
+ /** Does this stored session open with a protected system head? Uses the public reader. */
482
+ async inspectHead(sessionId) {
483
+ try {
484
+ const read = await this.readStoredSession(sessionId);
485
+ const first = read.events.find(
486
+ (event) => event.surfaceOp === 'append' || ['system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result'].includes(event.type),
487
+ );
488
+ return { sessionId, headOk: first?.type === 'system/message', firstType: first?.type || null, eventCount: read.events.length };
489
+ } catch (error) {
490
+ return { sessionId, headOk: false, firstType: null, unreadable: error.message };
491
+ }
492
+ }
493
+
494
+ /** Every mapping whose log predates the protected head, split by whether it can be re-imported. */
495
+ async legacyImports() {
496
+ const discovered = await this.discover({});
497
+ const available = new Set(discovered.map((row) => `${row.source}:${row.id}`));
498
+ const rows = [];
499
+ for (const [key, entry] of Object.entries(this.state.entries)) {
500
+ if (!entry.sessionId) continue;
501
+ const head = await this.inspectHead(entry.sessionId);
502
+ if (head.headOk) continue;
503
+ const split = key.indexOf(':');
504
+ rows.push({
505
+ key,
506
+ sessionId: entry.sessionId,
507
+ source: key.slice(0, split),
508
+ externalId: key.slice(split + 1),
509
+ title: entry.title || null,
510
+ reimportable: available.has(key),
511
+ firstType: head.firstType,
512
+ unreadable: head.unreadable || null,
513
+ });
514
+ }
515
+ return rows;
516
+ }
517
+
518
+ /**
519
+ * Archive a legacy mapping and re-import the same source conversation under a new
520
+ * native id (the importer's format salt guarantees a fresh identity). The old log is
521
+ * archived, never deleted, so `workspaceRegistry.unarchiveSession` reverses this.
522
+ */
523
+ async migrateLegacyHeads(options = {}) {
524
+ const rows = await this.legacyImports();
525
+ const candidates = rows.filter((row) => row.reimportable && !row.unreadable);
526
+ const batch = candidates.slice(0, Math.max(1, Math.min(50, Number(options.limit) || 20)));
527
+ const summary = {
528
+ total: rows.length,
529
+ reimportable: candidates.length,
530
+ unrecoverable: rows.filter((row) => !row.reimportable),
531
+ unreadable: rows.filter((row) => row.unreadable).length,
532
+ };
533
+ if (options.dryRun !== false) {
534
+ return { ...summary, dryRun: true, batch: batch.map(({ key, title, sessionId, firstType }) => ({ key, title, sessionId, firstType })) };
535
+ }
536
+ const journal = { startedAt: new Date().toISOString(), rows: [] };
537
+ const ids = [];
538
+ for (const row of batch) {
539
+ try {
540
+ await this.ctx.workspaceRegistry.archiveSession(row.sessionId, { stopActivity: false });
541
+ delete this.state.entries[row.key];
542
+ this.save();
543
+ ids.push(row.externalId);
544
+ journal.rows.push({ key: row.key, oldSessionId: row.sessionId, archived: true });
545
+ } catch (error) {
546
+ journal.rows.push({ key: row.key, oldSessionId: row.sessionId, archived: false, error: error.message });
547
+ }
548
+ }
549
+ const report = ids.length ? await this.run({ ids }) : null;
550
+ if (report) {
551
+ for (const item of report.imported) {
552
+ const row = journal.rows.find((entry) => entry.key === item.key);
553
+ if (row) row.newSessionId = item.id;
554
+ }
555
+ for (const item of report.failed) {
556
+ const row = journal.rows.find((entry) => entry.key === item.key);
557
+ if (row) row.importError = item.error;
558
+ }
559
+ }
560
+ journal.finishedAt = new Date().toISOString();
561
+ const root = path.join(this.home, 'external-session-sync');
562
+ fs.mkdirSync(root, { recursive: true });
563
+ fs.writeFileSync(path.join(root, `migration-${Date.now()}.json`), JSON.stringify(journal, null, 2));
564
+ const remaining = await this.legacyImports();
565
+ return {
566
+ ...summary,
567
+ dryRun: false,
568
+ batch: batch.length,
569
+ archived: journal.rows.filter((row) => row.archived).length,
570
+ archiveFailures: journal.rows.filter((row) => !row.archived),
571
+ imported: report ? report.imported.length : 0,
572
+ importFailures: report ? report.failed : [],
573
+ remaining: remaining.length,
574
+ };
575
+ }
576
+ }
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect x="4" y="4" width="56" height="56" rx="14" fill="#315fbd"/><path d="M16 20h32v22H30l-10 7v-7h-4z" fill="none" stroke="#fff" stroke-width="3" stroke-linejoin="round"/><path d="M23 28h18l-4-4m4 4-4 4M41 36H23l4-4m-4 4 4 4" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>