dsh-session-relocate 0.1.0 → 0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-relocate",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "跨工作区移动 DSH 对话:把某个 Session 的日志文件与工作区归属整体搬到另一个工作区(可自动注册新工作区)。带日志级崩溃恢复的安全事务,并且会先安全释放「已打开但空闲」的会话 —— 所以正在打开的对话也能直接搬,不需要重启 DSH。",
5
5
  "type": "module",
6
6
  "main": "src/plugin.js",
package/src/plugin.js CHANGED
@@ -18,7 +18,7 @@ import { randomBytes } from 'node:crypto';
18
18
  import { homedir } from 'node:os';
19
19
  import { dirname, join } from 'node:path';
20
20
  import { encodeSegment, sessionDir } from './paths.js';
21
- import { createMoveStore, MoveError, recoverPendingMoves, relocateSession, samePath } from './relocate.js';
21
+ import { commitMoves, createMoveStore, MoveError, recoverPendingMoves, relocateSession, samePath } from './relocate.js';
22
22
 
23
23
  /** 插件名(必须与 package.json 的 name 一致)。 */
24
24
  export const name = 'dsh-session-relocate';
@@ -219,6 +219,11 @@ export function apply(ctx, config) {
219
219
  journalsDir,
220
220
  sessionDirFor,
221
221
  log,
222
+ // 校验强度:auto(小日志全文解码,大日志帧级抽样)或 full(永远全文解码)。
223
+ verify: settings.verify === 'full' ? 'full' : 'auto',
224
+ fullVerifyLimit: Number.isSafeInteger(settings.fullVerifyLimit) && settings.fullVerifyLimit > 0
225
+ ? settings.fullVerifyLimit
226
+ : undefined,
222
227
  });
223
228
 
224
229
  /** 组装一次迁移需要的 DSH 运行时能力。 */
@@ -372,13 +377,59 @@ export function apply(ctx, config) {
372
377
  return { applied: false, refreshed: false, reason: '直接写注册表归属失败:' + String(error && error.message) };
373
378
  }
374
379
  },
380
+ /**
381
+ * 批量归属写入(commitMoves 用):先把这批会话的 header 缓存/路径索引一次性指到
382
+ * 目标 cwd,再**一次 mutate** 把整批加进目标工作区 —— 注册表只落盘一次。
383
+ * 和 adoptSession 同一条旁路,区别只是按批做。
384
+ */
385
+ async adoptSessions(sessionIds, targetEntity, targetCwd) {
386
+ const registry = ctx.workspaceRegistry;
387
+ try {
388
+ if (typeof targetEntity.mutate !== 'function') {
389
+ return { applied: false, refreshed: false, reason: '目标工作区实体没有 mutate 接口(DSH 版本变了)' };
390
+ }
391
+ for (const sessionId of sessionIds) {
392
+ const liveSession = ctx.get('sessions')?.get(sessionId);
393
+ const existing = registry.headers instanceof Map ? registry.headers.get(sessionId) : undefined;
394
+ const base = liveSession !== undefined && liveSession.header !== undefined
395
+ ? liveSession.header
396
+ : (existing !== undefined ? existing : { version: 4, id: sessionId, createdAt: Date.now(), isSeeded: false });
397
+ if (registry.sessionPaths instanceof Map) registry.sessionPaths.set(sessionId, targetCwd);
398
+ if (registry.invalidSessionPaths instanceof Map) registry.invalidSessionPaths.delete(sessionId);
399
+ if (registry.headers instanceof Map) registry.headers.set(sessionId, { ...base, cwd: targetCwd });
400
+ }
401
+ await targetEntity.mutate((record) => {
402
+ const add = sessionIds.filter((id) => !record.sessionIds.includes(id));
403
+ return add.length === 0 ? record : { ...record, sessionIds: [...add, ...record.sessionIds] };
404
+ });
405
+ return { applied: true, refreshed: false };
406
+ } catch (error) {
407
+ return { applied: false, refreshed: false, reason: '批量写目标归属失败:' + String(error && error.message) };
408
+ }
409
+ },
410
+ /** 批量摘除(commitMoves 用):一次 mutate 把整批从源工作区拿掉。 */
411
+ async detachSessions(sessionIds, sourceEntity) {
412
+ if (sourceEntity === undefined || sourceEntity === null || typeof sourceEntity.mutate !== 'function') {
413
+ return { applied: true };
414
+ }
415
+ try {
416
+ const drop = new Set(sessionIds);
417
+ await sourceEntity.mutate((record) => {
418
+ const keep = record.sessionIds.filter((id) => !drop.has(id));
419
+ return keep.length === record.sessionIds.length ? record : { ...record, sessionIds: keep };
420
+ });
421
+ return { applied: true };
422
+ } catch (error) {
423
+ return { applied: false, reason: '批量摘除源归属失败:' + String(error && error.message) };
424
+ }
425
+ },
375
426
  async releaseSession(sessionId) {
376
427
  const sessions = ctx.get('sessions');
377
428
  if (sessions === undefined || typeof sessions.get !== 'function') {
378
- return { released: true, detail: '没有 sessions 服务,视为无需释放' };
429
+ return { released: true, attempts: 0, detail: '没有 sessions 服务,视为无需释放' };
379
430
  }
380
431
  const live = sessions.get(sessionId);
381
- if (live === undefined) return { released: true, detail: '本来就不在内存里' };
432
+ if (live === undefined) return { released: true, attempts: 0, detail: '本来就不在内存里' };
382
433
 
383
434
  if (typeof sessions.flush === 'function') {
384
435
  try {
@@ -391,12 +442,15 @@ export function apply(ctx, config) {
391
442
  const entries = sessions.store;
392
443
  const entered = entries !== undefined && typeof entries.get === 'function' ? entries.get(sessionId) : undefined;
393
444
  if (entered === undefined || typeof entered.detach !== 'function') {
394
- return { released: false, detail: '拿不到可释放的 entered 记录(DSH 版本可能变了)' };
445
+ return { released: false, attempts: 0, detail: '拿不到可释放的 entered 记录(DSH 版本可能变了)' };
395
446
  }
396
447
  entered.detach();
397
448
 
398
449
  const persistence = ctx.sessionPersistence;
399
- if (typeof persistence.open !== 'function') return { released: true, detail: '已从内存摘除(没有 open 可探测)' };
450
+ if (typeof persistence.open !== 'function') return { released: true, attempts: 0, detail: '已从内存摘除(没有 open 可探测)' };
451
+ // 前几次探得很快(正常情况 detach 完立刻就能拿到租约),之后退回常规间隔。
452
+ // 这样"正常情况"几乎零等待,"被 GUI 抢着"时也仍然能等到,且总时长不变。
453
+ const quickDelays = [0, 10, 25, 50, 100];
400
454
  let last = 'unknown';
401
455
  for (let attempt = 0; attempt <= releaseRetries; attempt++) {
402
456
  let handle;
@@ -405,7 +459,8 @@ export function apply(ctx, config) {
405
459
  } catch (error) {
406
460
  last = String(error && error.message !== undefined ? error.message : error);
407
461
  if (attempt === releaseRetries) break;
408
- await sleep(releaseRetryDelayMs);
462
+ const delay = attempt < quickDelays.length ? quickDelays[attempt] : releaseRetryDelayMs;
463
+ if (delay > 0) await sleep(delay);
409
464
  continue;
410
465
  }
411
466
  try {
@@ -413,9 +468,9 @@ export function apply(ctx, config) {
413
468
  } catch (error) {
414
469
  log('warn', '探针句柄关闭失败(不影响结论):' + String(error && error.message));
415
470
  }
416
- return { released: true, detail: '写租约已释放(第 ' + String(attempt + 1) + ' 次探测拿到写所有权)' };
471
+ return { released: true, attempts: attempt + 1, detail: '写租约已释放(第 ' + String(attempt + 1) + ' 次探测拿到写所有权)' };
417
472
  }
418
- return { released: false, detail: '写所有权仍被占用:' + last };
473
+ return { released: false, attempts: releaseRetries + 1, detail: '写所有权仍被占用(试了 ' + String(releaseRetries + 1) + ' 次):' + last };
419
474
  },
420
475
  /**
421
476
  * 重建注册表的 header 缓存。
@@ -556,7 +611,15 @@ export function apply(ctx, config) {
556
611
  const targetWorkspaceId = typeof body.targetWorkspaceId === 'string' ? body.targetWorkspaceId : '';
557
612
  const targetPath = typeof body.targetPath === 'string' ? body.targetPath.trim() : '';
558
613
  try {
559
- const receipt = await relocateSession(buildHost(), store, { sessionId, targetWorkspaceId, targetPath, releaseLive, moveLive });
614
+ const receipt = await relocateSession(buildHost(), store, {
615
+ sessionId,
616
+ targetWorkspaceId,
617
+ targetPath,
618
+ releaseLive,
619
+ moveLive,
620
+ // 批量搬移时客户端逐条 defer:文件事务各自做完,注册表最后一次性写。
621
+ deferRegistry: body.deferRegistry === true,
622
+ });
560
623
  return { ok: true, ...receipt };
561
624
  } catch (error) {
562
625
  log('warn', '迁移失败:' + String(error && error.message));
@@ -564,6 +627,21 @@ export function apply(ctx, config) {
564
627
  }
565
628
  }
566
629
 
630
+ /** 批量收尾:把一串 defer 过的迁移的归属一次性写进注册表。 */
631
+ async function moveCommit(body) {
632
+ const ids = Array.isArray(body.sessionIds)
633
+ ? body.sessionIds.filter((entry) => typeof entry === 'string' && entry.length > 0)
634
+ : [];
635
+ if (ids.length === 0) return { ok: false, code: 'bad-request', message: '缺少 sessionIds' };
636
+ try {
637
+ const result = await commitMoves(buildHost(), store, ids);
638
+ return { ok: result.ok !== false, ...result };
639
+ } catch (error) {
640
+ log('warn', '批量结算失败:' + String(error && error.message));
641
+ return failure(error);
642
+ }
643
+ }
644
+
567
645
  /** 报告还有哪些迁移没收尾。 */
568
646
  async function status() {
569
647
  await kickRecovery();
@@ -577,6 +655,9 @@ export function apply(ctx, config) {
577
655
  moveLive,
578
656
  dragMove,
579
657
  selftest,
658
+ // 批量搬移的两段式(defer 文件事务 + 一次 commit 写注册表)由客户端按这个能力位决定是否启用。
659
+ bulkDefer: true,
660
+ verify: settings.verify === 'full' ? 'full' : 'auto',
580
661
  sessionsRoot: store.sessionsRoot,
581
662
  journalsDir: store.journalsDir,
582
663
  pending: journals.map((journal) => ({
@@ -778,6 +859,7 @@ export function apply(ctx, config) {
778
859
  const routes = [
779
860
  route(prefix + '/describe', ['POST'], describe),
780
861
  route(prefix + '/move', ['POST'], move),
862
+ route(prefix + '/move-commit', ['POST'], moveCommit),
781
863
  route(prefix + '/status', ['GET', 'POST'], status),
782
864
  ];
783
865
  if (selftest) {
package/src/relocate.js CHANGED
@@ -28,8 +28,9 @@ import { existsSync } from 'node:fs';
28
28
  import { cp, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
29
29
  import { randomBytes } from 'node:crypto';
30
30
  import { dirname, join } from 'node:path';
31
+ import { zstdDecompressSync } from 'node:zlib';
31
32
  import { encodeSegment, isCanonicalGenerationName } from './paths.js';
32
- import { decodeAllFrames, readFirstLine, replaceFirstLine } from './zstd.js';
33
+ import { isZstdArtifact, readFirstLine, replaceFirstLine, scanZstdFrames } from './zstd.js';
33
34
 
34
35
  /** 暂存区目录名(在会话存储根目录下,靠「深一层」对后端不可见)。 */
35
36
  export const STAGING_DIR_NAME = '_session-move-staging';
@@ -91,6 +92,88 @@ export function createMoveStore(options) {
91
92
  throw new Error('createMoveStore requires a sessionDirFor(sessionId, cwd) function');
92
93
  }
93
94
  const stagingRoot = join(sessionsRoot, STAGING_DIR_NAME);
95
+ /** 校验强度:'auto'(小日志全文解码、大日志帧级抽样)或 'full'(永远全文解码)。 */
96
+ const verifyMode = options.verify === 'full' ? 'full' : 'auto';
97
+ /** 超过这个大小(压缩后字节数)就走抽样校验。 */
98
+ const fullVerifyLimit = Number.isSafeInteger(options.fullVerifyLimit) && options.fullVerifyLimit > 0
99
+ ? options.fullVerifyLimit
100
+ : 2 * 1024 * 1024;
101
+
102
+ /**
103
+ * 校验「改写后的日志」与「源日志」等价:除首行(header 的 cwd)外一切不变。
104
+ *
105
+ * 两种强度:
106
+ * - full:逐帧解码 → 顺带证明每个完整帧都能解压、校验和对(小日志默认走这条);
107
+ * - sampled:帧级字节比对 + 解头 + 解尾 → 大日志走这条,调用方必须在回执里标明。
108
+ *
109
+ * @returns 'full' | 'sampled'
110
+ */
111
+ function verifyRewrite(source, patched) {
112
+ if (!isZstdArtifact(source)) {
113
+ // 明文日志:第一个换行之后的字节必须完全一致(等价于逐行比对,但没有解码成本)。
114
+ const nlSource = source.indexOf(10);
115
+ const nlPatched = patched.indexOf(10);
116
+ if (nlSource < 0 || nlPatched < 0) throw new MoveError('corrupt-log', '日志里找不到完整的一行');
117
+ if (source.subarray(nlSource).compare(patched.subarray(nlPatched)) !== 0) {
118
+ throw new MoveError('patch-differs', '改写后首行以外的内容与源不一致');
119
+ }
120
+ return 'full';
121
+ }
122
+ const before = scanZstdFrames(source);
123
+ const after = scanZstdFrames(patched);
124
+ if (before.frames.length !== after.frames.length) {
125
+ throw new MoveError('patch-lost-frames', '改写后帧数变了(' + String(before.frames.length) + ' -> ' + String(after.frames.length) + ')');
126
+ }
127
+ if (before.frames.length === 0) throw new MoveError('corrupt-log', '日志里没有完整帧');
128
+ // 第一帧:解出来,除 cwd 外必须完全一样,且首行必须真的变了。
129
+ const firstBefore = zstdDecompressSync(source.subarray(before.frames[0].start, before.frames[0].end));
130
+ const firstAfter = zstdDecompressSync(patched.subarray(after.frames[0].start, after.frames[0].end));
131
+ const nlBefore = firstBefore.indexOf(10);
132
+ const nlAfter = firstAfter.indexOf(10);
133
+ if (nlBefore < 0 || nlAfter < 0) throw new MoveError('corrupt-log', '第一帧里没有完整的 header 行');
134
+ const lineBefore = firstBefore.subarray(0, nlBefore).toString('utf8');
135
+ const lineAfter = firstAfter.subarray(0, nlAfter).toString('utf8');
136
+ if (lineBefore === lineAfter) throw new MoveError('patch-noop', '改写后 header 没有变化');
137
+ let headerBefore;
138
+ let headerAfter;
139
+ try {
140
+ headerBefore = JSON.parse(lineBefore);
141
+ headerAfter = JSON.parse(lineAfter);
142
+ } catch {
143
+ throw new MoveError('corrupt-log', 'header 行不是合法 JSON');
144
+ }
145
+ const left = { ...headerBefore };
146
+ const right = { ...headerAfter };
147
+ delete left.cwd;
148
+ delete right.cwd;
149
+ if (JSON.stringify(left) !== JSON.stringify(right)) throw new MoveError('patch-differs', 'header 除 cwd 之外还变了');
150
+ if (firstBefore.subarray(nlBefore).compare(firstAfter.subarray(nlAfter)) !== 0) {
151
+ throw new MoveError('patch-differs', '第一帧首行之后的内容变了');
152
+ }
153
+ // 其余帧:逐字节相同(我们根本没有重写它们)。
154
+ for (let i = 1; i < before.frames.length; i += 1) {
155
+ const fa = source.subarray(before.frames[i].start, before.frames[i].end);
156
+ const fb = patched.subarray(after.frames[i].start, after.frames[i].end);
157
+ if (fa.length !== fb.length || fa.compare(fb) !== 0) {
158
+ throw new MoveError('patch-differs', '第 ' + String(i + 1) + ' 帧被改动了');
159
+ }
160
+ }
161
+ // 尾部未写完的字节也必须原样保留。
162
+ const tailBefore = source.subarray(before.frames[before.frames.length - 1].end);
163
+ const tailAfter = patched.subarray(after.frames[after.frames.length - 1].end);
164
+ if (tailBefore.length !== tailAfter.length || tailBefore.compare(tailAfter) !== 0) {
165
+ throw new MoveError('patch-differs', '尾部未完成的字节变了');
166
+ }
167
+ if (verifyMode !== 'full' && source.length > fullVerifyLimit) {
168
+ // 抽样:只解最后一帧 —— 追加写崩溃留下的损坏几乎都在尾巴上。
169
+ const last = after.frames.length - 1;
170
+ zstdDecompressSync(patched.subarray(after.frames[last].start, after.frames[last].end));
171
+ return 'sampled';
172
+ }
173
+ // 全量:每一帧都解一遍,坏帧(校验和/位流损坏)会当场抛错。
174
+ for (const frame of before.frames) zstdDecompressSync(source.subarray(frame.start, frame.end));
175
+ return 'full';
176
+ }
94
177
 
95
178
  /**
96
179
  * 算出一次迁移涉及的全部路径。
@@ -169,6 +252,7 @@ export function createMoveStore(options) {
169
252
  if (names.length === 0) {
170
253
  throw new MoveError('no-generation', '会话目录里没有可识别的日志文件:' + plan.srcDir);
171
254
  }
255
+ const modes = [];
172
256
  for (const name of names) {
173
257
  const stagedPath = join(plan.stagingDir, name);
174
258
  const staged = await readFile(stagedPath);
@@ -186,24 +270,11 @@ export function createMoveStore(options) {
186
270
  throw new MoveError('id-mismatch', '会话日志 ' + name + ' 的 header id 与目标不一致,拒绝改写');
187
271
  }
188
272
  const patched = replaceFirstLine(staged, JSON.stringify({ ...header, cwd: toCwd }));
189
-
190
- // 自校验:除首行外,明文必须与源文件逐字节一致。
191
- const sourceLines = decodeAllFrames(await readFile(join(plan.srcDir, name))).toString('utf8').split('\n');
192
- const patchedLines = decodeAllFrames(patched).toString('utf8').split('\n');
193
- if (patchedLines[0] === sourceLines[0]) {
194
- throw new MoveError('patch-noop', '改写后 header 没有变化(' + name + '),拒绝继续');
195
- }
196
- if (patchedLines.length !== sourceLines.length) {
197
- throw new MoveError('patch-lost-lines', '改写后行数发生变化(' + name + '),拒绝继续');
198
- }
199
- for (let i = 1; i < sourceLines.length; i++) {
200
- if (sourceLines[i] !== patchedLines[i]) {
201
- throw new MoveError('patch-differs', '改写后第 ' + String(i + 1) + ' 行与源不一致(' + name + '),拒绝继续');
202
- }
203
- }
273
+ // 自校验:除首行外一切不变(小日志全文解码,大日志帧级比对,见 verifyRewrite)。
274
+ modes.push(verifyRewrite(staged, patched));
204
275
  await atomicWrite(stagedPath, patched);
205
276
  }
206
- return names;
277
+ return { names, verification: modes.includes('sampled') ? 'sampled' : 'full' };
207
278
  }
208
279
 
209
280
  /** 校验一个目录里每个 generation 的 header id 与 cwd 都对。 */
@@ -355,6 +426,7 @@ export async function relocateSession(host, store, request) {
355
426
 
356
427
  // release 路径:所有校验都过了才动状态,释放失败就整体放弃、绝不碰文件。
357
428
  let released = false;
429
+ let releaseAttempts = 0;
358
430
  if (live && !useHandoff) {
359
431
  const outcome = await host.releaseSession(sessionId).catch((error) => ({
360
432
  released: false,
@@ -367,6 +439,7 @@ export async function relocateSession(host, store, request) {
367
439
  );
368
440
  }
369
441
  released = true;
442
+ releaseAttempts = Number.isSafeInteger(outcome.attempts) ? outcome.attempts : 0;
370
443
  host.log('info', '已释放会话 ' + sessionId + ' 的写所有权:' + String(outcome.detail));
371
444
  if (!existsSync(plan.srcDir)) {
372
445
  throw new MoveError('source-dir-missing', '释放之后找不到这个会话的存储目录:' + plan.srcDir);
@@ -392,22 +465,18 @@ export async function relocateSession(host, store, request) {
392
465
  const performFileTransaction = async () => {
393
466
  let promoted = false;
394
467
  try {
395
- const names = await store.stageAndPatch(plan, sessionId, target.path);
396
- journal.generations = names;
397
- journal.phase = 'staged';
398
- await store.writeJournal(journal);
399
-
468
+ // 只写一次日志(下面不再逐相位重写):recoverOne 完全按「源在不在、目标在不在」
469
+ // 推导该补哪一步,相位字段对恢复没有作用,逐相位 atomicWrite 是纯开销。
470
+ const staged = await store.stageAndPatch(plan, sessionId, target.path);
471
+ const verification = staged !== null && staged !== undefined && typeof staged === 'object' && typeof staged.verification === 'string'
472
+ ? staged.verification
473
+ : 'full';
400
474
  await store.verifyPromoted(plan.stagingDir, sessionId, target.path);
401
475
  await mkdir(plan.dstProjectDir, { recursive: true });
402
476
  await rename(plan.stagingDir, plan.dstDir);
403
477
  promoted = true;
404
- journal.phase = 'moved';
405
- await store.writeJournal(journal);
406
-
407
478
  await rm(plan.srcDir, { recursive: true, force: true });
408
- journal.phase = 'src-removed';
409
- await store.writeJournal(journal);
410
- return { ok: true };
479
+ return { ok: true, verification };
411
480
  } catch (error) {
412
481
  if (!promoted) {
413
482
  // 源目录完好,整体回滚。
@@ -468,6 +537,27 @@ export async function relocateSession(host, store, request) {
468
537
  };
469
538
  }
470
539
 
540
+ // 批量搬移用:文件事务做完就返回,注册表留给 commitMoves 一次性写。
541
+ // 这样 N 条会话只付 2 次注册表写,而不是 2N 次。日志故意不删 —— 它既是
542
+ // commit 的输入,也是"commit 之前崩掉"时恢复的依据(recoverOne 按文件状态幂等补完)。
543
+ if (request.deferRegistry === true) {
544
+ return {
545
+ ok: true,
546
+ deferred: true,
547
+ opId,
548
+ sessionId,
549
+ from: sourceCanonical,
550
+ to: target.path,
551
+ targetWorkspaceId: target.id,
552
+ targetTitle: target.title,
553
+ movedTo: plan.dstDir,
554
+ released,
555
+ releaseAttempts,
556
+ handedOff,
557
+ verification: outcome.verification !== undefined ? outcome.verification : 'full',
558
+ };
559
+ }
560
+
471
561
  return await finishAndReport(host, store, {
472
562
  opId,
473
563
  sessionId,
@@ -476,7 +566,9 @@ export async function relocateSession(host, store, request) {
476
566
  source,
477
567
  dstDir: plan.dstDir,
478
568
  released,
569
+ releaseAttempts,
479
570
  handedOff,
571
+ verification: outcome.verification !== undefined ? outcome.verification : 'full',
480
572
  handoffWriter: outcome.writerRetargeted === true,
481
573
  });
482
574
  }
@@ -486,9 +578,19 @@ async function finishAndReport(host, store, ctx) {
486
578
  // 就地接管(会话还活着)时不能走 attachSession —— live Session 的 header 是
487
579
  // deep-frozen 的旧 cwd,注册表的 cwd 校验一定过不了。所以走 host.adoptSession
488
580
  // 这条旁路(它直接改注册表的归属表与路径索引)。
489
- const registry = ctx.handedOff === true && typeof host.adoptSession === 'function'
490
- ? await host.adoptSession(ctx.sessionId, ctx.target, ctx.source, ctx.target.path)
491
- : await finalizeRegistry(host, ctx.sessionId, ctx.target, ctx.source);
581
+ // 三条路径,优先级从快到慢:
582
+ // 1. 就地接管:走 adoptSession(live header 冻结,只能旁路写);
583
+ // 2. 冷搬移:走 adoptSessions + detachSessions(定向写索引 + 每边一次 mutate,
584
+ // **不**重建全量 header 索引 —— 那一步在大库上是白花的);
585
+ // 3. 主机没给批量原语(老版本):退回官方的 refresh + attach + detach。
586
+ let registry;
587
+ if (ctx.handedOff === true && typeof host.adoptSession === 'function') {
588
+ registry = await host.adoptSession(ctx.sessionId, ctx.target, ctx.source, ctx.target.path);
589
+ } else if (typeof host.adoptSessions === 'function' && typeof host.detachSessions === 'function') {
590
+ registry = await adoptCold(host, ctx.sessionId, ctx.target, ctx.source);
591
+ } else {
592
+ registry = await finalizeRegistry(host, ctx.sessionId, ctx.target, ctx.source);
593
+ }
492
594
  if (registry.applied) {
493
595
  await store.removeJournal(ctx.opId).catch(() => {});
494
596
  await store.dropStaging(ctx.opId).catch(() => {});
@@ -504,9 +606,11 @@ async function finishAndReport(host, store, ctx) {
504
606
  movedTo: ctx.dstDir,
505
607
  applied: 'live',
506
608
  released: ctx.released === true,
609
+ releaseAttempts: Number.isSafeInteger(ctx.releaseAttempts) ? ctx.releaseAttempts : 0,
507
610
  handedOff: ctx.handedOff === true,
508
611
  handoffWriter: ctx.handoffWriter === true,
509
612
  headerIndexRefreshed: registry.refreshed === true,
613
+ verification: ctx.verification !== undefined ? ctx.verification : 'full',
510
614
  };
511
615
  }
512
616
  // 磁盘已就位,但归属没写成:保留日志,下次桥接调用或下次启动自动补齐。
@@ -523,10 +627,29 @@ async function finishAndReport(host, store, ctx) {
523
627
  applied: 'pending',
524
628
  released: ctx.released === true,
525
629
  handedOff: ctx.handedOff === true,
630
+ verification: ctx.verification !== undefined ? ctx.verification : 'full',
526
631
  pendingReason: registry.reason,
527
632
  };
528
633
  }
529
634
 
635
+ /**
636
+ * 冷搬移的归属写入:定向更新本会话的 header 缓存/路径索引,然后目标、源各一次 mutate。
637
+ * 和批量 commit 用的是同一组原语,只是这里只有一条。
638
+ */
639
+ async function adoptCold(host, sessionId, target, source) {
640
+ const adopted = await host.adoptSessions([sessionId], target, target.path);
641
+ if (adopted === undefined || adopted === null || adopted.applied !== true) {
642
+ return { applied: false, refreshed: false, reason: adopted !== null && adopted !== undefined && typeof adopted.reason === 'string' ? adopted.reason : '写入目标工作区归属失败' };
643
+ }
644
+ if (source !== undefined && source.id !== target.id) {
645
+ const detached = await host.detachSessions([sessionId], source);
646
+ if (detached !== undefined && detached !== null && detached.applied === false) {
647
+ return { applied: false, refreshed: false, reason: typeof detached.reason === 'string' ? detached.reason : '从源工作区摘除失败' };
648
+ }
649
+ }
650
+ return { applied: true, refreshed: false };
651
+ }
652
+
530
653
  /**
531
654
  * 把工作区归属写进注册表:刷新 header 索引 → attach 到目标 → 从源 detach。
532
655
  *
@@ -582,6 +705,108 @@ export async function recoverPendingMoves(host, store) {
582
705
  return results;
583
706
  }
584
707
 
708
+ /** 把一个 id 归到 map[key] 的数组里。 */
709
+ function groupInto(map, key, value) {
710
+ const list = map.get(key);
711
+ if (list === undefined) map.set(key, [value]);
712
+ else list.push(value);
713
+ }
714
+
715
+ /**
716
+ * 批量收尾:把 deferRegistry 留下的一摞迁移日志一次性结算。
717
+ *
718
+ * 做三件事:
719
+ * 1. 逐条确认文件状态(源还在就删、目标没就位就重做),与 recoverOne 同一套幂等规则;
720
+ * 2. 注册表只写「每个目标工作区一次 + 每个源工作区一次」,不再是每会话两次;
721
+ * 3. 清日志、清暂存区、失效投影缓存。
722
+ *
723
+ * 注册表写失败时**故意保留日志**:recoverOne 会在下次桥接调用或下次启动时补完归属。
724
+ *
725
+ * @param host - DSH 适配层(需要 adoptSessions / detachSessions)。
726
+ * @param store - 迁移引擎。
727
+ * @param sessionIds - 只结算这些会话;缺省表示结算全部未完成日志。
728
+ * @returns { ok, results, message? }。
729
+ */
730
+ export async function commitMoves(host, store, sessionIds) {
731
+ const wanted = Array.isArray(sessionIds) && sessionIds.length > 0 ? new Set(sessionIds) : null;
732
+ const journals = (await store.readJournals()).filter((entry) => wanted === null || wanted.has(entry.sessionId));
733
+ const results = [];
734
+ const byTarget = new Map();
735
+ const bySource = new Map();
736
+ const settled = [];
737
+
738
+ for (const journal of journals) {
739
+ try {
740
+ const srcExists = existsSync(journal.srcDir);
741
+ const dstExists = existsSync(journal.dstDir);
742
+ if (!srcExists && !dstExists) {
743
+ await store.removeJournal(journal.opId).catch(() => {});
744
+ results.push({ sessionId: journal.sessionId, status: 'lost', message: '源目录与目标目录都不存在' });
745
+ continue;
746
+ }
747
+ if (!dstExists) {
748
+ // 目标还没就位(多半是 commit 之前崩了):照着日志重做一遍文件事务。
749
+ const plan = store.layout(journal.sessionId, journal.fromCwd, journal.toCwd, journal.opId);
750
+ plan.srcDir = journal.srcDir;
751
+ plan.dstDir = journal.dstDir;
752
+ await rm(plan.stagingOpDir, { recursive: true, force: true });
753
+ await store.stageAndPatch(plan, journal.sessionId, journal.toCwd);
754
+ await store.verifyPromoted(plan.stagingDir, journal.sessionId, journal.toCwd);
755
+ await mkdir(plan.dstProjectDir, { recursive: true });
756
+ await rename(plan.stagingDir, plan.dstDir);
757
+ }
758
+ if (existsSync(journal.srcDir)) await rm(journal.srcDir, { recursive: true, force: true });
759
+ const target = host.findWorkspaceByPath(journal.toCwd);
760
+ if (target === undefined) {
761
+ results.push({ sessionId: journal.sessionId, status: 'pending-workspace', message: '目标工作区未找到:' + journal.toCwd });
762
+ continue;
763
+ }
764
+ groupInto(byTarget, journal.toCwd, journal.sessionId);
765
+ groupInto(bySource, journal.fromCwd, journal.sessionId);
766
+ settled.push(journal);
767
+ results.push({ sessionId: journal.sessionId, status: 'moved', to: journal.toCwd, targetWorkspaceId: target.id });
768
+ } catch (error) {
769
+ results.push({ sessionId: journal.sessionId, status: 'failed', message: String(error && error.message !== undefined ? error.message : error) });
770
+ }
771
+ }
772
+
773
+ if (settled.length === 0) return { ok: true, results };
774
+
775
+ try {
776
+ for (const [toCwd, ids] of byTarget) {
777
+ const target = host.findWorkspaceByPath(toCwd);
778
+ const adopted = await host.adoptSessions(ids, target, toCwd);
779
+ if (adopted !== undefined && adopted !== null && adopted.applied === false) {
780
+ throw new MoveError('registry-failed', '写入目标工作区归属失败:' + String(adopted.reason));
781
+ }
782
+ }
783
+ for (const [fromCwd, ids] of bySource) {
784
+ const source = host.findWorkspaceByPath(fromCwd);
785
+ if (source === undefined) continue;
786
+ const detached = await host.detachSessions(ids, source);
787
+ if (detached !== undefined && detached !== null && detached.applied === false) {
788
+ throw new MoveError('registry-failed', '从源工作区摘除失败:' + String(detached.reason));
789
+ }
790
+ }
791
+ } catch (error) {
792
+ host.log('warn', '批量结算写注册表失败(文件已就位,日志保留待恢复):' + String(error && error.message));
793
+ return {
794
+ ok: false,
795
+ message: '文件已搬移,但工作区归属写入失败(下次桥接调用会自动补齐):' + String(error && error.message),
796
+ results: results.map((entry) => (entry.status === 'moved' ? { ...entry, status: 'failed', message: '归属待补齐' } : entry)),
797
+ };
798
+ }
799
+
800
+ for (const journal of settled) {
801
+ await store.removeJournal(journal.opId).catch(() => {});
802
+ await store.dropStaging(journal.opId).catch(() => {});
803
+ }
804
+ for (const journal of settled) {
805
+ await host.invalidateProjection(journal.sessionId);
806
+ }
807
+ return { ok: true, results };
808
+ }
809
+
585
810
  async function recoverOne(host, store, journal) {
586
811
  const { opId, sessionId, toCwd, srcDir, dstDir } = journal;
587
812
  const srcExists = existsSync(srcDir);