@jjh32456/longlive 0.0.0-stage → 2.0.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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Offline D1/D4 sample: replay the last N turns of a real session log through
4
+ * the same `measureTurn()` used live, then reconcile the ledger against the
5
+ * provider's usage numbers.
6
+ *
7
+ * Usage:
8
+ * node scripts/metrics-sample.mjs --log <session.v4.jsonl.zstd> \
9
+ * --turns 5 --out <dir>
10
+ *
11
+ * Error algorithm (documented in docs/METRICS.md):
12
+ * 1. each layer is estimated with CJK*1 + non-CJK/3.5;
13
+ * 2. rawTotal = sum(layers) + carried;
14
+ * 3. total = round(rawTotal * factor), with `factor` starting at 1.0;
15
+ * 4. after the turn, if usage exists, the cumulative ratio is updated:
16
+ * factor = clamp(0.5, 2, (actualSum + actual) / (rawSum + rawTotal));
17
+ * this is NOT an EWMA: one observed turn already removes the systematic
18
+ * bias, later turns only refine it;
19
+ * 5. error = total - actual; errorPct = error / actual * 100.
20
+ * The first sample is therefore the cold estimate; samples 2..N are warm.
21
+ */
22
+
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { parseSession } from '../src/codec.js';
26
+ import { measureTurn, clampFactor, DEFAULT_FACTOR } from '../src/metrics/measure.mjs';
27
+ import { findRequestHeader } from '../src/metrics/index.mjs';
28
+ import { ledgerPath, writeCalibration } from '../src/metrics/store.mjs';
29
+
30
+ function parseArgs(argv) {
31
+ const out = { log: '', turns: 5, out: path.resolve('metrics-sample'), seed: DEFAULT_FACTOR, help: false };
32
+ for (let index = 0; index < argv.length; index += 1) {
33
+ const arg = argv[index];
34
+ if (arg === '--help' || arg === '-h') out.help = true;
35
+ else if (arg === '--log') out.log = argv[++index] ?? '';
36
+ else if (arg === '--turns') out.turns = Math.max(1, Number.parseInt(argv[++index] ?? '', 10) || 5);
37
+ else if (arg === '--out') out.out = path.resolve(argv[++index] ?? out.out);
38
+ else if (arg === '--seed') out.seed = clampFactor(Number(argv[++index] ?? DEFAULT_FACTOR));
39
+ else if (arg.startsWith('--log=')) out.log = arg.slice('--log='.length);
40
+ else if (arg.startsWith('--turns=')) out.turns = Math.max(1, Number.parseInt(arg.slice('--turns='.length), 10) || 5);
41
+ else if (arg.startsWith('--out=')) out.out = path.resolve(arg.slice('--out='.length));
42
+ else if (arg.startsWith('--seed=')) out.seed = clampFactor(Number(arg.slice('--seed='.length)));
43
+ }
44
+ return out;
45
+ }
46
+
47
+ function usageEvents(events) {
48
+ const byTurn = new Map();
49
+ for (const event of events) {
50
+ if (event?.type !== 'assistant/message') continue;
51
+ const turn = event.data?.turn;
52
+ if (!Number.isInteger(turn)) continue;
53
+ if (event.data.usage === null || typeof event.data.usage !== 'object') continue;
54
+ byTurn.set(turn, event);
55
+ }
56
+ return [...byTurn.entries()].sort((a, b) => a[0] - b[0]);
57
+ }
58
+
59
+ function percent(value) {
60
+ return Number.isFinite(value) ? Number(value.toFixed(2)) : null;
61
+ }
62
+
63
+ function median(values) {
64
+ const list = values.filter((value) => Number.isFinite(value)).sort((a, b) => a - b);
65
+ if (list.length === 0) return null;
66
+ const middle = Math.floor(list.length / 2);
67
+ return list.length % 2 === 1 ? list[middle] : (list[middle - 1] + list[middle]) / 2;
68
+ }
69
+
70
+ function markdownTable(rows) {
71
+ const header = '| turn | fixed | recent | recall | conclusion | carried | total | actual | delta% | within5 | factor |';
72
+ const divider = '|---:|---:|---:|---:|---:|---:|---:|---:|---:|:---:|---:|';
73
+ const body = rows.map((row) => (
74
+ `| ${row.turn} | ${row.layers.fixed} | ${row.layers.recent} | ${row.layers.recall} | ` +
75
+ `${row.layers.conclusion} | ${row.carried} | ${row.total} | ${row.actualInput ?? '-'} | ` +
76
+ `${row.deltaPct ?? '-'} | ${row.within5pct === true ? 'yes' : row.within5pct === false ? 'no' : '-'} | ` +
77
+ `${row.factor} |`
78
+ ));
79
+ return `${header}\n${divider}\n${body.join('\n')}\n`;
80
+ }
81
+
82
+ const args = parseArgs(process.argv.slice(2));
83
+ if (args.help) {
84
+ process.stdout.write(
85
+ 'usage: node scripts/metrics-sample.mjs --log <session.v4.jsonl.zstd> [--turns 5] [--out <dir>] [--seed 1.0]\n',
86
+ );
87
+ process.exit(0);
88
+ }
89
+ if (args.log === '' || !fs.existsSync(args.log)) {
90
+ process.stderr.write(`metrics-sample: session log not found: ${args.log || '(missing --log)'}\n`);
91
+ process.exit(2);
92
+ }
93
+
94
+ const buffer = fs.readFileSync(args.log);
95
+ const parsed = parseSession(buffer);
96
+ const events = parsed.events;
97
+ const selected = usageEvents(events).slice(-args.turns);
98
+ if (selected.length === 0) {
99
+ process.stderr.write('metrics-sample: no assistant usage events in this log\n');
100
+ process.exit(2);
101
+ }
102
+
103
+ const sessionId = typeof parsed.header?.id === 'string'
104
+ ? parsed.header.id
105
+ : path.basename(path.dirname(args.log));
106
+ const rows = [];
107
+ const details = [];
108
+ let factor = args.seed;
109
+ let samples = 0;
110
+ let rawSum = 0;
111
+ let actualSum = 0;
112
+
113
+ for (const [turn, usageEvent] of selected) {
114
+ const cutSeq = usageEvent.seq;
115
+ const requestEvents = events.filter((event) => Number.isInteger(event?.seq) && event.seq < cutSeq);
116
+ const requestHeader = findRequestHeader(events, cutSeq);
117
+ const row = measureTurn({
118
+ events: requestEvents,
119
+ turn,
120
+ sessionId,
121
+ requestHeader,
122
+ actualUsage: usageEvent.data.usage,
123
+ config: { keepTurns: 12, targetTokens: 40000 },
124
+ factor,
125
+ calibrationSamples: samples,
126
+ now: new Date().toISOString(),
127
+ source: 'sample',
128
+ });
129
+ rows.push(row);
130
+ const actualInput = row.reconciliation?.actualInput ?? null;
131
+ details.push({
132
+ turn,
133
+ layers: row.layers,
134
+ carried: row.carried,
135
+ total: row.total,
136
+ actualInput,
137
+ deltaPct: row.reconciliation?.deltaPct ?? null,
138
+ within5pct: row.reconciliation?.within5pct ?? null,
139
+ factor: row.calibration.factor,
140
+ rawTotal: row.raw.total,
141
+ });
142
+ if (Number.isFinite(actualInput) && actualInput > 0 && Number.isFinite(row.raw.total) && row.raw.total > 0) {
143
+ rawSum += row.raw.total;
144
+ actualSum += actualInput;
145
+ factor = clampFactor(actualSum / rawSum);
146
+ samples += 1;
147
+ }
148
+ }
149
+
150
+ const errors = details.map((row) => row.deltaPct).filter((value) => Number.isFinite(value));
151
+ const warmErrors = errors.slice(1);
152
+ const summary = {
153
+ samples: details.length,
154
+ estimator: 'cjk*1+other/3.5',
155
+ calibration: 'factor=clamp(0.5,2, actualSum/rawSum) over all sampled turns',
156
+ coldFirstDeltaPct: details[0]?.deltaPct ?? null,
157
+ medianAbsErrorPct: percent(median(errors.map((value) => Math.abs(value)))),
158
+ warmMedianAbsErrorPct: percent(median(warmErrors.map((value) => Math.abs(value)))),
159
+ within5Turns: details.filter((row) => row.within5pct === true).length,
160
+ finalFactor: Number(factor.toFixed(4)),
161
+ };
162
+
163
+ const ledger = ledgerPath(args.out);
164
+ fs.mkdirSync(path.dirname(ledger), { recursive: true });
165
+ fs.writeFileSync(ledger, rows.map((row) => JSON.stringify(row)).join('\n') + '\n', 'utf8');
166
+ const calibration = writeCalibration(args.out, {
167
+ factor,
168
+ samples,
169
+ rawSum,
170
+ actualSum,
171
+ keepTurns: 12,
172
+ updatedAt: new Date().toISOString(),
173
+ });
174
+ const payload = {
175
+ v: 1,
176
+ generatedAt: new Date().toISOString(),
177
+ log: path.resolve(args.log),
178
+ ledger,
179
+ calibrationPath: calibration.path ?? '',
180
+ state: calibration.state ?? null,
181
+ sessionId,
182
+ turns: selected.map(([turn]) => turn),
183
+ summary,
184
+ rows: details,
185
+ };
186
+ fs.writeFileSync(path.join(args.out, 'reconcile.json'), `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
187
+ fs.writeFileSync(
188
+ path.join(args.out, 'reconcile.md'),
189
+ `# D1/D4 sample reconciliation\n\n` +
190
+ `- log: \`${path.resolve(args.log)}\`\n` +
191
+ `- turns: ${payload.turns.join(', ')}\n` +
192
+ `- estimator: CJK*1 + non-CJK/3.5; total = round(rawTotal * factor)\n` +
193
+ `- calibration: ${summary.calibration}\n` +
194
+ `- cold first turn error: ${summary.coldFirstDeltaPct ?? '-'}%\n` +
195
+ `- median absolute error (all): ${summary.medianAbsErrorPct ?? '-'}%\n` +
196
+ `- median absolute error (warm, excluding first): ${summary.warmMedianAbsErrorPct ?? '-'}%\n` +
197
+ `- turns within 5%: ${summary.within5Turns}/${summary.samples}\n` +
198
+ `- final factor: ${summary.finalFactor}\n\n` +
199
+ markdownTable(details),
200
+ 'utf8',
201
+ );
202
+
203
+ process.stdout.write(
204
+ `[metrics-sample] ${details.length} turn(s) from ${path.basename(args.log)}\n` +
205
+ `[metrics-sample] cold first error ${summary.coldFirstDeltaPct ?? '-'}% · ` +
206
+ `warm median |error| ${summary.warmMedianAbsErrorPct ?? '-'}% · ` +
207
+ `within5 ${summary.within5Turns}/${summary.samples}\n` +
208
+ `[metrics-sample] wrote ${ledger}\n`,
209
+ );
210
+ for (const row of details) {
211
+ process.stdout.write(
212
+ ` turn ${row.turn}: total ${row.total} vs actual ${row.actualInput ?? '-'} ` +
213
+ `(${row.deltaPct ?? '-'}%) factor ${row.factor}\n`,
214
+ );
215
+ }
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ // scripts/migrate-180.mjs — 1.8.0 / v2.8 §16.6:records.jsonl → claims.jsonl 迁移(默认 dry-run)
3
+ //
4
+ // node scripts/migrate-180.mjs [--memory-root <dir>] [--apply] [--json]
5
+ //
6
+ // 安全:默认 dry-run;--apply 先备份 records.jsonl 到 .longlive/backups/ 再追加 claims;
7
+ // 不物理删除任何文件;幂等(重复 apply 不重复追加)。
8
+
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+
13
+ import { migrateRecordsToClaims } from '../src/memory/migrate.js';
14
+
15
+ class CliError extends Error {
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.name = 'CliError';
19
+ this.code = code;
20
+ }
21
+ }
22
+
23
+ function parseArgs(argv) {
24
+ const out = { memoryRoot: '', apply: false, json: false, allowRealRoot: false };
25
+ for (let index = 0; index < argv.length; index += 1) {
26
+ const arg = argv[index];
27
+ const match = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
28
+ // 未知 flag / 位置参数必须显式 E_CLI_UNKNOWN_FLAG(exit 2),不许静默忽略。
29
+ if (!match) throw new CliError('E_CLI_UNKNOWN_FLAG', `unknown argument: ${arg}`);
30
+ let value = match[2];
31
+ if (value === undefined && index + 1 < argv.length && !String(argv[index + 1]).startsWith('--')) {
32
+ value = argv[index + 1];
33
+ index += 1;
34
+ }
35
+ // --root is an alias of --memory-root (sandbox drills used either spelling).
36
+ if (match[1] === 'memory-root' || match[1] === 'root') {
37
+ if (value === undefined || value === '') throw new CliError('E_CLI_INVALID_VALUE', '--memory-root/--root requires a value');
38
+ out.memoryRoot = value;
39
+ } else if (match[1] === 'apply') out.apply = true;
40
+ else if (match[1] === 'json') out.json = true;
41
+ else if (match[1] === 'allow-real-root') out.allowRealRoot = true;
42
+ else throw new CliError('E_CLI_UNKNOWN_FLAG', `unknown flag: --${match[1]}`);
43
+ }
44
+ return out;
45
+ }
46
+
47
+ function writeCliError(error, argv) {
48
+ const code = error?.code ?? 'E_MIGRATE_FAILED';
49
+ const exitCode = 2;
50
+ if (argv.includes('--json')) {
51
+ console.log(JSON.stringify({ ok: false, code, exitCode, error: String(error?.message ?? error) }, null, 2));
52
+ }
53
+ console.error(`[migrate-180] ${code}: ${error?.message ?? error}`);
54
+ process.exitCode = exitCode;
55
+ }
56
+
57
+ /** Resolve a path through junctions/symlinks when possible (fallback: lexical). */
58
+ function realPathOf(file) {
59
+ try {
60
+ return fs.realpathSync(file);
61
+ } catch {
62
+ return path.resolve(file);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Real memoryRoot candidates: env overrides, DSH longlive-memory, explicit host roots env.
68
+ * A migration must never silently write the real store from a sandbox drill.
69
+ */
70
+ function realMemoryRoots() {
71
+ const roots = new Set();
72
+ for (const name of ['DSH_LONGLIVE_MEMORY_ROOT', 'DSH_MEM']) {
73
+ const value = process.env[name];
74
+ if (typeof value === 'string' && value.trim() !== '') roots.add(path.resolve(value.trim()));
75
+ }
76
+ roots.add(path.join(dshHome(), 'longlive-memory'));
77
+ // Host-injected real roots (path.delimiter separated) for non-default stores.
78
+ const extra = process.env.DSH_LONGLIVE_REAL_ROOTS;
79
+ if (typeof extra === 'string' && extra.trim() !== '') {
80
+ for (const item of extra.split(path.delimiter)) {
81
+ if (item.trim() !== '') roots.add(path.resolve(item.trim()));
82
+ }
83
+ }
84
+ const out = new Set();
85
+ for (const candidate of roots) {
86
+ out.add(realPathOf(candidate));
87
+ out.add(path.resolve(candidate));
88
+ }
89
+ return out;
90
+ }
91
+
92
+ function isRealRoot(target) {
93
+ const resolved = realPathOf(target);
94
+ // Generic guard: a store directory named dsh-memory / longlive-memory is real
95
+ // unless the operator passed --allow-real-root (no machine paths in shipped code).
96
+ const base = path.basename(resolved).toLowerCase();
97
+ if (base === 'dsh-memory' || base === 'longlive-memory') return true;
98
+ for (const real of realMemoryRoots()) {
99
+ if (resolved === real) return true;
100
+ }
101
+ return false;
102
+ }
103
+
104
+ function dshHome() {
105
+ const raw = process.env.DSH_HOME;
106
+ if (typeof raw === 'string' && raw.trim() !== '') return path.resolve(raw.trim());
107
+ return path.join(os.homedir(), '.dsh');
108
+ }
109
+
110
+ function defaultMemoryRoot() {
111
+ for (const name of ['DSH_LONGLIVE_MEMORY_ROOT', 'DSH_MEM']) {
112
+ const value = process.env[name];
113
+ if (typeof value === 'string' && value.trim() !== '') return path.resolve(value.trim());
114
+ }
115
+ return path.join(dshHome(), 'longlive-memory');
116
+ }
117
+
118
+ function main() {
119
+ const args = parseArgs(process.argv.slice(2));
120
+ const memoryRoot = path.resolve(args.memoryRoot !== '' ? args.memoryRoot : defaultMemoryRoot());
121
+ // P0 防呆:沙箱演练绝不允许悄悄迁移真实 memoryRoot(dry-run 也一样拒绝)。
122
+ if (isRealRoot(memoryRoot) && args.allowRealRoot !== true) {
123
+ console.error(`[migrate-180] REFUSE target=${memoryRoot} is real memoryRoot (pass --allow-real-root only if intended)`);
124
+ process.exitCode = 3;
125
+ return;
126
+ }
127
+ const receipt = migrateRecordsToClaims({ memoryRoot, apply: args.apply });
128
+ if (receipt.code === 'E_NOTHING_TO_MIGRATE') {
129
+ // §16.6 / P0-2:空 records 不是成功退出。JSON 必须带
130
+ // recordsPresent/recordsTotal/countMatched,且 countMatched=false。
131
+ if (args.json) {
132
+ console.log(JSON.stringify(receipt, null, 2));
133
+ } else {
134
+ console.error(`[migrate-180] ${receipt.code}: recordsPresent=${receipt.recordsPresent} recordsTotal=${receipt.recordsTotal} countMatched=${receipt.countMatched}`);
135
+ }
136
+ process.exitCode = receipt.exitCode ?? 2;
137
+ return;
138
+ }
139
+ if (args.json) {
140
+ console.log(JSON.stringify(receipt, null, 2));
141
+ } else {
142
+ console.log(`[migrate-180] mode=${receipt.mode} memoryRoot=${receipt.memoryRoot}`);
143
+ console.log(`[migrate-180] records=${receipt.recordsTotal} mapped=${receipt.mapped} duplicates=${receipt.duplicates} unmappable=${receipt.unmappable.length} appended=${receipt.appended} skippedExisting=${receipt.skippedExisting}`);
144
+ console.log(`[migrate-180] claims before=${receipt.beforeClaims} after=${receipt.afterClaims} countMatched=${receipt.countMatched}`);
145
+ if (receipt.backup) console.log(`[migrate-180] backup=${receipt.backup.path} sha256=${receipt.backup.sha256}`);
146
+ if (!args.apply) console.log('[migrate-180] dry-run: nothing written (pass --apply to write claims)');
147
+ }
148
+ if (receipt.recordsTotal > 0 && !receipt.countMatched && args.apply) {
149
+ console.error('[migrate-180] FAIL: migration count mismatch');
150
+ process.exitCode = 1;
151
+ }
152
+ }
153
+
154
+ try {
155
+ main();
156
+ } catch (error) {
157
+ if (String(error?.code ?? '').startsWith('E_CLI_')) {
158
+ writeCliError(error, process.argv.slice(2));
159
+ } else {
160
+ console.error(`[migrate-180] FAILED: ${error?.stack ?? error}`);
161
+ process.exitCode = 1;
162
+ }
163
+ }
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // B7 CLI 入口:1.8.x → 2.0.0 迁移 + 冷层迁移二次 approve(plan/backup/manifest 三件套)。
3
+ // 默认 dry-run 只读;数据移动必须 plan --write → 第一次 approve → apply(备份) → 第二次 approve → apply。
4
+ // 详细契约见 src/memory/migrate-200.js 文件头与 M200-DRAFT-REPORT.md。
5
+ import { main } from '../src/memory/migrate-200.js';
6
+
7
+ const exitCode = await main(process.argv.slice(2));
8
+ process.exitCode = exitCode;
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // RC.5 A1 legacy migration CLI.
3
+ // Dry-run by default. --apply moves legacy cards into .longlive staging, writes
4
+ // a receipt/log, then rebuilds INDEX.md. It never deletes card content.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { migrateLegacyA1, preflightA1Legacy } from '../src/memory/a1-migration.js';
8
+ import { memoryIndex } from '../src/memory/index.js';
9
+
10
+ const args = process.argv.slice(2);
11
+ let memoryRoot = '';
12
+ let apply = false;
13
+ let checkOnly = false;
14
+ let out = '';
15
+ let json = false;
16
+ for (let i = 0; i < args.length; i += 1) {
17
+ const arg = args[i];
18
+ if (arg === '--memory-root' || arg === '--root') memoryRoot = args[++i] ?? '';
19
+ else if (arg.startsWith('--memory-root=')) memoryRoot = arg.slice('--memory-root='.length);
20
+ else if (arg.startsWith('--root=')) memoryRoot = arg.slice('--root='.length);
21
+ else if (arg === '--apply') apply = true;
22
+ else if (arg === '--dry-run') apply = false;
23
+ else if (arg === '--check-only' || arg === '--preflight') checkOnly = true;
24
+ else if (arg === '--json') json = true;
25
+ else if (arg === '--out') out = args[++i] ?? '';
26
+ else {
27
+ console.error(`[migrate-a1-legacy] unknown argument: ${arg}`);
28
+ process.exit(2);
29
+ }
30
+ }
31
+ if (memoryRoot === '') {
32
+ console.error('usage: node scripts/migrate-a1-legacy.mjs --memory-root <path> [--dry-run|--apply|--check-only] [--json] [--out <file>]');
33
+ process.exit(2);
34
+ }
35
+ const root = path.resolve(memoryRoot);
36
+ const preflight = preflightA1Legacy(root);
37
+ let result;
38
+ if (checkOnly) {
39
+ result = { ok: true, checkOnly: true, ...preflight };
40
+ const text = `${JSON.stringify(result, null, 2)}\n`;
41
+ if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(path.resolve(out), text, 'utf8'); }
42
+ process.stdout.write(text);
43
+ process.exit(preflight.blocking ? 2 : 0);
44
+ }
45
+ result = migrateLegacyA1({ memoryRoot: root, dryRun: !apply, now: new Date() });
46
+ result.preflight = preflight;
47
+ let index = null;
48
+ if (apply) {
49
+ try {
50
+ index = memoryIndex({ apply: true }, { memoryRoot: root });
51
+ result.indexRebuilt = index.applied === true;
52
+ result.indexCards = index.cards;
53
+ } catch (error) {
54
+ result.indexError = String(error?.message ?? error);
55
+ }
56
+ }
57
+ const text = `${JSON.stringify(result, null, 2)}\n`;
58
+ if (out) {
59
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
60
+ fs.writeFileSync(path.resolve(out), text, 'utf8');
61
+ }
62
+ process.stdout.write(json || !out ? text : '');
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lifecycle 迁移 CLI(1.8.11 D1/D7)。
4
+ *
5
+ * node scripts/migrate-lifecycle.mjs --mode plan [--memory-root <path>] [--plan <file>]
6
+ * node scripts/migrate-lifecycle.mjs --mode dry-run --memory-root <path> [--copy-root <dir>] [--cleanup]
7
+ * node scripts/migrate-lifecycle.mjs --mode apply --memory-root <path> --allow-real-root
8
+ * node scripts/migrate-lifecycle.mjs --mode rollback --memory-root <path> [--migration-id <id>]
9
+ * node scripts/migrate-lifecycle.mjs --mode list [--memory-root <path>]
10
+ *
11
+ * 安全阀:apply/rollback 在没有显式 --allow-real-root 时拒绝,且对默认记忆根
12
+ * (<DSH home>/longlive-memory)永远拒绝 —— 真库迁移要 lead 批准后另跑一次。
13
+ * 输出永远是 JSON(stdout),便于验收与红队复算。
14
+ */
15
+ import path from 'node:path';
16
+ import fs from 'node:fs';
17
+ import {
18
+ loadLifecyclePlan,
19
+ planLifecycleMigration,
20
+ applyLifecycleMigration,
21
+ rollbackLifecycleMigration,
22
+ dryRunLifecycleMigration,
23
+ listLifecycleMigrations,
24
+ resolveDefaultPlanPath,
25
+ } from '../src/memory/migrate-lifecycle.js';
26
+ import { memoryRootFromConfig, defaultMemoryRoot, isInsideRoot } from '../src/memory/paths.js';
27
+
28
+ function realPathOf(target) {
29
+ try {
30
+ return fs.realpathSync.native(target);
31
+ } catch {
32
+ return path.resolve(target);
33
+ }
34
+ }
35
+
36
+ function parseArgs(argv) {
37
+ const args = { _: [], json: true };
38
+ for (let i = 0; i < argv.length; i += 1) {
39
+ const token = argv[i];
40
+ if (!token.startsWith('--')) {
41
+ args._.push(token);
42
+ continue;
43
+ }
44
+ const eq = token.indexOf('=');
45
+ const key = (eq >= 0 ? token.slice(2, eq) : token.slice(2)).trim();
46
+ if (eq >= 0) {
47
+ args[key] = token.slice(eq + 1);
48
+ continue;
49
+ }
50
+ const next = argv[i + 1];
51
+ if (next == null || next.startsWith('--')) {
52
+ args[key] = true;
53
+ continue;
54
+ }
55
+ args[key] = next;
56
+ i += 1;
57
+ }
58
+ return args;
59
+ }
60
+
61
+ function fail(code, message, extra = {}) {
62
+ const receipt = { ok: false, code, message, ...extra };
63
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
64
+ process.exit(3);
65
+ }
66
+
67
+ const args = parseArgs(process.argv.slice(2));
68
+ const mode = typeof args.mode === 'string'
69
+ ? args.mode
70
+ : (args['dry-run'] ? 'dry-run' : args.apply ? 'apply' : args.rollback ? 'rollback' : 'plan');
71
+ const explicitRoot = typeof args['memory-root'] === 'string' ? args['memory-root']
72
+ : (typeof args['mem-root'] === 'string' ? args['mem-root'] : null);
73
+ let root = null;
74
+ try {
75
+ root = memoryRootFromConfig(explicitRoot == null ? {} : { memoryRoot: explicitRoot });
76
+ } catch (error) {
77
+ fail(error.code ?? 'E_MEMORY_ROOT', error.message);
78
+ }
79
+ // 红队 R12 P1-1:字符串比较可被 junction/符号链接别名绕过(mklink /J 指向真库后守卫不触发)。
80
+ // 这里用 realpathSync.native 解析:别名目标一律拒绝,只有「解析后确实是默认真根」才认。
81
+ const defaultRootReal = realPathOf(defaultMemoryRoot());
82
+ const rootResolved = path.resolve(root);
83
+ const rootReal = realPathOf(root);
84
+ const aliasDetected = rootResolved !== rootReal;
85
+ const touchesRealRoot = rootReal === defaultRootReal || isInsideRoot(defaultRootReal, rootReal);
86
+
87
+ if ((mode === 'apply' || mode === 'rollback') && aliasDetected) {
88
+ fail('E_REAL_ROOT_REFUSED', 'memory-root 是符号链接/junction 别名,可能指向真实记忆根;apply/rollback 拒绝通过别名执行', {
89
+ root,
90
+ rootReal,
91
+ defaultRootReal,
92
+ });
93
+ }
94
+ if ((mode === 'apply' || mode === 'rollback') && touchesRealRoot && args['allow-real-root'] !== true) {
95
+ fail('E_REAL_ROOT_REFUSED', '默认记忆根(或其子路径)上的 apply/rollback 需要 lead 批准后显式 --allow-real-root;请先用 --mode dry-run 在临时副本上验证', {
96
+ root,
97
+ rootReal,
98
+ defaultRootReal,
99
+ });
100
+ }
101
+
102
+ const planPath = resolveDefaultPlanPath({
103
+ memoryRoot: root,
104
+ planPath: typeof args.plan === 'string' ? args.plan : null,
105
+ });
106
+
107
+ // 1.8.13 隐私修复:npm 包不再随附 lifecycle-plan.json(逐字含真实记忆内容)。
108
+ // plan/dry-run/apply 在找不到计划时给出明确指引,而不是抽象 E_PLAN_MISSING。
109
+ if ((mode === 'plan' || mode === 'dry-run' || mode === 'apply') && !fs.existsSync(planPath)) {
110
+ fail('E_PLAN_MISSING', `lifecycle 迁移映射不在 npm 包内(1.8.13 起):${planPath}。`
111
+ + '请用 --plan 指定仓库内 src/memory/lifecycle-plan.json,或把计划放到 <memoryRoot>/.longlive/lifecycle-plan.json。', {
112
+ planPath,
113
+ memoryRoot: root,
114
+ });
115
+ }
116
+
117
+ try {
118
+ let receipt = null;
119
+ if (mode === 'plan') {
120
+ const loaded = loadLifecyclePlan(planPath);
121
+ receipt = planLifecycleMigration({ memoryRoot: root, plan: loaded.plan, planSha256: loaded.sha256, planPath: loaded.path });
122
+ } else if (mode === 'dry-run') {
123
+ const loaded = loadLifecyclePlan(planPath);
124
+ receipt = dryRunLifecycleMigration({
125
+ memoryRoot: root,
126
+ plan: loaded.plan,
127
+ planPath: loaded.path,
128
+ planSha256: loaded.sha256,
129
+ copyRoot: typeof args['copy-root'] === 'string' ? args['copy-root'] : null,
130
+ cleanup: args.cleanup === true,
131
+ query: typeof args.query === 'string' ? args.query : undefined,
132
+ });
133
+ } else if (mode === 'apply') {
134
+ const loaded = loadLifecyclePlan(planPath);
135
+ receipt = applyLifecycleMigration({ memoryRoot: root, plan: loaded.plan, planPath: loaded.path, planSha256: loaded.sha256 });
136
+ } else if (mode === 'rollback') {
137
+ receipt = rollbackLifecycleMigration({
138
+ memoryRoot: root,
139
+ migrationId: typeof args['migration-id'] === 'string' ? args['migration-id'] : null,
140
+ });
141
+ } else if (mode === 'list') {
142
+ receipt = listLifecycleMigrations({ memoryRoot: root });
143
+ } else {
144
+ fail('E_BAD_MODE', `不支持的 mode:${JSON.stringify(mode)}(plan|dry-run|apply|rollback|list)`);
145
+ }
146
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
147
+ process.exit(receipt.ok === false ? 2 : 0);
148
+ } catch (error) {
149
+ const receipt = {
150
+ ok: false,
151
+ code: error.code ?? 'E_MIGRATION_FAILED',
152
+ message: error.message,
153
+ manifestRel: error.manifestRel ?? null,
154
+ };
155
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
156
+ process.exit(1);
157
+ }