@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,290 @@
1
+ // B3 已落 worktree · 每轮统一预算块(单一拆账,单位=字符/字;2026-11-29 接线于 src/recall/index.js composeInjectionTurnBudget)
2
+ //
3
+ // 规格依据:
4
+ // - DESIGN.v0.5.2 预算节(L103):per-turn 注入总上限 2,000 字;九项拆账;超限从尾裁剪;
5
+ // 余量 240 不得被单项挤占;2,000 字 ≈ 1,000 token;开机卡/深度档另账。
6
+ // - V0.5.2-MERGE-PLAN §10(L89-104):同一张九项表,合计 2,000。
7
+ // - checks/lib/breaking-map.json B3:tokens 990 / 240;sumTokens 九项;expectedSum 2000。
8
+ //
9
+ // 机械可识别性(L3/L7 的验收口径):
10
+ // - 九个数值必须在同一文件里各自独立出现(L3 的 countStandalone 正则 `(?<![\d,])V(?![\d,])`;
11
+ // L7 的 `(^|[^0-9])V([^0-9]|$)`),所以本文件每个数值都写成独立的 `= 数字;` 一行,
12
+ // 对象字面量只引用常量、不重复写裸数字。
13
+ // - 120 必须独立出现 ≥2 次(前瞻 120 + 复习 120),且唯一值和必须 = 2,000。
14
+ // - 本文件不得出现被废弃的旧预算值(1,600 / 1,680 / 2,060 / 2,233 / 4,000 裸数字),
15
+ // 旧值只在测试里作为反事实输入传入,不写进源码。
16
+ //
17
+ // 本模块只做「预算口径 + 裁剪 + 机械自审」,不 import 插件内其它模块,便于单文件搬进 worktree。
18
+
19
+ export const TURN_BUDGET_SCHEMA = 'turn-budget/v1';
20
+
21
+ export const TURN_BUDGET_TOTAL_CHARS = 2000;
22
+ export const TURN_BUDGET_RECALL_CHARS = 990;
23
+ export const TURN_BUDGET_WORKING_CHARS = 300;
24
+ export const TURN_BUDGET_PROSPECTIVE_CHARS = 120;
25
+ export const TURN_BUDGET_REVIEW_CHARS = 120;
26
+ export const TURN_BUDGET_ANTI_FABRICATION_CHARS = 50;
27
+ export const TURN_BUDGET_CONFLICT_CHARS = 40;
28
+ export const TURN_BUDGET_ACTIVITY_CHARS = 60;
29
+ export const TURN_BUDGET_ALERT_CHARS = 80;
30
+ export const TURN_BUDGET_MARGIN_CHARS = 240;
31
+
32
+ // 九项车道(顺序即注入顺序):召回 → 工作记忆 → 前瞻 → 复习 → 防编 → 冲突 → 活动 → 告警 → 余量。
33
+ export const TURN_BUDGET_LANE_ORDER = Object.freeze([
34
+ 'recall',
35
+ 'working',
36
+ 'prospective',
37
+ 'review',
38
+ 'antiFabrication',
39
+ 'conflict',
40
+ 'activity',
41
+ 'alert',
42
+ 'margin',
43
+ ]);
44
+
45
+ export const TURN_BUDGET_LANES = Object.freeze({
46
+ recall: TURN_BUDGET_RECALL_CHARS,
47
+ working: TURN_BUDGET_WORKING_CHARS,
48
+ prospective: TURN_BUDGET_PROSPECTIVE_CHARS,
49
+ review: TURN_BUDGET_REVIEW_CHARS,
50
+ antiFabrication: TURN_BUDGET_ANTI_FABRICATION_CHARS,
51
+ conflict: TURN_BUDGET_CONFLICT_CHARS,
52
+ activity: TURN_BUDGET_ACTIVITY_CHARS,
53
+ alert: TURN_BUDGET_ALERT_CHARS,
54
+ margin: TURN_BUDGET_MARGIN_CHARS,
55
+ });
56
+
57
+ // 超限从尾裁剪的顺序:先裁增值最低的车道;防编 / 告警 / 余量是保护车道,不参与裁剪。
58
+ export const TURN_BUDGET_TRIM_ORDER = Object.freeze([
59
+ 'review',
60
+ 'prospective',
61
+ 'activity',
62
+ 'conflict',
63
+ 'working',
64
+ 'recall',
65
+ ]);
66
+
67
+ export const TURN_BUDGET_PROTECTED_LANES = Object.freeze(['antiFabrication', 'alert', 'margin']);
68
+
69
+ // 供机械自审使用的九项取值(含重复 120;L7 要求独立 120 出现 ≥2 次)。
70
+ export const TURN_BUDGET_BLOCK_VALUES = Object.freeze([
71
+ TURN_BUDGET_RECALL_CHARS,
72
+ TURN_BUDGET_WORKING_CHARS,
73
+ TURN_BUDGET_PROSPECTIVE_CHARS,
74
+ TURN_BUDGET_REVIEW_CHARS,
75
+ TURN_BUDGET_ANTI_FABRICATION_CHARS,
76
+ TURN_BUDGET_CONFLICT_CHARS,
77
+ TURN_BUDGET_ACTIVITY_CHARS,
78
+ TURN_BUDGET_ALERT_CHARS,
79
+ TURN_BUDGET_MARGIN_CHARS,
80
+ ]);
81
+
82
+ function codedError(code, message, detail) {
83
+ const error = new Error(`${code} ${message}`);
84
+ error.code = code;
85
+ if (detail !== undefined) error.detail = detail;
86
+ return error;
87
+ }
88
+
89
+ export function sumTurnBudgetLanes(lanes = TURN_BUDGET_LANES) {
90
+ return TURN_BUDGET_LANE_ORDER.reduce((sum, lane) => sum + Number(lanes?.[lane] ?? 0), 0);
91
+ }
92
+
93
+ export function assertTurnBudgetIntegrity() {
94
+ const sum = sumTurnBudgetLanes(TURN_BUDGET_LANES);
95
+ if (sum !== TURN_BUDGET_TOTAL_CHARS) {
96
+ throw codedError('E_HG_TURN_BUDGET_SUM', `九项预算和 ${sum} ≠ ${TURN_BUDGET_TOTAL_CHARS}`, { sum, total: TURN_BUDGET_TOTAL_CHARS });
97
+ }
98
+ const invalid = TURN_BUDGET_LANE_ORDER.filter((lane) => !(Number(TURN_BUDGET_LANES[lane]) > 0));
99
+ if (invalid.length > 0) {
100
+ throw codedError('E_HG_TURN_BUDGET_LANE', `车道预算非正数:${invalid.join(',')}`, { invalid });
101
+ }
102
+ return { schema: TURN_BUDGET_SCHEMA, total: TURN_BUDGET_TOTAL_CHARS, lanes: { ...TURN_BUDGET_LANES } };
103
+ }
104
+
105
+ export function getTurnBudgetCap(lane) {
106
+ return Number(TURN_BUDGET_LANES[lane] ?? 0);
107
+ }
108
+
109
+ // 生成本轮预算清单:单车道只允许下调(overrides),不允许把某车道抬过基准后侵占余量。
110
+ export function createTurnBudgetManifest(overrides = {}) {
111
+ const caps = {};
112
+ for (const lane of TURN_BUDGET_LANE_ORDER) {
113
+ const base = getTurnBudgetCap(lane);
114
+ const requested = overrides?.[lane];
115
+ const cap = Number.isFinite(Number(requested)) ? Math.max(0, Math.min(base, Math.floor(Number(requested)))) : base;
116
+ caps[lane] = cap;
117
+ }
118
+ return { schema: TURN_BUDGET_SCHEMA, totalChars: TURN_BUDGET_TOTAL_CHARS, caps: Object.freeze(caps) };
119
+ }
120
+
121
+ export function charLength(text) {
122
+ return Array.from(typeof text === 'string' ? text : String(text ?? '')).length;
123
+ }
124
+
125
+ // 按 code point 裁剪(汉字/emoji 不会被切半),超限时补省略号,返回值自带「实际字数」。
126
+ export function trimToChars(text, maxChars, options = {}) {
127
+ const source = typeof text === 'string' ? text : String(text ?? '');
128
+ const limit = Math.max(0, Math.floor(Number(maxChars) || 0));
129
+ const points = Array.from(source);
130
+ if (points.length <= limit) return { text: source, chars: points.length, trimmed: false };
131
+ if (limit === 0) return { text: '', chars: 0, trimmed: true };
132
+ const ellipsis = String(options.ellipsis ?? '…');
133
+ const keep = Math.max(0, limit - Array.from(ellipsis).length);
134
+ const cut = points.slice(0, keep).join('') + ellipsis;
135
+ return { text: cut, chars: Array.from(cut).length, trimmed: true };
136
+ }
137
+
138
+ export function measureTurnBlocks(blocks) {
139
+ return (Array.isArray(blocks) ? blocks : []).map((block) => {
140
+ const lane = String(block?.lane ?? '');
141
+ const source = typeof block?.text === 'string' ? block.text : '';
142
+ return { lane, text: source, chars: charLength(source) };
143
+ });
144
+ }
145
+
146
+ // 把本轮各车道文本按预算合成一条注入消息。
147
+ // - 每条先压到本车道 cap;
148
+ // - 合计超过 totalChars 时按 TRIM_ORDER 从尾继续裁;
149
+ // - 余量 240 只做保留额度(freeChars 里体现),任何单项不得挤占;
150
+ // - margin 车道不是文本块,忽略并记为 reservedMargin。
151
+ export function composeTurnBlocks(blocks, options = {}) {
152
+ const manifest = options.manifest ?? createTurnBudgetManifest();
153
+ const totalChars = Number.isFinite(Number(options.totalChars))
154
+ ? Math.max(0, Math.floor(Number(options.totalChars)))
155
+ : Number(manifest.totalChars ?? TURN_BUDGET_TOTAL_CHARS);
156
+ const reservedMargin = Number(manifest.caps?.margin ?? 0);
157
+ const measured = measureTurnBlocks(blocks).filter((part) => part.chars > 0 && part.lane !== 'margin');
158
+ if (measured.length === 0) {
159
+ return {
160
+ schema: TURN_BUDGET_SCHEMA,
161
+ text: '',
162
+ parts: [],
163
+ totalChars,
164
+ usedChars: 0,
165
+ freeChars: totalChars,
166
+ reservedMargin,
167
+ trimmedLanes: [],
168
+ overBudget: false,
169
+ };
170
+ }
171
+ const parts = measured.map((part) => {
172
+ const cap = Number(manifest.caps?.[part.lane] ?? 0);
173
+ const holder = trimToChars(part.text, cap);
174
+ return { lane: part.lane, text: holder.text, chars: holder.chars, cap, trimmed: holder.trimmed };
175
+ });
176
+ const trimmedLanes = new Set(parts.filter((part) => part.trimmed).map((part) => part.lane));
177
+ const separators = Math.max(0, parts.length - 1) * 2; // 段间 '\n\n'
178
+ const budgetForParts = Math.max(0, totalChars - separators);
179
+ let used = parts.reduce((sum, part) => sum + part.chars, 0);
180
+ let over = Math.max(0, used - budgetForParts);
181
+ for (const lane of TURN_BUDGET_TRIM_ORDER) {
182
+ if (over <= 0) break;
183
+ const part = parts.find((candidate) => candidate.lane === lane && candidate.chars > 0);
184
+ if (!part) continue;
185
+ const target = Math.max(0, part.chars - over);
186
+ const holder = trimToChars(part.text, target);
187
+ part.text = holder.text;
188
+ part.chars = holder.chars;
189
+ part.trimmed = true;
190
+ used = parts.reduce((sum, candidate) => sum + candidate.chars, 0);
191
+ over = Math.max(0, used - budgetForParts);
192
+ trimmedLanes.add(lane);
193
+ }
194
+ const text = parts.filter((part) => part.chars > 0).map((part) => part.text).join('\n\n');
195
+ const composedChars = charLength(text);
196
+ return {
197
+ schema: TURN_BUDGET_SCHEMA,
198
+ text,
199
+ parts: parts.map(({ lane, chars, cap, trimmed }) => ({ lane, chars, cap, trimmed })),
200
+ totalChars,
201
+ usedChars: composedChars,
202
+ freeChars: Math.max(0, totalChars - composedChars),
203
+ reservedMargin,
204
+ trimmedLanes: [...trimmedLanes],
205
+ overBudget: composedChars > totalChars,
206
+ };
207
+ }
208
+
209
+ export function assertTurnBudgetMessage(message, options = {}) {
210
+ const totalChars = Number.isFinite(Number(options.totalChars)) ? Math.max(0, Math.floor(Number(options.totalChars))) : TURN_BUDGET_TOTAL_CHARS;
211
+ const chars = charLength(message);
212
+ if (chars > totalChars) {
213
+ throw codedError('E_HG_TURN_BUDGET_OVERFLOW', `注入 ${chars} 字超上限 ${totalChars}`, { chars, totalChars });
214
+ }
215
+ return { chars, totalChars };
216
+ }
217
+
218
+ export function assertInjectionWithinLane(message, lane = 'recall') {
219
+ const cap = getTurnBudgetCap(lane);
220
+ const chars = charLength(message);
221
+ if (chars > cap) {
222
+ throw codedError('E_HG_TURN_BUDGET_LANE_OVERFLOW', `车道 ${lane} 注入 ${chars} 字超上限 ${cap}`, { lane, chars, cap });
223
+ }
224
+ return { lane, chars, cap };
225
+ }
226
+
227
+ // DESIGN L103:2,000 字 ≈ 1,000 token(中文约 2 字/token),只用于报告与 gate-log 记录,不参与判分。
228
+ export function estimateTurnTokens(chars) {
229
+ const value = Math.max(0, Math.floor(Number(chars) || 0));
230
+ return Math.ceil(value / 2);
231
+ }
232
+
233
+ export function countStandaloneL3(text, token) {
234
+ const re = new RegExp(`(?<![\\d,])${token}(?![\\d,])`, 'g');
235
+ return (String(text ?? '').match(re) ?? []).length;
236
+ }
237
+
238
+ export function countStandaloneL7(text, token) {
239
+ const re = new RegExp(`(?:^|[^0-9])${token}(?:[^0-9]|$)`, 'gm');
240
+ return (String(text ?? '').match(re) ?? []).length;
241
+ }
242
+
243
+ // 机械自审:把 L3 / L7 对「统一预算块」的识别方式在本模块源文本上重放一遍。
244
+ // oldValues 由调用方传入(源码里不允许出现旧值,所以旧值清单不能写进本文件)。
245
+ export function auditBudgetBlockSource(sourceText, options = {}) {
246
+ const source = String(sourceText ?? '');
247
+ const values = TURN_BUDGET_BLOCK_VALUES.map((value) => Number(value));
248
+ const uniqueValues = [...new Set(values)];
249
+ const l3 = {};
250
+ const l7 = {};
251
+ for (const value of uniqueValues) {
252
+ l3[value] = countStandaloneL3(source, value);
253
+ l7[value] = countStandaloneL7(source, value);
254
+ }
255
+ // 两种求和口径必须分开记:L7 按数组(含重复 120)求和=2,000;L3 现状 `[...new Set(sumTokens)]` 去重后=1,880。
256
+ const l7Sum = values.reduce((total, value) => total + value, 0);
257
+ const l3UniqueSum = uniqueValues.reduce((total, value) => total + value, 0);
258
+ const oldValues = Array.isArray(options.oldValues) ? options.oldValues : [];
259
+ const oldValuesFound = oldValues
260
+ .map((value) => Number(value))
261
+ .filter((value) => Number.isFinite(value) && countStandaloneL7(source, value) > 0);
262
+ const missingL3 = uniqueValues.filter((value) => (l3[value] ?? 0) === 0);
263
+ const missingL7 = uniqueValues.filter((value) => (l7[value] ?? 0) === 0);
264
+ return {
265
+ // found 只代表「L7 口径」的机械块成立:九项独立出现、120 出现 ≥2、数组和 2,000、无旧值。
266
+ found: missingL3.length === 0 && missingL7.length === 0 && l7Sum === TURN_BUDGET_TOTAL_CHARS && (l7[120] ?? 0) >= 2 && oldValuesFound.length === 0,
267
+ l7Sum,
268
+ l3UniqueSum,
269
+ expectedSum: TURN_BUDGET_TOTAL_CHARS,
270
+ l7Passable: missingL7.length === 0 && l7Sum === TURN_BUDGET_TOTAL_CHARS && (l7[120] ?? 0) >= 2,
271
+ // 已知验收口 bug(报告第一章 P1):L3 去重求和 1,880 ≠ breaking-map.B3.expectedSum 2,000,
272
+ // 只改源码永远 PASS 不了,必须先由健康体检侧修 L3 的求和口径(或用例 expectedSum 改 1,880 并改规格)。
273
+ l3SumMatchesMap: l3UniqueSum === Number(options.l3ExpectedSum ?? TURN_BUDGET_TOTAL_CHARS),
274
+ missingL3,
275
+ missingL7,
276
+ count120L7: l7[120] ?? 0,
277
+ oldValuesFound,
278
+ };
279
+ }
280
+
281
+ export function describeTurnBudget() {
282
+ return {
283
+ schema: TURN_BUDGET_SCHEMA,
284
+ totalChars: TURN_BUDGET_TOTAL_CHARS,
285
+ estimatedTokens: estimateTurnTokens(TURN_BUDGET_TOTAL_CHARS),
286
+ lanes: TURN_BUDGET_LANE_ORDER.map((lane) => ({ lane, chars: TURN_BUDGET_LANES[lane] })),
287
+ protectedLanes: [...TURN_BUDGET_PROTECTED_LANES],
288
+ trimOrder: [...TURN_BUDGET_TRIM_ORDER],
289
+ };
290
+ }
@@ -0,0 +1,264 @@
1
+ // src/memory/version-chain.js — M2-D:蒸馏版本链 / active 指针 / 回滚 / 审计
2
+ //
3
+ // 设计依据 MEMORY-RECALL-V2-PROPOSAL §4.3/§4.4:
4
+ // * 每个蒸馏 id 一个 append-only JSONL(`.longlive/distill/<topic>-<period>.jsonl`),
5
+ // 一行一个版本,旧版本永久保留、绝不覆盖/删除;
6
+ // * `.longlive/distill/index.json` 只存 activeVersion 指针,回滚=切指针(ms 级);
7
+ // * 每次 append / rollback 写 1 行 `.longlive/distill.log`(JSON,可审计)+
8
+ // 1 行 `.longlive/audit/records.jsonl`(统一审计,A5 口径);
9
+ // * 本模块只做“链/指针/审计”原语,不做抽取、不做保护判定(见 distill.js / l2-gate.js)。
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ import { appendAuditRecord } from './audit-records.js';
15
+ import { memoryError } from './paths.js';
16
+ import { appendAudit, ensureDir, sha256Text, writeFileAtomic } from './state.js';
17
+
18
+ export const VERSION_CHAIN_SCHEMA = 'version-chain/v1';
19
+ export const DISTILL_DIR = '.longlive/distill';
20
+ export const DISTILL_INDEX_FILE = '.longlive/distill/index.json';
21
+ export const DISTILL_LOG_FILE = '.longlive/distill.log';
22
+ export const DISTILL_INDEX_SCHEMA = 'distill-index/v1';
23
+
24
+ export function distillDirOf(root) {
25
+ return path.join(path.resolve(String(root)), DISTILL_DIR);
26
+ }
27
+
28
+ export function chainIndexPathOf(root) {
29
+ return path.join(path.resolve(String(root)), DISTILL_INDEX_FILE);
30
+ }
31
+
32
+ export function chainLogPathOf(root) {
33
+ return path.join(path.resolve(String(root)), DISTILL_LOG_FILE);
34
+ }
35
+
36
+ /** File name for one chain: only [A-Za-z0-9._-] survives (path traversal impossible). */
37
+ export function chainFileName({ topic, period }) {
38
+ const slug = (value) => String(value ?? 'unknown')
39
+ .normalize('NFKC')
40
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
41
+ .replace(/^-+|-+$/g, '')
42
+ .slice(0, 80) || 'unknown';
43
+ return `${slug(topic)}-${slug(period)}.jsonl`;
44
+ }
45
+
46
+ export function chainFilePathOf(root, id, file = null) {
47
+ const name = typeof file === 'string' && file !== '' ? file : chainFileName({ topic: id, period: 'chain' });
48
+ return path.join(distillDirOf(root), path.basename(name));
49
+ }
50
+
51
+ /** Deterministic JSON: object keys sorted recursively (idempotency hashes). */
52
+ export function stableStringify(value) {
53
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`;
54
+ if (value && typeof value === 'object') {
55
+ const keys = Object.keys(value).sort();
56
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
57
+ }
58
+ return JSON.stringify(value === undefined ? null : value);
59
+ }
60
+
61
+ export function contentHashOf(value) {
62
+ return sha256Text(stableStringify(value));
63
+ }
64
+
65
+ export function isEmptyIndex() {
66
+ return { schema: DISTILL_INDEX_SCHEMA, version: 1, entries: {} };
67
+ }
68
+
69
+ /** Read the active-pointer index; missing file => empty index, corrupt file => refuse (fail-safe). */
70
+ export function readChainIndex(root) {
71
+ const file = chainIndexPathOf(root);
72
+ let raw;
73
+ try {
74
+ raw = fs.readFileSync(file, 'utf8');
75
+ } catch (error) {
76
+ if (error?.code === 'ENOENT') return { ...isEmptyIndex(), file };
77
+ throw memoryError('E_CHAIN_INDEX_READ', `读不到 ${file}`, error);
78
+ }
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch (error) {
83
+ throw memoryError('E_CHAIN_INDEX_CORRUPT', `版本索引损坏(拒绝覆盖,先人工核对):${file}`, error);
84
+ }
85
+ const entries = parsed && typeof parsed === 'object' && parsed.entries && typeof parsed.entries === 'object'
86
+ ? parsed.entries
87
+ : {};
88
+ return { schema: parsed?.schema ?? DISTILL_INDEX_SCHEMA, version: parsed?.version ?? 1, entries, file };
89
+ }
90
+
91
+ export function readIndexEntry(root, id) {
92
+ const index = readChainIndex(root);
93
+ const entry = index.entries[String(id)];
94
+ if (!entry || typeof entry !== 'object') return null;
95
+ return {
96
+ id: String(id),
97
+ file: typeof entry.file === 'string' ? entry.file : null,
98
+ activeVersion: Number.isInteger(entry.activeVersion) ? entry.activeVersion : null,
99
+ versionCount: Number.isInteger(entry.versionCount) ? entry.versionCount : null,
100
+ contentHash: typeof entry.contentHash === 'string' ? entry.contentHash : null,
101
+ updatedAt: typeof entry.updatedAt === 'string' ? entry.updatedAt : null,
102
+ };
103
+ }
104
+
105
+ export function listChains(root) {
106
+ const index = readChainIndex(root);
107
+ return Object.keys(index.entries).sort().map((id) => ({
108
+ id,
109
+ ...readIndexEntry(root, id),
110
+ }));
111
+ }
112
+
113
+ /** Parse one chain file into versions (append-only order). Corrupt line => refuse. */
114
+ export function readVersions(file) {
115
+ let raw;
116
+ try {
117
+ raw = fs.readFileSync(file, 'utf8');
118
+ } catch (error) {
119
+ if (error?.code === 'ENOENT') return [];
120
+ throw memoryError('E_CHAIN_READ', `读不到版本链:${file}`, error);
121
+ }
122
+ const versions = [];
123
+ raw.split(/\r?\n/).forEach((line, index) => {
124
+ if (line.trim() === '') return;
125
+ try {
126
+ const row = JSON.parse(line);
127
+ if (!row || typeof row !== 'object' || !Number.isInteger(row.version)) {
128
+ throw new Error('version is not an integer');
129
+ }
130
+ versions.push(row);
131
+ } catch (error) {
132
+ throw memoryError('E_CHAIN_CORRUPT', `版本链第 ${index + 1} 行损坏:${file}`, error);
133
+ }
134
+ });
135
+ return versions;
136
+ }
137
+
138
+ /** Append one version line (fsync; never rewrites existing bytes). */
139
+ export function appendVersionLine({ file, record }) {
140
+ if (!record || !Number.isInteger(record.version) || record.version < 1) {
141
+ throw memoryError('E_CHAIN_VERSION', 'appendVersionLine requires record.version >= 1');
142
+ }
143
+ fs.mkdirSync(path.dirname(file), { recursive: true });
144
+ const fd = fs.openSync(file, 'a');
145
+ try {
146
+ fs.writeSync(fd, `${JSON.stringify(record)}\n`, null, 'utf8');
147
+ fs.fsyncSync(fd);
148
+ } finally {
149
+ fs.closeSync(fd);
150
+ }
151
+ return { file, version: record.version, line: JSON.stringify(record) };
152
+ }
153
+
154
+ /** Atomically set the active version pointer for one chain. */
155
+ export function setActiveVersion({ root, id, file, version, versionCount, contentHash = null, now = new Date() }) {
156
+ const index = readChainIndex(root);
157
+ index.entries[String(id)] = {
158
+ file: path.basename(String(file)),
159
+ activeVersion: version,
160
+ versionCount,
161
+ contentHash,
162
+ updatedAt: now.toISOString(),
163
+ };
164
+ const next = { schema: DISTILL_INDEX_SCHEMA, version: 1, entries: index.entries, updatedAt: now.toISOString() };
165
+ writeFileAtomic(root, chainIndexPathOf(root), `${JSON.stringify(next, null, 2)}\n`, { backup: false, now });
166
+ return { file: chainIndexPathOf(root), entry: index.entries[String(id)] };
167
+ }
168
+
169
+ /** Append one structured audit line to `.longlive/distill.log` (JSONL). */
170
+ export function appendChainLog({ root, op, id = null, file = null, fromVersion = null, toVersion = null, by = 'admin', reason = '', contentHash = null, now = new Date() }) {
171
+ const row = {
172
+ schema: 'distill-log/v1',
173
+ at: now.toISOString(),
174
+ op,
175
+ id,
176
+ file: file === null ? null : path.basename(String(file)),
177
+ fromVersion,
178
+ toVersion,
179
+ by,
180
+ reason,
181
+ contentHash,
182
+ };
183
+ const target = chainLogPathOf(root);
184
+ ensureDir(root, path.dirname(target));
185
+ fs.appendFileSync(target, `${JSON.stringify(row)}\n`, 'utf8');
186
+ return { file: target, row };
187
+ }
188
+
189
+ function appendUnifiedAudit({ root, action, recordId, extra, now }) {
190
+ try {
191
+ appendAuditRecord({
192
+ memoryRoot: root,
193
+ action,
194
+ recordId,
195
+ readerTier: 'host',
196
+ questionId: 'unknown',
197
+ expectedTurns: null,
198
+ answerText: null,
199
+ at: now.toISOString(),
200
+ extra,
201
+ });
202
+ } catch {
203
+ /* 统一审计是 best-effort:链日志已写,不能让审计写失败吞掉回滚结果 */
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Roll one chain back to a concrete version: only the active pointer moves;
209
+ * every version row stays on disk. Writes 1 distill.log row + 1 unified audit row.
210
+ */
211
+ export function rollbackVersion({ root, id, toVersion, by = 'admin', reason = '', now = new Date() }) {
212
+ const entry = readIndexEntry(root, id);
213
+ if (!entry || !entry.file || entry.activeVersion === null) {
214
+ throw memoryError('E_CHAIN_NOT_FOUND', `没有这个蒸馏 id(或尚未建链):${id}`);
215
+ }
216
+ const file = chainFilePathOf(root, id, entry.file);
217
+ const versions = readVersions(file);
218
+ const target = versions.find((row) => row.version === toVersion);
219
+ if (!target) {
220
+ throw memoryError('E_CHAIN_NO_VERSION', `链 ${id} 没有 v${toVersion}(现有 v${versions[0]?.version}..v${versions.at(-1)?.version})`);
221
+ }
222
+ if (entry.activeVersion === toVersion) {
223
+ return { ok: true, changed: false, id, file, fromVersion: entry.activeVersion, toVersion, versions: versions.length };
224
+ }
225
+ const fromVersion = entry.activeVersion;
226
+ setActiveVersion({
227
+ root,
228
+ id,
229
+ file,
230
+ version: toVersion,
231
+ versionCount: versions.length,
232
+ contentHash: target.contentHash ?? null,
233
+ now,
234
+ });
235
+ appendChainLog({ root, op: 'rollback', id, file, fromVersion, toVersion, by, reason, contentHash: target.contentHash ?? null, now });
236
+ appendAudit(root, { action: 'memory_distill_rollback', object: `${id}@v${fromVersion}->v${toVersion}`, result: `by=${by} reason=${reason || '-'}`, now });
237
+ appendUnifiedAudit({
238
+ root,
239
+ action: 'distill_rollback',
240
+ recordId: id,
241
+ extra: { fromVersion, toVersion, by, reason, file: path.basename(file) },
242
+ now,
243
+ });
244
+ return { ok: true, changed: true, id, file, fromVersion, toVersion, versions: versions.length };
245
+ }
246
+
247
+ /** Field-level diff between two version rows (audit/createdAt excluded). */
248
+ export function diffVersions(from, to) {
249
+ const changed = [];
250
+ const keys = new Set([...Object.keys(from ?? {}), ...Object.keys(to ?? {})]);
251
+ for (const key of [...keys].sort()) {
252
+ if (key === 'audit' || key === 'contentHash') continue;
253
+ const left = stableStringify(from?.[key] ?? null);
254
+ const right = stableStringify(to?.[key] ?? null);
255
+ if (left !== right) changed.push({ field: key, from: from?.[key] ?? null, to: to?.[key] ?? null });
256
+ }
257
+ return {
258
+ changed,
259
+ fromVersion: from?.version ?? null,
260
+ toVersion: to?.version ?? null,
261
+ fromGist: from?.gist ?? null,
262
+ toGist: to?.gist ?? null,
263
+ };
264
+ }