@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,415 @@
1
+ // memory/archive.mjs — hardgate 归档写点(批 C / W1c 实装)
2
+ //
3
+ // 契约(DESIGN v0.5.1 §9 / MERGE-PLAN §4⑧、§12):
4
+ // - edges.jsonl 只追加不删卡;每条边带 schema、时间、证据与来源。
5
+ // - 归档移动 = 卡文件移入 topics/archive/<YYYY-MM>/ + 写 lifecycle:historical
6
+ // + 追加一条移动边 + 重建 INDEX(同一批内完成,避免悬空边)。
7
+ // - auto-run 槽表命中才跑,且按 last-run 节流(默认 6h)。
8
+ // - 写守卫:备份不可用必须拒写(E_HG_BACKUP),绝不静默成功。
9
+ // - fail-closed:未配置 memoryRoot / 坏 manifest 一律抛错,不许返回“看起来成功”。
10
+ //
11
+ // 对外错误码(A6 五码,见 MERGE-PLAN §17 L163):
12
+ // E_HG_ARCHIVE_OFFLINE / E_HG_ARCHIVE_READONLY / E_HG_ARCHIVE_LOW_SPACE /
13
+ // E_HG_ARCHIVE_WRONG_VOLUME / E_HG_ARCHIVE_MIGRATE_MISMATCH
14
+ // 旧名 STATE_INVALID / DIGEST_MISSING / DIGEST_INVALID / E_HG_ARCHIVE_DIGEST_INVALID
15
+ // 全部作废,不得再作为对外码出现。
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import crypto from 'node:crypto';
20
+
21
+ import { dayString, isoStamp } from './frontmatter.js';
22
+ import { ensureBackup } from '../backup.js';
23
+ import { memoryIndex as rebuildMemoryIndex } from './index.js';
24
+
25
+ export const BATCH = 'C';
26
+ export const MODULE = 'memory/archive.mjs';
27
+ // 仅作兼容保留:骨架时代的外部常量,现在不再抛出。
28
+ export const UNIMPLEMENTED_CODE = 'E_HG_ARCHIVE_UNIMPLEMENTED';
29
+ export const ARCHIVE_SCHEMA = 'archive/v1';
30
+ export const EDGES_SCHEMA = 'edges/v1';
31
+ export const EDGES_LOG_REL = '.longlive/hardgate/edges.jsonl';
32
+ export const ARCHIVE_STATE_REL = '.longlive/hardgate/archive-state.json';
33
+ export const ARCHIVE_QUEUE_REL = '.longlive/hardgate/archive-queue.jsonl';
34
+ export const ARCHIVE_DIR_REL = 'topics/archive';
35
+ export const ARCHIVE_SLOTS = Object.freeze(['distill', 'rotation', 'archive-move', 'manual']);
36
+ export const ARCHIVE_MIN_INTERVAL_MS = 6 * 60 * 60 * 1000;
37
+ export const MAX_QUEUE_LINES = 1000;
38
+
39
+ export const EDGE_TYPES = Object.freeze([
40
+ 'supersedes', 'superseded_by', 'deprecated_by', 'conflicts_with',
41
+ 'answers_with', 'derived_from', 'mentions', 'same_topic', 'moved_to',
42
+ ]);
43
+
44
+ /** 骨架兼容对象:implemented=true 表示本文件已是真实实现(保留导出名)。 */
45
+ export const SKELETON = Object.freeze({
46
+ version: '2.0.0', failClosed: true, batch: 'C', implemented: true,
47
+ });
48
+
49
+ export function archiveError(code, message, extra = {}) {
50
+ const error = new Error(message ?? String(code));
51
+ error.name = 'HardgateArchiveError';
52
+ error.code = code;
53
+ error.status = code;
54
+ Object.assign(error, extra);
55
+ return error;
56
+ }
57
+
58
+ function sha256(text) {
59
+ return crypto.createHash('sha256').update(String(text)).digest('hex');
60
+ }
61
+
62
+ function toDate(now) {
63
+ const at = now instanceof Date ? now : new Date(now ?? Date.now());
64
+ if (Number.isNaN(at.getTime())) throw archiveError('E_HG_ARCHIVE_OFFLINE', 'bad clock');
65
+ return at;
66
+ }
67
+
68
+ function resolveRoot(memoryRoot) {
69
+ const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? path.resolve(memoryRoot) : null;
70
+ if (!root) throw archiveError('E_HG_ARCHIVE_OFFLINE', 'memoryRoot 未配置:归档写点 fail-closed');
71
+ return root;
72
+ }
73
+
74
+ function insideRoot(root, rel) {
75
+ const abs = path.resolve(root, rel);
76
+ return abs === root || abs.startsWith(root + path.sep);
77
+ }
78
+
79
+ function normalizeEdge(edge, now) {
80
+ const src = edge && typeof edge === 'object' ? edge : {};
81
+ const from = String(src.from ?? '').trim();
82
+ const to = String(src.to ?? '').trim();
83
+ if (from === '' || to === '') throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', 'edge 缺少 from/to');
84
+ const type = String(src.type ?? '').trim();
85
+ if (!EDGE_TYPES.includes(type)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `edge type 非法: ${type}`);
86
+ const evidence = Array.isArray(src.evidence)
87
+ ? src.evidence.map((item) => String(item))
88
+ : src.evidence
89
+ ? [String(src.evidence)]
90
+ : [];
91
+ const row = {
92
+ schema: EDGES_SCHEMA,
93
+ at: isoStamp(now),
94
+ from: from.replace(/\\/g, '/'),
95
+ to: to.replace(/\\/g, '/'),
96
+ type,
97
+ evidence,
98
+ confidence: Number.isFinite(Number(src.confidence)) ? Number(src.confidence) : null,
99
+ source: String(src.source ?? 'archive'),
100
+ };
101
+ row.sha256 = sha256(JSON.stringify(row));
102
+ return row;
103
+ }
104
+
105
+ /**
106
+ * 追加一条边到 .longlive/hardgate/edges.jsonl(只追加,绝不改写/删除)。
107
+ * @returns {{ok:true, row:object, file:string, appended:true}}
108
+ */
109
+ export function appendEdge(input = {}) {
110
+ const root = resolveRoot(input.memoryRoot);
111
+ const now = toDate(input.now);
112
+ const row = normalizeEdge(input.edge ?? input, now);
113
+ const file = path.join(root, EDGES_LOG_REL);
114
+ fs.mkdirSync(path.dirname(file), { recursive: true });
115
+ // 幂等:同一条边(from/to/type 相同)只保留一次;仍然只追加、绝不重写旧行。
116
+ if (fs.existsSync(file)) {
117
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
118
+ if (line.trim() === '') continue;
119
+ try {
120
+ const existing = JSON.parse(line);
121
+ if (existing.from === row.from && existing.to === row.to && existing.type === row.type) {
122
+ return { ok: true, row: existing, file, appended: false, duplicate: true };
123
+ }
124
+ } catch {
125
+ // 坏行不阻断新边;诊断走 readEdges()。
126
+ }
127
+ }
128
+ }
129
+ // 一开一闭的追加写;不读旧行、不重写旧行。
130
+ const fd = fs.openSync(file, 'a');
131
+ try {
132
+ fs.writeSync(fd, JSON.stringify(row) + '\n');
133
+ fs.fsyncSync(fd);
134
+ } finally {
135
+ fs.closeSync(fd);
136
+ }
137
+ return { ok: true, row, file, appended: true };
138
+ }
139
+
140
+ /** 兼容别名:骨架期名字,语义与 appendEdge 完全一致。 */
141
+ export function appendArchiveEdge(input = {}) {
142
+ const row = appendEdge(input);
143
+ return { ...row, edge: row.row };
144
+ }
145
+
146
+ /** 读边(诊断用):缺失 = 空;坏行如实记 corrupt,不抛。 */
147
+ export function readEdges({ memoryRoot } = {}) {
148
+ const root = resolveRoot(memoryRoot);
149
+ const file = path.join(root, EDGES_LOG_REL);
150
+ if (!fs.existsSync(file)) return { ok: true, file, rows: [], corrupt: null };
151
+ const rows = [];
152
+ let corrupt = null;
153
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
154
+ for (const [index, line] of lines.entries()) {
155
+ if (line.trim() === '') continue;
156
+ try {
157
+ const parsed = JSON.parse(line);
158
+ if (parsed && parsed.schema === EDGES_SCHEMA) rows.push(parsed);
159
+ else corrupt = corrupt ?? { line: index + 1, reason: 'schema' };
160
+ } catch {
161
+ corrupt = corrupt ?? { line: index + 1, reason: 'json' };
162
+ }
163
+ }
164
+ return { ok: corrupt === null, file, rows, corrupt };
165
+ }
166
+
167
+ function ensureFrontmatterHistorical(text) {
168
+ const src = typeof text === 'string' ? text : '';
169
+ const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(src);
170
+ if (!block) {
171
+ // 没有 frontmatter:补一个最小头,绝不丢正文。
172
+ return `---\nlifecycle: historical\n---\n\n${src}`;
173
+ }
174
+ if (/^[ \t]*lifecycle[ \t]*:/m.test(block[1])) {
175
+ return src.replace(/^([ \t]*lifecycle[ \t]*:[ \t]*).+$/m, '$1historical');
176
+ }
177
+ return `---\n${block[1]}\nlifecycle: historical\n---\n${src.slice(block[0].length)}`;
178
+ }
179
+
180
+ /**
181
+ * 归档一张卡:移动到 topics/archive/<YYYY-MM>/,写 lifecycle:historical,
182
+ * 追加 moved_to 边,并重建 INDEX。失败不写半成品(先算后写)。
183
+ */
184
+ export function archiveTurn(input = {}) {
185
+ const root = resolveRoot(input.memoryRoot ?? input.root);
186
+ const now = toDate(input.now);
187
+ const rel = String(input.rel ?? input.cardRel ?? input.path ?? '').trim();
188
+ if (rel === '') throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', 'archiveTurn 缺少相对卡路径');
189
+ const fromRel = rel.replace(/\\/g, '/');
190
+ if (!insideRoot(root, fromRel)) throw archiveError('E_HG_ARCHIVE_WRONG_VOLUME', `路径越界: ${fromRel}`);
191
+ const abs = path.join(root, fromRel);
192
+ if (!fs.existsSync(abs)) throw archiveError('E_HG_ARCHIVE_OFFLINE', `待归档卡不存在: ${fromRel}`);
193
+ if (input.dryRun === true) {
194
+ return { ok: true, dryRun: true, from: fromRel, to: null, moved: false, archived: false };
195
+ }
196
+ const month = dayString(now).slice(0, 7);
197
+ // B7b 裁决:staging 过期清退不走 archiveTurn(它写 topics/archive,是 L2 活跃卡归档);
198
+ // staging 清退由 archive-staging.mjs 自己写 `.longlive/archive/staging-expired/`。
199
+ const toRel = `${ARCHIVE_DIR_REL}/${month}/${path.basename(fromRel)}`;
200
+ const toAbs = path.join(root, toRel);
201
+ if (fs.existsSync(toAbs)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `归档目标已存在: ${toRel}`);
202
+ const text = fs.readFileSync(abs, 'utf8');
203
+ const next = ensureFrontmatterHistorical(text);
204
+ fs.mkdirSync(path.dirname(toAbs), { recursive: true });
205
+ fs.writeFileSync(toAbs, next, 'utf8');
206
+ fs.unlinkSync(abs);
207
+ const edge = appendEdge({
208
+ memoryRoot: root,
209
+ now,
210
+ edge: {
211
+ from: fromRel,
212
+ to: toRel,
213
+ type: 'moved_to',
214
+ evidence: [String(input.reason ?? 'archive')],
215
+ source: 'archive',
216
+ },
217
+ });
218
+ let index = null;
219
+ try {
220
+ index = rebuildMemoryIndex({ apply: true }, { memoryRoot: root, now });
221
+ } catch (error) {
222
+ throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `归档后 INDEX 重建失败: ${error?.code ?? error?.message ?? error}`);
223
+ }
224
+ return {
225
+ ok: true,
226
+ moved: true,
227
+ archived: true,
228
+ from: fromRel,
229
+ to: toRel,
230
+ bytes: Buffer.byteLength(next, 'utf8'),
231
+ edge: edge.row,
232
+ indexSha: index?.contentHash ?? index?.sha256 ?? null,
233
+ indexPath: index?.indexPath ?? null,
234
+ };
235
+ }
236
+
237
+ function readArchiveState(root) {
238
+ const file = path.join(root, ARCHIVE_STATE_REL);
239
+ if (!fs.existsSync(file)) return { ok: true, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: null };
240
+ try {
241
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
242
+ if (!parsed || parsed.schema !== 'archive-state/v1') return { ok: false, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: 'schema' };
243
+ return { ok: true, state: parsed, corrupt: null };
244
+ } catch (error) {
245
+ return { ok: false, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: String(error?.message ?? error) };
246
+ }
247
+ }
248
+
249
+ function writeArchiveState(root, state, now) {
250
+ const file = path.join(root, ARCHIVE_STATE_REL);
251
+ fs.mkdirSync(path.dirname(file), { recursive: true });
252
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
253
+ const text = JSON.stringify({ ...state, schema: 'archive-state/v1', updatedAt: isoStamp(now) }, null, 2) + '\n';
254
+ const fd = fs.openSync(tmp, 'w');
255
+ try {
256
+ fs.writeSync(fd, text);
257
+ fs.fsyncSync(fd);
258
+ } finally {
259
+ fs.closeSync(fd);
260
+ }
261
+ fs.renameSync(tmp, file);
262
+ return { path: file, sha256: sha256(text), bytes: Buffer.byteLength(text, 'utf8') };
263
+ }
264
+
265
+ /**
266
+ * 槽位自动运行:按 slot 记录 lastRunAt,节流;未命中槽表不跑。
267
+ * 传入 rel/cardRel 时才做一次归档移动。
268
+ */
269
+ export function maybeAutoRunArchive(input = {}) {
270
+ const root = resolveRoot(input.memoryRoot ?? input.root);
271
+ const now = toDate(input.now);
272
+ const slot = String(input.slot ?? 'manual');
273
+ if (!ARCHIVE_SLOTS.includes(slot)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `未知归档槽: ${slot}`);
274
+ const interval = Number.isFinite(input.minIntervalMs) ? Math.max(0, Number(input.minIntervalMs)) : ARCHIVE_MIN_INTERVAL_MS;
275
+ const read = input.lastRun && typeof input.lastRun === 'object' ? { ok: true, state: input.lastRun } : readArchiveState(root);
276
+ const last = read.state?.slots?.[slot] ?? read.state?.lastRunAt ?? null;
277
+ const lastMs = typeof last === 'string' ? Date.parse(last) : NaN;
278
+ if (Number.isFinite(lastMs) && now.getTime() - lastMs < interval) {
279
+ return { ok: true, ran: false, reason: 'throttled', slot, nextAt: new Date(lastMs + interval).toISOString() };
280
+ }
281
+ const rel = String(input.rel ?? input.cardRel ?? '').trim();
282
+ let result = null;
283
+ if (rel !== '') result = archiveTurn({ memoryRoot: root, now, rel, reason: `slot:${slot}` });
284
+ const state = {
285
+ ...read.state,
286
+ lastRunAt: isoStamp(now),
287
+ slots: { ...(read.state?.slots ?? {}), [slot]: isoStamp(now) },
288
+ };
289
+ const write = writeArchiveState(root, state, now);
290
+ return { ok: true, ran: result !== null, reason: result ? 'moved' : 'no-target', slot, result, state: write };
291
+ }
292
+
293
+ /**
294
+ * 写守卫:先确认可回滚备份,否则拒写。EPERM/EACCES 等 IO 拒绝一律转 E_HG_BACKUP。
295
+ * 传入 writer 时执行 writer();否则传入 path+content 时做原子写。
296
+ */
297
+ export function guardWriteArchive(input = {}) {
298
+ const sessionPath = String(input.sessionPath ?? '').trim();
299
+ if (sessionPath === '') {
300
+ throw archiveError('E_HG_ARCHIVE_OFFLINE', '写守卫缺少 sessionPath:无法确认备份可用,拒写');
301
+ }
302
+ let backup;
303
+ try {
304
+ backup = ensureBackup(sessionPath, {
305
+ date: toDate(input.now),
306
+ sourceBuf: input.sourceBuf ?? null,
307
+ sha256: input.sha256 ?? null,
308
+ size: input.size ?? null,
309
+ });
310
+ } catch (error) {
311
+ if (error?.code === 'E_HG_BACKUP') throw error;
312
+ throw archiveError('E_HG_BACKUP', `备份不可用,拒写: ${error?.code ?? error?.message ?? error}`, { cause: error });
313
+ }
314
+ if (typeof input.writer === 'function') {
315
+ const written = input.writer(backup);
316
+ return { ok: true, backup, written };
317
+ }
318
+ const target = String(input.path ?? input.cardPath ?? '').trim();
319
+ if (target === '') return { ok: true, backup, written: false };
320
+ const file = path.isAbsolute(target) ? target : path.resolve(input.memoryRoot ?? process.cwd(), target);
321
+ const content = String(input.content ?? '');
322
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
323
+ fs.mkdirSync(path.dirname(file), { recursive: true });
324
+ fs.writeFileSync(tmp, content, 'utf8');
325
+ fs.renameSync(tmp, file);
326
+ return { ok: true, backup, written: true, path: file, bytes: Buffer.byteLength(content, 'utf8') };
327
+ }
328
+
329
+ /** 别名:守卫 + 可注入 writer。 */
330
+ export function writeWithBackupArchive(input = {}, writer = null) {
331
+ const opts = writer ? { ...input, writer } : input;
332
+ return guardWriteArchive(opts);
333
+ }
334
+
335
+ /** 离线队列:归档盘不可用时只追加账(≤1000 行 / 90 天),不抛给调用方。 */
336
+ export function enqueueArchiveQueue({ memoryRoot, now = new Date(), code, sha256: digest = null, archiveRoot = null, batch = 'C' } = {}) {
337
+ const root = resolveRoot(memoryRoot);
338
+ const at = toDate(now);
339
+ const file = path.join(root, ARCHIVE_QUEUE_REL);
340
+ fs.mkdirSync(path.dirname(file), { recursive: true });
341
+ const row = {
342
+ schema: 'archive-queue/v1',
343
+ at: isoStamp(at),
344
+ code: String(code ?? 'E_HG_ARCHIVE_OFFLINE'),
345
+ sha256: digest ? String(digest) : null,
346
+ archiveRoot: archiveRoot ? String(archiveRoot) : null,
347
+ batch: String(batch),
348
+ };
349
+ let lines = [];
350
+ if (fs.existsSync(file)) {
351
+ lines = fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim() !== '');
352
+ }
353
+ const cutoff = at.getTime() - 90 * 24 * 60 * 60 * 1000;
354
+ lines = lines.filter((line) => {
355
+ try {
356
+ const parsed = JSON.parse(line);
357
+ const ms = Date.parse(parsed.at);
358
+ return !Number.isFinite(ms) || ms >= cutoff;
359
+ } catch {
360
+ return false;
361
+ }
362
+ });
363
+ lines.push(JSON.stringify(row));
364
+ const kept = lines.slice(-MAX_QUEUE_LINES);
365
+ fs.writeFileSync(file, `${kept.join('\n')}\n`, 'utf8');
366
+ return { ok: true, file, rows: kept.length, dropped: lines.length - kept.length + Math.max(0, lines.length - kept.length) };
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // 批次 C 出口门用的显式断言(M18)
371
+ // ---------------------------------------------------------------------------
372
+
373
+ /** 产卡只允许写 staging;任何直写 topics/ 的调用都必须当场失败。 */
374
+ export function assertNoDirectTopicsWrite(rel, { allowAuto = false } = {}) {
375
+ const normalized = String(rel ?? '').replace(/\\/g, '/');
376
+ const topics = normalized.startsWith('topics/');
377
+ const staging = normalized.startsWith('.longlive/staging/');
378
+ if (topics && !(allowAuto && normalized.startsWith('topics/auto/'))) {
379
+ throw archiveError('E_HG_DISTILL_TOPICS_WRITE', `蒸馏产卡不得直写 topics/: ${normalized}`);
380
+ }
381
+ if (!staging && !topics) {
382
+ throw archiveError('E_HG_DISTILL_TOPICS_WRITE', `蒸馏产卡必须在 staging 下: ${normalized}`);
383
+ }
384
+ return true;
385
+ }
386
+
387
+ // ---------------------------------------------------------------------------
388
+ // B7b 草案接线(2026-11-29):冷层归档状态机 + staging 过期归档
389
+ // ---------------------------------------------------------------------------
390
+ // 冷层迁移状态机(scan→approve#1→copy→verify→approve#2→migrated→才可删原件),
391
+ // 只 re-export 不改既有归档行为;janitor/维护槽经这些入口调用,绝不复制实现。
392
+ export {
393
+ COLD_MANIFEST_SCHEMA,
394
+ COLD_MANIFEST_REL,
395
+ COLD_INTENTS_REL,
396
+ COLD_PHASES,
397
+ COLD_CODES,
398
+ coldError,
399
+ planColdManifest,
400
+ readColdManifest,
401
+ readColdState,
402
+ writeColdState,
403
+ approveColdOnce,
404
+ copyColdFiles,
405
+ verifyColdCopies,
406
+ approveColdWithManifest,
407
+ markColdMigrated,
408
+ gateColdArchive,
409
+ gateColdDeletion,
410
+ beginColdDelete,
411
+ finishColdDelete,
412
+ reconcileColdIntents,
413
+ deleteOriginalAfterMigrate,
414
+ coldMovePlan,
415
+ } from './archive-cold-state.mjs';
@@ -0,0 +1,222 @@
1
+ // src/memory/audit-records.js — 1.8.0 A5 前置:读/写审计行(#22 audit-records 生产者)
2
+ //
3
+ // 字段(v2.8.5 / answer-guard 口径):
4
+ // questionId 答题标识(answer-guard = ag-001…);缺失时显式 'unknown',绝不臆造
5
+ // expectedTurns 该题期望覆盖的轮数(整数;缺失 null)
6
+ // answerText 该次回答正文(缺失 null;不截断证据时由调用方保证完整)
7
+ // 每行 schema='audit-records/v1',供 #22 /api/longlive/audit/records 只读展示。
8
+ //
9
+ // P0 遗忘链:每行追加 rowHash(sha256(canonical row))与 prevRowHash(前一行链);
10
+ // 若宿主 auditKey 可读(env / .hostkey),再附 HMAC-SHA256。缺 key 不阻塞写,
11
+ // 但显式标 hmac:null + hmacResidual:'hostkey-unavailable',不冒充已签名。
12
+
13
+ import crypto from 'node:crypto';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ import { stableStringify } from '../actions/fs.js';
18
+
19
+ export const AUDIT_RECORDS_SCHEMA = 'audit-records/v1';
20
+ export const AUDIT_HMAC_ENV = 'DSH_LONGLIVE_AUDIT_KEY';
21
+ const HOSTKEY_REL = ['.longlive', '.hostkey'];
22
+ const CHAIN_FIELDS = new Set(['rowHash', 'prevRowHash', 'hmac', 'hmacAlgo', 'hmacKey', 'hmacResidual']);
23
+
24
+ export function auditRecordsPathOf(memoryRoot) {
25
+ return path.join(path.resolve(String(memoryRoot)), '.longlive', 'audit', 'records.jsonl');
26
+ }
27
+
28
+ export function auditHeadPathOf(memoryRoot) {
29
+ return path.join(path.resolve(String(memoryRoot)), '.longlive', 'audit', 'records.head.json');
30
+ }
31
+
32
+ function nowIso(now) {
33
+ const value = typeof now === 'function' ? now() : new Date();
34
+ return (value instanceof Date ? value : new Date(value)).toISOString();
35
+ }
36
+
37
+ function sha256Hex(text) {
38
+ return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
39
+ }
40
+
41
+ function canonicalRow(row) {
42
+ const clean = {};
43
+ for (const [key, value] of Object.entries(row)) {
44
+ if (!CHAIN_FIELDS.has(key)) clean[key] = value;
45
+ }
46
+ return stableStringify(clean);
47
+ }
48
+
49
+ function rowHashOf(row) {
50
+ return sha256Hex(canonicalRow(row));
51
+ }
52
+
53
+ /** Optional host key: env first, then the persisted fallback. Never creates a key. */
54
+ export function resolveAuditKey(memoryRoot, env = process.env) {
55
+ const fromEnv = env?.[AUDIT_HMAC_ENV];
56
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return { key: fromEnv.trim(), source: 'env' };
57
+ try {
58
+ const text = fs.readFileSync(path.join(path.resolve(String(memoryRoot)), ...HOSTKEY_REL), 'utf8').trim();
59
+ if (text !== '') return { key: text, source: 'hostkey-file' };
60
+ } catch {
61
+ /* absent: caller records the residual */
62
+ }
63
+ return { key: null, source: 'absent' };
64
+ }
65
+
66
+ function lastChain(file) {
67
+ try {
68
+ const text = fs.readFileSync(file, 'utf8').trim();
69
+ if (text === '') return { prevRowHash: 'genesis', seq: 0 };
70
+ const lines = text.split(/\r?\n/);
71
+ const lastRaw = lines[lines.length - 1];
72
+ let last = null;
73
+ try { last = JSON.parse(lastRaw); } catch { /* legacy/corrupt tail */ }
74
+ return {
75
+ prevRowHash: typeof last?.rowHash === 'string' && /^[0-9a-f]{64}$/.test(last.rowHash)
76
+ ? last.rowHash
77
+ : sha256Hex(lastRaw),
78
+ seq: lines.length,
79
+ };
80
+ } catch {
81
+ return { prevRowHash: 'genesis', seq: 0 };
82
+ }
83
+ }
84
+
85
+ function writeHead(memoryRoot, { rows, lastHash, now }) {
86
+ const file = auditHeadPathOf(memoryRoot);
87
+ fs.mkdirSync(path.dirname(file), { recursive: true });
88
+ const head = {
89
+ schema: 'audit-head/v1',
90
+ rows,
91
+ lastHash,
92
+ updatedAt: nowIso(now),
93
+ };
94
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
95
+ fs.writeFileSync(tmp, `${JSON.stringify(head)}\n`, 'utf8');
96
+ fs.renameSync(tmp, file);
97
+ return head;
98
+ }
99
+
100
+ /** Read-side normalization: missing fields stay explicit (unknown/null), never fabricated. */
101
+ export function normalizeAuditRecordRow(row) {
102
+ const value = row && typeof row === 'object' ? row : {};
103
+ return {
104
+ schema: AUDIT_RECORDS_SCHEMA,
105
+ questionId: typeof value.questionId === 'string' && value.questionId !== '' ? value.questionId : 'unknown',
106
+ expectedTurns: Number.isInteger(value.expectedTurns) && value.expectedTurns >= 0 ? value.expectedTurns : null,
107
+ answerText: typeof value.answerText === 'string' ? value.answerText : null,
108
+ recordId: typeof value.recordId === 'string' ? value.recordId : null,
109
+ readerTier: typeof value.readerTier === 'string' ? value.readerTier : null,
110
+ action: typeof value.action === 'string' ? value.action : 'read',
111
+ at: typeof value.at === 'string' ? value.at : null,
112
+ };
113
+ }
114
+
115
+ /** Append one audit row (fsync so a crash cannot lose an answered question's audit). */
116
+ export function appendAuditRecord(input = {}) {
117
+ const memoryRoot = String(input.memoryRoot ?? '');
118
+ if (memoryRoot === '') throw new Error('E_MEMORY_ROOT: appendAuditRecord requires memoryRoot');
119
+ const row = {
120
+ schema: AUDIT_RECORDS_SCHEMA,
121
+ questionId: typeof input.questionId === 'string' && input.questionId !== '' ? input.questionId : 'unknown',
122
+ expectedTurns: Number.isInteger(input.expectedTurns) && input.expectedTurns >= 0 ? input.expectedTurns : null,
123
+ answerText: typeof input.answerText === 'string' ? input.answerText : null,
124
+ recordId: typeof input.recordId === 'string' ? input.recordId : null,
125
+ readerTier: typeof input.readerTier === 'string' ? input.readerTier : null,
126
+ action: typeof input.action === 'string' ? input.action : 'read',
127
+ at: typeof input.at === 'string' ? input.at : nowIso(input.now),
128
+ ...(input.extra && typeof input.extra === 'object' ? input.extra : {}),
129
+ };
130
+ const file = auditRecordsPathOf(memoryRoot);
131
+ const chain = lastChain(file);
132
+ row.prevRowHash = chain.prevRowHash;
133
+ row.rowHash = rowHashOf(row);
134
+ const resolved = resolveAuditKey(memoryRoot);
135
+ if (resolved.key !== null) {
136
+ row.hmac = crypto.createHmac('sha256', resolved.key).update(row.rowHash, 'utf8').digest('hex');
137
+ row.hmacAlgo = 'sha256';
138
+ row.hmacKey = resolved.source;
139
+ } else {
140
+ row.hmac = null;
141
+ row.hmacAlgo = 'sha256';
142
+ row.hmacKey = null;
143
+ row.hmacResidual = 'hostkey-unavailable';
144
+ }
145
+ fs.mkdirSync(path.dirname(file), { recursive: true });
146
+ const fd = fs.openSync(file, 'a');
147
+ try {
148
+ fs.writeSync(fd, `${JSON.stringify(row)}\n`, null, 'utf8');
149
+ fs.fsyncSync(fd);
150
+ } finally {
151
+ fs.closeSync(fd);
152
+ }
153
+ try {
154
+ if (input.skipHead !== true) {
155
+ writeHead(memoryRoot, { rows: chain.seq + 1, lastHash: row.rowHash, now: row.at });
156
+ }
157
+ } catch { /* head is an early-warning anchor; a head failure must not lose the row */ }
158
+ return { ok: true, row, file, chain: { prevRowHash: row.prevRowHash, seq: chain.seq + 1 } };
159
+ }
160
+
161
+ /**
162
+ * Verify the append-only audit hash chain (and HMAC when a key is available).
163
+ * Legacy rows without rowHash are reported as legacy, not silently trusted.
164
+ */
165
+ export function verifyAuditChain({ memoryRoot, auditKey = null } = {}) {
166
+ const file = auditRecordsPathOf(memoryRoot);
167
+ let text = '';
168
+ let fileMissing = false;
169
+ try { text = fs.readFileSync(file, 'utf8'); } catch { fileMissing = true; text = ''; }
170
+ const rows = text.split(/\r?\n/).filter(Boolean).map((line) => {
171
+ try { return JSON.parse(line); } catch { return null; }
172
+ });
173
+ let head = null;
174
+ let headPresent = false;
175
+ try {
176
+ head = JSON.parse(fs.readFileSync(auditHeadPathOf(memoryRoot), 'utf8'));
177
+ headPresent = true;
178
+ } catch {
179
+ head = null;
180
+ }
181
+ const errors = [];
182
+ const lastParsed = [...rows].reverse().find((row) => row && typeof row.rowHash === 'string');
183
+ if (headPresent) {
184
+ if (!Number.isInteger(head?.rows) || head.rows !== rows.length) errors.push({ code: 'E_AUDIT_HEAD_ROWS', headRows: head?.rows ?? null, rows: rows.length });
185
+ if (typeof head?.lastHash !== 'string' || head.lastHash !== (lastParsed?.rowHash ?? null)) {
186
+ errors.push({ code: 'E_AUDIT_HEAD_LAST', headLastHash: head?.lastHash ?? null, lastHash: lastParsed?.rowHash ?? null });
187
+ }
188
+ }
189
+ if (fileMissing && headPresent && head?.rows > 0) errors.push({ code: 'E_AUDIT_HEAD_ROWS', headRows: head.rows, rows: 0 });
190
+ const key = auditKey !== null
191
+ ? { key: String(auditKey), source: 'injected' }
192
+ : resolveAuditKey(memoryRoot);
193
+ let previous = null;
194
+ let legacyRows = 0;
195
+ for (let index = 0; index < rows.length; index += 1) {
196
+ const row = rows[index];
197
+ if (!row) { errors.push({ index, code: 'E_JSON' }); continue; }
198
+ if (typeof row.rowHash !== 'string') { legacyRows += 1; continue; }
199
+ if (row.rowHash !== rowHashOf(row)) errors.push({ index, code: 'E_AUDIT_ROW_HASH' });
200
+ // The first chained row may follow legacy rows; its prevRowHash is the
201
+ // legacy-tail hash or genesis. Later rows must chain strictly.
202
+ if (previous !== null && row.prevRowHash !== previous) errors.push({ index, code: 'E_AUDIT_CHAIN_PREV' });
203
+ if (typeof row.hmac === 'string' && key.key !== null) {
204
+ const expected = crypto.createHmac('sha256', key.key).update(row.rowHash, 'utf8').digest('hex');
205
+ if (row.hmac !== expected) errors.push({ index, code: 'E_AUDIT_HMAC' });
206
+ }
207
+ previous = row.rowHash;
208
+ }
209
+ return {
210
+ ok: errors.length === 0,
211
+ file,
212
+ present: true,
213
+ rows: rows.length,
214
+ legacyRows,
215
+ headPresent,
216
+ headRows: head?.rows ?? null,
217
+ headLastHash: head?.lastHash ?? null,
218
+ hmacKeySource: key.source,
219
+ hmacKeyPresent: key.key !== null,
220
+ errors,
221
+ };
222
+ }