@jjh32456/longlive 1.8.12 → 2.1.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 (92) hide show
  1. package/CHANGELOG.md +258 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +61 -18
  5. package/SPEC.md +3 -3
  6. package/build-info.json +259 -129
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ANSWER-GUARD.md +1 -1
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +5 -3
  11. package/docs/AUTO-RECALL.md +10 -4
  12. package/docs/CONFIG.md +46 -11
  13. package/docs/ERRORS.md +1 -1
  14. package/docs/FAQ.md +9 -9
  15. package/docs/FEATURES.md +19 -16
  16. package/docs/OPERATIONS.md +3 -3
  17. package/docs/PANEL-INTEGRATION.md +1 -1
  18. package/docs/PRIVACY.md +6 -6
  19. package/docs/QUICKSTART.md +5 -5
  20. package/docs/README.en.md +5 -3
  21. package/docs/TOOLS.md +1 -1
  22. package/docs/TROUBLESHOOTING.md +4 -4
  23. package/package.json +6 -3
  24. package/runbook.md +3 -3
  25. package/scripts/migrate-200.mjs +8 -0
  26. package/scripts/migrate-lifecycle.mjs +2 -2
  27. package/src/answer/claim-guard.mjs +234 -0
  28. package/src/backup.js +165 -1
  29. package/src/config.js +18 -7
  30. package/src/features.js +132 -5
  31. package/src/handoff/index.js +133 -0
  32. package/src/handoff/model.js +48 -0
  33. package/src/identity/handover.js +203 -15
  34. package/src/identity/inject-position.js +3 -1
  35. package/src/index.js +2 -2
  36. package/src/memory/a1-migration.js +72 -6
  37. package/src/memory/archive-cold-state.mjs +794 -0
  38. package/src/memory/archive-staging.mjs +305 -0
  39. package/src/memory/archive.mjs +415 -0
  40. package/src/memory/capture-host.js +71 -2
  41. package/src/memory/capture.js +45 -6
  42. package/src/memory/catchup.mjs +534 -0
  43. package/src/memory/conclusion-distill.js +51 -2
  44. package/src/memory/conclusion-drafts.js +7 -3
  45. package/src/memory/conflicts.js +915 -2
  46. package/src/memory/consolidate.js +20 -1
  47. package/src/memory/forget-v2.js +272 -2
  48. package/src/memory/forget.js +20 -1
  49. package/src/memory/frames-activation.js +3 -1
  50. package/src/memory/fts-query.js +2 -2
  51. package/src/memory/index.js +80 -7
  52. package/src/memory/land.mjs +743 -0
  53. package/src/memory/lifecycle.js +128 -0
  54. package/src/memory/maintenance.js +386 -22
  55. package/src/memory/memory-health.mjs +607 -0
  56. package/src/memory/memory-reader.mjs +1003 -0
  57. package/src/memory/migrate-200.js +1681 -0
  58. package/src/memory/migrate-lifecycle.js +3 -3
  59. package/src/memory/procedure-candidate.mjs +377 -0
  60. package/src/memory/procedure.js +20 -1
  61. package/src/memory/prospective-memory.mjs +362 -0
  62. package/src/memory/recall-feedback.mjs +406 -0
  63. package/src/memory/recall-v2.js +13 -1
  64. package/src/memory/recall.js +102 -1
  65. package/src/memory/reinforce.js +138 -2
  66. package/src/memory/retention.js +34 -0
  67. package/src/memory/turn-budget.mjs +290 -0
  68. package/src/memory/wake-bridge.mjs +2999 -0
  69. package/src/memory/working-frame.js +271 -8
  70. package/src/metrics/classify.mjs +3 -1
  71. package/src/recall/archive-config.mjs +130 -0
  72. package/src/recall/archive-fallback.mjs +174 -19
  73. package/src/recall/archive-search.mjs +3 -0
  74. package/src/recall/archive-state.mjs +588 -0
  75. package/src/recall/brain.mjs +501 -0
  76. package/src/recall/continuity-log.mjs +435 -0
  77. package/src/recall/continuity-volatile.mjs +1001 -0
  78. package/src/recall/current-line.mjs +110 -0
  79. package/src/recall/edges.js +21 -2
  80. package/src/recall/explain.mjs +10 -0
  81. package/src/recall/gate-log.mjs +280 -0
  82. package/src/recall/gate-metrics.mjs +191 -0
  83. package/src/recall/index.js +663 -29
  84. package/src/recall/inject-order.mjs +3 -1
  85. package/src/recall/link-fastpath.mjs +662 -0
  86. package/src/recall/recall-core.mjs +74 -2
  87. package/src/recall/turn-budget-inject.mjs +154 -0
  88. package/src/retention/cold-gate.mjs +146 -0
  89. package/src/retention/config.js +58 -1
  90. package/src/retention/index.js +193 -35
  91. package/src/router/design-headings.json +10 -10
  92. package/src/tools.js +122 -6
@@ -0,0 +1,1681 @@
1
+ // B7:1.8.x → 2.0.0 版本迁移内核 + 冷层迁移二次 approve 门 + plan/backup/manifest 三件套。
2
+ //
3
+ // 设计口径(DESIGN v0.5.2 §15 L214/L216,逐字引用见 M200-DRAFT-REPORT.md):
4
+ // - 迁移:旧键全保留、新键可选;migrate-200.mjs --mode plan|dry-run|apply|rollback
5
+ // (输出 .longlive/migrate-200/{plan,backup,manifest}.json,默认 dry-run,apply 前整目录快照;
6
+ // 旧数据读取器 version-tolerant、不重写);迁移报告逐文件 sha。
7
+ // - 冷层迁移需二次 approve、无卷降级、失败不删原件。
8
+ //
9
+ // 本模块的硬约束:
10
+ // 1) 默认 dry-run:plan/dry-run 只读,绝不在 memoryRoot 建目录、写文件、移动数据;
11
+ // 2) 不许静默迁移:任何数据移动必须先有一份可复算 plan + 第一次 approve(plan),
12
+ // 备份完成后必须再有第二次 approve(apply),缺任一次都 fail-closed;
13
+ // 3) 失败不删原件:移动=同卷 rename(失败原子回退),备份快照按 sha 校验;
14
+ // rollback 只恢复备份里记录的文件,不删除迁移之外的东西;
15
+ // 4) manifest.json 里 files[] 只列“迁移后仍然存在、可在 memoryRoot 下重算 sha256”的文件
16
+ // (L4-migrate-200 契约:rel|path + sha256|sha [+bytes]),manifest 自身与它的
17
+ // .sha256 sidecar 不进 files[](否则自引用成环),由 .longlive/migrate-200/manifest.sha256 旁证;
18
+ // 5) 200 = 目标版本 2.0.0(1.8.x→2.0.0),不是 200 条、也不是 200 token。
19
+ //
20
+ // 状态机(持久化在 .longlive/migrate-200/state.json;权威 approve 记录在 approve.json):
21
+ // absent → planned(plan --write)
22
+ // → backup-ready(apply 的备份阶段;此时 apply 会以 rc=3 要求第二次 approve)
23
+ // → applied(第二次 approve 后 apply 落数据 + manifest.json)
24
+ // → planned(rollback 恢复数据后回到可重跑态;apply 阶段的 approve 记录被撤销,
25
+ // 必须重新走备份 + 二次 approve)
26
+ // 任一步失败都停在原状态并把原因写进 state.history 与 stderr,不写入半成品 manifest。
27
+ //
28
+ // 退出码:
29
+ // 0 ok;2 用法/未知参数;3 等待 approve(缺一次或二次确认值不符);
30
+ // 4 plan 过期/被篡改;5 备份损坏;6 manifest 复算失败;7 状态冲突(如已 applied 又重跑)。
31
+ import crypto from 'node:crypto';
32
+ import fs from 'node:fs';
33
+ import os from 'node:os';
34
+ import path from 'node:path';
35
+
36
+ export const MODULE = 'src/memory/migrate-200.js';
37
+ export const CLI_MODULE = 'scripts/migrate-200.mjs';
38
+ export const BATCH = 'B7';
39
+ export const MODES = Object.freeze(['plan', 'dry-run', 'apply', 'rollback', 'approve', 'verify']);
40
+ export const DEFAULT_MODE = 'dry-run';
41
+ export const FROM_VERSION = '1.8.x';
42
+ export const TO_VERSION = '2.0.0';
43
+
44
+ export const OUTPUT_DIR_REL = '.longlive/migrate-200';
45
+ export const REL = Object.freeze({
46
+ plan: 'plan.json',
47
+ planHash: 'plan.json.sha256',
48
+ backup: 'backup.json',
49
+ backupHash: 'backup.json.sha256',
50
+ approve: 'approve.json',
51
+ approveHash: 'approve.json.sha256',
52
+ request: 'approve-request.json',
53
+ requestHash: 'approve-request.json.sha256',
54
+ state: 'state.json',
55
+ manifest: 'manifest.json',
56
+ manifestHash: 'manifest.json.sha256',
57
+ pending: 'pending.json',
58
+ });
59
+
60
+ export const SCHEMA = Object.freeze({
61
+ plan: 'migrate-200-plan/v1',
62
+ backup: 'migrate-200-backup/v1',
63
+ approve: 'migrate-200-approve/v1',
64
+ request: 'migrate-200-approve-request/v1',
65
+ pending: 'migrate-200-pending/v1',
66
+ state: 'migrate-200-state/v1',
67
+ manifest: 'migrate-200-manifest/v1',
68
+ hash: 'migrate-200-hash/v1',
69
+ cli: 'migrate-200-cli/v1',
70
+ });
71
+
72
+ export const APPROVAL_STAGES = Object.freeze(['plan', 'apply']);
73
+ export const REQUIRED_APPROVALS = Object.freeze(['plan', 'apply']);
74
+
75
+ export const EXIT = Object.freeze({
76
+ ok: 0,
77
+ usage: 2,
78
+ approvalRequired: 3,
79
+ stale: 4,
80
+ backupMismatch: 5,
81
+ verifyFail: 6,
82
+ conflict: 7,
83
+ });
84
+
85
+ export const CODE = Object.freeze({
86
+ usage: 'E_HG_MIGRATE_USAGE',
87
+ rootMissing: 'E_HG_MIGRATE_ROOT_MISSING',
88
+ approveRequired: 'E_HG_MIGRATE_APPROVE_REQUIRED',
89
+ approveConfirm: 'E_HG_MIGRATE_APPROVE_CONFIRM_MISMATCH',
90
+ approveOrder: 'E_HG_MIGRATE_APPROVE_ORDER',
91
+ planMissing: 'E_HG_MIGRATE_PLAN_MISSING',
92
+ planStale: 'E_HG_MIGRATE_PLAN_STALE',
93
+ artifactTampered: 'E_HG_MIGRATE_ARTIFACT_TAMPERED',
94
+ backupMissing: 'E_HG_MIGRATE_BACKUP_MISSING',
95
+ backupMismatch: 'E_HG_MIGRATE_BACKUP_MISMATCH',
96
+ applyConflict: 'E_HG_MIGRATE_APPLY_CONFLICT',
97
+ applySourceMismatch: 'E_HG_MIGRATE_SOURCE_MISMATCH',
98
+ verifyFail: 'E_HG_MIGRATE_VERIFY_FAIL',
99
+ conflict: 'E_HG_MIGRATE_CONFLICT',
100
+ probeFailed: 'E_HG_MIGRATE_PROBE_FAILED',
101
+ });
102
+
103
+ export class MigrationError extends Error {
104
+ constructor(code, message, { exitCode = EXIT.conflict, status = 'error', detail = null } = {}) {
105
+ super(message);
106
+ this.name = 'MigrationError';
107
+ this.code = code;
108
+ this.exitCode = exitCode;
109
+ this.status = status;
110
+ this.detail = detail;
111
+ }
112
+ }
113
+
114
+ function fail(code, message, exitCode, detail) {
115
+ throw new MigrationError(code, message, { exitCode, detail });
116
+ }
117
+
118
+ // ---------------------------------------------------------------- utilities
119
+
120
+ export function sha256Hex(buf) {
121
+ return crypto.createHash('sha256').update(buf).digest('hex');
122
+ }
123
+
124
+ /** 分块同步 sha256(不把大文件整块读进内存)。 */
125
+ export function sha256FileSync(file) {
126
+ const hash = crypto.createHash('sha256');
127
+ const fd = fs.openSync(file, 'r');
128
+ try {
129
+ const chunk = Buffer.allocUnsafe(1 << 20);
130
+ let n = 0;
131
+ while ((n = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0) {
132
+ hash.update(chunk.subarray(0, n));
133
+ }
134
+ } finally {
135
+ fs.closeSync(fd);
136
+ }
137
+ return hash.digest('hex');
138
+ }
139
+
140
+ export function toRel(...parts) {
141
+ return parts.filter((x) => x !== undefined && x !== null && x !== '').join('/').split(path.sep).join('/').replace(/\/+/g, '/');
142
+ }
143
+
144
+ export function fromRel(root, rel) {
145
+ return path.join(root, ...String(rel).split('/'));
146
+ }
147
+
148
+ function jsonBytes(obj) {
149
+ return `${JSON.stringify(obj, null, 2)}\n`;
150
+ }
151
+
152
+ function writeAtomic(file, data) {
153
+ fs.mkdirSync(path.dirname(file), { recursive: true });
154
+ const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
155
+ fs.writeFileSync(tmp, data);
156
+ fs.renameSync(tmp, file);
157
+ }
158
+
159
+ function readJson(file) {
160
+ try {
161
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ function existsFile(file) {
168
+ try {
169
+ return fs.statSync(file).isFile();
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+
175
+ function isDir(dir) {
176
+ try {
177
+ return fs.statSync(dir).isDirectory();
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ function listDirNames(dir) {
184
+ try {
185
+ return fs.readdirSync(dir).sort();
186
+ } catch {
187
+ return [];
188
+ }
189
+ }
190
+
191
+ function walkFiles(root, relDir) {
192
+ const out = [];
193
+ const base = fromRel(root, relDir);
194
+ if (!isDir(base)) return out;
195
+ const stack = [''];
196
+ while (stack.length > 0) {
197
+ const sub = stack.pop();
198
+ const abs = sub === '' ? base : path.join(base, sub);
199
+ for (const name of listDirNames(abs)) {
200
+ const childAbs = path.join(abs, name);
201
+ let stat = null;
202
+ try {
203
+ stat = fs.statSync(childAbs);
204
+ } catch {
205
+ continue;
206
+ }
207
+ const childRel = sub === '' ? name : path.join(sub, name);
208
+ if (stat.isDirectory()) stack.push(childRel);
209
+ else if (stat.isFile()) out.push(toRel(relDir, childRel.split(path.sep).join('/')));
210
+ }
211
+ }
212
+ return out.sort();
213
+ }
214
+
215
+ function nowIso(now) {
216
+ return new Date(now).toISOString();
217
+ }
218
+
219
+ export function stampOf(now) {
220
+ return nowIso(now).replace(/[:.]/g, '-');
221
+ }
222
+
223
+ export function pathsOf(memoryRoot) {
224
+ const root = path.resolve(String(memoryRoot ?? ''));
225
+ const dirAbs = fromRel(root, OUTPUT_DIR_REL);
226
+ return {
227
+ root,
228
+ dirAbs,
229
+ file: (rel) => path.join(dirAbs, rel),
230
+ relPath: (rel) => toRel(OUTPUT_DIR_REL, rel),
231
+ };
232
+ }
233
+
234
+ /**
235
+ * 根相对写 JSON + 旁证 sidecar(用于 `.longlive/migrations` 下的 receipt/marker 等)。
236
+ * 与 writeHashed 的区别:rel 相对 memoryRoot,而不是相对 `.longlive/migrate-200`。
237
+ */
238
+ export function writeRootHashed(root, rel, obj, { now = new Date() } = {}) {
239
+ const base = path.resolve(String(root ?? ''));
240
+ const abs = fromRel(base, rel);
241
+ const bytes = Buffer.from(jsonBytes(obj), 'utf8');
242
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
243
+ writeAtomic(abs, bytes);
244
+ const sidecar = {
245
+ schema: SCHEMA.hash,
246
+ rel,
247
+ sha256: sha256Hex(bytes),
248
+ bytes: bytes.length,
249
+ writtenAt: nowIso(now),
250
+ };
251
+ writeAtomic(`${abs}.sha256`, jsonBytes(sidecar));
252
+ return { rel, abs, sha256: sidecar.sha256, bytes: sidecar.bytes, sidecar };
253
+ }
254
+
255
+ /**
256
+ * 写 JSON + 旁证 sidecar(`<file>.sha256`,内容 {schema, rel, sha256, bytes})。
257
+ * rel 相对 `.longlive/migrate-200`;旁证文件本身不进 manifest.files。
258
+ */
259
+ export function writeHashed(root, rel, obj, { now = new Date() } = {}) {
260
+ return writeRootHashed(root, toRel(OUTPUT_DIR_REL, rel), obj, { now });
261
+ }
262
+
263
+ /**
264
+ * 读 JSON 并用 sidecar 复算;返回 {obj, sha256, bytes, sidecar, sidecarOk}。
265
+ * sidecar 缺失/不符 → sidecarOk=false,调用方决定是否 fail-closed。
266
+ */
267
+ export function readHashed(root, rel) {
268
+ const p = pathsOf(root);
269
+ const abs = p.file(rel);
270
+ if (!existsFile(abs)) return null;
271
+ const bytes = fs.readFileSync(abs);
272
+ const sha256 = sha256Hex(bytes);
273
+ let obj = null;
274
+ try {
275
+ obj = JSON.parse(bytes.toString('utf8'));
276
+ } catch {
277
+ obj = null;
278
+ }
279
+ const sidecarRel = `${rel}.sha256`;
280
+ const sidecar = readJson(p.file(sidecarRel));
281
+ const sidecarOk = Boolean(sidecar && sidecar.sha256 === sha256 && Number(sidecar.bytes) === bytes.length);
282
+ return { rel, abs, obj, sha256, bytes: bytes.length, sidecar, sidecarOk };
283
+ }
284
+
285
+ // ---------------------------------------------------------------- scanning
286
+
287
+ const JOURNAL_MONTH_RE = /^\d{4}-\d{2}\.md$/;
288
+ const A1_DIRECT_PREFIX = 'conclusion-';
289
+
290
+ function frontmatterHasTag(text, tag) {
291
+ const match = text.match(/^---\s*\n([\s\S]*?)\n---/);
292
+ if (!match) return false;
293
+ const tags = match[1].match(/^tags:\s*\[([^\]]*)\]/m);
294
+ if (!tags) return false;
295
+ const list = tags[1].split(',').map((item) => item.trim().replace(/^['"]|['"]$/g, ''));
296
+ return list.includes(tag);
297
+ }
298
+
299
+ /** 旧版直写卡:topics/conclusion-*.md 且 frontmatter tags 含 auto-conclusion(A1 语义)。 */
300
+ export function listLegacyDirectCards(root) {
301
+ const out = [];
302
+ for (const name of listDirNames(fromRel(root, 'topics'))) {
303
+ if (!name.startsWith(A1_DIRECT_PREFIX) || !name.endsWith('.md')) continue;
304
+ const rel = toRel('topics', name);
305
+ const abs = fromRel(root, rel);
306
+ let text = '';
307
+ try {
308
+ text = fs.readFileSync(abs, 'utf8');
309
+ } catch {
310
+ continue;
311
+ }
312
+ if (!frontmatterHasTag(text, 'auto-conclusion')) continue;
313
+ out.push({ rel, name });
314
+ }
315
+ return out;
316
+ }
317
+
318
+ export function listAutoCards(root) {
319
+ const dirRel = 'topics/auto';
320
+ return listDirNames(fromRel(root, dirRel))
321
+ .filter((name) => name.endsWith('.md'))
322
+ .map((name) => ({ rel: toRel(dirRel, name), name }));
323
+ }
324
+
325
+ export function listJournalMonths(root) {
326
+ const dirRel = 'journal';
327
+ return listDirNames(fromRel(root, dirRel))
328
+ .filter((name) => JOURNAL_MONTH_RE.test(name))
329
+ .map((name) => ({ rel: toRel(dirRel, name), name }));
330
+ }
331
+
332
+ function destBaseForAuto(name) {
333
+ return toRel('.longlive/staging/auto-cards', name);
334
+ }
335
+
336
+ function destBaseForDirect(name) {
337
+ return toRel('.longlive/staging/auto-cards/legacy-1.8.0', name);
338
+ }
339
+
340
+ /**
341
+ * 目标存在时:同 sha → skip-same(幂等重跑可恢复);不同 → 确定性 duplicate 后缀;
342
+ * 仍冲突 → fail-closed(不覆盖任何既有卡)。
343
+ */
344
+ function resolveDest(root, baseRel, sourceSha256) {
345
+ const p = fromRel(root, baseRel);
346
+ if (!fs.existsSync(p)) return { dest: baseRel, action: 'move', destSha256: null };
347
+ if (existsFile(p)) {
348
+ const destSha256 = sha256FileSync(p);
349
+ if (destSha256 === sourceSha256) return { dest: baseRel, action: 'skip-same', destSha256 };
350
+ const ext = path.extname(baseRel);
351
+ const stem = baseRel.slice(0, -ext.length);
352
+ const dupRel = `${stem}.duplicate-${sourceSha256.slice(0, 8)}${ext}`;
353
+ const dupAbs = fromRel(root, dupRel);
354
+ if (!fs.existsSync(dupAbs)) return { dest: dupRel, action: 'move', destSha256: null };
355
+ if (existsFile(dupAbs)) {
356
+ const dupSha = sha256FileSync(dupAbs);
357
+ if (dupSha === sourceSha256) return { dest: dupRel, action: 'skip-same', destSha256: dupSha };
358
+ }
359
+ fail(
360
+ CODE.conflict,
361
+ `迁移目标冲突:${baseRel} 已存在且内容不同(source sha=${sourceSha256.slice(0, 12)}),拒绝覆盖`,
362
+ EXIT.conflict,
363
+ { baseRel, sourceSha256 },
364
+ );
365
+ }
366
+ return { dest: baseRel, action: 'move', destSha256: null };
367
+ }
368
+
369
+ // ---------------------------------------------------------------- plan
370
+
371
+ function collectDir(self, relDir) {
372
+ if (isDir(fromRel(self.root, relDir))) self.dirFlags[relDir] = true;
373
+ }
374
+
375
+ function makePlan(memoryRoot, now) {
376
+ const root = path.resolve(String(memoryRoot));
377
+ if (!isDir(root)) {
378
+ fail(CODE.rootMissing, `memoryRoot 不存在或不是目录:${root}`, EXIT.usage, { memoryRoot: root });
379
+ }
380
+ const dirFlags = {};
381
+ for (const rel of ['.longlive', 'topics', 'journal', 'procedures', 'handover']) collectDir({ root, dirFlags }, rel);
382
+
383
+ const changes = [];
384
+ for (const card of listAutoCards(root)) {
385
+ const sourceSha256 = sha256FileSync(fromRel(root, card.rel));
386
+ const bytes = fs.statSync(fromRel(root, card.rel)).size;
387
+ const dest = resolveDest(root, destBaseForAuto(card.name), sourceSha256);
388
+ changes.push({
389
+ id: `a1-auto:${card.rel}`,
390
+ kind: 'a1-auto-card',
391
+ action: dest.action,
392
+ source: card.rel,
393
+ dest: dest.dest,
394
+ sourceSha256,
395
+ destSha256: dest.destSha256,
396
+ bytes,
397
+ note: dest.action === 'skip-same' ? '目标已存在且 sha 相同(上次迁移的半成品可恢复)' : 'topics/auto 旧卡移入 .longlive/staging/auto-cards',
398
+ });
399
+ }
400
+ for (const card of listLegacyDirectCards(root)) {
401
+ const sourceSha256 = sha256FileSync(fromRel(root, card.rel));
402
+ const bytes = fs.statSync(fromRel(root, card.rel)).size;
403
+ const dest = resolveDest(root, destBaseForDirect(card.name), sourceSha256);
404
+ changes.push({
405
+ id: `a1-direct:${card.rel}`,
406
+ kind: 'a1-direct-card',
407
+ action: dest.action,
408
+ source: card.rel,
409
+ dest: dest.dest,
410
+ sourceSha256,
411
+ destSha256: dest.destSha256,
412
+ bytes,
413
+ note: dest.action === 'skip-same' ? '目标已存在且 sha 相同(上次迁移的半成品可恢复)' : '1.8.0 直写卡移入 .longlive/staging/auto-cards/legacy-1.8.0',
414
+ });
415
+ }
416
+
417
+ const deferred = listJournalMonths(root).map((month) => {
418
+ const abs = fromRel(root, month.rel);
419
+ const stat = fs.statSync(abs);
420
+ return {
421
+ id: `journal-month:${month.rel}`,
422
+ kind: 'journal-month-to-day',
423
+ owner: 'D',
424
+ action: 'split',
425
+ source: month.rel,
426
+ sourceSha256: sha256FileSync(abs),
427
+ bytes: stat.size,
428
+ note: '月文件按行时间戳拆成 journal/YYYY-MM-DD.md(D 批 G8 月→日迁移;本脚本不执行、不重写)',
429
+ };
430
+ });
431
+
432
+ const plan = {
433
+ schema: SCHEMA.plan,
434
+ manifestSchema: SCHEMA.manifest,
435
+ generatedAt: nowIso(now),
436
+ fromVersion: FROM_VERSION,
437
+ toVersion: TO_VERSION,
438
+ memoryRoot: root,
439
+ memoryRootExists: true,
440
+ dirExists: dirFlags,
441
+ writes: [],
442
+ artifacts: [REL.plan, REL.backup, REL.manifest],
443
+ snapshot: {
444
+ required: true,
445
+ beforeApply: true,
446
+ target: toRel(OUTPUT_DIR_REL, REL.backup),
447
+ scope: '迁移影响面整目录快照(变更源所在目录 + .longlive/migrations 既有文件;不复制 memoryRoot 全量)',
448
+ },
449
+ config: {
450
+ rewrite: false,
451
+ preserveOldKeys: true,
452
+ newKeysOptional: true,
453
+ note: '旧键全保留、新键可选;旧数据读取器 version-tolerant,不重写(DESIGN §15 L216)',
454
+ },
455
+ changes,
456
+ deferred,
457
+ counts: {
458
+ changes: changes.length,
459
+ moves: changes.filter((item) => item.action === 'move').length,
460
+ skipSame: changes.filter((item) => item.action === 'skip-same').length,
461
+ deferred: deferred.length,
462
+ legacyCards: changes.length,
463
+ journalMonthFiles: deferred.length,
464
+ },
465
+ fingerprint: null,
466
+ };
467
+ const fingerprintBody = {
468
+ schema: plan.schema,
469
+ fromVersion: plan.fromVersion,
470
+ toVersion: plan.toVersion,
471
+ memoryRoot: plan.memoryRoot,
472
+ changes: plan.changes,
473
+ deferred: plan.deferred,
474
+ };
475
+ plan.fingerprint = `sha256:${sha256Hex(Buffer.from(JSON.stringify(fingerprintBody), 'utf8'))}`;
476
+ return plan;
477
+ }
478
+
479
+ /** 只读 plan(dry-run/plan 都用它;生成 plan 不落盘)。 */
480
+ export function buildPlan({ memoryRoot, now = new Date() } = {}) {
481
+ const plan = makePlan(memoryRoot, now);
482
+ const bytes = Buffer.from(jsonBytes(plan), 'utf8');
483
+ return {
484
+ ok: true,
485
+ plan,
486
+ fingerprint: plan.fingerprint,
487
+ planSha256: sha256Hex(bytes),
488
+ planBytes: bytes.length,
489
+ };
490
+ }
491
+
492
+ function shortOf(fingerprint) {
493
+ return String(fingerprint ?? '').replace(/^sha256:/, '').slice(0, 8);
494
+ }
495
+
496
+ function planFreshness(root, now, { stage = 'apply' } = {}) {
497
+ const current = readHashed(root, REL.plan);
498
+ if (!current || !current.obj) {
499
+ fail(CODE.planMissing, '未找到 plan.json:先执行 --mode plan --write', EXIT.approvalRequired, { stage });
500
+ }
501
+ if (!current.sidecarOk) {
502
+ fail(CODE.artifactTampered, 'plan.json 与 plan.json.sha256 不符(可能被改过)', EXIT.stale, { rel: REL.plan });
503
+ }
504
+ const fresh = makePlan(root, now);
505
+ if (current.obj.fingerprint !== fresh.fingerprint) {
506
+ fail(
507
+ CODE.planStale,
508
+ `plan 已过期:memoryRoot 内容在 plan 之后发生变更(plan=${shortOf(current.obj.fingerprint)},now=${shortOf(fresh.fingerprint)});请重新 --mode plan --write`,
509
+ EXIT.stale,
510
+ { planFingerprint: current.obj.fingerprint, currentFingerprint: fresh.fingerprint },
511
+ );
512
+ }
513
+ return { plan: current.obj, sha256: current.sha256, bytes: current.bytes };
514
+ }
515
+
516
+ // ---------------------------------------------------------------- state
517
+
518
+ export function readState(root) {
519
+ return readHashed(root, REL.state);
520
+ }
521
+
522
+ function writeState(root, state, now) {
523
+ state.updatedAt = nowIso(now);
524
+ return writeHashed(root, REL.state, state, { now });
525
+ }
526
+
527
+ function baseState({ now, planSha256, fingerprint }) {
528
+ return {
529
+ schema: SCHEMA.state,
530
+ status: 'planned',
531
+ planSha256,
532
+ planFingerprint: fingerprint,
533
+ backupSha256: null,
534
+ manifestSha256: null,
535
+ requiredApprovals: [...REQUIRED_APPROVALS],
536
+ approvals: {},
537
+ counts: null,
538
+ createdAt: nowIso(now),
539
+ updatedAt: nowIso(now),
540
+ history: [],
541
+ };
542
+ }
543
+
544
+ function pushHistory(state, now, event, detail = null) {
545
+ state.history = Array.isArray(state.history) ? state.history : [];
546
+ state.history.push({ at: nowIso(now), event, detail });
547
+ return state;
548
+ }
549
+
550
+ // ---------------------------------------------------------------- approve ledger
551
+
552
+ export function readApproveLedger(root) {
553
+ return readHashed(root, REL.approve);
554
+ }
555
+
556
+ function emptyLedger() {
557
+ return { schema: SCHEMA.approve, planFingerprint: null, planSha256: null, backupSha256: null, approvals: [], aggregateSha256: null };
558
+ }
559
+
560
+ function normalizeConfirm(value) {
561
+ return String(value ?? '').trim().toLowerCase().replace(/^sha256:/, '').replace(/^0x/, '');
562
+ }
563
+
564
+ function confirmMatches(confirm, expectedSha256) {
565
+ const c = normalizeConfirm(confirm);
566
+ const e = normalizeConfirm(expectedSha256);
567
+ return c.length >= 8 && e.startsWith(c);
568
+ }
569
+
570
+ function aggregateOf(approvals) {
571
+ return sha256Hex(Buffer.from(JSON.stringify(approvals), 'utf8'));
572
+ }
573
+
574
+ function writeLedger(root, ledger, now) {
575
+ ledger.aggregateSha256 = aggregateOf(ledger.approvals);
576
+ return writeHashed(root, REL.approve, ledger, { now });
577
+ }
578
+
579
+ function approvalEntry({ stage, now, by, confirm, fingerprint, planSha256, backupSha256, stdinIsTTY, env }) {
580
+ return {
581
+ stage,
582
+ at: nowIso(now),
583
+ by: String(by || os.userInfo().username || 'unknown'),
584
+ confirm: normalizeConfirm(confirm),
585
+ planFingerprint: fingerprint,
586
+ planSha256,
587
+ backupSha256: stage === 'apply' ? backupSha256 : null,
588
+ unattended: stdinIsTTY !== true,
589
+ stdinIsTTY: stdinIsTTY === true,
590
+ node: process.version,
591
+ host: os.hostname(),
592
+ envMemoryRoot: env?.HG_MEMORY_ROOT ? 'set' : 'unset',
593
+ nonce: crypto.randomBytes(8).toString('hex'),
594
+ };
595
+ }
596
+
597
+ /** 冷层迁移二次 approve 门(供 retention 冷档门/未来冷 job 复用):两次都齐才算 approved。 */
598
+ export function isColdMoveApproved({ memoryRoot, checkFresh = false, now = new Date() } = {}) {
599
+ const root = path.resolve(String(memoryRoot ?? ''));
600
+ if (!isDir(root)) return { approved: false, code: CODE.rootMissing, reason: 'memory-root-missing' };
601
+ const current = readApproveLedger(root);
602
+ // B7a P1-1:账本必须带有效旁证(approve.json.sha256 与字节一致);否则手工追加的
603
+ // apply 条目即可绕过二次 approve 门——本函数同时是 apply 与 retention 冷档门的复用点。
604
+ if (current?.obj && !current.sidecarOk) {
605
+ return { approved: false, code: CODE.artifactTampered, reason: 'approve-ledger-sidecar-mismatch' };
606
+ }
607
+ const ledger = current?.obj ?? null;
608
+ if (!ledger || !Array.isArray(ledger.approvals)) {
609
+ return { approved: false, code: CODE.approveRequired, reason: 'approve-ledger-missing' };
610
+ }
611
+ const planEntry = ledger.approvals.find((item) => item.stage === 'plan');
612
+ const applyEntry = ledger.approvals.find((item) => item.stage === 'apply');
613
+ if (!planEntry) return { approved: false, code: CODE.approveRequired, reason: 'plan-approval-missing' };
614
+ if (!applyEntry) return { approved: false, code: CODE.approveRequired, reason: 'second-approval-missing' };
615
+ if (planEntry.planFingerprint !== applyEntry.planFingerprint) {
616
+ return { approved: false, code: CODE.approveOrder, reason: 'fingerprint-mismatch' };
617
+ }
618
+ if (checkFresh) {
619
+ try {
620
+ const plan = planFreshness(root, now);
621
+ if (plan.plan.fingerprint !== planEntry.planFingerprint) {
622
+ return { approved: false, code: CODE.planStale, reason: 'plan-stale' };
623
+ }
624
+ if (plan.sha256 !== planEntry.planSha256) {
625
+ return { approved: false, code: CODE.artifactTampered, reason: 'plan-sha-mismatch' };
626
+ }
627
+ } catch (error) {
628
+ return { approved: false, code: error.code ?? CODE.planStale, reason: 'plan-not-fresh' };
629
+ }
630
+ }
631
+ return { approved: true, code: null, reason: null, ledger: current.obj, ledgerSha256: current.sha256 };
632
+ }
633
+
634
+ // ---------------------------------------------------------------- approve
635
+
636
+ export function approveStage({ memoryRoot, stage, confirm, by, now = new Date(), stdinIsTTY = null, env = process.env } = {}) {
637
+ const root = path.resolve(String(memoryRoot ?? ''));
638
+ if (!APPROVAL_STAGES.includes(stage)) {
639
+ fail(CODE.usage, `--approve-stage 必须是 ${APPROVAL_STAGES.join('|')}`, EXIT.usage, { stage });
640
+ }
641
+ const currentPlan = planFreshness(root, now, { stage });
642
+ const stateWrap = readState(root);
643
+ if (!stateWrap || !stateWrap.obj) {
644
+ fail(CODE.planMissing, '未找到 state.json:先执行 --mode plan --write', EXIT.approvalRequired, { stage });
645
+ }
646
+ const state = stateWrap.obj;
647
+ const ledgerWrap = readApproveLedger(root);
648
+ const ledger = ledgerWrap?.obj ?? emptyLedger();
649
+ if (!Array.isArray(ledger.approvals)) ledger.approvals = [];
650
+ const existing = ledger.approvals.find((item) => item.stage === stage);
651
+
652
+ if (stage === 'plan') {
653
+ const expected = shortOf(currentPlan.plan.fingerprint);
654
+ if (!confirmMatches(confirm, currentPlan.plan.fingerprint) && !confirmMatches(confirm, currentPlan.sha256)) {
655
+ fail(
656
+ CODE.approveConfirm,
657
+ `第一次 approve 需要二次确认值:--confirm ${expected}(plan fingerprint 前 8 位;也接受 plan.json 的 sha256)`,
658
+ EXIT.approvalRequired,
659
+ { expected, planFingerprint: currentPlan.plan.fingerprint, planSha256: currentPlan.sha256 },
660
+ );
661
+ }
662
+ if (existing) {
663
+ if (existing.planFingerprint === currentPlan.plan.fingerprint && existing.planSha256 === currentPlan.sha256) {
664
+ return { ok: true, status: 'ok', stage, alreadyApproved: true, ledger: ledger, ledgerSha256: ledgerWrap.sha256 };
665
+ }
666
+ fail(CODE.approveOrder, '已存在不同版本的 plan approve,拒绝覆盖(先 --mode plan --write --force 重来)', EXIT.conflict);
667
+ }
668
+ ledger.planFingerprint = currentPlan.plan.fingerprint;
669
+ ledger.planSha256 = currentPlan.sha256;
670
+ ledger.approvals.push(
671
+ approvalEntry({
672
+ stage,
673
+ now,
674
+ by,
675
+ confirm,
676
+ fingerprint: currentPlan.plan.fingerprint,
677
+ planSha256: currentPlan.sha256,
678
+ stdinIsTTY,
679
+ env,
680
+ }),
681
+ );
682
+ state.approvals = Object.fromEntries(ledger.approvals.map((item) => [item.stage, { at: item.at, by: item.by, confirm: item.confirm }]));
683
+ pushHistory(state, now, 'approve:plan', { planFingerprint: currentPlan.plan.fingerprint, by: ledger.approvals.at(-1).by });
684
+ const written = writeLedger(root, ledger, now);
685
+ writeState(root, state, now);
686
+ return {
687
+ ok: true,
688
+ status: 'ok',
689
+ stage,
690
+ approved: true,
691
+ requiredApprovals: [...REQUIRED_APPROVALS],
692
+ next: '运行 --mode apply 生成备份快照并请求第二次 approve',
693
+ ledgerSha256: written.sha256,
694
+ aggregateSha256: ledger.aggregateSha256,
695
+ };
696
+ }
697
+
698
+ // stage === 'apply':必须已有 plan approve,且备份完好
699
+ const planEntry = ledger.approvals.find((item) => item.stage === 'plan');
700
+ if (!planEntry) {
701
+ fail(
702
+ CODE.approveOrder,
703
+ '第二次 approve 之前必须先完成第一次 approve:--mode approve --approve-stage plan --confirm <plan指纹前8位>',
704
+ EXIT.approvalRequired,
705
+ { stage },
706
+ );
707
+ }
708
+ if (state.status !== 'backup-ready') {
709
+ fail(
710
+ CODE.approveRequired,
711
+ `apply 阶段 approve 需要先有备份(state.status=${state.status}):先运行 --mode apply 生成备份并拿到 confirm 值`,
712
+ EXIT.approvalRequired,
713
+ { status: state.status },
714
+ );
715
+ }
716
+ const backup = readHashed(root, REL.backup);
717
+ if (!backup || !backup.obj || !backup.sidecarOk) {
718
+ fail(CODE.backupMissing, '备份文件缺失或被篡改(backup.json / backup.json.sha256)', EXIT.backupMismatch);
719
+ }
720
+ const integrity = verifyBackupIntegrity(root, backup.obj);
721
+ if (!integrity.ok) {
722
+ fail(CODE.backupMismatch, `备份自检失败:${integrity.bad.length} 个文件 sha/bytes 不符`, EXIT.backupMismatch, integrity);
723
+ }
724
+ if (backup.obj.planFingerprint !== planEntry.planFingerprint) {
725
+ fail(CODE.planStale, '备份对应的 plan 与已 approve 的 plan 不一致(plan 发生过变更)', EXIT.stale);
726
+ }
727
+ const expected = String(backup.sha256 ?? '').slice(0, 8);
728
+ if (!confirmMatches(confirm, backup.sha256)) {
729
+ fail(
730
+ CODE.approveConfirm,
731
+ `第二次 approve 需要二次确认值:--confirm ${expected}(backup.json 的 sha256 前 8 位)`,
732
+ EXIT.approvalRequired,
733
+ { expected, backupSha256: backup.sha256 },
734
+ );
735
+ }
736
+ if (existing) {
737
+ if (existing.backupSha256 === backup.sha256 && existing.planFingerprint === planEntry.planFingerprint) {
738
+ return { ok: true, status: 'ok', stage, alreadyApproved: true, ledger, ledgerSha256: ledgerWrap.sha256 };
739
+ }
740
+ fail(CODE.approveOrder, '已存在不同备份的 apply approve,拒绝覆盖(重新备份后再 approve)', EXIT.conflict);
741
+ }
742
+ ledger.backupSha256 = backup.sha256;
743
+ ledger.approvals.push(
744
+ approvalEntry({
745
+ stage,
746
+ now,
747
+ by,
748
+ confirm,
749
+ fingerprint: planEntry.planFingerprint,
750
+ planSha256: planEntry.planSha256,
751
+ backupSha256: backup.sha256,
752
+ stdinIsTTY,
753
+ env,
754
+ }),
755
+ );
756
+ state.approvals = Object.fromEntries(ledger.approvals.map((item) => [item.stage, { at: item.at, by: item.by, confirm: item.confirm }]));
757
+ pushHistory(state, now, 'approve:apply', { backupSha256: backup.sha256, by: ledger.approvals.at(-1).by });
758
+ const written = writeLedger(root, ledger, now);
759
+ writeState(root, state, now);
760
+ return {
761
+ ok: true,
762
+ status: 'ok',
763
+ stage,
764
+ approved: true,
765
+ requiredApprovals: [...REQUIRED_APPROVALS],
766
+ next: '二次 approve 齐备:运行 --mode apply 执行迁移并生成 manifest.json',
767
+ ledgerSha256: written.sha256,
768
+ aggregateSha256: ledger.aggregateSha256,
769
+ };
770
+ }
771
+
772
+ // ---------------------------------------------------------------- backup
773
+
774
+ function backupScope(root, plan) {
775
+ const dirs = new Set();
776
+ const files = new Set();
777
+ for (const change of plan.changes || []) {
778
+ const dir = path.posix.dirname(change.source);
779
+ if (dir === '.') files.add(change.source);
780
+ else dirs.add(dir);
781
+ }
782
+ if (isDir(fromRel(root, '.longlive/migrations'))) dirs.add('.longlive/migrations');
783
+ // 去掉被上层目录覆盖的嵌套目录(例如 topics/auto 已被 topics 包含),避免重复备份/重复 bytes。
784
+ const sorted = [...dirs].sort();
785
+ const pruned = sorted.filter((dir) => !sorted.some((other) => other !== dir && dir.startsWith(`${other}/`)));
786
+ return { dirs: pruned, files: [...files].sort() };
787
+ }
788
+
789
+ export function verifyBackupIntegrity(root, backup) {
790
+ const bad = [];
791
+ const files = Array.isArray(backup?.files) ? backup.files : [];
792
+ for (const entry of files) {
793
+ const abs = fromRel(root, entry.backupRel);
794
+ if (!existsFile(abs)) {
795
+ bad.push({ rel: entry.backupRel, reason: 'missing' });
796
+ continue;
797
+ }
798
+ const bytes = fs.statSync(abs).size;
799
+ if (Number(entry.bytes) !== bytes) bad.push({ rel: entry.backupRel, reason: 'bytes-mismatch' });
800
+ else if (sha256FileSync(abs) !== entry.sha256) bad.push({ rel: entry.backupRel, reason: 'sha256-mismatch' });
801
+ }
802
+ return { ok: bad.length === 0, files: files.length, bad };
803
+ }
804
+
805
+ export function runBackup({ memoryRoot, now = new Date() } = {}) {
806
+ const root = path.resolve(String(memoryRoot ?? ''));
807
+ const fresh = planFreshness(root, now, { stage: 'backup' });
808
+ const stateWrap = readState(root);
809
+ if (!stateWrap || !stateWrap.obj) {
810
+ fail(CODE.planMissing, '未找到 state.json:先执行 --mode plan --write', EXIT.approvalRequired);
811
+ }
812
+ const state = stateWrap.obj;
813
+ const ledgerWrap = readApproveLedger(root);
814
+ const ledger = ledgerWrap?.obj ?? null;
815
+ const planEntry = ledger?.approvals?.find((item) => item.stage === 'plan');
816
+ if (!planEntry) {
817
+ fail(
818
+ CODE.approveRequired,
819
+ '备份阶段之前必须先完成第一次 approve:--mode approve --approve-stage plan --confirm <plan指纹前8位>',
820
+ EXIT.approvalRequired,
821
+ { stage: 'plan' },
822
+ );
823
+ }
824
+ if (planEntry.planFingerprint !== fresh.plan.fingerprint) {
825
+ fail(CODE.planStale, 'approve 绑定的 plan 与当前 memoryRoot 不一致', EXIT.stale);
826
+ }
827
+ if (state.status === 'backup-ready') {
828
+ const existing = readHashed(root, REL.backup);
829
+ if (existing?.obj) {
830
+ const integrity = verifyBackupIntegrity(root, existing.obj);
831
+ if (integrity.ok) {
832
+ return {
833
+ ok: true,
834
+ status: 'approval-required',
835
+ stage: 'apply',
836
+ backupSha256: existing.sha256,
837
+ confirm: String(existing.sha256).slice(0, 8),
838
+ stateStatus: state.status,
839
+ message: '备份已就绪,等待第二次 approve',
840
+ };
841
+ }
842
+ }
843
+ }
844
+ if (state.status !== 'planned' && state.status !== 'backup-ready') {
845
+ fail(CODE.conflict, `当前 state.status=${state.status},不能重新备份(先 rollback 或重置)`, EXIT.conflict);
846
+ }
847
+
848
+ const stamp = stampOf(now);
849
+ const backupRootRel = toRel(OUTPUT_DIR_REL, 'backup', stamp);
850
+ const scope = backupScope(root, fresh.plan);
851
+ const files = [];
852
+ const pushCopy = (rel) => {
853
+ const abs = fromRel(root, rel);
854
+ if (!existsFile(abs)) return;
855
+ const backupRel = toRel(backupRootRel, rel);
856
+ const backupAbs = fromRel(root, backupRel);
857
+ fs.mkdirSync(path.dirname(backupAbs), { recursive: true });
858
+ fs.copyFileSync(abs, backupAbs);
859
+ const stat = fs.statSync(abs);
860
+ try {
861
+ fs.utimesSync(backupAbs, stat.atime, stat.mtime);
862
+ } catch {
863
+ /* utime 失败不影响 sha 校验 */
864
+ }
865
+ const sha256 = sha256FileSync(backupAbs);
866
+ if (sha256 !== sha256FileSync(abs)) {
867
+ fail(CODE.backupMismatch, `备份读回 sha 不符:${rel}`, EXIT.backupMismatch, { rel, backupRel });
868
+ }
869
+ files.push({ rel, backupRel, bytes: fs.statSync(backupAbs).size, sha256 });
870
+ };
871
+ for (const dir of scope.dirs) for (const rel of walkFiles(root, dir)) pushCopy(rel);
872
+ for (const rel of scope.files) pushCopy(rel);
873
+
874
+ const backup = {
875
+ schema: SCHEMA.backup,
876
+ generatedAt: nowIso(now),
877
+ planFingerprint: fresh.plan.fingerprint,
878
+ planSha256: fresh.sha256,
879
+ memoryRoot: root,
880
+ root: backupRootRel,
881
+ scope: { dirs: scope.dirs, files: scope.files, note: '迁移影响面快照(不是 memoryRoot 全量;避免把索引/事件库整库复制)' },
882
+ files,
883
+ totalBytes: files.reduce((sum, item) => sum + item.bytes, 0),
884
+ counts: { files: files.length, totalBytes: files.reduce((sum, item) => sum + item.bytes, 0) },
885
+ note: '备份快照只用于失败回滚;apply 成功后原件不删(迁移=移动,不是删除)',
886
+ };
887
+ const written = writeHashed(root, REL.backup, backup, { now });
888
+ const integrity = verifyBackupIntegrity(root, backup);
889
+ if (!integrity.ok) {
890
+ fail(CODE.backupMismatch, `备份写后自检失败:${integrity.bad.length} 个文件`, EXIT.backupMismatch, integrity);
891
+ }
892
+ state.status = 'backup-ready';
893
+ state.backupSha256 = written.sha256;
894
+ state.counts = backup.counts;
895
+ pushHistory(state, now, 'backup', { backupSha256: written.sha256, files: backup.counts.files });
896
+ writeState(root, state, now);
897
+ return {
898
+ ok: true,
899
+ status: 'approval-required',
900
+ stage: 'apply',
901
+ backupSha256: written.sha256,
902
+ confirm: String(written.sha256).slice(0, 8),
903
+ backupRel: toRel(OUTPUT_DIR_REL, REL.backup),
904
+ counts: backup.counts,
905
+ message: '备份快照已完成并自检;缺第二次 approve,数据未移动(fail-closed)',
906
+ };
907
+ }
908
+
909
+ // ---------------------------------------------------------------- apply
910
+
911
+ function writeA1Receipt(root, { now, planFingerprint, moved, recovered, items }) {
912
+ const stamp = stampOf(now);
913
+ const receiptRel = toRel('.longlive/migrations', `a1-legacy-migrate-200-${stamp}.json`);
914
+ const receipt = {
915
+ schema: 'a1-legacy-migration/v1',
916
+ generator: MODULE,
917
+ generatedAt: nowIso(now),
918
+ memoryRoot: root,
919
+ dryRun: false,
920
+ moved,
921
+ recovered,
922
+ skipped: 0,
923
+ planFingerprint,
924
+ items,
925
+ totalLegacy: moved + recovered,
926
+ };
927
+ const written = writeRootHashed(root, receiptRel, receipt, { now });
928
+ const marker = {
929
+ schema: 'a1-legacy-marker/v1',
930
+ migratedAt: nowIso(now),
931
+ memoryRoot: root,
932
+ receiptPath: fromRel(root, receiptRel),
933
+ receiptSha256: written.sha256,
934
+ moved,
935
+ recovered,
936
+ totalLegacy: moved + recovered,
937
+ by: 'migrate-200',
938
+ };
939
+ const markerWritten = writeRootHashed(root, '.longlive/migrations/a1-legacy.done', marker, { now });
940
+ return { receiptRel, receiptSha256: written.sha256, markerRel: '.longlive/migrations/a1-legacy.done', markerSha256: markerWritten.sha256 };
941
+ }
942
+
943
+ function applyChanges(root, plan, now) {
944
+ const items = [];
945
+ let moved = 0;
946
+ let recovered = 0;
947
+ for (const change of plan.changes || []) {
948
+ const sourceAbs = fromRel(root, change.source);
949
+ if (!existsFile(sourceAbs)) {
950
+ fail(CODE.applySourceMismatch, `迁移源文件不存在:${change.source}`, EXIT.conflict, { source: change.source });
951
+ }
952
+ const sourceSha256 = sha256FileSync(sourceAbs);
953
+ if (sourceSha256 !== change.sourceSha256) {
954
+ fail(
955
+ CODE.applySourceMismatch,
956
+ `迁移源文件在 plan 之后发生变化(sha 不符):${change.source}`,
957
+ EXIT.stale,
958
+ { source: change.source, expectedSha256: change.sourceSha256, actualSha256: sourceSha256 },
959
+ );
960
+ }
961
+ const destAbs = fromRel(root, change.dest);
962
+ if (change.action === 'skip-same') {
963
+ if (!existsFile(destAbs) || sha256FileSync(destAbs) !== change.sourceSha256) {
964
+ fail(CODE.applySourceMismatch, `skip-same 目标状态异常:${change.dest}`, EXIT.conflict, { dest: change.dest });
965
+ }
966
+ recovered += 1;
967
+ items.push({ ...change, action: 'skip-same', movedAt: nowIso(now) });
968
+ continue;
969
+ }
970
+ fs.mkdirSync(path.dirname(destAbs), { recursive: true });
971
+ fs.renameSync(sourceAbs, destAbs);
972
+ const destSha256 = sha256FileSync(destAbs);
973
+ if (destSha256 !== change.sourceSha256) {
974
+ fail(CODE.applySourceMismatch, `移动后目标 sha 不符:${change.dest}`, EXIT.conflict, { dest: change.dest });
975
+ }
976
+ moved += 1;
977
+ items.push({ ...change, action: 'move', destSha256, movedAt: nowIso(now) });
978
+ }
979
+ // 只清理变空的旧目录(卡本身已移动,不删内容)。
980
+ for (const relDir of ['topics/auto']) {
981
+ const dir = fromRel(root, relDir);
982
+ try {
983
+ if (isDir(dir) && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
984
+ } catch {
985
+ /* leave */
986
+ }
987
+ }
988
+ return { items, moved, recovered };
989
+ }
990
+
991
+ function listManifestFiles(root, { planSha256, backup, changes, receipts, now }) {
992
+ const candidates = [];
993
+ // artifact 列在 OUTPUT_DIR_REL 下,rel 必须转成根相对(与 L4 的 path.join(memoryRoot, rel) 对齐)。
994
+ for (const name of [REL.plan, REL.planHash, REL.request, REL.requestHash, REL.backup, REL.backupHash, REL.approve, REL.approveHash, REL.state, REL.pending]) {
995
+ candidates.push({ rel: toRel(OUTPUT_DIR_REL, name), role: 'artifact' });
996
+ }
997
+ for (const entry of backup?.files ?? []) candidates.push({ rel: entry.backupRel, role: 'backup' });
998
+ for (const change of changes ?? []) {
999
+ if (change.action === 'skip-same' || existsFile(fromRel(root, change.dest))) candidates.push({ rel: change.dest, role: 'migrated' });
1000
+ }
1001
+ for (const receipt of receipts ?? []) {
1002
+ candidates.push({ rel: receipt.receiptRel, role: 'receipt' });
1003
+ candidates.push({ rel: `${receipt.receiptRel}.sha256`, role: 'receipt' });
1004
+ candidates.push({ rel: receipt.markerRel, role: 'receipt' });
1005
+ candidates.push({ rel: `${receipt.markerRel}.sha256`, role: 'receipt' });
1006
+ }
1007
+ const seen = new Set();
1008
+ const out = [];
1009
+ for (const entry of candidates) {
1010
+ if (seen.has(entry.rel)) continue;
1011
+ const abs = fromRel(root, entry.rel);
1012
+ if (!existsFile(abs)) continue;
1013
+ seen.add(entry.rel);
1014
+ out.push({ rel: entry.rel, bytes: fs.statSync(abs).size, sha256: sha256FileSync(abs), role: entry.role });
1015
+ }
1016
+ out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
1017
+ return out;
1018
+ }
1019
+
1020
+ export function applyMigration({ memoryRoot, now = new Date() } = {}) {
1021
+ const root = path.resolve(String(memoryRoot ?? ''));
1022
+ const stateWrap = readState(root);
1023
+ if (!stateWrap || !stateWrap.obj) {
1024
+ fail(CODE.approveRequired, '未找到 state.json:先 --mode plan --write 并完成第一次 approve', EXIT.approvalRequired);
1025
+ }
1026
+ if (stateWrap.obj.status === 'applied') {
1027
+ const verify = verifyManifest({ memoryRoot: root });
1028
+ if (verify.ok) {
1029
+ return {
1030
+ ok: true,
1031
+ status: 'ok',
1032
+ alreadyApplied: true,
1033
+ manifestRel: toRel(OUTPUT_DIR_REL, REL.manifest),
1034
+ manifestSha256: verify.manifestSha256,
1035
+ counts: verify.counts,
1036
+ message: '迁移已 applied 且 manifest 复算通过,幂等跳过',
1037
+ };
1038
+ }
1039
+ fail(CODE.verifyFail, `已 applied 但 manifest 复算失败:${verify.bad.length} 项`, EXIT.verifyFail, verify);
1040
+ }
1041
+ const planWrap = readHashed(root, REL.plan);
1042
+ if (!planWrap || !planWrap.obj) {
1043
+ fail(CODE.planMissing, '未找到 plan.json:先 --mode plan --write', EXIT.approvalRequired);
1044
+ }
1045
+ const fresh = planFreshness(root, now, { stage: 'apply' });
1046
+ const state = stateWrap.obj;
1047
+ if (state.status === 'planned') {
1048
+ return runBackup({ memoryRoot: root, now });
1049
+ }
1050
+ const ledgerWrap = readApproveLedger(root);
1051
+ // B7a P1-1:账本旁证必须与字节一致(approve.json.sha256 复算),否则手工追加的
1052
+ // apply 条目可以打着「已两次 approve」的旗号直接执行迁移。
1053
+ if (ledgerWrap?.obj && !ledgerWrap.sidecarOk) {
1054
+ fail(CODE.artifactTampered, 'approve.json 旁证(.sha256)缺失或与字节不符:approve 账本被篡改,拒绝迁移', EXIT.stale, {
1055
+ rel: REL.approve,
1056
+ sha256: ledgerWrap.sha256 ?? null,
1057
+ });
1058
+ }
1059
+ const ledger = ledgerWrap?.obj ?? null;
1060
+ const planEntry = ledger?.approvals?.find((item) => item.stage === 'plan');
1061
+ if (!planEntry) {
1062
+ fail(CODE.approveRequired, '缺第一次 approve:--mode approve --approve-stage plan --confirm <plan指纹前8位>', EXIT.approvalRequired);
1063
+ }
1064
+ const applyEntry = ledger?.approvals?.find((item) => item.stage === 'apply');
1065
+ const backup = readHashed(root, REL.backup);
1066
+ if (!backup?.obj || !backup.sidecarOk) {
1067
+ fail(CODE.backupMissing, '备份缺失或被篡改:重新 --mode apply 生成备份', EXIT.backupMismatch);
1068
+ }
1069
+ const backupIntegrity = verifyBackupIntegrity(root, backup.obj);
1070
+ if (!backupIntegrity.ok) {
1071
+ fail(CODE.backupMismatch, `备份自检失败:${backupIntegrity.bad.length} 个文件`, EXIT.backupMismatch, backupIntegrity);
1072
+ }
1073
+ if (!applyEntry) {
1074
+ fail(
1075
+ CODE.approveRequired,
1076
+ `缺第二次 approve:先运行 --mode approve --approve-stage apply --confirm ${String(backup.sha256).slice(0, 8)}`,
1077
+ EXIT.approvalRequired,
1078
+ { stage: 'apply', backupSha256: backup.sha256, confirm: String(backup.sha256).slice(0, 8) },
1079
+ );
1080
+ }
1081
+ if (state.status !== 'backup-ready') {
1082
+ fail(CODE.conflict, `当前 state.status=${state.status},不能执行迁移`, EXIT.conflict);
1083
+ }
1084
+ if (planEntry.planFingerprint !== fresh.plan.fingerprint || applyEntry.planFingerprint !== fresh.plan.fingerprint) {
1085
+ fail(CODE.planStale, 'approve 绑定的 plan 与当前 memoryRoot 不一致', EXIT.stale);
1086
+ }
1087
+ if (applyEntry.backupSha256 !== backup.sha256) {
1088
+ fail(CODE.backupMismatch, '第二次 approve 绑定的备份与当前 backup.json 不一致(备份被重新生成过,需重新 approve)', EXIT.backupMismatch);
1089
+ }
1090
+
1091
+ const { items, moved, recovered } = applyChanges(root, fresh.plan, now);
1092
+ const receipts = [];
1093
+ if (fresh.plan.changes.length > 0) {
1094
+ receipts.push(writeA1Receipt(root, { now, planFingerprint: fresh.plan.fingerprint, moved, recovered, items }));
1095
+ }
1096
+
1097
+ state.status = 'applied';
1098
+ state.appliedAt = nowIso(now);
1099
+ state.counts = { changes: fresh.plan.changes.length, moved, recovered, deferred: fresh.plan.deferred.length };
1100
+ state.manifestSha256 = null; // manifest 写出后由 manifest.json.sha256 旁证;state 不再二次改写,保证 manifest 可复算
1101
+ pushHistory(state, now, 'applied', { moved, recovered });
1102
+ writeState(root, state, now);
1103
+
1104
+ const files = listManifestFiles(root, { planSha256: fresh.sha256, backup: backup.obj, changes: fresh.plan.changes, receipts, now });
1105
+ const manifest = {
1106
+ schema: SCHEMA.manifest,
1107
+ generatedAt: nowIso(now),
1108
+ fromVersion: FROM_VERSION,
1109
+ toVersion: TO_VERSION,
1110
+ memoryRoot: root,
1111
+ planFingerprint: fresh.plan.fingerprint,
1112
+ planSha256: fresh.sha256,
1113
+ backupSha256: backup.sha256,
1114
+ approveSha256: ledgerWrap.sha256,
1115
+ approvals: (ledger.approvals || []).map((item) => ({ stage: item.stage, at: item.at, by: item.by, confirm: item.confirm, planFingerprint: item.planFingerprint, backupSha256: item.backupSha256 ?? null })),
1116
+ requiredApprovals: [...REQUIRED_APPROVALS],
1117
+ counts: {
1118
+ files: files.length,
1119
+ moved,
1120
+ recovered,
1121
+ changes: fresh.plan.changes.length,
1122
+ backedUp: backup.obj.files.length,
1123
+ deferred: fresh.plan.deferred.length,
1124
+ bytes: files.reduce((sum, item) => sum + item.bytes, 0),
1125
+ },
1126
+ changes: (fresh.plan.changes || []).map((change) => ({
1127
+ id: change.id,
1128
+ kind: change.kind,
1129
+ action: change.action,
1130
+ source: change.source,
1131
+ dest: change.dest,
1132
+ sourceSha256: change.sourceSha256,
1133
+ destSha256: change.destSha256,
1134
+ bytes: change.bytes,
1135
+ })),
1136
+ deferred: fresh.plan.deferred || [],
1137
+ receipts,
1138
+ files,
1139
+ verify: {
1140
+ l4Contract: 'files[] 每项含 rel|path + sha256|sha(可带 bytes),相对 memoryRoot 重算;manifest 自身与 manifest.json.sha256 不进 files[](自引用成环)',
1141
+ recompute: 'node scripts/migrate-200.mjs --mode verify --memory-root <root>',
1142
+ },
1143
+ };
1144
+ const manifestWritten = writeHashed(root, REL.manifest, manifest, { now });
1145
+ const verify = verifyManifest({ memoryRoot: root });
1146
+ if (!verify.ok) {
1147
+ fail(CODE.verifyFail, `manifest 写后复算失败:${verify.bad.length} 项`, EXIT.verifyFail, verify);
1148
+ }
1149
+ return {
1150
+ ok: true,
1151
+ status: 'ok',
1152
+ applied: true,
1153
+ manifestRel: toRel(OUTPUT_DIR_REL, REL.manifest),
1154
+ manifestSha256: manifestWritten.sha256,
1155
+ manifestBytes: manifestWritten.bytes,
1156
+ counts: manifest.counts,
1157
+ approvals: REQUIRED_APPROVALS.length,
1158
+ verify,
1159
+ };
1160
+ }
1161
+
1162
+ // ---------------------------------------------------------------- verify(L4 复算口径)
1163
+
1164
+ export function verifyManifest({ memoryRoot, manifestPath = null } = {}) {
1165
+ const root = path.resolve(String(memoryRoot ?? ''));
1166
+ const manifestAbs = manifestPath ? path.resolve(manifestPath) : fromRel(root, toRel(OUTPUT_DIR_REL, REL.manifest));
1167
+ const bad = [];
1168
+ if (!existsFile(manifestAbs)) {
1169
+ return { ok: false, verified: 0, files: 0, bad: [{ rel: REL.manifest, reason: 'E_MIGRATE200_MANIFEST_MISSING' }], manifestSha256: null, counts: null };
1170
+ }
1171
+ const bytes = fs.readFileSync(manifestAbs);
1172
+ let manifest = null;
1173
+ try {
1174
+ manifest = JSON.parse(bytes.toString('utf8'));
1175
+ } catch (error) {
1176
+ return { ok: false, verified: 0, files: 0, bad: [{ rel: REL.manifest, reason: 'E_MIGRATE200_MANIFEST_JSON' }], manifestSha256: sha256Hex(bytes), counts: null };
1177
+ }
1178
+ const files = Array.isArray(manifest?.files) ? manifest.files : [];
1179
+ if (files.length === 0) bad.push({ rel: REL.manifest, reason: 'E_MIGRATE200_MANIFEST_SHAPE', detail: 'files[] 为空或不是数组' });
1180
+ let verified = 0;
1181
+ for (const [index, entry] of files.entries()) {
1182
+ const rel = entry && (entry.rel ?? entry.path);
1183
+ const expectedSha = entry && (entry.sha256 ?? entry.sha);
1184
+ if (typeof rel !== 'string' || rel === '' || typeof expectedSha !== 'string' || expectedSha === '') {
1185
+ bad.push({ rel: `files[${index}]`, reason: 'E_MIGRATE200_MANIFEST_SHAPE' });
1186
+ continue;
1187
+ }
1188
+ const normalized = String(rel).split('\\').join('/').replace(/^\.\//, '');
1189
+ if (path.isAbsolute(normalized) || normalized.split('/').includes('..')) {
1190
+ bad.push({ rel: normalized, reason: 'E_MIGRATE200_MANIFEST_PATH_ESCAPE' });
1191
+ continue;
1192
+ }
1193
+ const abs = path.join(root, normalized);
1194
+ if (!existsFile(abs)) {
1195
+ bad.push({ rel: normalized, reason: 'missing' });
1196
+ continue;
1197
+ }
1198
+ const stat = fs.statSync(abs);
1199
+ if (entry.bytes !== undefined && Number(entry.bytes) !== stat.size) {
1200
+ bad.push({ rel: normalized, reason: 'E_MIGRATE200_MANIFEST_BYTES' });
1201
+ continue;
1202
+ }
1203
+ if (sha256FileSync(abs) !== String(expectedSha).toLowerCase()) {
1204
+ bad.push({ rel: normalized, reason: 'E_MIGRATE200_MANIFEST_MISMATCH' });
1205
+ continue;
1206
+ }
1207
+ verified += 1;
1208
+ }
1209
+ const ok = bad.length === 0 && verified === files.length;
1210
+ return {
1211
+ ok,
1212
+ verified,
1213
+ files: files.length,
1214
+ bad,
1215
+ manifestSha256: sha256Hex(bytes),
1216
+ manifestBytes: bytes.length,
1217
+ counts: manifest?.counts ?? null,
1218
+ };
1219
+ }
1220
+
1221
+ // ---------------------------------------------------------------- rollback
1222
+
1223
+ function restoreBackupFile(root, entry) {
1224
+ const backupAbs = fromRel(root, entry.backupRel);
1225
+ const targetAbs = fromRel(root, entry.rel);
1226
+ if (!existsFile(backupAbs)) {
1227
+ fail(CODE.backupMismatch, `回滚备份缺失:${entry.backupRel}`, EXIT.backupMismatch, { rel: entry.backupRel });
1228
+ }
1229
+ if (sha256FileSync(backupAbs) !== entry.sha256) {
1230
+ fail(CODE.backupMismatch, `回滚备份被篡改:${entry.backupRel}`, EXIT.backupMismatch, { rel: entry.backupRel });
1231
+ }
1232
+ if (existsFile(targetAbs)) {
1233
+ const currentSha = sha256FileSync(targetAbs);
1234
+ if (currentSha === entry.sha256) return { rel: entry.rel, action: 'already-restored' };
1235
+ fail(CODE.conflict, `回滚目标已存在且内容不同,拒绝覆盖:${entry.rel}`, EXIT.conflict, { rel: entry.rel });
1236
+ }
1237
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1238
+ fs.copyFileSync(backupAbs, targetAbs);
1239
+ if (sha256FileSync(targetAbs) !== entry.sha256) {
1240
+ fail(CODE.backupMismatch, `回滚写回 sha 不符:${entry.rel}`, EXIT.backupMismatch, { rel: entry.rel });
1241
+ }
1242
+ return { rel: entry.rel, action: 'restored' };
1243
+ }
1244
+
1245
+ export function rollbackMigration({ memoryRoot, now = new Date() } = {}) {
1246
+ const root = path.resolve(String(memoryRoot ?? ''));
1247
+ const stateWrap = readState(root);
1248
+ if (!stateWrap || !stateWrap.obj) {
1249
+ fail(CODE.conflict, '未找到 state.json,无可回滚内容', EXIT.conflict);
1250
+ }
1251
+ const state = stateWrap.obj;
1252
+ if (state.status !== 'applied') {
1253
+ fail(CODE.conflict, `当前 state.status=${state.status},只有 applied 可 rollback`, EXIT.conflict);
1254
+ }
1255
+ const manifestWrap = readHashed(root, REL.manifest);
1256
+ if (!manifestWrap?.obj || !manifestWrap.sidecarOk) {
1257
+ fail(CODE.verifyFail, 'manifest 缺失或被篡改,拒绝回滚(先人工核对)', EXIT.verifyFail);
1258
+ }
1259
+ const manifest = manifestWrap.obj;
1260
+ const backup = readHashed(root, REL.backup);
1261
+ if (!backup?.obj || !backup.sidecarOk) {
1262
+ fail(CODE.backupMissing, '备份缺失,无法回滚', EXIT.backupMismatch);
1263
+ }
1264
+ const integrity = verifyBackupIntegrity(root, backup.obj);
1265
+ if (!integrity.ok) {
1266
+ fail(CODE.backupMismatch, `备份自检失败:${integrity.bad.length} 个文件`, EXIT.backupMismatch, integrity);
1267
+ }
1268
+
1269
+ const backupByRel = new Map((backup.obj.files || []).map((entry) => [entry.rel, entry]));
1270
+ const actions = [];
1271
+ // 1) 撤销数据移动:dest 回到 source;仅当 dest 内容仍是本次迁移写入的 sha。
1272
+ for (const change of manifest.changes || []) {
1273
+ const destAbs = fromRel(root, change.dest);
1274
+ const sourceAbs = fromRel(root, change.source);
1275
+ if (change.action === 'skip-same') {
1276
+ actions.push({ rel: change.source, action: 'skip-same' });
1277
+ continue;
1278
+ }
1279
+ if (existsFile(destAbs)) {
1280
+ const destSha = sha256FileSync(destAbs);
1281
+ if (destSha !== change.sourceSha256) {
1282
+ fail(CODE.conflict, `回滚拒绝:${change.dest} 内容已被后续修改`, EXIT.conflict, { dest: change.dest });
1283
+ }
1284
+ if (existsFile(sourceAbs)) {
1285
+ fail(CODE.conflict, `回滚拒绝:源已存在 ${change.source},不覆盖`, EXIT.conflict, { source: change.source });
1286
+ }
1287
+ fs.mkdirSync(path.dirname(sourceAbs), { recursive: true });
1288
+ fs.renameSync(destAbs, sourceAbs);
1289
+ actions.push({ rel: change.source, action: 'moved-back' });
1290
+ } else if (existsFile(sourceAbs)) {
1291
+ actions.push({ rel: change.source, action: 'already-back' });
1292
+ } else {
1293
+ const backupEntry = backupByRel.get(change.source);
1294
+ if (!backupEntry) fail(CODE.backupMissing, `回滚缺少源备份:${change.source}`, EXIT.backupMismatch);
1295
+ actions.push({ rel: change.source, ...restoreBackupFile(root, backupEntry) });
1296
+ }
1297
+ }
1298
+ // 2) 撤销本次迁移写出的 receipt/marker 及其旁证:
1299
+ // 备份里有(迁移前就存在)→ 恢复;没有 → 只删 manifest 记录且 sha 未变的本次写入,绝不覆盖他人文件。
1300
+ const restoreOrRemove = (rel) => {
1301
+ const targetAbs = fromRel(root, rel);
1302
+ const backupEntry = backupByRel.get(rel);
1303
+ if (backupEntry) {
1304
+ if (!existsFile(targetAbs)) {
1305
+ actions.push({ rel, ...restoreBackupFile(root, backupEntry) });
1306
+ return;
1307
+ }
1308
+ const currentSha = sha256FileSync(targetAbs);
1309
+ if (currentSha === backupEntry.sha256) {
1310
+ actions.push({ rel, action: 'already-restored' });
1311
+ return;
1312
+ }
1313
+ const markerObj = rel.endsWith('.sha256') ? null : readJson(targetAbs);
1314
+ const ours = rel.endsWith('.sha256') || (markerObj && String(markerObj.receiptPath || '').includes('migrate-200'));
1315
+ if (!ours) fail(CODE.conflict, `回滚拒绝覆盖:${rel}(不是本次 migrate-200 写入)`, EXIT.conflict, { rel });
1316
+ fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
1317
+ fs.copyFileSync(fromRel(root, backupEntry.backupRel), targetAbs);
1318
+ if (sha256FileSync(targetAbs) !== backupEntry.sha256) {
1319
+ fail(CODE.backupMismatch, `回滚恢复失败:${rel}`, EXIT.backupMismatch, { rel });
1320
+ }
1321
+ actions.push({ rel, action: 'restored' });
1322
+ return;
1323
+ }
1324
+ if (!existsFile(targetAbs)) return;
1325
+ const manifestEntry = (manifest.files || []).find((item) => item.rel === rel);
1326
+ if (manifestEntry && manifestEntry.sha256 === sha256FileSync(targetAbs)) {
1327
+ fs.unlinkSync(targetAbs);
1328
+ actions.push({ rel, action: 'removed' });
1329
+ }
1330
+ };
1331
+ for (const receipt of manifest.receipts || []) {
1332
+ for (const rel of [receipt.markerRel, `${receipt.markerRel}.sha256`, receipt.receiptRel, `${receipt.receiptRel}.sha256`]) {
1333
+ restoreOrRemove(rel);
1334
+ }
1335
+ }
1336
+ // 3) 归档 applied manifest(rollback 后 manifest.json 不应继续存在,避免 L4 复算已回滚的产物)。
1337
+ const archivedRel = toRel(OUTPUT_DIR_REL, `manifest.applied-${stampOf(now)}.json`);
1338
+ fs.renameSync(fromRel(root, toRel(OUTPUT_DIR_REL, REL.manifest)), fromRel(root, archivedRel));
1339
+ for (const suffix of ['', '.sha256']) {
1340
+ const sidecarAbs = fromRel(root, toRel(OUTPUT_DIR_REL, REL.manifest) + suffix);
1341
+ if (successiveExists(sidecarAbs)) fs.renameSync(sidecarAbs, fromRel(root, archivedRel + suffix));
1342
+ }
1343
+ // 4) 撤销 apply 阶段 approve(保留 plan approve;回滚后备份 sha 会变,必须重新二次 approve)。
1344
+ const ledgerWrap = readApproveLedger(root);
1345
+ const ledger = ledgerWrap?.obj ?? null;
1346
+ if (ledger && Array.isArray(ledger.approvals)) {
1347
+ ledger.approvals = ledger.approvals.filter((item) => item.stage !== 'apply');
1348
+ ledger.backupSha256 = null;
1349
+ writeLedger(root, ledger, now);
1350
+ }
1351
+ const rollback = {
1352
+ schema: 'migrate-200-rollback/v1',
1353
+ generatedAt: nowIso(now),
1354
+ memoryRoot: root,
1355
+ planFingerprint: manifest.planFingerprint,
1356
+ appliedManifestSha256: manifestWrap.sha256,
1357
+ archivedManifest: archivedRel,
1358
+ actions,
1359
+ counts: { movedBack: actions.filter((item) => item.action === 'moved-back' || item.action === 'restored').length, total: actions.length },
1360
+ };
1361
+ const written = writeHashed(root, 'rollback.json', rollback, { now });
1362
+ state.status = 'planned';
1363
+ state.manifestSha256 = null;
1364
+ state.counts = null;
1365
+ pushHistory(state, now, 'rollback', { archivedManifest: archivedRel, counts: rollback.counts });
1366
+ writeState(root, state, now);
1367
+ return {
1368
+ ok: true,
1369
+ status: 'ok',
1370
+ rolledBack: true,
1371
+ archivedManifest: toRel(OUTPUT_DIR_REL, archivedRel),
1372
+ rollbackRel: toRel(OUTPUT_DIR_REL, 'rollback.json'),
1373
+ rollbackSha256: written.sha256,
1374
+ counts: rollback.counts,
1375
+ next: '数据已按备份恢复;重新 apply 需重新备份并重新第二次 approve',
1376
+ };
1377
+ }
1378
+
1379
+ function successiveExists(file) {
1380
+ return existsFile(file);
1381
+ }
1382
+
1383
+ // ---------------------------------------------------------------- probe(维护槽只读探测;不迁移)
1384
+
1385
+ export function probePending({ memoryRoot, now = new Date(), write = true } = {}) {
1386
+ const root = path.resolve(String(memoryRoot ?? ''));
1387
+ if (!isDir(root)) return { ok: false, code: CODE.rootMissing, message: `memoryRoot 不存在:${root}` };
1388
+ let plan = null;
1389
+ try {
1390
+ plan = makePlan(root, now);
1391
+ } catch (error) {
1392
+ return { ok: false, code: error.code ?? CODE.probeFailed, message: String(error?.message ?? error) };
1393
+ }
1394
+ const p = pathsOf(root);
1395
+ const manifestExists = existsFile(p.file(REL.manifest));
1396
+ const planExists = existsFile(p.file(REL.plan));
1397
+ const pending = {
1398
+ schema: SCHEMA.pending,
1399
+ generatedAt: nowIso(now),
1400
+ memoryRoot: root,
1401
+ status: manifestExists ? 'applied' : planExists ? 'planned' : plan.counts.moves > 0 || plan.counts.deferred > 0 ? 'needs-plan' : 'clean',
1402
+ manifestExists,
1403
+ planExists,
1404
+ counts: plan.counts,
1405
+ planFingerprint: plan.fingerprint,
1406
+ requiredApprovals: [...REQUIRED_APPROVALS],
1407
+ commands: {
1408
+ plan: `node scripts/migrate-200.mjs --mode plan --write --memory-root "${root}"`,
1409
+ approvePlan: 'node scripts/migrate-200.mjs --mode approve --approve-stage plan --confirm <plan 指纹前 8 位> --memory-root "<root>"',
1410
+ backup: 'node scripts/migrate-200.mjs --mode apply --memory-root "<root>"',
1411
+ approveApply: 'node scripts/migrate-200.mjs --mode approve --approve-stage apply --confirm <backup.json sha256 前 8 位> --memory-root "<root>"',
1412
+ apply: 'node scripts/migrate-200.mjs --mode apply --memory-root "<root>"',
1413
+ },
1414
+ note: '探测本身不迁移、不移动、不删除任何数据;需人工两次 approve 后由 CLI 迁移',
1415
+ };
1416
+ if (write) {
1417
+ try {
1418
+ writeHashed(root, REL.pending, pending, { now });
1419
+ } catch (error) {
1420
+ return { ok: false, code: CODE.probeFailed, message: String(error?.message ?? error) };
1421
+ }
1422
+ }
1423
+ return {
1424
+ ok: true,
1425
+ pending,
1426
+ wrote: write,
1427
+ // 顶层别名:维护钩子/面板可直接取用(与 pending.* 同值)。
1428
+ status: pending.status,
1429
+ counts: pending.counts,
1430
+ pendingPath: fromRel(root, toRel(OUTPUT_DIR_REL, REL.pending)),
1431
+ manifestExists,
1432
+ planExists,
1433
+ };
1434
+ }
1435
+
1436
+ // ---------------------------------------------------------------- CLI main
1437
+
1438
+ function parseArgv(argv) {
1439
+ const args = Array.isArray(argv) ? argv.slice() : [];
1440
+ const out = {
1441
+ mode: DEFAULT_MODE,
1442
+ memoryRoot: '',
1443
+ write: false,
1444
+ force: false,
1445
+ out: '',
1446
+ now: new Date(),
1447
+ approveStage: '',
1448
+ confirm: '',
1449
+ by: '',
1450
+ help: false,
1451
+ };
1452
+ const takeValue = (index, flag) => {
1453
+ const value = args[index + 1];
1454
+ if (value === undefined) fail(CODE.usage, `${flag} 缺少参数值`, EXIT.usage);
1455
+ return value;
1456
+ };
1457
+ for (let i = 0; i < args.length; i += 1) {
1458
+ const arg = String(args[i]);
1459
+ if (arg === '--help' || arg === '-h') out.help = true;
1460
+ else if (arg === '--mode') out.mode = takeValue(i++, '--mode');
1461
+ else if (arg.startsWith('--mode=')) out.mode = arg.slice('--mode='.length);
1462
+ else if (arg === '--memory-root' || arg === '--root') out.memoryRoot = takeValue(i++, arg);
1463
+ else if (arg.startsWith('--memory-root=')) out.memoryRoot = arg.slice('--memory-root='.length);
1464
+ else if (arg.startsWith('--root=')) out.memoryRoot = arg.slice('--root='.length);
1465
+ else if (arg === '--write') out.write = true;
1466
+ else if (arg === '--force') out.force = true;
1467
+ else if (arg === '--out') out.out = takeValue(i++, '--out');
1468
+ else if (arg.startsWith('--out=')) out.out = arg.slice('--out='.length);
1469
+ else if (arg === '--now') out.now = new Date(takeValue(i++, '--now'));
1470
+ else if (arg.startsWith('--now=')) out.now = new Date(arg.slice('--now='.length));
1471
+ else if (arg === '--approve-stage') out.approveStage = takeValue(i++, '--approve-stage');
1472
+ else if (arg.startsWith('--approve-stage=')) out.approveStage = arg.slice('--approve-stage='.length);
1473
+ else if (arg === '--confirm') out.confirm = takeValue(i++, '--confirm');
1474
+ else if (arg.startsWith('--confirm=')) out.confirm = arg.slice('--confirm='.length);
1475
+ else if (arg === '--by') out.by = takeValue(i++, '--by');
1476
+ else if (arg.startsWith('--by=')) out.by = arg.slice('--by='.length);
1477
+ else fail(CODE.usage, `未知参数:${arg}`, EXIT.usage);
1478
+ }
1479
+ if (Number.isNaN(out.now.getTime())) fail(CODE.usage, '--now 不是合法时间', EXIT.usage);
1480
+ return out;
1481
+ }
1482
+
1483
+ export function resolveMemoryRoot(cli, env = process.env) {
1484
+ const fromCli = String(cli.memoryRoot ?? '').trim();
1485
+ if (fromCli !== '') return path.resolve(fromCli);
1486
+ const fromEnv = String(env.HG_MEMORY_ROOT ?? '').trim();
1487
+ if (fromEnv !== '') return path.resolve(fromEnv);
1488
+ fail(
1489
+ CODE.usage,
1490
+ '缺少 --memory-root:迁移必须显式指定 memoryRoot(不猜 cwd、不猜默认记忆根)',
1491
+ EXIT.usage,
1492
+ );
1493
+ }
1494
+
1495
+ function planPayload(plan, extra) {
1496
+ return {
1497
+ schema: SCHEMA.cli,
1498
+ status: 'ok',
1499
+ mode: 'plan',
1500
+ memoryRoot: plan.memoryRoot,
1501
+ planFingerprint: plan.fingerprint,
1502
+ counts: plan.counts,
1503
+ changes: plan.changes,
1504
+ deferred: plan.deferred,
1505
+ ...extra,
1506
+ };
1507
+ }
1508
+
1509
+ export async function main(argv = process.argv.slice(2), { env = process.env, stdinIsTTY = process.stdin.isTTY, now = null } = {}) {
1510
+ let cli = null;
1511
+ try {
1512
+ cli = parseArgv(argv);
1513
+ if (cli.help) {
1514
+ const help = {
1515
+ schema: SCHEMA.cli,
1516
+ status: 'ok',
1517
+ usage: 'node scripts/migrate-200.mjs --mode <plan|dry-run|apply|rollback|approve|verify> --memory-root <path> [--write] [--force] [--approve-stage plan|apply --confirm <sha8>] [--out <file>] [--now <iso>]',
1518
+ modes: MODES,
1519
+ defaultMode: DEFAULT_MODE,
1520
+ exitCodes: EXIT,
1521
+ note: '默认 dry-run 只读;plan --write 落 plan.json;apply 先备份再要求第二次 approve;两次 approve 缺一即拒绝(fail-closed)',
1522
+ };
1523
+ process.stdout.write(jsonBytes(help));
1524
+ return EXIT.ok;
1525
+ }
1526
+ if (!MODES.includes(cli.mode)) {
1527
+ fail(CODE.usage, `--mode 必须是 ${MODES.join('|')},收到:${cli.mode}`, EXIT.usage);
1528
+ }
1529
+ if (cli.mode === 'dry-run' && cli.write) {
1530
+ fail(CODE.usage, 'dry-run 不写盘:要落 plan.json 请用 --mode plan --write', EXIT.usage);
1531
+ }
1532
+ const root = resolveMemoryRoot(cli, env);
1533
+ const nowDate = now instanceof Date ? now : cli.now;
1534
+
1535
+ if (cli.mode === 'plan' || cli.mode === 'dry-run') {
1536
+ const built = buildPlan({ memoryRoot: root, now: nowDate });
1537
+ if (cli.out) {
1538
+ const outAbs = path.resolve(cli.out);
1539
+ writeAtomic(outAbs, Buffer.from(jsonBytes(built.plan), 'utf8'));
1540
+ }
1541
+ if (cli.mode === 'dry-run' || !cli.write) {
1542
+ const payload = planPayload(built.plan, {
1543
+ mode: cli.mode,
1544
+ planSha256: built.planSha256,
1545
+ planBytes: built.planBytes,
1546
+ wrote: Boolean(cli.out),
1547
+ requiresApprovals: [...REQUIRED_APPROVALS],
1548
+ message: '只读 plan,未写盘、未建目录、未移动数据;要落盘请 --mode plan --write',
1549
+ });
1550
+ process.stdout.write(jsonBytes(payload));
1551
+ return EXIT.ok;
1552
+ }
1553
+ // --mode plan --write
1554
+ const p = pathsOf(root);
1555
+ const stateWrap = readState(root);
1556
+ if (stateWrap?.obj && (stateWrap.obj.status === 'backup-ready' || stateWrap.obj.status === 'applied')) {
1557
+ if (!cli.force) {
1558
+ fail(
1559
+ CODE.conflict,
1560
+ `当前 state.status=${stateWrap.obj.status}:不能重写 plan(--force 仅允许覆盖 planned 状态)`,
1561
+ EXIT.conflict,
1562
+ { status: stateWrap.obj.status },
1563
+ );
1564
+ }
1565
+ }
1566
+ fs.mkdirSync(p.dirAbs, { recursive: true });
1567
+ const planWritten = writeHashed(root, REL.plan, built.plan, { now: nowDate });
1568
+ const request = {
1569
+ schema: SCHEMA.request,
1570
+ generatedAt: nowIso(nowDate),
1571
+ stage: 'plan',
1572
+ memoryRoot: root,
1573
+ planFingerprint: built.plan.fingerprint,
1574
+ planSha256: planWritten.sha256,
1575
+ planBytes: planWritten.bytes,
1576
+ requiredApprovals: [...REQUIRED_APPROVALS],
1577
+ confirm: shortOf(built.plan.fingerprint),
1578
+ command: `node scripts/migrate-200.mjs --mode approve --approve-stage plan --confirm ${shortOf(built.plan.fingerprint)} --memory-root "${root}"`,
1579
+ note: '第一次 approve 由人工执行并核对 plan 变更清单;AI 不得代签(G4 口径)',
1580
+ };
1581
+ writeHashed(root, REL.request, request, { now: nowDate });
1582
+ const state = stateWrap?.obj && stateWrap.obj.status === 'planned' ? stateWrap.obj : baseState({ now: nowDate, planSha256: planWritten.sha256, fingerprint: built.plan.fingerprint });
1583
+ state.status = 'planned';
1584
+ state.planSha256 = planWritten.sha256;
1585
+ state.planFingerprint = built.plan.fingerprint;
1586
+ state.backupSha256 = null;
1587
+ state.counts = built.plan.counts;
1588
+ pushHistory(state, nowDate, 'plan', { changes: built.plan.counts.changes, deferred: built.plan.counts.deferred });
1589
+ writeState(root, state, nowDate);
1590
+ const payload = planPayload(built.plan, {
1591
+ mode: 'plan',
1592
+ wrote: true,
1593
+ planRel: toRel(OUTPUT_DIR_REL, REL.plan),
1594
+ planSha256: planWritten.sha256,
1595
+ planBytes: planWritten.bytes,
1596
+ requestRel: toRel(OUTPUT_DIR_REL, REL.request),
1597
+ next: `第一次 approve:--mode approve --approve-stage plan --confirm ${shortOf(built.plan.fingerprint)}`,
1598
+ });
1599
+ process.stdout.write(jsonBytes(payload));
1600
+ return EXIT.ok;
1601
+ }
1602
+
1603
+ if (cli.mode === 'approve') {
1604
+ const result = approveStage({
1605
+ memoryRoot: root,
1606
+ stage: cli.approveStage,
1607
+ confirm: cli.confirm,
1608
+ by: cli.by,
1609
+ now: nowDate,
1610
+ stdinIsTTY,
1611
+ env,
1612
+ });
1613
+ process.stdout.write(jsonBytes({ schema: SCHEMA.cli, mode: 'approve', ...result }));
1614
+ return EXIT.ok;
1615
+ }
1616
+
1617
+ if (cli.mode === 'apply') {
1618
+ const result = applyMigration({ memoryRoot: root, now: nowDate });
1619
+ process.stdout.write(jsonBytes({ schema: SCHEMA.cli, mode: 'apply', ...result }));
1620
+ return result.status === 'approval-required' ? EXIT.approvalRequired : EXIT.ok;
1621
+ }
1622
+
1623
+ if (cli.mode === 'rollback') {
1624
+ const result = rollbackMigration({ memoryRoot: root, now: nowDate });
1625
+ process.stdout.write(jsonBytes({ schema: SCHEMA.cli, mode: 'rollback', ...result }));
1626
+ return EXIT.ok;
1627
+ }
1628
+
1629
+ if (cli.mode === 'verify') {
1630
+ const result = verifyManifest({ memoryRoot: root });
1631
+ process.stdout.write(
1632
+ jsonBytes({
1633
+ schema: SCHEMA.cli,
1634
+ mode: 'verify',
1635
+ status: result.ok ? 'ok' : 'error',
1636
+ code: result.ok ? null : CODE.verifyFail,
1637
+ ...result,
1638
+ }),
1639
+ );
1640
+ return result.ok ? EXIT.ok : EXIT.verifyFail;
1641
+ }
1642
+
1643
+ fail(CODE.usage, `未支持的 mode:${cli.mode}`, EXIT.usage);
1644
+ return EXIT.usage;
1645
+ } catch (error) {
1646
+ const code = error?.code ?? CODE.conflict;
1647
+ const exitCode = typeof error?.exitCode === 'number' ? error.exitCode : EXIT.conflict;
1648
+ const payload = {
1649
+ schema: SCHEMA.cli,
1650
+ mode: cli?.mode ?? null,
1651
+ status: 'error',
1652
+ code,
1653
+ message: String(error?.message ?? error),
1654
+ detail: error?.detail ?? null,
1655
+ };
1656
+ process.stdout.write(jsonBytes(payload));
1657
+ process.stderr.write(`[migrate-200] ${code}: ${payload.message}\n`);
1658
+ return exitCode;
1659
+ }
1660
+ }
1661
+
1662
+ export const __test = Object.freeze({
1663
+ jsonBytes,
1664
+ writeAtomic,
1665
+ readJson,
1666
+ existsFile,
1667
+ isDir,
1668
+ walkFiles,
1669
+ shortOf,
1670
+ planFreshness,
1671
+ emptyLedger,
1672
+ aggregateOf,
1673
+ confirmMatches,
1674
+ normalizeConfirm,
1675
+ backupScope,
1676
+ baseState,
1677
+ pushHistory,
1678
+ writeState,
1679
+ writeRootHashed,
1680
+ restoreBackupFile,
1681
+ });