@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,1808 @@
1
+ /**
2
+ * lifecycle 迁移(1.8.11 D1/D7)。
3
+ *
4
+ * 把「哪张卡是当前正典」写成卡片 frontmatter 的 lifecycle 字段
5
+ * (canonical | historical),**绝不改 status**、绝不改 status 枚举、绝不写第二套
6
+ * 权威/状态机(D6/E6)。旧说法原文不删:整卡能降级就整卡降级,整卡不能降级(还载着
7
+ * 大量现行口径)就把旧段原文移入独立历史卡,原行换成回指行 —— 每一步都备份、都可回滚。
8
+ *
9
+ * 迁移映射文件:src/memory/lifecycle-plan.json(schema lifecycle-plan/v1)。
10
+ * 备份与 manifest:<memoryRoot>/.longlive/lifecycle-migrations/<stamp>/。
11
+ *
12
+ * 真库只读:本模块只接受调用方显式给的 memoryRoot;apply/rollback 的验证只在临时副本
13
+ * (dryRunLifecycleMigration 会自动复制)上进行,真库 apply 由上层(lead 批准后)决定。
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import os from 'node:os';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ import { memoryRootFromConfig, resolveInside, relativePath } from './paths.js';
21
+ import { parseFrontmatter, serializeFrontmatter, updateExtras, normalizedBody } from './frontmatter.js';
22
+ import { memoryIndex } from './index.js';
23
+ import { memoryRecall } from './recall.js';
24
+ import { memoryReinforce } from './reinforce.js';
25
+ import { memoryConsolidate } from './consolidate.js';
26
+ import {
27
+ LONGLIVE_DIR,
28
+ stampToken,
29
+ sha256File,
30
+ sha256Text,
31
+ ensureDir,
32
+ backupInto,
33
+ restoreBackup,
34
+ writeFileAtomic,
35
+ appendAudit,
36
+ } from './state.js';
37
+ import { readLifecycleFromText, readCardLifecycle, LIFECYCLE_VALUES } from './lifecycle.js';
38
+ import {
39
+ edgesPaths,
40
+ normalizeEdge,
41
+ dedupeEdges,
42
+ symmetrizeEdges,
43
+ serializeEdges,
44
+ EDGE_TYPES,
45
+ } from '../recall/edges.js';
46
+
47
+ export const MIGRATION_SCHEMA = 'lifecycle-migration/v1';
48
+ export const PLAN_SCHEMA = 'lifecycle-plan/v1';
49
+ export const MIGRATIONS_DIR = '.longlive/lifecycle-migrations';
50
+ export const LIFECYCLE_INDEX_BEGIN = '<!-- LIFECYCLE-BEGIN -->';
51
+ export const LIFECYCLE_INDEX_END = '<!-- LIFECYCLE-END -->';
52
+ export const DEFAULT_PLAN_FILE = 'lifecycle-plan.json';
53
+
54
+ /** 迁移会备份/恢复的 .longlive 状态文件(存在才备)。 */
55
+ export const STATE_FILES = Object.freeze([
56
+ '.longlive/memory-state.json',
57
+ '.longlive/audit.log',
58
+ '.longlive/manifest.json',
59
+ '.longlive/index-freshness.json',
60
+ ]);
61
+
62
+ const COPY_ROOT_FILES = Object.freeze(['INDEX.md', 'STATE.md']);
63
+ // 1.8.11 D7(红队 R11 P1-5):生产召回默认 dirs = topics + handover;副本必须带 handover,
64
+ // 否则 dry-run 的下游 recall 没有生产代表性(handover 里同样有旧口径卡)。
65
+ const COPY_ROOT_DIRS = Object.freeze(['topics', 'journal', 'procedures', 'handover']);
66
+ const COPY_LONGLIVE_FILES = Object.freeze([
67
+ '.longlive/memory-state.json',
68
+ '.longlive/audit.log',
69
+ '.longlive/manifest.json',
70
+ '.longlive/index-freshness.json',
71
+ '.longlive/recall/links.jsonl',
72
+ '.longlive/recall/links-audit.jsonl',
73
+ '.longlive/recall/edges.jsonl',
74
+ ]);
75
+
76
+ function memoryError(code, message, cause) {
77
+ const error = new Error(message);
78
+ error.code = code;
79
+ if (cause) error.cause = cause;
80
+ return error;
81
+ }
82
+
83
+ function collapse(value) {
84
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
85
+ }
86
+
87
+ /**
88
+ * 红队 R12 P2-2:legacyQuote 必须与来源「整行原文」逐字比对。
89
+ * 只规范行尾(去掉 CR 与尾随空白);行内每个字符都要相等,不看子串。
90
+ */
91
+ function normalizeQuoteLine(value) {
92
+ return String(value ?? '').replace(/\r$/, '').replace(/\s+$/, '');
93
+ }
94
+
95
+ function relAbs(root, rel) {
96
+ if (typeof rel !== 'string' || rel.trim() === '') {
97
+ throw memoryError('E_BAD_ARGUMENT', '迁移路径必须是非空字符串');
98
+ }
99
+ const abs = path.resolve(root, rel);
100
+ resolveInside(root, abs);
101
+ return abs;
102
+ }
103
+
104
+ function readTextOrNull(abs) {
105
+ try {
106
+ if (!fs.statSync(abs).isFile()) return null;
107
+ return fs.readFileSync(abs, 'utf8');
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function lineOfText(text, n) {
114
+ const lines = String(text ?? '').split(/\r?\n/);
115
+ return Number.isInteger(n) && n >= 1 && n <= lines.length ? lines[n - 1] : null;
116
+ }
117
+
118
+ function eolOf(text) {
119
+ return String(text ?? '').includes('\r\n') ? '\r\n' : '\n';
120
+ }
121
+
122
+ /**
123
+ * 宽容拆 frontmatter / body(不再调用 parseFrontmatter:块状列表卡会抛
124
+ * E_FRONTMATTER_MULTILINE,迁移只做字节级改写,不需要 strict 解析)。
125
+ * bodyStartLine 是 body 第一行在整份文件里的 1-based 行号。
126
+ */
127
+ function splitFrontmatterText(text) {
128
+ const value = String(text ?? '');
129
+ const bom = value.startsWith('\uFEFF') ? '\uFEFF' : '';
130
+ const rest = value.slice(bom.length);
131
+ const lines = [];
132
+ const separators = [];
133
+ let pos = 0;
134
+ while (pos <= rest.length) {
135
+ const match = /([^\r\n]*)(\r\n|\n|\r)?/.exec(rest.slice(pos));
136
+ if (!match || (match[0] === '' && pos === rest.length && lines.length > 0)) break;
137
+ lines.push(match[1]);
138
+ const end = pos + match[0].length;
139
+ separators.push(match[2] ?? '');
140
+ if (end >= rest.length) break;
141
+ pos = end;
142
+ }
143
+ const crlfCount = separators.filter((sep) => sep === '\r\n').length;
144
+ const lfCount = separators.filter((sep) => sep === '\n').length;
145
+ const eol = crlfCount > lfCount ? '\r\n' : '\n';
146
+ const joinFrom = (index) => lines.slice(index).map((line, offset) => `${line}${separators[index + offset] ?? ''}`).join('');
147
+ let hasFrontmatter = false;
148
+ let close = -1;
149
+ if (lines[0] !== undefined && lines[0].trim() === '---') {
150
+ for (let index = 1; index < lines.length; index += 1) {
151
+ if (lines[index].trim() === '---') {
152
+ close = index;
153
+ break;
154
+ }
155
+ }
156
+ hasFrontmatter = close > 0;
157
+ }
158
+ const bodyStartLine = hasFrontmatter ? close + 2 : 1;
159
+ return {
160
+ bom,
161
+ eol,
162
+ hasFrontmatter,
163
+ lines,
164
+ separators,
165
+ fmLines: hasFrontmatter ? lines.slice(1, close) : [],
166
+ body: hasFrontmatter ? joinFrom(close + 1) : rest,
167
+ bodyStartLine,
168
+ };
169
+ }
170
+
171
+ function frontmatterKeyOf(line) {
172
+ const match = /^([A-Za-z_][\w-]*)\s*:/.exec(String(line ?? '').trim());
173
+ return match ? match[1] : null;
174
+ }
175
+
176
+ function statusFromFmLines(fmLines) {
177
+ for (const line of fmLines ?? []) {
178
+ if (frontmatterKeyOf(line) !== 'status') continue;
179
+ const value = String(line).split(':').slice(1).join(':').trim().replace(/^["']|["']$/g, '');
180
+ return value || 'active';
181
+ }
182
+ return 'active';
183
+ }
184
+
185
+ /**
186
+ * 组合目标文本:frontmatter 只允许 lifecycle 变化(无 frontmatter 的卡只写 lifecycle,
187
+ * 不注入 salience/strength/revisions 等默认字段 —— 红队 R12-R2 P2-1),body 用快照替换结果。
188
+ */
189
+ function composeCardText(parsed, lifecycle, body) {
190
+ const eol = parsed.eol;
191
+ const fmLines = parsed.fmLines.slice();
192
+ if (lifecycle != null) {
193
+ const index = fmLines.findIndex((line) => frontmatterKeyOf(line) === 'lifecycle');
194
+ if (index >= 0) fmLines[index] = `lifecycle: ${lifecycle}`;
195
+ else fmLines.push(`lifecycle: ${lifecycle}`);
196
+ }
197
+ const block = fmLines.length > 0 ? `---${eol}${fmLines.join(eol)}${eol}---${eol}` : '';
198
+ const keys = fmLines.map(frontmatterKeyOf).filter(Boolean);
199
+ return {
200
+ text: `${parsed.bom}${block}${body}`,
201
+ fmLines,
202
+ keys,
203
+ frontmatterAdded: !parsed.hasFrontmatter && lifecycle != null,
204
+ };
205
+ }
206
+
207
+ /** 在快照 body 上按 plan 行号替换(行号是快照 body 内的 0-based 下标,保留原始行尾)。 */
208
+ function bodyLinesWithReplacements(snapshot, replacements) {
209
+ const bodyLines = (snapshot.lines ?? []).slice(snapshot.bodyStartLine - 1);
210
+ const separators = (snapshot.separators ?? []).slice(snapshot.bodyStartLine - 1);
211
+ for (const rep of replacements) {
212
+ if (!Number.isInteger(rep.bodyLineIndex) || rep.bodyLineIndex < 0 || rep.bodyLineIndex >= bodyLines.length) {
213
+ return { ok: false, reason: `行号越界:${rep.id} bodyLineIndex=${rep.bodyLineIndex}(body 共 ${bodyLines.length} 行)` };
214
+ }
215
+ bodyLines[rep.bodyLineIndex] = rep.replaceWith;
216
+ }
217
+ const body = bodyLines.map((line, index) => `${line}${separators[index] ?? ''}`).join('');
218
+ return { ok: true, body };
219
+ }
220
+
221
+ export function defaultPlanPath() {
222
+ return fileURLToPath(new URL(`./${DEFAULT_PLAN_FILE}`, import.meta.url));
223
+ }
224
+
225
+ /**
226
+ * 1.8.13 隐私修复:npm 包不再随附 lifecycle-plan.json(它逐字包含真实记忆内容)。
227
+ * 默认计划解析顺序:显式 --plan > <memoryRoot>/.longlive/lifecycle-plan.json > 包内默认(仅仓库内存在)。
228
+ */
229
+ export function resolveDefaultPlanPath({ memoryRoot = '', planPath = null } = {}) {
230
+ if (planPath) return planPath;
231
+ if (memoryRoot) {
232
+ const rooted = path.join(memoryRoot, LONGLIVE_DIR, DEFAULT_PLAN_FILE);
233
+ if (fs.existsSync(rooted)) return rooted;
234
+ }
235
+ return defaultPlanPath();
236
+ }
237
+
238
+ export function migrationsDir(root) {
239
+ return resolveInside(root, path.join(LONGLIVE_DIR, 'lifecycle-migrations'));
240
+ }
241
+
242
+ /** 校验 plan 文件形状;只接受 lifecycle-plan/v1。 */
243
+ export function loadLifecyclePlan(planPath = defaultPlanPath()) {
244
+ const abs = path.resolve(planPath);
245
+ let text = null;
246
+ try {
247
+ text = fs.readFileSync(abs, 'utf8');
248
+ } catch (error) {
249
+ throw memoryError('E_PLAN_MISSING', `lifecycle 迁移映射文件不存在:${abs}`, error);
250
+ }
251
+ let plan = null;
252
+ try {
253
+ plan = JSON.parse(text);
254
+ } catch (error) {
255
+ throw memoryError('E_PLAN_INVALID', `lifecycle 迁移映射不是合法 JSON:${abs}`, error);
256
+ }
257
+ validatePlan(plan);
258
+ return { plan, path: abs, sha256: sha256Text(text) };
259
+ }
260
+
261
+ function assertPlanRel(rel, label) {
262
+ if (typeof rel !== 'string' || !rel.trim()) {
263
+ throw memoryError('E_PLAN_INVALID', `${label} 缺失`);
264
+ }
265
+ const value = rel.trim();
266
+ if (path.isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith('/') || value.includes('\\')) {
267
+ throw memoryError('E_PLAN_INVALID', `${label} 必须是 posix 相对路径(不许绝对路径/反斜杠):${rel}`);
268
+ }
269
+ const segments = value.split('/');
270
+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
271
+ throw memoryError('E_PLAN_INVALID', `${label} 含非法路径段:${rel}`);
272
+ }
273
+ return value;
274
+ }
275
+
276
+ function assertSingleLine(value, label) {
277
+ if (typeof value !== 'string' || !value.trim()) {
278
+ throw memoryError('E_PLAN_INVALID', `${label} 必须是非空字符串`);
279
+ }
280
+ if (/[\r\n]/.test(value)) throw memoryError('E_PLAN_INVALID', `${label} 必须是单行文本(不许换行)`);
281
+ return value;
282
+ }
283
+
284
+ function assertIsoOrNull(value, label) {
285
+ if (value == null) return;
286
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
287
+ throw memoryError('E_PLAN_INVALID', `${label} 必须是 ISO 时间字符串:${value}`);
288
+ }
289
+ }
290
+
291
+ function assertEvidenceShape(evidence, label) {
292
+ if (!evidence || typeof evidence !== 'object') {
293
+ throw memoryError('E_PLAN_INVALID', `${label}.evidence 缺失`);
294
+ }
295
+ assertPlanRel(evidence.path, `${label}.evidence.path`);
296
+ assertSingleLine(evidence.quote, `${label}.evidence.quote`);
297
+ if (evidence.lines != null) {
298
+ const lines = Array.isArray(evidence.lines) ? evidence.lines.map(Number) : null;
299
+ if (!lines || lines.length !== 2 || !Number.isInteger(lines[0]) || !Number.isInteger(lines[1]) || lines[0] < 1 || lines[1] < lines[0]) {
300
+ throw memoryError('E_PLAN_INVALID', `${label}.evidence.lines 必须是 [start,end] 且 1 ≤ start ≤ end`);
301
+ }
302
+ }
303
+ if (evidence.sha256 != null && (typeof evidence.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(evidence.sha256))) {
304
+ throw memoryError('E_PLAN_INVALID', `${label}.evidence.sha256 必须是 64 位 hex`);
305
+ }
306
+ }
307
+
308
+ /**
309
+ * 校验 plan 文件形状;只接受 lifecycle-plan/v1。
310
+ *
311
+ * 红队 R11 P1-1:这里必须 fail-closed —— 枚举、路径、字段完整性都要在 validatePlan 就拒绝,
312
+ * 不能等到 apply 才默认成 'historical' 或让非法 lifecycle 静默落盘。
313
+ */
314
+ export function validatePlan(plan) { if (!plan || typeof plan !== 'object' || plan.schema !== PLAN_SCHEMA) {
315
+ throw memoryError('E_PLAN_INVALID', `plan.schema 必须是 ${PLAN_SCHEMA}`);
316
+ }
317
+ if (!Array.isArray(plan.cards)) throw memoryError('E_PLAN_INVALID', 'plan.cards 必须是数组');
318
+ if (!Array.isArray(plan.extracts)) throw memoryError('E_PLAN_INVALID', 'plan.extracts 必须是数组');
319
+ if (!Array.isArray(plan.edges)) throw memoryError('E_PLAN_INVALID', 'plan.edges 必须是数组');
320
+ assertIsoOrNull(plan.generated_at, 'plan.generated_at');
321
+ const cardRels = new Set();
322
+ for (const card of plan.cards) {
323
+ if (!card || typeof card !== 'object') throw memoryError('E_PLAN_INVALID', 'plan.cards[] 必须是对象');
324
+ const rel = assertPlanRel(card.rel, 'plan.cards[].rel');
325
+ if (cardRels.has(rel)) throw memoryError('E_PLAN_INVALID', `plan.cards rel 重复:${rel}`);
326
+ cardRels.add(rel);
327
+ if (!LIFECYCLE_VALUES.includes(card.lifecycle)) {
328
+ throw memoryError('E_PLAN_INVALID', `plan.cards[${rel}].lifecycle 非法:${card.lifecycle}`);
329
+ }
330
+ if (card.reason != null && typeof card.reason !== 'string') {
331
+ throw memoryError('E_PLAN_INVALID', `plan.cards[${rel}].reason 必须是字符串`);
332
+ }
333
+ assertEvidenceShape(card.evidence, `plan.cards[${rel}]`);
334
+ }
335
+ const seen = new Set();
336
+ for (const extract of plan.extracts) {
337
+ if (!extract || typeof extract !== 'object') throw memoryError('E_PLAN_INVALID', 'plan.extracts[] 必须是对象');
338
+ if (typeof extract.id !== 'string' || !extract.id) {
339
+ throw memoryError('E_PLAN_INVALID', 'plan.extracts[].id 缺失');
340
+ }
341
+ if (seen.has(extract.id)) throw memoryError('E_PLAN_INVALID', `plan.extracts id 重复:${extract.id}`);
342
+ seen.add(extract.id);
343
+ const fromRel = assertPlanRel(extract.fromRel, `plan.extracts[${extract.id}].fromRel`);
344
+ const extractLines = Array.isArray(extract.lines) ? extract.lines.map(Number) : null;
345
+ const singleLine = extractLines && (extractLines.length === 1
346
+ || (extractLines.length === 2 && extractLines[0] === extractLines[1]));
347
+ if (!singleLine || !Number.isInteger(extractLines[0]) || extractLines[0] < 1) {
348
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}] 需要单行 fromRel/lines(如 [65,65])`);
349
+ }
350
+ assertSingleLine(extract.quote, `plan.extracts[${extract.id}].quote`);
351
+ assertSingleLine(extract.replaceWith, `plan.extracts[${extract.id}].replaceWith`);
352
+ if (extract.legacyQuote != null) {
353
+ if (typeof extract.legacyQuote !== 'string' || !extract.legacyQuote.trim()) {
354
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}].legacyQuote 必须是非空字符串(历史卡要收录的来源整行原文)`);
355
+ }
356
+ if (/[\r\n]/.test(extract.legacyQuote)) {
357
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}].legacyQuote 必须来自单行来源(不许换行)`);
358
+ }
359
+ }
360
+ if (extract.sourceHandling != null && !['pointer', 'annotated'].includes(extract.sourceHandling)) {
361
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}].sourceHandling 只能是 pointer / annotated`);
362
+ }
363
+ if (extract.legacyNote != null && typeof extract.legacyNote !== 'string') {
364
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}].legacyNote 必须是字符串`);
365
+ }
366
+ const targetRel = assertPlanRel(extract.targetCard?.rel, `plan.extracts[${extract.id}].targetCard.rel`);
367
+ // 红队 P1-1 根因:targetCard.lifecycle 不校验枚举 → 'bogus' 也能静默落盘。
368
+ const targetLifecycle = extract.targetCard?.lifecycle ?? 'historical';
369
+ if (!LIFECYCLE_VALUES.includes(targetLifecycle)) {
370
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}].targetCard.lifecycle 非法:${extract.targetCard?.lifecycle}`);
371
+ }
372
+ if (targetRel === fromRel) {
373
+ throw memoryError('E_PLAN_INVALID', `plan.extracts[${extract.id}] 的来源与目标卡相同:${fromRel}`);
374
+ }
375
+ void fromRel;
376
+ }
377
+ for (const edge of plan.edges) {
378
+ if (!edge || typeof edge !== 'object') throw memoryError('E_PLAN_INVALID', 'plan.edges[] 必须是对象');
379
+ assertPlanRel(edge.from, 'plan.edges[].from');
380
+ assertPlanRel(edge.to, 'plan.edges[].to');
381
+ if (edge.from === edge.to) throw memoryError('E_PLAN_INVALID', `plan.edges[] from === to:${edge.from}`);
382
+ if (typeof edge.type !== 'string' || !EDGE_TYPES.includes(edge.type)) {
383
+ throw memoryError('E_PLAN_INVALID', `plan.edges[] type 非法:${edge.type}`);
384
+ }
385
+ if (edge.confidence != null && (typeof edge.confidence !== 'number' || edge.confidence < 0 || edge.confidence > 1)) {
386
+ throw memoryError('E_PLAN_INVALID', `plan.edges[] confidence 必须是 0..1 数字`);
387
+ }
388
+ assertIsoOrNull(edge.created_at, 'plan.edges[].created_at');
389
+ assertEvidenceShape(edge.evidence, 'plan.edges[]');
390
+ }
391
+ return true;
392
+ }
393
+
394
+ /** 证据校验:路径存在、行号在范围内、引文在那些行里逐字出现(空白折叠后)。 */
395
+ /** plan 的规范序列化(与 loadLifecyclePlan 落盘格式一致:2 空格 + 结尾换行)。 */
396
+ function canonicalPlanText(plan) {
397
+ return `${JSON.stringify(plan, null, 2)}\n`;
398
+ }
399
+
400
+ /** 给定 plan 的合法 sha256 候选(规范序列化 / 无尾换行)。plan 文件形态一致时也接受文件 sha。 */
401
+ export function planShaCandidates(plan, planPath = null) {
402
+ const candidates = new Set();
403
+ const canonical = canonicalPlanText(plan);
404
+ const compact = JSON.stringify(plan, null, 2);
405
+ candidates.add(sha256Text(canonical));
406
+ candidates.add(sha256Text(compact));
407
+ // 红队 R12 P2-1:只有 plan 文件字节确实等于同一 plan 的序列化时才接受文件 sha;
408
+ // 否则调用方可以指向任意文件、拿它的 sha 去「验证」一个被篡改过的 plan 对象。
409
+ if (planPath != null) {
410
+ const abs = path.resolve(planPath);
411
+ if (fs.existsSync(abs)) {
412
+ const fileText = fs.readFileSync(abs, 'utf8');
413
+ if (fileText === canonical || fileText === compact) candidates.add(sha256File(abs));
414
+ }
415
+ }
416
+ return candidates;
417
+ }
418
+
419
+ /**
420
+ * 红队 R12 P2-1:传了 planSha256 就必须校验,不匹配 fail-closed。
421
+ * 否则调用方可以传一个真 sha 却塞任意篡改过的 plan 对象(replaceWith 写任意内容)。
422
+ */
423
+ export function assertPlanSha(plan, planSha256, planPath = null) {
424
+ if (planSha256 == null) return null;
425
+ if (typeof planSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(planSha256)) {
426
+ throw memoryError('E_PLAN_SHA_MISMATCH', `planSha256 格式非法:${JSON.stringify(planSha256)}`);
427
+ }
428
+ const candidates = planShaCandidates(plan, planPath);
429
+ if (!candidates.has(planSha256)) {
430
+ throw memoryError(
431
+ 'E_PLAN_SHA_MISMATCH',
432
+ `planSha256 与 plan 内容不匹配:传入 ${planSha256},实算 ${[...candidates][0]}`,
433
+ );
434
+ }
435
+ return planSha256;
436
+ }
437
+
438
+ export function checkEvidence(root, evidence) {
439
+ if (!evidence || typeof evidence !== 'object' || typeof evidence.path !== 'string') {
440
+ return { ok: false, code: 'E_EVIDENCE_MISSING', detail: 'evidence.path 缺失' };
441
+ }
442
+ let abs = null;
443
+ try {
444
+ abs = relAbs(root, evidence.path);
445
+ } catch (error) {
446
+ return { ok: false, code: error.code ?? 'E_EVIDENCE_PATH', detail: error.message };
447
+ }
448
+ const text = readTextOrNull(abs);
449
+ if (text == null) return { ok: false, code: 'E_EVIDENCE_MISSING_FILE', detail: `证据文件不存在:${evidence.path}` };
450
+ const lines = text.split(/\r?\n/);
451
+ const range = Array.isArray(evidence.lines) && evidence.lines.length === 2
452
+ ? evidence.lines.map(Number)
453
+ : [1, lines.length];
454
+ const [start, end] = range;
455
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 1 || end < start || end > lines.length) {
456
+ return { ok: false, code: 'E_EVIDENCE_LINES', detail: `行号越界:${evidence.path}:${start}-${end}(共 ${lines.length} 行)` };
457
+ }
458
+ const quote = collapse(evidence.quote);
459
+ const hay = collapse(lines.slice(start - 1, end).join('\n'));
460
+ if (!quote) return { ok: false, code: 'E_EVIDENCE_QUOTE', detail: 'evidence.quote 缺失' };
461
+ if (!hay.includes(quote)) {
462
+ return {
463
+ ok: false,
464
+ code: 'E_EVIDENCE_MISMATCH',
465
+ detail: `引文未在 ${evidence.path}:${start}-${end} 逐字出现`,
466
+ actual: hay.slice(0, 240),
467
+ };
468
+ }
469
+ return { ok: true, path: evidence.path, lines: [start, end], quote, sha256: sha256Text(text) };
470
+ }
471
+
472
+ function planCardActions(root, plan) {
473
+ const actions = [];
474
+ for (const card of plan.cards) {
475
+ const action = {
476
+ rel: card.rel,
477
+ desired: card.lifecycle,
478
+ reason: card.reason ?? '',
479
+ status: 'pending',
480
+ current: null,
481
+ sha256Before: null,
482
+ evidence: checkEvidence(root, card.evidence),
483
+ };
484
+ const abs = relAbs(root, card.rel);
485
+ const text = readTextOrNull(abs);
486
+ if (text == null) {
487
+ action.status = 'missing-card';
488
+ actions.push(action);
489
+ continue;
490
+ }
491
+ action.sha256Before = sha256Text(text);
492
+ const current = readLifecycleFromText(text);
493
+ action.current = current;
494
+ // 红队 R12 P2-7:已迁移状态(lifecycle 已是期望值)一律 already,不再因证据行号漂移改判
495
+ // evidence-mismatch —— 否则二次 apply 会报 blocker,迁移动词不幂等。
496
+ if (current === card.lifecycle) action.status = 'already';
497
+ else if (current != null && current !== card.lifecycle) action.status = 'conflict';
498
+ else action.status = 'pending';
499
+ if (action.status !== 'already' && !action.evidence.ok) action.status = 'evidence-mismatch';
500
+ actions.push(action);
501
+ }
502
+ return actions;
503
+ }
504
+
505
+ function groupExtractTargets(plan) {
506
+ const groups = new Map();
507
+ for (const extract of plan.extracts) {
508
+ const target = extract.targetCard;
509
+ if (!groups.has(target.rel)) groups.set(target.rel, { target, extracts: [] });
510
+ groups.get(target.rel).extracts.push(extract);
511
+ }
512
+ return groups;
513
+ }
514
+
515
+ /**
516
+ * P0(R12-R2):apply 的「一次快照」阶段。所有读写决策都基于这里拍的原始快照:
517
+ * - cards 与 extracts 命中同一文件时,先在快照 body 上做行替换,再合成 frontmatter(只加 lifecycle);
518
+ * - 历史卡收录快照的原始整行与原始 sha(provenance 不许记先写 frontmatter 后的 sha);
519
+ * - 任何前置校验失败都进 failures,apply 直接 fail-closed(E_APPLY_VERIFY),一个字节都不写。
520
+ */
521
+ function buildApplyFiles({ root, plan, preview }) {
522
+ const snapshot = new Map();
523
+ const snapOf = (rel) => {
524
+ if (!snapshot.has(rel)) {
525
+ const abs = relAbs(root, rel);
526
+ const text = readTextOrNull(abs);
527
+ snapshot.set(rel, text == null
528
+ ? { rel, exists: false }
529
+ : { rel, exists: true, text, sha256: sha256Text(text), ...splitFrontmatterText(text) });
530
+ }
531
+ return snapshot.get(rel);
532
+ };
533
+ const files = new Map();
534
+ const fileOf = (rel) => {
535
+ if (!files.has(rel)) files.set(rel, { rel, lifecycle: null, replacements: [] });
536
+ return files.get(rel);
537
+ };
538
+ const archive = new Map();
539
+ const targetGroups = groupExtractTargets(plan);
540
+ // preview 的 extract action 只带运行状态字段;quote/reason/sourceHandling 等仍以 plan 为准。
541
+ const extractById = new Map((plan.extracts ?? []).map((item) => [item.id, item]));
542
+ const failures = [];
543
+ const pendingCards = preview.cards.filter((card) => card.status === 'pending');
544
+ const pendingExtracts = preview.extracts.filter((item) => item.status === 'pending');
545
+ const pendingTargets = preview.targets.filter((item) => item.status === 'pending');
546
+
547
+ for (const card of pendingCards) {
548
+ const snap = snapOf(card.rel);
549
+ if (!snap.exists) failures.push({ kind: 'card-missing', rel: card.rel });
550
+ else fileOf(card.rel).lifecycle = card.desired;
551
+ }
552
+ for (const extract of pendingExtracts) {
553
+ const spec = extractById.get(extract.id) ?? extract;
554
+ const fromRel = spec.fromRel ?? extract.fromRel;
555
+ const targetRel = extract.targetRel ?? spec.targetCard?.rel ?? null;
556
+ const lineNumber = (spec.lines ?? extract.lines)[0];
557
+ const snap = snapOf(fromRel);
558
+ if (!snap.exists) {
559
+ failures.push({ kind: 'source-missing', rel: fromRel, id: spec.id });
560
+ continue;
561
+ }
562
+ const wholeLine = snap.lines[lineNumber - 1];
563
+ if (wholeLine == null) {
564
+ failures.push({ kind: 'source-line-out-of-range', rel: fromRel, id: spec.id, line: lineNumber });
565
+ continue;
566
+ }
567
+ const archiveQuote = spec.legacyQuote ?? spec.quote;
568
+ const verified = spec.legacyQuote != null
569
+ ? normalizeQuoteLine(wholeLine) === normalizeQuoteLine(archiveQuote)
570
+ : collapse(wholeLine).includes(collapse(archiveQuote));
571
+ if (!verified) {
572
+ failures.push({ kind: 'legacy-line-mismatch', rel: fromRel, id: spec.id, line: lineNumber, expected: collapse(archiveQuote).slice(0, 160) });
573
+ continue;
574
+ }
575
+ if (wholeLine === spec.replaceWith) {
576
+ archive.set(spec.id, { id: spec.id, extract: spec, targetRel, origSha256: snap.sha256, archiveQuote, verified, already: true });
577
+ continue;
578
+ }
579
+ const bodyLineIndex = lineNumber - snap.bodyStartLine;
580
+ if (bodyLineIndex < 0) {
581
+ failures.push({ kind: 'source-line-before-body', rel: fromRel, id: spec.id, line: lineNumber });
582
+ continue;
583
+ }
584
+ fileOf(fromRel).replacements.push({
585
+ id: spec.id,
586
+ bodyLineIndex,
587
+ replaceWith: spec.replaceWith,
588
+ wholeLine,
589
+ oldQuote: spec.quote,
590
+ sourceHandling: spec.sourceHandling ?? 'pointer',
591
+ });
592
+ archive.set(spec.id, { id: spec.id, extract: spec, targetRel, origSha256: snap.sha256, archiveQuote, verified, already: false });
593
+ }
594
+
595
+ const outFiles = [];
596
+ for (const file of files.values()) {
597
+ const snap = snapOf(file.rel);
598
+ const replaced = bodyLinesWithReplacements(snap, file.replacements);
599
+ if (!replaced.ok) {
600
+ failures.push({ kind: 'body-replacement', rel: file.rel, detail: replaced.reason });
601
+ continue;
602
+ }
603
+ for (const rep of file.replacements) {
604
+ if (rep.sourceHandling !== 'annotated' && collapse(replaced.body).includes(collapse(rep.oldQuote))) {
605
+ failures.push({ kind: 'old-quote-not-gone', rel: file.rel, id: rep.id, detail: collapse(rep.oldQuote).slice(0, 160) });
606
+ }
607
+ }
608
+ const composed = composeCardText(snap, file.lifecycle, replaced.body);
609
+ // 只允许 frontmatter 新增/改写 lifecycle;其它 key 集合变化即 fail-closed(P2-1)。
610
+ const keysBefore = snap.fmLines.map(frontmatterKeyOf).filter(Boolean);
611
+ const addedKeys = composed.keys.filter((key) => !keysBefore.includes(key));
612
+ const removedKeys = keysBefore.filter((key) => !composed.keys.includes(key));
613
+ if (addedKeys.some((key) => key !== 'lifecycle') || removedKeys.length > 0) {
614
+ failures.push({ kind: 'frontmatter-changed', rel: file.rel, addedKeys, removedKeys });
615
+ }
616
+ outFiles.push({
617
+ rel: file.rel,
618
+ snapshot: snap,
619
+ expectedText: composed.text,
620
+ expectedSha256: sha256Text(composed.text),
621
+ expectedBodySha256: sha256Text(replaced.body),
622
+ frontmatterAdded: composed.frontmatterAdded,
623
+ keysBefore,
624
+ keysAfter: composed.keys,
625
+ statusBefore: statusFromFmLines(snap.fmLines),
626
+ lifecycleAfter: file.lifecycle,
627
+ replacements: file.replacements.map((rep) => ({ ...rep })),
628
+ });
629
+ }
630
+
631
+ const outTargets = [];
632
+ for (const target of pendingTargets) {
633
+ const group = targetGroups.get(target.rel);
634
+ const extracts = [...archive.values()].filter((item) => item.targetRel === target.rel);
635
+ if (extracts.length === 0) {
636
+ failures.push({ kind: 'target-without-extracts', rel: target.rel });
637
+ continue;
638
+ }
639
+ const text = buildLegacyCardText({ target: group.target, extracts });
640
+ outTargets.push({
641
+ rel: target.rel,
642
+ lifecycle: group.target.lifecycle ?? 'historical',
643
+ expectedText: text,
644
+ expectedSha256: sha256Text(text),
645
+ extracts: extracts.map((item) => ({
646
+ id: item.id,
647
+ fromRel: item.extract.fromRel,
648
+ origSha256: item.origSha256,
649
+ archiveQuote: item.archiveQuote,
650
+ verified: item.verified,
651
+ })),
652
+ });
653
+ }
654
+ return { ok: failures.length === 0, failures, files: outFiles, targets: outTargets, archive };
655
+ }
656
+
657
+ /**
658
+ * 历史卡正文:来源整行原文从快照取(P0:不许读已改写文件),provenance 记快照的原始 sha。
659
+ * extracts 形如 buildApplyFiles().archive 里的条目:{extract, origSha256, archiveQuote, verified}。
660
+ */
661
+ function buildLegacyCardText({ target, extracts }) {
662
+ const fields = {
663
+ title: target.title ?? target.rel,
664
+ date: target.frontmatter?.date,
665
+ tags: target.frontmatter?.tags,
666
+ salience: target.frontmatter?.salience ?? 2,
667
+ strength: target.frontmatter?.strength ?? 2,
668
+ };
669
+ const extras = { lifecycle: target.lifecycle ?? 'historical' };
670
+ const block = serializeFrontmatter(fields, extras, '\n');
671
+ const sections = [];
672
+ for (const item of extracts) {
673
+ const extract = item.extract;
674
+ const handling = extract.legacyNote
675
+ ?? (extract.sourceHandling === 'annotated'
676
+ ? '原文行原位保留并追加更正指针(未删原文)'
677
+ : '原文行已把旧子句换成回指行(其余文字逐字不变)');
678
+ sections.push([
679
+ `## 原文(${extract.fromRel}:${extract.lines[0]})`,
680
+ '',
681
+ `> ${collapse(item.archiveQuote)}`,
682
+ '',
683
+ `- 迁移前文件 sha256:\`${item.origSha256}\``,
684
+ `- 迁移原因:${collapse(extract.reason)}`,
685
+ `- 原文处理:${collapse(handling)}(历史卡收录整行原文校验:${item.verified ? '通过' : '未通过(本轮校验不通过)'})`,
686
+ ].join('\n'));
687
+ }
688
+ const header = collapse(target.bodyHeader);
689
+ const parts = [block, ''];
690
+ if (header) parts.push(`> ${header.replace(/^>\s*/, '')}`, '');
691
+ parts.push(sections.join('\n\n'), '');
692
+ return parts.join('\n').replace(/\n{3,}/g, '\n\n');
693
+ }
694
+
695
+ function planExtractActions(root, plan) {
696
+ const actions = [];
697
+ for (const extract of plan.extracts) {
698
+ const action = {
699
+ id: extract.id,
700
+ fromRel: extract.fromRel,
701
+ lines: extract.lines,
702
+ targetRel: extract.targetCard.rel,
703
+ status: 'pending',
704
+ sha256Before: null,
705
+ legacyQuoteOk: null,
706
+ evidence: checkEvidence(root, {
707
+ path: extract.fromRel,
708
+ lines: extract.lines,
709
+ quote: extract.quote,
710
+ }),
711
+ };
712
+ const abs = relAbs(root, extract.fromRel);
713
+ const text = readTextOrNull(abs);
714
+ if (text == null) {
715
+ action.status = 'missing-source';
716
+ } else {
717
+ action.sha256Before = sha256Text(text);
718
+ const line = lineOfText(text, extract.lines[0]);
719
+ // 可选 legacyQuote:历史卡要收录的来源整行原文(M1:整行除旧子句外还有现行事实,
720
+ // 历史卡保留整行原文;来源行只替换旧子句,其余逐字不动)。
721
+ // 红队 R12 P2-2:必须「整行原文」逐字相等(只规范行尾),不再接受子串命中。
722
+ const lineNormalized = line == null ? null : normalizeQuoteLine(line);
723
+ const legacyNormalized = extract.legacyQuote == null ? null : normalizeQuoteLine(extract.legacyQuote);
724
+ const legacyQuoteOk = extract.legacyQuote == null || (line != null && lineNormalized === legacyNormalized);
725
+ action.legacyQuoteOk = extract.legacyQuote == null ? null : legacyQuoteOk;
726
+ // 红队 R12 P2-7:已迁移(来源文件里已出现 replaceWith)时判 already,不因证据行号漂移
727
+ // 报 blocker。P0 之后无 frontmatter 卡会多出 frontmatter 行,行号必漂,必须按内容判断。
728
+ if (collapse(text).includes(collapse(extract.replaceWith))) action.status = 'already';
729
+ else if (!action.evidence.ok || !legacyQuoteOk) action.status = 'evidence-mismatch';
730
+ }
731
+ actions.push(action);
732
+ }
733
+ const targets = [];
734
+ for (const [rel, group] of groupExtractTargets(plan)) {
735
+ const abs = relAbs(root, rel);
736
+ const existing = readTextOrNull(abs);
737
+ let status = 'pending';
738
+ if (existing != null) {
739
+ const current = readLifecycleFromText(existing);
740
+ status = current === (group.target.lifecycle ?? 'historical') ? 'already' : 'conflict';
741
+ }
742
+ const planned = existing == null
743
+ ? { rel, lifecycle: group.target.lifecycle ?? 'historical', title: group.target.title ?? rel }
744
+ : { rel, lifecycle: readLifecycleFromText(existing), title: group.target.title ?? rel };
745
+ targets.push({ ...planned, status, sha256Before: existing == null ? null : sha256Text(existing) });
746
+ }
747
+ return { actions, targets };
748
+ }
749
+
750
+ function planEdgeActions(root, plan) {
751
+ const store = loadExistingEdges(root);
752
+ const actions = [];
753
+ for (const raw of plan.edges) {
754
+ const evidence = checkEvidence(root, raw.evidence);
755
+ const enriched = {
756
+ ...raw,
757
+ created_at: raw.created_at ?? plan.generated_at ?? null,
758
+ evidence: evidence.ok ? { ...raw.evidence, sha256: evidence.sha256 } : raw.evidence,
759
+ };
760
+ const normalized = normalizeEdge(enriched, { memoryRoot: root });
761
+ let status = 'pending';
762
+ const key = normalized ? `${normalized.from}|${normalized.to}|${normalized.type}` : null;
763
+ // 红队 R12 P2-7:plan 边已在 store 里 → already(先于证据校验),否则插入 lifecycle 行
764
+ // 造成的证据行号漂移会让二次 apply 报 evidence-mismatch blocker。
765
+ if (!normalized) status = 'invalid-edge';
766
+ else if (key && store.keys.has(key)) status = 'already';
767
+ else if (!evidence.ok) status = 'evidence-mismatch';
768
+ actions.push({
769
+ from: raw.from,
770
+ to: raw.to,
771
+ type: raw.type,
772
+ status,
773
+ evidence,
774
+ normalized,
775
+ });
776
+ }
777
+ return { actions, existing: store };
778
+ }
779
+
780
+ function loadExistingEdges(root) {
781
+ const paths = edgesPaths(root);
782
+ const text = readTextOrNull(paths.file);
783
+ const edges = [];
784
+ const badLines = [];
785
+ if (text != null) {
786
+ for (const line of text.split(/\r?\n/)) {
787
+ if (!line.trim()) continue;
788
+ try {
789
+ const raw = JSON.parse(line);
790
+ const normalized = normalizeEdge(raw, { memoryRoot: root });
791
+ if (normalized) edges.push(normalized);
792
+ else badLines.push(line.slice(0, 120));
793
+ } catch {
794
+ badLines.push(line.slice(0, 120));
795
+ }
796
+ }
797
+ }
798
+ return {
799
+ path: paths.file,
800
+ rel: relativePath(root, paths.file),
801
+ present: text != null,
802
+ sha256: text == null ? null : sha256Text(text),
803
+ edges,
804
+ badLines,
805
+ keys: new Set(edges.map((edge) => `${edge.from}|${edge.to}|${edge.type}`)),
806
+ };
807
+ }
808
+
809
+ function countByStatus(list) {
810
+ const counts = {};
811
+ for (const item of list) counts[item.status] = (counts[item.status] ?? 0) + 1;
812
+ return counts;
813
+ }
814
+
815
+ /**
816
+ * plan 模式:只读。给出每张卡/每条抽取/每条边会做什么、证据是否可核。
817
+ * `ok` 只有在没有 conflict / missing / evidence-mismatch 时为 true。
818
+ */
819
+ export function planLifecycleMigration({ memoryRoot, plan, planSha256 = null, planPath = null, now = new Date() } = {}) {
820
+ const root = memoryRootFromConfig({ memoryRoot });
821
+ if (!plan || typeof plan !== 'object') throw memoryError('E_PLAN_INVALID', 'plan 缺失');
822
+ validatePlan(plan);
823
+ assertPlanSha(plan, planSha256, planPath);
824
+ const cards = planCardActions(root, plan);
825
+ const extractPlan = planExtractActions(root, plan);
826
+ const edgePlan = planEdgeActions(root, plan);
827
+ const blockers = [];
828
+ for (const list of [cards, extractPlan.actions, extractPlan.targets, edgePlan.actions]) {
829
+ for (const item of list) {
830
+ if (item.status !== 'pending' && item.status !== 'already') blockers.push(item);
831
+ }
832
+ }
833
+ const indexPath = resolveInside(root, 'INDEX.md');
834
+ return {
835
+ ok: blockers.length === 0,
836
+ schema: PLAN_SCHEMA,
837
+ migrationSchema: MIGRATION_SCHEMA,
838
+ mode: 'plan',
839
+ root,
840
+ planSha256,
841
+ now: now.toISOString(),
842
+ cards,
843
+ extracts: extractPlan.actions,
844
+ targets: extractPlan.targets,
845
+ edges: edgePlan.actions,
846
+ edgesStore: { rel: edgePlan.existing.rel, present: edgePlan.existing.present, count: edgePlan.existing.edges.length },
847
+ index: { rel: 'INDEX.md', present: fs.existsSync(indexPath), sha256: fileSha(indexPath) },
848
+ counts: {
849
+ cards: countByStatus(cards),
850
+ extracts: countByStatus(extractPlan.actions),
851
+ targets: countByStatus(extractPlan.targets),
852
+ edges: countByStatus(edgePlan.actions),
853
+ blockers: blockers.length,
854
+ },
855
+ blockers,
856
+ readOnly: true,
857
+ };
858
+ }
859
+
860
+ function fileSha(abs) {
861
+ try {
862
+ return sha256File(abs);
863
+ } catch {
864
+ return null;
865
+ }
866
+ }
867
+
868
+ function migrationStamp(now) {
869
+ return `${stampToken(now)}-${process.pid}`;
870
+ }
871
+
872
+ function backUpFile(root, rel, backupDirRel, backups) {
873
+ const abs = relAbs(root, rel);
874
+ if (!fs.existsSync(abs)) return null;
875
+ const stored = backupInto(root, abs, backupDirRel, { now: new Date() });
876
+ const entry = {
877
+ rel,
878
+ backupRel: stored.rel,
879
+ sha256: stored.sha256,
880
+ bytes: fs.statSync(stored.path).size,
881
+ };
882
+ backups.push(entry);
883
+ return entry;
884
+ }
885
+
886
+ function writeJson(abs, value) {
887
+ fs.writeFileSync(abs, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
888
+ }
889
+
890
+ /**
891
+ * apply 模式:备份 → 写 lifecycle → 抽取旧段成历史卡 → 改回指行 → INDEX 注记 → 写 edges → 审计。
892
+ * 任何一步抛错都会留下 manifest 之前的备份(manifest 先写),便于 rollback。
893
+ */
894
+ export function applyLifecycleMigration({ memoryRoot, plan, planPath = null, planSha256 = null, now = new Date() } = {}) {
895
+ const root = memoryRootFromConfig({ memoryRoot });
896
+ const preview = planLifecycleMigration({ memoryRoot: root, plan, planSha256, planPath, now });
897
+ if (!preview.ok) {
898
+ throw memoryError('E_PLAN_UNSAFE', `plan 有 ${preview.blockers.length} 个阻塞项,拒绝 apply(先修 plan 或数据)`);
899
+ }
900
+ const alreadyPending = (
901
+ preview.cards.some((card) => card.status === 'pending')
902
+ || preview.extracts.some((item) => item.status === 'pending')
903
+ || preview.targets.some((item) => item.status === 'pending')
904
+ || preview.edges.some((item) => item.status === 'pending')
905
+ );
906
+ if (!alreadyPending) {
907
+ return {
908
+ ok: true,
909
+ schema: MIGRATION_SCHEMA,
910
+ mode: 'apply',
911
+ memoryRoot: root,
912
+ migrationId: null,
913
+ planSha256,
914
+ manifestRel: null,
915
+ backupDirRel: null,
916
+ backups: [],
917
+ created: [],
918
+ applied: { cards: [], extracts: [], targets: [], edges: 0, index: null },
919
+ changed: false,
920
+ alreadyApplied: true,
921
+ readOnly: false,
922
+ };
923
+ }
924
+
925
+ // P0(R12-R2):apply 先拍一次快照、在快照上算好所有目标字节,再统一写盘;
926
+ // 后续任何步骤都不许读已改写的文件(否则 cards+extracts 同文件会按错行替换)。
927
+ const prepared = buildApplyFiles({ root, plan, preview });
928
+ const migrationId = migrationStamp(now);
929
+ const backupDirRel = `${MIGRATIONS_DIR}/${migrationId}/backup`;
930
+ const backupDirAbs = ensureDir(root, backupDirRel);
931
+ const backups = [];
932
+ const created = [];
933
+
934
+ const manifestPathAbs = resolveInside(root, `${MIGRATIONS_DIR}/${migrationId}/manifest.json`);
935
+ fs.mkdirSync(path.dirname(manifestPathAbs), { recursive: true });
936
+
937
+ const pendingCards = preview.cards.filter((card) => card.status === 'pending');
938
+ const pendingExtracts = preview.extracts.filter((item) => item.status === 'pending');
939
+ const pendingSources = [...new Set(pendingExtracts.map((item) => item.fromRel))];
940
+ const pendingTargets = preview.targets.filter((item) => item.status === 'pending');
941
+ const pendingEdges = preview.edges.filter((item) => item.status === 'pending');
942
+
943
+ const manifest = {
944
+ schema: MIGRATION_SCHEMA,
945
+ migrationId,
946
+ at: now.toISOString(),
947
+ status: 'in-progress',
948
+ backupDir: relativePath(root, backupDirAbs),
949
+ planPath: planPath == null ? null : path.resolve(planPath),
950
+ planSha256,
951
+ root: relativePath(root, root) || '.',
952
+ rootAbs: path.resolve(root),
953
+ cards: pendingCards.map((card) => ({ rel: card.rel, lifecycle: card.desired, reason: card.reason })),
954
+ extracts: pendingExtracts.map((item) => ({ id: item.id, fromRel: item.fromRel, lines: item.lines, targetRel: item.targetRel })),
955
+ backups: [],
956
+ created: [],
957
+ createdEdges: null,
958
+ edges: { rel: preview.edgesStore.rel, added: 0, beforeSha256: null },
959
+ index: { rel: 'INDEX.md', beforeSha256: preview.index.sha256 },
960
+ };
961
+
962
+ for (const rel of [...new Set([...pendingCards.map((card) => card.rel), ...pendingSources])]) {
963
+ backUpFile(root, rel, backupDirRel, backups);
964
+ }
965
+ backUpFile(root, 'INDEX.md', backupDirRel, backups);
966
+ for (const rel of STATE_FILES) backUpFile(root, rel, backupDirRel, backups);
967
+ if (preview.edgesStore.present) {
968
+ const stored = backUpFile(root, preview.edgesStore.rel, backupDirRel, backups);
969
+ manifest.edges.beforeSha256 = stored?.sha256 ?? null;
970
+ }
971
+ manifest.backups = backups;
972
+ writeJson(manifestPathAbs, manifest);
973
+
974
+ const applied = { cards: [], extracts: [], targets: [], edges: 0, index: null };
975
+ const verificationPlan = {
976
+ planSha256,
977
+ files: prepared.files.map((file) => ({
978
+ rel: file.rel,
979
+ beforeSha256: file.snapshot.sha256,
980
+ expectedSha256: file.expectedSha256,
981
+ expectedBodySha256: file.expectedBodySha256,
982
+ frontmatterAdded: file.frontmatterAdded,
983
+ keysBefore: file.keysBefore,
984
+ keysAfter: file.keysAfter,
985
+ statusBefore: file.statusBefore,
986
+ lifecycleAfter: file.lifecycleAfter,
987
+ replacements: file.replacements.map((rep) => ({
988
+ id: rep.id,
989
+ bodyLineIndex: rep.bodyLineIndex,
990
+ oldQuote: rep.oldQuote,
991
+ replaceWith: rep.replaceWith,
992
+ sourceHandling: rep.sourceHandling,
993
+ })),
994
+ })),
995
+ targets: prepared.targets.map((target) => ({
996
+ rel: target.rel,
997
+ expectedSha256: target.expectedSha256,
998
+ extracts: target.extracts,
999
+ })),
1000
+ };
1001
+
1002
+ const undo = () => {
1003
+ // fail-closed:任何校验失败都把已写的字节还原(卡/来源/INDEX/状态/edges),
1004
+ // 并删掉本次新建的历史卡与 edges 文件;审计日志 append-only 不还原。
1005
+ for (const backup of backups) {
1006
+ if (backup.rel === '.longlive/audit.log') continue;
1007
+ try {
1008
+ restoreBackup(root, backup.backupRel, backup.rel);
1009
+ } catch { /* 尽力还原 */ }
1010
+ }
1011
+ for (const item of created) {
1012
+ try {
1013
+ const abs = relAbs(root, item.rel);
1014
+ if (fs.existsSync(abs)) fs.unlinkSync(abs);
1015
+ } catch { /* 尽力清理 */ }
1016
+ }
1017
+ if (manifest.createdEdges) {
1018
+ try {
1019
+ const abs = relAbs(root, manifest.createdEdges);
1020
+ if (fs.existsSync(abs)) fs.unlinkSync(abs);
1021
+ } catch { /* 尽力清理 */ }
1022
+ }
1023
+ };
1024
+
1025
+ try {
1026
+ if (!prepared.ok) {
1027
+ const error = memoryError('E_APPLY_VERIFY', `apply 前置快照校验失败(${prepared.failures.length} 项),未写任何文件`);
1028
+ error.failures = prepared.failures;
1029
+ throw error;
1030
+ }
1031
+
1032
+ // 1) 来源卡/来源行:每份文件只写一次(frontmatter lifecycle + body 行替换在同一份快照上合成)。
1033
+ for (const file of prepared.files) {
1034
+ const abs = relAbs(root, file.rel);
1035
+ const written = writeFileAtomic(root, abs, file.expectedText, { backup: false, now });
1036
+ const readback = fs.readFileSync(abs, 'utf8');
1037
+ if (sha256Text(readback) !== file.expectedSha256) {
1038
+ throw memoryError('E_WRITE_VERIFY', `写入后字节不一致:${file.rel}`);
1039
+ }
1040
+ const parsed = splitFrontmatterText(readback);
1041
+ if (statusFromFmLines(parsed.fmLines) !== file.statusBefore) {
1042
+ throw memoryError('E_STATUS_CHANGED', `迁移意外改动了 status:${file.rel}`);
1043
+ }
1044
+ if (sha256Text(parsed.body) !== file.expectedBodySha256) {
1045
+ throw memoryError('E_BODY_CHANGED', `迁移意外改动了正文:${file.rel}`);
1046
+ }
1047
+ if (file.lifecycleAfter != null && readLifecycleFromText(readback) !== file.lifecycleAfter) {
1048
+ throw memoryError('E_WRITE_VERIFY', `lifecycle 回读不一致:${file.rel}`);
1049
+ }
1050
+ const bodyLines = parsed.lines.slice(parsed.bodyStartLine - 1);
1051
+ for (const rep of file.replacements) {
1052
+ if (bodyLines[rep.bodyLineIndex] !== rep.replaceWith) {
1053
+ throw memoryError('E_WRITE_VERIFY', `来源行回读不一致:${file.rel} bodyLineIndex=${rep.bodyLineIndex}`);
1054
+ }
1055
+ if (rep.sourceHandling !== 'annotated' && collapse(parsed.body).includes(collapse(rep.oldQuote))) {
1056
+ throw memoryError('E_APPLY_VERIFY', `旧句未消失:${file.rel}(${rep.id})`);
1057
+ }
1058
+ }
1059
+ for (const card of pendingCards.filter((item) => item.rel === file.rel)) {
1060
+ applied.cards.push({ rel: card.rel, lifecycle: card.desired, sha256Before: card.sha256Before, sha256After: written.sha256 });
1061
+ }
1062
+ for (const extract of pendingExtracts.filter((item) => item.fromRel === file.rel)) {
1063
+ const rep = file.replacements.find((item) => item.id === extract.id);
1064
+ applied.extracts.push({
1065
+ id: extract.id,
1066
+ fromRel: extract.fromRel,
1067
+ line: extract.lines[0],
1068
+ targetRel: extract.targetRel,
1069
+ sha256After: written.sha256,
1070
+ bodyLineIndex: rep?.bodyLineIndex ?? null,
1071
+ });
1072
+ }
1073
+ }
1074
+
1075
+ // 2) 历史卡:整行原文与 provenance 全部来自快照。
1076
+ for (const target of prepared.targets) {
1077
+ const abs = relAbs(root, target.rel);
1078
+ const written = writeFileAtomic(root, abs, target.expectedText, { backup: false, now });
1079
+ const readback = fs.readFileSync(abs, 'utf8');
1080
+ if (sha256Text(readback) !== target.expectedSha256) {
1081
+ throw memoryError('E_WRITE_VERIFY', `历史卡写入后字节不一致:${target.rel}`);
1082
+ }
1083
+ if (readLifecycleFromText(readback) !== target.lifecycle) {
1084
+ throw memoryError('E_WRITE_VERIFY', `历史卡 lifecycle 回读不一致:${target.rel}`);
1085
+ }
1086
+ created.push({ rel: target.rel, sha256: written.sha256 });
1087
+ applied.targets.push({ rel: target.rel, lifecycle: target.lifecycle, sha256After: written.sha256 });
1088
+ }
1089
+
1090
+ // 3) INDEX.md 的历史口径注记。
1091
+ const indexNote = buildIndexNote(preview, plan);
1092
+ const indexPath = resolveInside(root, 'INDEX.md');
1093
+ if (fs.existsSync(indexPath)) {
1094
+ const before = fs.readFileSync(indexPath, 'utf8');
1095
+ const after = upsertLifecycleSection(before, indexNote);
1096
+ if (after !== before) {
1097
+ const written = writeFileAtomic(root, indexPath, after, { backup: false, now });
1098
+ applied.index = { rel: 'INDEX.md', sha256After: written.sha256 };
1099
+ }
1100
+ }
1101
+
1102
+ // 4) edges.jsonl:plan 里的边 → normalize → 补反向 → 去重 → 追加写。
1103
+ const edgeStore = loadExistingEdges(root);
1104
+ const dedupedLocal = dedupeEdges([...edgeStore.edges, ...pendingEdges.map((item) => item.normalized)]);
1105
+ const symmetricLocal = symmetrizeEdges(dedupedLocal.edges);
1106
+ const merged = symmetricLocal.edges;
1107
+ const added = merged.length - edgeStore.edges.length;
1108
+ const edgesText = serializeEdges(merged);
1109
+ const edgesFileAbs = relAbs(root, relativePath(root, edgesPaths(root).file));
1110
+ const edgesWritten = writeFileAtomic(root, edgesFileAbs, edgesText, { backup: false, now });
1111
+ applied.edges = added;
1112
+ manifest.edges.afterSha256 = edgesWritten.sha256;
1113
+ manifest.edges.added = added;
1114
+ manifest.edges.total = merged.length;
1115
+ if (!preview.edgesStore.present) manifest.createdEdges = relativePath(root, edgesPaths(root).file);
1116
+
1117
+ // P0/P1(R12-R2):验证门基于「apply 前快照 vs apply 后」;失败即 fail-closed。
1118
+ manifest.verificationPlan = verificationPlan;
1119
+ const verification = verifyAppliedMigration(root, plan, { manifest });
1120
+ manifest.verification = { ok: verification.ok, failures: verification.failures, counts: verification.counts };
1121
+ if (!verification.ok) {
1122
+ const error = memoryError('E_APPLY_VERIFY', `apply 后验证失败(${verification.failures.length} 项)`);
1123
+ error.failures = verification.failures;
1124
+ throw error;
1125
+ }
1126
+
1127
+ for (const entry of backups) {
1128
+ if (entry.rel === '.longlive/audit.log') {
1129
+ entry.appliedSha256 = null;
1130
+ entry.appendOnly = true;
1131
+ continue;
1132
+ }
1133
+ entry.appliedSha256 = fileSha(relAbs(root, entry.rel));
1134
+ }
1135
+ for (const item of created) item.sha256After = fileSha(relAbs(root, item.rel));
1136
+
1137
+ manifest.status = 'applied';
1138
+ manifest.applied = applied;
1139
+ manifest.created = created;
1140
+ writeJson(manifestPathAbs, manifest);
1141
+
1142
+ appendAudit(root, {
1143
+ action: 'lifecycle-migration',
1144
+ object: `migrations/${migrationId}`,
1145
+ result: `applied cards=${applied.cards.length} extracts=${applied.extracts.length} targets=${applied.targets.length} edges=+${added}`,
1146
+ now,
1147
+ });
1148
+
1149
+ return {
1150
+ ok: true,
1151
+ schema: MIGRATION_SCHEMA,
1152
+ mode: 'apply',
1153
+ memoryRoot: root,
1154
+ migrationId,
1155
+ planSha256,
1156
+ manifestRel: relativePath(root, manifestPathAbs),
1157
+ backupDirRel,
1158
+ backups,
1159
+ created,
1160
+ applied,
1161
+ verification: { ok: true, counts: verification.counts },
1162
+ readOnly: false,
1163
+ };
1164
+ } catch (error) {
1165
+ undo();
1166
+ manifest.status = 'failed';
1167
+ manifest.created = created;
1168
+ manifest.error = { code: error.code ?? 'E_MIGRATION_FAILED', message: error.message, failures: error.failures ?? null };
1169
+ manifest.restoredOnFailure = true;
1170
+ writeJson(manifestPathAbs, manifest);
1171
+ error.manifestRel = relativePath(root, manifestPathAbs);
1172
+ throw error;
1173
+ }
1174
+ }
1175
+
1176
+
1177
+
1178
+ function buildIndexNote(preview, plan = null) {
1179
+ const lines = [LIFECYCLE_INDEX_BEGIN, '', '## lifecycle 历史口径(迁移注记)', ''];
1180
+ lines.push('| 卡 | lifecycle | 原因 |', '|---|---|---|');
1181
+ for (const card of preview.cards) {
1182
+ if (card.status === 'already' && card.desired !== 'historical') continue;
1183
+ if (card.desired !== 'historical') continue;
1184
+ lines.push(`| ${card.rel} | historical | ${collapse(card.reason)} |`);
1185
+ }
1186
+ // 红队 R12 P2-4:来源行的处理方式按 sourceHandling 如实写,不许把 annotated(原位保留)也写成「已换成回指行」。
1187
+ const handlingByTarget = new Map();
1188
+ for (const extract of plan?.extracts ?? []) {
1189
+ const targetRel = extract?.targetCard?.rel;
1190
+ if (!targetRel) continue;
1191
+ const note = extract.sourceHandling === 'annotated'
1192
+ ? '来源行原位标注(原文保留)'
1193
+ : '来源行已换成回指行(其余文字逐字保留)';
1194
+ if (!handlingByTarget.has(targetRel)) handlingByTarget.set(targetRel, new Set());
1195
+ handlingByTarget.get(targetRel).add(note);
1196
+ }
1197
+ for (const target of preview.targets) {
1198
+ const notes = [...(handlingByTarget.get(target.rel) ?? [])].join(';') || '旧口径原文归档';
1199
+ lines.push(`| ${target.rel} | ${target.lifecycle} | 旧口径原文归档(${notes}) |`);
1200
+ }
1201
+ lines.push('', '> 说明:historical 只表示「不是当前正典」;status 不变(仍 active),正文不删。', '', LIFECYCLE_INDEX_END);
1202
+ return lines.join('\n');
1203
+ }
1204
+
1205
+ function upsertLifecycleSection(existing, note) {
1206
+ const start = existing.indexOf(LIFECYCLE_INDEX_BEGIN);
1207
+ const end = existing.indexOf(LIFECYCLE_INDEX_END);
1208
+ if (start >= 0 && end > start) {
1209
+ const afterEnd = end + LIFECYCLE_INDEX_END.length;
1210
+ return `${existing.slice(0, start)}${note}${existing.slice(afterEnd)}`;
1211
+ }
1212
+ const eol = eolOf(existing);
1213
+ const trimmed = existing.replace(/[\r\n]+$/, '');
1214
+ return `${trimmed}${eol}${eol}${note}${eol}`;
1215
+ }
1216
+
1217
+ export function listLifecycleMigrations({ memoryRoot } = {}) {
1218
+ const root = memoryRootFromConfig({ memoryRoot });
1219
+ const dir = migrationsDir(root);
1220
+ if (!fs.existsSync(dir)) return { ok: true, root, migrations: [] };
1221
+ const migrations = [];
1222
+ for (const name of fs.readdirSync(dir).sort()) {
1223
+ const abs = path.join(dir, name);
1224
+ let stat = null;
1225
+ try {
1226
+ stat = fs.statSync(abs);
1227
+ } catch {
1228
+ continue;
1229
+ }
1230
+ if (!stat.isDirectory()) continue;
1231
+ const manifestAbs = path.join(abs, 'manifest.json');
1232
+ let manifest = null;
1233
+ try {
1234
+ manifest = JSON.parse(fs.readFileSync(manifestAbs, 'utf8'));
1235
+ } catch {
1236
+ manifest = null;
1237
+ }
1238
+ migrations.push({ migrationId: name, manifestRel: relativePath(root, manifestAbs), manifest });
1239
+ }
1240
+ return { ok: true, root, migrations };
1241
+ }
1242
+
1243
+ function pickRollbackMigration(root, migrationId) {
1244
+ if (migrationId) {
1245
+ const abs = resolveInside(root, `${MIGRATIONS_DIR}/${migrationId}/manifest.json`);
1246
+ if (!fs.existsSync(abs)) throw memoryError('E_MIGRATION_MISSING', `找不到迁移 manifest:${migrationId}`);
1247
+ return { abs, manifest: JSON.parse(fs.readFileSync(abs, 'utf8')) };
1248
+ }
1249
+ const listed = listLifecycleMigrations({ memoryRoot: root }).migrations.filter((item) => item.manifest?.status === 'applied');
1250
+ if (listed.length === 0) throw memoryError('E_NOTHING_TO_ROLLBACK', '没有可回滚的 applied 迁移');
1251
+ return {
1252
+ abs: resolveInside(root, listed[listed.length - 1].manifestRel),
1253
+ manifest: listed[listed.length - 1].manifest,
1254
+ };
1255
+ }
1256
+
1257
+ /**
1258
+ * rollback:按 manifest 还原所有备份文件(卡 / INDEX.md / .longlive 状态 / edges.jsonl),
1259
+ * 删除本次新建的卡,逐字节校验 sha256。返回 countMatched / mismatched。
1260
+ */
1261
+ export function rollbackLifecycleMigration({ memoryRoot, migrationId = null, now = new Date(), overrideConcurrent = false } = {}) {
1262
+ const root = memoryRootFromConfig({ memoryRoot });
1263
+ const picked = pickRollbackMigration(root, migrationId);
1264
+ const manifest = picked.manifest;
1265
+ if (manifest.schema !== MIGRATION_SCHEMA) {
1266
+ throw memoryError('E_MIGRATION_INVALID', `manifest schema 非法:${manifest.schema}`);
1267
+ }
1268
+ // 红队 R12 P2-6:恢复前逐个比对「当前 sha」与 manifest 记录的 apply 后 sha;
1269
+ // 不一致说明 apply 之后有人并发写,整文件还原会静默覆盖,必须 fail-closed(除非显式 override)。
1270
+ const conflicts = [];
1271
+ for (const backup of manifest.backups ?? []) {
1272
+ if (backup.appendOnly === true || backup.rel === '.longlive/audit.log') continue;
1273
+ const current = fileSha(relAbs(root, backup.rel));
1274
+ if (backup.appliedSha256 != null && current !== backup.appliedSha256) {
1275
+ conflicts.push({ rel: backup.rel, expected: backup.appliedSha256, actual: current, kind: 'backup' });
1276
+ }
1277
+ }
1278
+ for (const item of manifest.created ?? []) {
1279
+ const abs = relAbs(root, item.rel);
1280
+ if (!fs.existsSync(abs)) continue;
1281
+ const actual = fileSha(abs);
1282
+ if (item.sha256After != null && actual !== item.sha256After) {
1283
+ conflicts.push({ rel: item.rel, expected: item.sha256After, actual, kind: 'created' });
1284
+ }
1285
+ }
1286
+ if (manifest.createdEdges != null) {
1287
+ const abs = relAbs(root, manifest.createdEdges);
1288
+ if (fs.existsSync(abs)) {
1289
+ const actual = fileSha(abs);
1290
+ const after = manifest.edges?.afterSha256 ?? null;
1291
+ if (after != null && actual !== after) {
1292
+ conflicts.push({ rel: manifest.createdEdges, expected: after, actual, kind: 'created-edges' });
1293
+ }
1294
+ }
1295
+ }
1296
+ if (conflicts.length > 0 && overrideConcurrent !== true) {
1297
+ const error = memoryError(
1298
+ 'E_ROLLBACK_CONFLICT',
1299
+ `apply 之后有 ${conflicts.length} 个文件被并发改写,拒绝覆盖式回滚(确认后用 overrideConcurrent 重试)`,
1300
+ );
1301
+ error.conflicts = conflicts;
1302
+ throw error;
1303
+ }
1304
+ const restored = [];
1305
+ const mismatched = [];
1306
+ const preserved = [];
1307
+ for (const backup of manifest.backups ?? []) {
1308
+ // 审计日志 append-only:保留 apply 审计行,不整文件还原。
1309
+ if (backup.appendOnly === true || backup.rel === '.longlive/audit.log') {
1310
+ preserved.push(backup.rel);
1311
+ continue;
1312
+ }
1313
+ const targetAbs = relAbs(root, backup.rel);
1314
+ if (!fs.existsSync(targetAbs)) {
1315
+ const dir = path.dirname(targetAbs);
1316
+ fs.mkdirSync(dir, { recursive: true });
1317
+ }
1318
+ const result = restoreBackup(root, backup.backupRel, backup.rel);
1319
+ const ok = result.sha256 === backup.sha256;
1320
+ restored.push({ rel: backup.rel, sha256: result.sha256, expected: backup.sha256, ok });
1321
+ if (!ok) mismatched.push(backup.rel);
1322
+ }
1323
+ const removed = [];
1324
+ for (const item of manifest.created ?? []) {
1325
+ const abs = relAbs(root, item.rel);
1326
+ if (fs.existsSync(abs)) {
1327
+ fs.unlinkSync(abs);
1328
+ removed.push(item.rel);
1329
+ }
1330
+ }
1331
+ if (manifest.createdEdges) {
1332
+ const abs = relAbs(root, manifest.createdEdges);
1333
+ if (fs.existsSync(abs)) {
1334
+ fs.unlinkSync(abs);
1335
+ removed.push(manifest.createdEdges);
1336
+ }
1337
+ }
1338
+ const afterIndex = fileSha(resolveInside(root, 'INDEX.md'));
1339
+ const receipt = {
1340
+ ok: mismatched.length === 0,
1341
+ schema: MIGRATION_SCHEMA,
1342
+ mode: 'rollback',
1343
+ memoryRoot: root,
1344
+ migrationId: manifest.migrationId,
1345
+ manifestRel: manifest.manifestRel ?? picked.manifest.migrationId,
1346
+ restored: restored.length,
1347
+ removed: removed.length,
1348
+ mismatched,
1349
+ indexSha256: afterIndex,
1350
+ countMatched: restored.filter((item) => item.ok).length,
1351
+ countExpected: restored.length,
1352
+ auditLogPreserved: true,
1353
+ auditLogBackedUp: preserved.length > 0,
1354
+ preserved,
1355
+ concurrentConflicts: conflicts,
1356
+ concurrentOverride: conflicts.length > 0 && overrideConcurrent === true,
1357
+ now: now.toISOString(),
1358
+ };
1359
+ // 红队 R12 P2-5:rollback 自己也要留审计(与 apply 审计行并存,不许抹掉 apply 记录)。
1360
+ appendAudit(root, {
1361
+ action: 'lifecycle-migration-rollback',
1362
+ object: `migrations/${manifest.migrationId}`,
1363
+ result: `rolled-back restored=${restored.length} removed=${removed.length}${conflicts.length ? ` overrides=${conflicts.length}` : ''}`,
1364
+ now,
1365
+ });
1366
+ const manifestAbs = picked.abs;
1367
+ const updated = {
1368
+ ...manifest,
1369
+ status: 'rolled-back',
1370
+ rolledBackAt: now.toISOString(),
1371
+ rollback: { restored: restored.length, removed: removed.length, mismatched, conflicts, overrideConcurrent: conflicts.length > 0 && overrideConcurrent === true },
1372
+ };
1373
+ writeJson(manifestAbs, updated);
1374
+ return receipt;
1375
+ }
1376
+
1377
+ /** 选择性复制记忆根(真库 4.4 GB,不能整根拷);只拷记忆模块会用到的文件。 */
1378
+ export function copyMemoryRootForDryRun({ memoryRoot, destination, now = new Date() } = {}) {
1379
+ const root = memoryRootFromConfig({ memoryRoot });
1380
+ if (!destination) throw memoryError('E_BAD_ARGUMENT', 'dry-run 需要显式 destination');
1381
+ const dest = path.resolve(destination);
1382
+ if (dest === path.resolve(root)) throw memoryError('E_BAD_ARGUMENT', 'destination 不能等于源根');
1383
+ fs.mkdirSync(dest, { recursive: true });
1384
+ for (const rel of COPY_ROOT_FILES) copyIfExists(path.resolve(root, rel), path.resolve(dest, rel));
1385
+ for (const rel of COPY_ROOT_DIRS) {
1386
+ const src = path.resolve(root, rel);
1387
+ if (!fs.existsSync(src)) continue;
1388
+ fs.cpSync(src, path.resolve(dest, rel), { recursive: true, force: true });
1389
+ }
1390
+ for (const rel of COPY_LONGLIVE_FILES) copyIfExists(path.resolve(root, rel), path.resolve(dest, rel));
1391
+ return { sourceRoot: root, copyRoot: dest, copiedAt: now.toISOString() };
1392
+ }
1393
+
1394
+ function copyIfExists(src, dest) {
1395
+ if (!fs.existsSync(src)) return false;
1396
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1397
+ fs.copyFileSync(src, dest);
1398
+ return true;
1399
+ }
1400
+
1401
+ function fingerprintFiles(root, rels) {
1402
+ const map = {};
1403
+ for (const rel of rels) {
1404
+ const abs = path.resolve(root, rel);
1405
+ map[rel] = fs.existsSync(abs) ? sha256File(abs) : null;
1406
+ }
1407
+ return map;
1408
+ }
1409
+
1410
+ function plannedTouchList(preview) {
1411
+ const rels = new Set(['INDEX.md']);
1412
+ for (const card of preview.cards) rels.add(card.rel);
1413
+ for (const extract of preview.extracts) rels.add(extract.fromRel);
1414
+ for (const target of preview.targets) rels.add(target.rel);
1415
+ if (preview.edgesStore.rel) rels.add(preview.edgesStore.rel);
1416
+ for (const rel of STATE_FILES) rels.add(rel);
1417
+ return [...rels];
1418
+ }
1419
+
1420
+ /** 下游四入口:memory_index → memory_recall → memory_reinforce → memory_consolidate。 */
1421
+ export function runDownstreamLifecycleChecks({ memoryRoot, query = '', reinforcePath = null, now = new Date() } = {}) {
1422
+ const root = memoryRootFromConfig({ memoryRoot });
1423
+ const steps = [];
1424
+ let index = null;
1425
+ try {
1426
+ index = memoryIndex({ apply: true }, { memoryRoot: root, now });
1427
+ steps.push({ name: 'memory_index', ok: index?.status !== 'error', status: index?.status, rel: index?.rel ?? index?.indexRel ?? 'INDEX.md', sha256: index?.sha256 ?? null, changed: index?.changed ?? null });
1428
+ } catch (error) {
1429
+ steps.push({ name: 'memory_index', ok: false, error: error.code ?? error.message });
1430
+ }
1431
+ let recall = null;
1432
+ try {
1433
+ recall = memoryRecall({ query, topK: 5 }, { memoryRoot: root, now });
1434
+ const ok = recall?.ok === true && Array.isArray(recall.results) && recall.results.length > 0;
1435
+ steps.push({ name: 'memory_recall', ok, count: recall?.results?.length ?? 0, titles: (recall?.results ?? []).map((item) => item.title) });
1436
+ } catch (error) {
1437
+ steps.push({ name: 'memory_recall', ok: false, error: error.code ?? error.message });
1438
+ }
1439
+ let reinforce = null;
1440
+ try {
1441
+ const target = reinforcePath ?? firstHistoricalCard(memoryRoot, root) ?? firstPendingCardRel();
1442
+ // 红队 R11 P1-1:reinforce 前后必须真读卡比对(lifecycle/status/正文),不再字面量 true。
1443
+ const before = readCardState(root, target);
1444
+ if (!before.ok) throw memoryError('E_DRYRUN_FAILED', `下游 reinforce 目标卡不可读:${target}(${before.reason})`);
1445
+ reinforce = memoryReinforce({ path: target, why: 'lifecycle-migration dry-run downstream check' }, { memoryRoot: root, now });
1446
+ const verify = verifyLifecyclePreserved(root, target, {
1447
+ lifecycle: before.lifecycle,
1448
+ status: before.status,
1449
+ bodyNorm: before.bodyNorm,
1450
+ });
1451
+ steps.push({ name: 'memory_reinforce', ok: reinforce?.ok === true && verify.ok, path: target, strength: reinforce?.fields?.strength ?? reinforce?.strength ?? null, verify });
1452
+ } catch (error) {
1453
+ steps.push({ name: 'memory_reinforce', ok: false, error: error.code ?? error.message });
1454
+ }
1455
+ try {
1456
+ const consolidate = memoryConsolidate({ action: 'report' }, { memoryRoot: root, now });
1457
+ steps.push({ name: 'memory_consolidate', ok: consolidate?.ok === true, status: consolidate?.status, proposals: consolidate?.proposals?.length ?? 0, backlog: consolidate?.backlog ?? null, reportRel: consolidate?.reportRel ?? null });
1458
+ } catch (error) {
1459
+ steps.push({ name: 'memory_consolidate', ok: false, error: error.code ?? error.message });
1460
+ }
1461
+ return {
1462
+ ok: steps.every((step) => step.ok === true),
1463
+ root,
1464
+ query,
1465
+ steps,
1466
+ };
1467
+ }
1468
+
1469
+ let _pendingPlan = null;
1470
+
1471
+ function firstPendingCardRel() {
1472
+ return _pendingPlan?.cards?.find((card) => card.status === 'pending')?.rel ?? null;
1473
+ }
1474
+
1475
+ function firstHistoricalCard() {
1476
+ const preview = _pendingPlan;
1477
+ const historical = preview?.cards?.find((card) => card.desired === 'historical');
1478
+ if (historical) return historical.rel;
1479
+ const created = preview?.targets?.find((target) => target.lifecycle === 'historical');
1480
+ return created ? created.rel : null;
1481
+ }
1482
+
1483
+ /** 读一张卡的真实状态(lifecycle/status/正文),供迁移前后逐字段比对。 */
1484
+ export function readCardState(root, rel) {
1485
+ if (!rel) return { ok: false, rel: null, reason: 'no-rel' };
1486
+ const abs = path.resolve(root, rel);
1487
+ let text = null;
1488
+ try {
1489
+ if (!fs.statSync(abs).isFile()) return { ok: false, rel, reason: 'not-file' };
1490
+ text = fs.readFileSync(abs, 'utf8');
1491
+ } catch {
1492
+ return { ok: false, rel, reason: 'missing' };
1493
+ }
1494
+ let parsed = null;
1495
+ try {
1496
+ parsed = parseFrontmatter(text);
1497
+ } catch (error) {
1498
+ return { ok: false, rel, reason: 'bad-frontmatter', code: error?.code ?? null };
1499
+ }
1500
+ return {
1501
+ ok: true,
1502
+ rel,
1503
+ text,
1504
+ lifecycle: readLifecycleFromText(text),
1505
+ status: parsed.fields.status ?? 'active',
1506
+ body: parsed.body,
1507
+ bodyNorm: normalizedBody(parsed.body),
1508
+ sha256: sha256Text(text),
1509
+ };
1510
+ }
1511
+
1512
+ /**
1513
+ * 迁移后校验(红队 R11 P1-1):不再「卡存在即 ok」。
1514
+ * - lifecycle 必须是合法枚举(null 表示没有该字段,属于普通卡,允许但要和 expected 一致);
1515
+ * - expected 给了就必须逐项相等:lifecycle / status / 正文(去掉 rev 注释行后逐字)。
1516
+ */
1517
+ export function verifyLifecyclePreserved(root, rel, expected = null) {
1518
+ const state = readCardState(root, rel);
1519
+ if (!state.ok) return { ok: false, rel, reason: state.reason, code: state.code ?? null };
1520
+ const out = {
1521
+ ok: true,
1522
+ rel,
1523
+ lifecycle: state.lifecycle,
1524
+ status: state.status,
1525
+ bodyUnchanged: null,
1526
+ lifecycleUnchanged: null,
1527
+ statusUnchanged: null,
1528
+ };
1529
+ if (state.lifecycle != null && !LIFECYCLE_VALUES.includes(state.lifecycle)) {
1530
+ out.ok = false;
1531
+ out.reason = 'invalid-lifecycle';
1532
+ return out;
1533
+ }
1534
+ if (expected) {
1535
+ out.lifecycleUnchanged = state.lifecycle === (expected.lifecycle ?? null);
1536
+ out.statusUnchanged = state.status === expected.status;
1537
+ out.bodyUnchanged = state.bodyNorm === expected.bodyNorm;
1538
+ out.ok = out.lifecycleUnchanged && out.statusUnchanged && out.bodyUnchanged;
1539
+ if (!out.ok) out.reason = 'expected-mismatch';
1540
+ }
1541
+ return out;
1542
+ }
1543
+
1544
+ function findLatestAppliedManifest(root, planSha256 = null) {
1545
+ const dir = migrationsDir(root);
1546
+ if (!fs.existsSync(dir)) return null;
1547
+ const names = fs.readdirSync(dir).sort().reverse();
1548
+ for (const name of names) {
1549
+ const abs = path.join(dir, name, 'manifest.json');
1550
+ try {
1551
+ const manifest = JSON.parse(fs.readFileSync(abs, 'utf8'));
1552
+ if (manifest?.status !== 'applied') continue;
1553
+ if (planSha256 != null && manifest.planSha256 != null && manifest.planSha256 !== planSha256) continue;
1554
+ return manifest;
1555
+ } catch {
1556
+ // 损坏的 manifest 跳过(fail-open 只用于发现历史记录,不作为通过依据)。
1557
+ }
1558
+ }
1559
+ return null;
1560
+ }
1561
+
1562
+ export function verifyAppliedMigration(root, plan, options = {}) {
1563
+ validatePlan(plan);
1564
+ const manifest = options.manifest ?? (options.manifestRel
1565
+ ? (() => {
1566
+ try {
1567
+ return JSON.parse(fs.readFileSync(path.resolve(root, options.manifestRel), 'utf8'));
1568
+ } catch {
1569
+ return null;
1570
+ }
1571
+ })()
1572
+ : findLatestAppliedManifest(root, options.planSha256 ?? null));
1573
+ const failures = [];
1574
+ const counts = { cards: 0, extracts: 0, targets: 0, edges: 0, files: 0 };
1575
+
1576
+ for (const card of plan.cards) {
1577
+ const state = readCardState(root, card.rel);
1578
+ if (!state.ok) {
1579
+ failures.push({ kind: 'card-missing', rel: card.rel, detail: state.reason });
1580
+ continue;
1581
+ }
1582
+ counts.cards += 1;
1583
+ if (state.lifecycle !== card.lifecycle) {
1584
+ failures.push({ kind: 'card-lifecycle', rel: card.rel, expected: card.lifecycle, actual: state.lifecycle });
1585
+ }
1586
+ }
1587
+
1588
+ const verificationPlan = manifest?.verificationPlan ?? null;
1589
+ if (verificationPlan) {
1590
+ // P1(R12-R2):有 apply 前快照时,逐份文件按「快照 + 期望字节」校验,
1591
+ // 不再按「apply 后同一行号」自洽读取(那会把错行替换也判成通过)。
1592
+ for (const file of verificationPlan.files ?? []) {
1593
+ const abs = path.resolve(root, file.rel);
1594
+ const text = readTextOrNull(abs);
1595
+ if (text == null) {
1596
+ failures.push({ kind: 'file-missing', rel: file.rel });
1597
+ continue;
1598
+ }
1599
+ counts.files += 1;
1600
+ if (file.expectedSha256 && sha256Text(text) !== file.expectedSha256) {
1601
+ failures.push({ kind: 'body-mismatch', rel: file.rel, expected: file.expectedSha256, actual: sha256Text(text) });
1602
+ }
1603
+ const parsed = splitFrontmatterText(text);
1604
+ if (file.expectedBodySha256 && sha256Text(parsed.body) !== file.expectedBodySha256) {
1605
+ failures.push({
1606
+ kind: 'body-mismatch',
1607
+ rel: file.rel,
1608
+ expectedBody: file.expectedBodySha256,
1609
+ actualBody: sha256Text(parsed.body),
1610
+ });
1611
+ }
1612
+ const keys = parsed.fmLines.map(frontmatterKeyOf).filter(Boolean);
1613
+ if (file.frontmatterAdded) {
1614
+ // P2-1:无 frontmatter 的源卡只允许加 lifecycle 一个键。
1615
+ if (keys.length !== 1 || keys[0] !== 'lifecycle') {
1616
+ failures.push({ kind: 'frontmatter-defaults', rel: file.rel, keys });
1617
+ }
1618
+ } else {
1619
+ const unexpected = keys.filter((key) => !(file.keysBefore ?? []).includes(key));
1620
+ const removed = (file.keysBefore ?? []).filter((key) => !keys.includes(key));
1621
+ const badUnexpected = unexpected.filter((key) => key !== 'lifecycle');
1622
+ if (badUnexpected.length > 0 || removed.length > 0) {
1623
+ failures.push({ kind: 'frontmatter-changed', rel: file.rel, unexpected: badUnexpected, removed });
1624
+ }
1625
+ }
1626
+ const status = statusFromFmLines(parsed.fmLines);
1627
+ if (file.statusBefore != null && status !== file.statusBefore) {
1628
+ failures.push({ kind: 'status-changed', rel: file.rel, expected: file.statusBefore, actual: status });
1629
+ }
1630
+ if (file.lifecycleAfter != null && readLifecycleFromText(text) !== file.lifecycleAfter) {
1631
+ failures.push({ kind: 'card-lifecycle', rel: file.rel, expected: file.lifecycleAfter, actual: readLifecycleFromText(text) });
1632
+ }
1633
+ const bodyLines = parsed.lines.slice(parsed.bodyStartLine - 1);
1634
+ for (const rep of file.replacements ?? []) {
1635
+ const actualLine = bodyLines[rep.bodyLineIndex];
1636
+ if (actualLine !== rep.replaceWith) {
1637
+ failures.push({
1638
+ kind: 'source-line',
1639
+ rel: file.rel,
1640
+ bodyLineIndex: rep.bodyLineIndex,
1641
+ expected: collapse(rep.replaceWith).slice(0, 160),
1642
+ actual: collapse(actualLine ?? '').slice(0, 160),
1643
+ });
1644
+ }
1645
+ if (rep.sourceHandling !== 'annotated' && collapse(parsed.body).includes(collapse(rep.oldQuote))) {
1646
+ failures.push({ kind: 'old-quote-present', rel: file.rel, id: rep.id });
1647
+ }
1648
+ }
1649
+ }
1650
+ for (const target of verificationPlan.targets ?? []) {
1651
+ const state = readCardState(root, target.rel);
1652
+ if (!state.ok) {
1653
+ failures.push({ kind: 'target-missing', rel: target.rel, detail: state.reason });
1654
+ continue;
1655
+ }
1656
+ counts.targets += 1;
1657
+ if (target.expectedSha256 && state.sha256 !== target.expectedSha256) {
1658
+ failures.push({ kind: 'target-body-mismatch', rel: target.rel, expected: target.expectedSha256, actual: state.sha256 });
1659
+ }
1660
+ const archivedLines = state.text.split(/\r?\n/).map((line) => normalizeQuoteLine(line.replace(/^\s*>\s?/, '')));
1661
+ for (const item of target.extracts ?? []) {
1662
+ if (!state.text.includes(`迁移前文件 sha256:\`${item.origSha256}\``)) {
1663
+ failures.push({ kind: 'provenance-mismatch', rel: target.rel, id: item.id, expected: item.origSha256 });
1664
+ }
1665
+ if (!archivedLines.includes(normalizeQuoteLine(item.archiveQuote))) {
1666
+ failures.push({ kind: 'target-archive-quote', rel: target.rel, id: item.id });
1667
+ }
1668
+ }
1669
+ if (state.text.includes('校验:未通过')) {
1670
+ failures.push({ kind: 'legacy-verify-failed', rel: target.rel });
1671
+ }
1672
+ }
1673
+ counts.extracts = (verificationPlan.files ?? []).reduce((sum, file) => sum + (file.replacements ?? []).length, 0);
1674
+ } else {
1675
+ // 兼容路径(没有 apply 快照):只能做结构校验,dry-run/apply 必须走上面的快照口径。
1676
+ for (const extract of plan.extracts) {
1677
+ const text = readTextOrNull(path.resolve(root, extract.fromRel));
1678
+ if (text == null) {
1679
+ failures.push({ kind: 'source-missing', rel: extract.fromRel });
1680
+ continue;
1681
+ }
1682
+ counts.extracts += 1;
1683
+ if (!collapse(text).includes(collapse(extract.replaceWith))) {
1684
+ failures.push({ kind: 'source-line', rel: extract.fromRel });
1685
+ }
1686
+ }
1687
+ const seen = new Map();
1688
+ for (const extract of plan.extracts) {
1689
+ if (!seen.has(extract.targetCard.rel)) seen.set(extract.targetCard.rel, extract);
1690
+ }
1691
+ for (const [rel, extract] of seen) {
1692
+ const state = readCardState(root, rel);
1693
+ if (!state.ok) {
1694
+ failures.push({ kind: 'target-missing', rel, detail: state.reason });
1695
+ continue;
1696
+ }
1697
+ counts.targets += 1;
1698
+ const expected = extract.targetCard.lifecycle ?? 'historical';
1699
+ if (state.lifecycle !== expected) {
1700
+ failures.push({ kind: 'target-lifecycle', rel, expected, actual: state.lifecycle });
1701
+ }
1702
+ const archiveQuote = extract.legacyQuote ?? extract.quote;
1703
+ const archivedLines = state.text.split(/\r?\n/).map((line) => normalizeQuoteLine(line.replace(/^\s*>\s?/, '')));
1704
+ const quoteOk = extract.legacyQuote != null
1705
+ ? archivedLines.includes(normalizeQuoteLine(archiveQuote))
1706
+ : collapse(state.text).includes(collapse(archiveQuote));
1707
+ if (!quoteOk) {
1708
+ failures.push({ kind: 'target-archive-quote', rel, expected: collapse(archiveQuote).slice(0, 160) });
1709
+ }
1710
+ }
1711
+ }
1712
+
1713
+ const store = loadExistingEdges(root);
1714
+ for (const edge of plan.edges) {
1715
+ counts.edges += 1;
1716
+ const key = `${edge.from}|${edge.to}|${edge.type}`;
1717
+ if (!store.keys.has(key)) {
1718
+ failures.push({ kind: 'edge-missing', from: edge.from, to: edge.to, type: edge.type, rel: store.rel });
1719
+ }
1720
+ }
1721
+
1722
+ const indexPath = resolveInside(root, 'INDEX.md');
1723
+ let indexText = '';
1724
+ try {
1725
+ indexText = fs.readFileSync(indexPath, 'utf8');
1726
+ } catch {
1727
+ // INDEX.md 允许缺失;存在时必须有 lifecycle 注记段。
1728
+ }
1729
+ if (indexText && (!indexText.includes(LIFECYCLE_INDEX_BEGIN) || !indexText.includes(LIFECYCLE_INDEX_END))) {
1730
+ failures.push({ kind: 'index-note-missing', rel: 'INDEX.md' });
1731
+ }
1732
+
1733
+ return { ok: failures.length === 0, failures, counts };
1734
+ }
1735
+
1736
+ /**
1737
+ * dry-run:真库只读 → 选择性复制到临时根 → 在副本上 plan/apply/验证/下游四入口 →
1738
+ * 校验真库所有相关文件 sha256 未变。返回副本路径供检查,默认不删。
1739
+ */
1740
+ export function dryRunLifecycleMigration({ memoryRoot, plan, planPath = null, planSha256 = null, now = new Date(), copyRoot = null, query = '', cleanup = false } = {}) {
1741
+ const root = memoryRootFromConfig({ memoryRoot });
1742
+ validatePlan(plan);
1743
+ const preview = planLifecycleMigration({ memoryRoot: root, plan, planSha256, planPath, now });
1744
+ const before = fingerprintFiles(root, plannedTouchList(preview));
1745
+ const dest = copyRoot == null
1746
+ ? path.join(os.tmpdir(), `dsh-lifecycle-dryrun-${migrationStamp(now)}`)
1747
+ : path.resolve(copyRoot);
1748
+ if (fs.existsSync(dest)) {
1749
+ throw memoryError('E_COPY_EXISTS', `dry-run 副本目录已存在,请先删除或换路径:${dest}`);
1750
+ }
1751
+ const copy = copyMemoryRootForDryRun({ memoryRoot: root, destination: dest, now });
1752
+ let migration = null;
1753
+ let downstream = null;
1754
+ let verification = null;
1755
+ let error = null;
1756
+ try {
1757
+ migration = applyLifecycleMigration({ memoryRoot: copy.copyRoot, plan, planPath, planSha256, now });
1758
+ verification = verifyAppliedMigration(copy.copyRoot, plan, { manifestRel: migration?.manifestRel ?? null, planSha256 });
1759
+ _pendingPlan = preview;
1760
+ downstream = runDownstreamLifecycleChecks({
1761
+ memoryRoot: copy.copyRoot,
1762
+ query,
1763
+ reinforcePath: firstHistoricalCard(),
1764
+ now,
1765
+ });
1766
+ } catch (caught) {
1767
+ error = { code: caught.code ?? 'E_DRYRUN_FAILED', message: caught.message, manifestRel: caught.manifestRel ?? null };
1768
+ } finally {
1769
+ _pendingPlan = null;
1770
+ }
1771
+ const after = fingerprintFiles(root, plannedTouchList(preview));
1772
+ const untouched = { ok: true, changed: [], checked: Object.keys(before).length };
1773
+ for (const [rel, sha] of Object.entries(before)) {
1774
+ if (after[rel] !== sha) {
1775
+ untouched.ok = false;
1776
+ untouched.changed.push(rel);
1777
+ }
1778
+ }
1779
+ const result = {
1780
+ ok: preview.ok && !error && verification?.ok === true && downstream?.ok === true && untouched.ok,
1781
+ schema: MIGRATION_SCHEMA,
1782
+ mode: 'dry-run',
1783
+ sourceRoot: root,
1784
+ copyRoot: copy.copyRoot,
1785
+ planSha256,
1786
+ now: now.toISOString(),
1787
+ preview: {
1788
+ ok: preview.ok,
1789
+ counts: preview.counts,
1790
+ blockers: preview.blockers.map((item) => ({ status: item.status, rel: item.rel ?? item.fromRel ?? item.id ?? item.targetRel, detail: item.evidence?.detail ?? null })),
1791
+ },
1792
+ realRootUntouched: untouched,
1793
+ migration: error ? null : {
1794
+ ok: migration.ok,
1795
+ migrationId: migration.migrationId,
1796
+ manifestRel: migration.manifestRel,
1797
+ backupDirRel: migration.backupDirRel,
1798
+ applied: migration.applied,
1799
+ backups: migration.backups.map((item) => item.rel),
1800
+ },
1801
+ verification,
1802
+ downstream,
1803
+ error,
1804
+ cleanupRequested: cleanup,
1805
+ };
1806
+ if (cleanup && fs.existsSync(dest)) fs.rmSync(dest, { recursive: true, force: true });
1807
+ return result;
1808
+ }