@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,328 @@
1
+ // src/autoprocedure/session-reader.js — 异步采样原语(F3/N5)。
2
+ //
3
+ // 本模块只在 setTimeout 的异步 drain 里被调用,绝不在 `session/event` 回调里:
4
+ // * 解压上限可配(autoProcedure.maxDecompressBytes,默认 8 MiB,硬上限
5
+ // 64 MiB),超限抛 E_AP_SAMPLE_TOO_BIG → reject too_big;
6
+ // * MAJ-2/D7:解压后文本超过上限时,不再整包失败,而是退化为「尾段窗口」
7
+ // 解析——用 codec.zstdFrameLength 只扫帧边界(不解压),从最后一帧向前
8
+ // 逐帧解压,累计 ≤ 上限为止;目标 turn 是刚结束的最后一轮,必然落在尾段。
9
+ // 只有单帧本身就超过上限时才继续抛 TOO_BIG;
10
+ // * 任何不可读/非 JSON/seq 不连续 → E_AP_SAMPLE_PARSE → reject parse(重试 ≤1);
11
+ // * 每一行记录「解压文本的 UTF-8 字节偏移」,供证据 excerptOffset/excerptLen
12
+ // 使用(offsetSpace = utf8-bytes-decompressed-session,见 N5)。整包解析时
13
+ // 偏移从文件起点算;尾段解析时是尾段文本内的偏移——校验侧会先做精确匹配,
14
+ // 失败后在 turn 内按「同长度 + 同 sha256」重定位,因此两种解析都能通过;
15
+ // * 只读会话日志,绝不改写。
16
+ //
17
+ // turnDigest 的锚定口径复用 src/memory/anchors.js#turnDigest(投影掉 seq/turn 等
18
+ // 会因截断重排的坐标),所以会话被 session_truncate_visible 重排 seq 后 digest
19
+ // 仍然可重算一致。
20
+
21
+ import crypto from 'node:crypto';
22
+ import fs from 'node:fs';
23
+
24
+ import { decompressFrame, splitFrames, zstdFrameLength } from '../codec.js';
25
+ import { findSessionFile } from '../auto-truncate.js';
26
+ import { turnDigest, turnWindowOf } from '../memory/anchors.js';
27
+ import { AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES } from './config.js';
28
+
29
+ export const SAMPLE_CODES = Object.freeze({
30
+ MISSING: 'E_AP_SAMPLE_MISSING',
31
+ PARSE: 'E_AP_SAMPLE_PARSE',
32
+ TOO_BIG: 'E_AP_SAMPLE_TOO_BIG',
33
+ TURN: 'E_AP_SAMPLE_TURN',
34
+ });
35
+
36
+ export class AutoProcedureSampleError extends Error {
37
+ constructor(code, message, detail = undefined) {
38
+ super(message);
39
+ this.name = 'AutoProcedureSampleError';
40
+ this.code = code;
41
+ if (detail !== undefined) this.detail = detail;
42
+ }
43
+ }
44
+
45
+ export function sha256Hex(text) {
46
+ return crypto.createHash('sha256').update(Buffer.isBuffer(text) ? text : String(text ?? ''), 'utf8').digest('hex');
47
+ }
48
+
49
+ function byteLength(text) {
50
+ return Buffer.byteLength(String(text ?? ''), 'utf8');
51
+ }
52
+
53
+ /**
54
+ * Decompress a session log with a hard cap on DECOMPRESSED bytes.
55
+ * A frame that would push the total past the cap aborts immediately.
56
+ */
57
+ export function decompressSessionCapped(buf, maxBytes = AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES) {
58
+ let frames;
59
+ try {
60
+ frames = splitFrames(buf);
61
+ } catch (error) {
62
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话帧结构损坏:${error?.message ?? error}`);
63
+ }
64
+ let totalBytes = 0;
65
+ const texts = [];
66
+ for (const frame of frames) {
67
+ let text;
68
+ try {
69
+ text = decompressFrame(buf.subarray(frame.start, frame.end));
70
+ } catch (error) {
71
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话帧解压失败:${error?.message ?? error}`);
72
+ }
73
+ totalBytes += byteLength(text);
74
+ if (totalBytes > maxBytes) {
75
+ throw new AutoProcedureSampleError(SAMPLE_CODES.TOO_BIG, `会话解压后超过 ${maxBytes} 字节(too_big)`, {
76
+ maxBytes,
77
+ frames: frames.length,
78
+ });
79
+ }
80
+ texts.push(text);
81
+ }
82
+ return { text: texts.join(''), frames: frames.length, bytes: totalBytes };
83
+ }
84
+
85
+ /**
86
+ * Walk the zstd frame structure WITHOUT decompressing payloads (D7).
87
+ * Cheap enough to run on a 60 MB log: only frame headers are parsed.
88
+ * @returns {Array<{start:number,end:number}>}
89
+ */
90
+ export function scanFrameSpans(buf) {
91
+ if (!Buffer.isBuffer(buf) || buf.length === 0) {
92
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '会话文件为空');
93
+ }
94
+ const spans = [];
95
+ let start = 0;
96
+ try {
97
+ while (start < buf.length) {
98
+ const end = zstdFrameLength(buf, start);
99
+ if (!Number.isInteger(end) || end <= start || end > buf.length) {
100
+ throw new Error(`bad frame length at ${start}: ${String(end)}`);
101
+ }
102
+ spans.push({ start, end });
103
+ start = end;
104
+ }
105
+ } catch (error) {
106
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话帧结构损坏:${error?.message ?? error}`);
107
+ }
108
+ if (spans.length === 0) throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '会话没有可读帧');
109
+ return spans;
110
+ }
111
+
112
+ function decompressSpan(buf, span) {
113
+ try {
114
+ return decompressFrame(buf.subarray(span.start, span.end));
115
+ } catch (error) {
116
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话帧解压失败:${error?.message ?? error}`);
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Split decompressed session text into non-empty lines with byte offsets.
122
+ * `start`/`end` are UTF-8 byte offsets into the provided decompressed text.
123
+ */
124
+ export function indexSessionLines(text) {
125
+ const records = [];
126
+ let offset = 0;
127
+ for (const line of String(text ?? '').split('\n')) {
128
+ const length = byteLength(line);
129
+ if (line !== '') records.push({ text: line, start: offset, end: offset + length });
130
+ offset += length + 1; // the '\n' the split consumed
131
+ }
132
+ return records;
133
+ }
134
+
135
+ function parseEventLines(lines, baseSeq) {
136
+ const events = [];
137
+ // Sparse array: index === event.seq, so downstream lookups by seq keep working
138
+ // for a tail window whose seqs start above 0 (D7).
139
+ const eventLines = [];
140
+ for (let index = 0; index < lines.length; index += 1) {
141
+ let event;
142
+ try {
143
+ event = JSON.parse(lines[index].text);
144
+ } catch (error) {
145
+ throw new AutoProcedureSampleError(
146
+ SAMPLE_CODES.PARSE,
147
+ `事件行不是 JSON(base seq ${baseSeq} + ${index}):${error?.message ?? error}`,
148
+ );
149
+ }
150
+ const expected = baseSeq + index;
151
+ if (event?.seq !== expected) {
152
+ throw new AutoProcedureSampleError(
153
+ SAMPLE_CODES.PARSE,
154
+ `事件 seq 不连续:index ${index} 的 seq=${JSON.stringify(event?.seq)},期望 ${expected}`,
155
+ );
156
+ }
157
+ events.push(event);
158
+ eventLines[event.seq] = lines[index];
159
+ }
160
+ return { events, eventLines };
161
+ }
162
+
163
+ function parseFull(buf, spans, maxBytes) {
164
+ const texts = [];
165
+ let totalBytes = 0;
166
+ for (const span of spans) {
167
+ const text = decompressSpan(buf, span);
168
+ totalBytes += byteLength(text);
169
+ if (totalBytes > maxBytes) {
170
+ throw new AutoProcedureSampleError(SAMPLE_CODES.TOO_BIG, `会话解压后超过 ${maxBytes} 字节(too_big)`, {
171
+ maxBytes,
172
+ frames: spans.length,
173
+ });
174
+ }
175
+ texts.push(text);
176
+ }
177
+ const fullText = texts.join('');
178
+ const lines = indexSessionLines(fullText);
179
+ if (lines.length === 0) throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '会话为空');
180
+ let header;
181
+ try {
182
+ header = JSON.parse(lines[0].text);
183
+ } catch (error) {
184
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话头不是 JSON:${error?.message ?? error}`);
185
+ }
186
+ if (header?.type !== 'session') {
187
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '会话第一行不是 session 头');
188
+ }
189
+ const { events, eventLines } = parseEventLines(lines.slice(1), 0);
190
+ return { header, events, lines, eventLines, bytes: totalBytes, frames: spans.length, tail: false, baseSeq: 0 };
191
+ }
192
+
193
+ /**
194
+ * D7 tail window: decompress whole frames from the end until the cap is reached.
195
+ * The just-completed turn lives at the end of the log, so the tail always covers
196
+ * it; a single frame bigger than the cap is the only remaining too_big case.
197
+ */
198
+ function parseTail(buf, spans, maxBytes) {
199
+ const pieces = [];
200
+ let totalBytes = 0;
201
+ let frameBytes = 0;
202
+ for (let index = spans.length - 1; index >= 1; index -= 1) {
203
+ const span = spans[index];
204
+ let text;
205
+ try {
206
+ text = decompressSpan(buf, span);
207
+ } catch (error) {
208
+ if (pieces.length === 0) throw error;
209
+ break;
210
+ }
211
+ frameBytes = byteLength(text);
212
+ if (totalBytes + frameBytes > maxBytes) {
213
+ if (pieces.length === 0) {
214
+ throw new AutoProcedureSampleError(SAMPLE_CODES.TOO_BIG, `最后一帧解压后超过 ${maxBytes} 字节(too_big)`, {
215
+ maxBytes,
216
+ frames: spans.length,
217
+ frameBytes,
218
+ });
219
+ }
220
+ break;
221
+ }
222
+ pieces.unshift(text);
223
+ totalBytes += frameBytes;
224
+ }
225
+ if (pieces.length === 0) {
226
+ throw new AutoProcedureSampleError(SAMPLE_CODES.TOO_BIG, `会话没有可采样的尾段(too_big)`, {
227
+ maxBytes,
228
+ frames: spans.length,
229
+ });
230
+ }
231
+ const tailText = pieces.join('');
232
+ const lines = indexSessionLines(tailText);
233
+ if (lines.length === 0) throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '会话尾段没有事件');
234
+ // We do not know the absolute startSeq in advance; the first event line carries
235
+ // it, and contiguity is enforced from there.
236
+ let baseSeq = null;
237
+ try {
238
+ const first = JSON.parse(lines[0].text);
239
+ baseSeq = Number.isInteger(first?.seq) ? first.seq : null;
240
+ } catch (error) {
241
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `尾段首行不是 JSON:${error?.message ?? error}`);
242
+ }
243
+ if (baseSeq === null || baseSeq < 0) {
244
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, '尾段首事件没有合法 seq');
245
+ }
246
+ const { events, eventLines } = parseEventLines(lines, baseSeq);
247
+ return {
248
+ header: null,
249
+ events,
250
+ lines,
251
+ eventLines,
252
+ bytes: totalBytes,
253
+ frames: spans.length,
254
+ tail: true,
255
+ baseSeq,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Parse a session log buffer into header + events + byte-indexed lines.
261
+ * Does not look at any turn yet; that is findTurnSample's job.
262
+ *
263
+ * Whole-file parsing is tried first (cheap for normal logs). When the decompressed
264
+ * size would exceed `maxBytes`, the tail window is parsed instead (D7) instead of
265
+ * failing with too_big.
266
+ */
267
+ export function parseSessionBuffer(buf, { maxBytes = AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES } = {}) {
268
+ const cap = Number.isInteger(maxBytes) && maxBytes > 0 ? maxBytes : AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES;
269
+ const spans = scanFrameSpans(buf);
270
+ try {
271
+ return parseFull(buf, spans, cap);
272
+ } catch (error) {
273
+ if (!(error instanceof AutoProcedureSampleError) || error.code !== SAMPLE_CODES.TOO_BIG) throw error;
274
+ return parseTail(buf, spans, cap);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Locate the requested turn: seq window + byte window + per-event line records.
280
+ * Returns null when the turn is not in the log (caller counts it as a sample miss).
281
+ */
282
+ export function findTurnSample(parsed, turn) {
283
+ if (!Number.isInteger(turn) || turn < 1) return null;
284
+ const window = turnWindowOf(parsed.events, turn);
285
+ if (!window) return null;
286
+ const events = parsed.events.filter((event) => Number.isInteger(event?.seq)
287
+ && event.seq >= window.seqStart && event.seq <= window.seqEnd);
288
+ const firstLine = parsed.eventLines[window.seqStart];
289
+ const lastLine = parsed.eventLines[window.seqEnd];
290
+ if (!firstLine || !lastLine) return null;
291
+ // Tail window guard: the requested turn is normally the last one, but never
292
+ // emit a digest for a turn whose beginning was cut off by the window.
293
+ if (parsed.tail === true && window.seqStart === parsed.baseSeq) {
294
+ const firstEvent = events[0];
295
+ if (firstEvent?.type !== 'turn/start') return null;
296
+ }
297
+ return {
298
+ turn,
299
+ seqStart: window.seqStart,
300
+ seqEnd: window.seqEnd,
301
+ byteStart: firstLine.start,
302
+ byteEnd: lastLine.end,
303
+ events,
304
+ digest: turnDigest(parsed.events, window.seqStart, window.seqEnd),
305
+ eventLine(seq) {
306
+ const line = parsed.eventLines[seq];
307
+ if (!line) return null;
308
+ return { text: line.text, offset: line.start, length: line.end - line.start };
309
+ },
310
+ };
311
+ }
312
+
313
+ /**
314
+ * Read one session file from disk and parse it. Never writes.
315
+ * @returns {{file:string, parsed:object}}
316
+ */
317
+ export function readSessionFile({ home, sessionId, maxBytes = AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES, readFile = null } = {}) {
318
+ const file = findSessionFile(home, sessionId);
319
+ if (!file) throw new AutoProcedureSampleError(SAMPLE_CODES.MISSING, `找不到会话文件:${sessionId}`);
320
+ let buf;
321
+ try {
322
+ // io: this is called only from the async drain, never from the event callback.
323
+ buf = readFile ? readFile(file) : fs.readFileSync(file);
324
+ } catch (error) {
325
+ throw new AutoProcedureSampleError(SAMPLE_CODES.PARSE, `会话文件不可读:${error?.message ?? error}`);
326
+ }
327
+ return { file, parsed: parseSessionBuffer(buf, { maxBytes }) };
328
+ }
package/src/backup.js ADDED
@@ -0,0 +1,310 @@
1
+ // @local/dsh-longlive — backup
2
+ //
3
+ // A backup is a byte-for-byte copy next to the session log:
4
+ // session.v4.jsonl.zstd -> session.v4.jsonl.zstd.bak-YYYYMMDD
5
+ // plus a sha256 recorded in backups.json (the ledger lives next to the log).
6
+ // Backups are never deleted by this plugin; the ledger only marks old ones
7
+ // as deletable.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+
13
+ import { appendGateLog } from './recall/gate-log.mjs';
14
+
15
+ // 批 C(M22):备份是写路径的前置条件。备份不可用时必须 fail-closed,
16
+ // 对外只认一个错误码:E_HG_BACKUP。
17
+ export const BACKUP_ERROR_CODE = 'E_HG_BACKUP';
18
+ export const BACKUP_KEEP = 7;
19
+ const BACKUP_IO_CODES = ['EPERM', 'EACCES', 'EROFS', 'EBUSY', 'ENOSPC', 'ENOTDIR', 'EMFILE', 'ENFILE'];
20
+
21
+ export function sha256File(file) {
22
+ const hash = crypto.createHash('sha256');
23
+ hash.update(fs.readFileSync(file));
24
+ return hash.digest('hex');
25
+ }
26
+
27
+ export function statOf(file) {
28
+ const s = fs.statSync(file);
29
+ return { size: s.size, mtimeMs: s.mtimeMs };
30
+ }
31
+
32
+ export function ledgerPath(sessionPath) {
33
+ return path.join(path.dirname(sessionPath), 'backups.json');
34
+ }
35
+
36
+ export function readLedger(sessionPath) {
37
+ const file = ledgerPath(sessionPath);
38
+ if (!fs.existsSync(file)) return { version: 1, backups: [], truncations: [] };
39
+ try {
40
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
41
+ return {
42
+ version: parsed.version ?? 1,
43
+ backups: Array.isArray(parsed.backups) ? parsed.backups : [],
44
+ truncations: Array.isArray(parsed.truncations) ? parsed.truncations : [],
45
+ };
46
+ } catch {
47
+ return { version: 1, backups: [], truncations: [] };
48
+ }
49
+ }
50
+
51
+ export function writeLedger(sessionPath, ledger) {
52
+ fs.writeFileSync(ledgerPath(sessionPath), JSON.stringify(ledger, null, 2) + '\n', 'utf8');
53
+ }
54
+
55
+ export function stamp(date = new Date()) {
56
+ const y = date.getFullYear();
57
+ const m = String(date.getMonth() + 1).padStart(2, '0');
58
+ const d = String(date.getDate()).padStart(2, '0');
59
+ return `${y}${m}${d}`;
60
+ }
61
+
62
+ /** All backup files that belong to this session log, oldest first. */
63
+ export function listBackups(sessionPath) {
64
+ const dir = path.dirname(sessionPath);
65
+ const base = path.basename(sessionPath);
66
+ if (!fs.existsSync(dir)) return [];
67
+ return fs
68
+ .readdirSync(dir)
69
+ .filter((name) => name.startsWith(`${base}.bak-`))
70
+ .map((name) => {
71
+ const file = path.join(dir, name);
72
+ const s = fs.statSync(file);
73
+ return { file, size: s.size, mtimeMs: s.mtimeMs };
74
+ })
75
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
76
+ }
77
+
78
+ /** Pick the backup path for today, never overwriting a different existing file. */
79
+ export function nextBackupPath(sessionPath, date = new Date(), expected = null) {
80
+ const dir = path.dirname(sessionPath);
81
+ const base = path.basename(sessionPath);
82
+ const day = stamp(date);
83
+ let candidate = path.join(dir, `${base}.bak-${day}`);
84
+ let n = 2;
85
+ while (fs.existsSync(candidate)) {
86
+ const s = fs.statSync(candidate);
87
+ // Same day, same bytes: reuse it. Different bytes: never overwrite, add -n.
88
+ // `expected` (the caller's snapshot) is compared instead of re-reading the
89
+ // session log, so a log that moved on cannot make two different byte sets
90
+ // look alike mid-run.
91
+ const same = expected
92
+ ? s.size === expected.size && sha256File(candidate) === expected.sha256
93
+ : s.size === fs.statSync(sessionPath).size && sha256File(candidate) === sha256File(sessionPath);
94
+ if (same) return candidate;
95
+ candidate = path.join(dir, `${base}.bak-${day}-${n}`);
96
+ n += 1;
97
+ }
98
+ return candidate;
99
+ }
100
+
101
+ /**
102
+ * Make sure a backup whose sha256 equals the caller's snapshot exists.
103
+ *
104
+ * The copy is written from those exact bytes (`sourceBuf`), never from a second
105
+ * read of the session log, and the sha256 recorded in the ledger is recomputed
106
+ * from the file we just wrote. A concurrent append therefore cannot slip into a
107
+ * backup that claims to represent the bytes the plan was built from.
108
+ */
109
+ export function ensureBackup(sessionPath, options = {}) {
110
+ try {
111
+ return ensureBackupUnsafe(sessionPath, options);
112
+ } catch (error) {
113
+ throw asBackupError(error, sessionPath);
114
+ }
115
+ }
116
+
117
+ function ensureBackupUnsafe(sessionPath, { date = new Date(), sourceBuf = null, sha256: expectedSha = null, size = null } = {}) {
118
+ const source = sourceBuf ?? fs.readFileSync(sessionPath);
119
+ const bytes = size ?? source.length;
120
+ if (source.length !== bytes) {
121
+ const error = new Error(`snapshot size mismatch: buffer is ${source.length} bytes, the plan recorded ${bytes}`);
122
+ error.code = 'SESSION_CHANGED';
123
+ throw error;
124
+ }
125
+ const sourceSha = expectedSha ?? crypto.createHash('sha256').update(source).digest('hex');
126
+ const ledger = readLedger(sessionPath);
127
+ const known = listBackups(sessionPath).filter((b) => b.size === bytes);
128
+ for (const b of known) {
129
+ if (sha256File(b.file) === sourceSha) {
130
+ return { created: false, file: b.file, sha256: sourceSha, size: bytes };
131
+ }
132
+ }
133
+ const target = nextBackupPath(sessionPath, date, { sha256: sourceSha, size: bytes });
134
+ // 'wx': an existing file is never clobbered, so two runs cannot share a name.
135
+ fs.writeFileSync(target, source, { flag: 'wx' });
136
+ const copied = sha256File(target);
137
+ if (copied !== sourceSha) {
138
+ try { fs.unlinkSync(target); } catch { /* best effort */ }
139
+ const error = new Error(`backup verification failed: ${target} sha256 ${copied} != source ${sourceSha}`);
140
+ error.code = 'BACKUP_SHA256_MISMATCH';
141
+ throw error;
142
+ }
143
+ ledger.backups.push({
144
+ file: target,
145
+ sha256: copied,
146
+ size: bytes,
147
+ createdAt: new Date().toISOString(),
148
+ deletable: ledger.backups.length + 1 > 7,
149
+ });
150
+ writeLedger(sessionPath, ledger);
151
+ return { created: true, file: target, sha256: copied, size: bytes };
152
+ }
153
+
154
+ /** Verify that the given backup file still matches the recorded sha256. */
155
+ export function verifyBackup(file, expectedSha256) {
156
+ if (!fs.existsSync(file)) return { ok: false, reason: 'backup file does not exist' };
157
+ const actual = sha256File(file);
158
+ if (expectedSha256 && actual !== expectedSha256) {
159
+ return { ok: false, reason: `sha256 mismatch: ${actual} != ${expectedSha256}`, sha256: actual };
160
+ }
161
+ return { ok: true, sha256: actual };
162
+ }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // 批 C(M22):backup fail-closed 四守卫 + 保留上限
166
+ // ---------------------------------------------------------------------------
167
+
168
+ export function backupError(code, message, cause = null) {
169
+ const error = new Error(message ?? String(code));
170
+ error.name = 'HardgateBackupError';
171
+ error.code = code;
172
+ if (cause) error.cause = cause;
173
+ return error;
174
+ }
175
+
176
+ /** 任何 IO 拒绝(EPERM/EACCES/只读/磁盘满…)统一转 E_HG_BACKUP;业务错误原样透传。 */
177
+ export function asBackupError(error, sessionPath = '') {
178
+ if (!error) return backupError(BACKUP_ERROR_CODE, '备份失败(未知原因)');
179
+ if (error.code === BACKUP_ERROR_CODE) return error;
180
+ if (BACKUP_IO_CODES.includes(error.code)) {
181
+ return backupError(
182
+ BACKUP_ERROR_CODE,
183
+ `备份不可用,拒写(${error.code})${sessionPath ? `:${sessionPath}` : ''}`,
184
+ error,
185
+ );
186
+ }
187
+ return error;
188
+ }
189
+
190
+ /**
191
+ * 写前守卫 1:备份必须先成功,返回备份回执;备份失败抛 E_HG_BACKUP。
192
+ */
193
+ export function assertBackupReady(sessionPath, options = {}) {
194
+ if (typeof sessionPath !== 'string' || sessionPath.trim() === '') {
195
+ throw backupError(BACKUP_ERROR_CODE, 'assertBackupReady 缺少 sessionPath:无法确认备份,拒写');
196
+ }
197
+ return ensureBackup(sessionPath, options);
198
+ }
199
+
200
+ /**
201
+ * 写前守卫 2:备份成功后再执行 writer(backup)。
202
+ * writer 抛错时备份保留(可回滚),错误原样抛出(不伪装成成功)。
203
+ */
204
+ export function ensureBackupThenWrite(input = {}, writer = null) {
205
+ const sessionPath = input.sessionPath;
206
+ const backup = assertBackupReady(sessionPath, {
207
+ date: input.date ?? new Date(),
208
+ sourceBuf: input.sourceBuf ?? null,
209
+ sha256: input.sha256 ?? null,
210
+ size: input.size ?? null,
211
+ });
212
+ const run = typeof writer === 'function' ? writer : (typeof input.writer === 'function' ? input.writer : null);
213
+ if (!run) return { ok: true, backup, written: false };
214
+ const written = run(backup);
215
+ return { ok: true, backup, written };
216
+ }
217
+
218
+ /**
219
+ * 写前守卫 3:guardedWrite。给卡片/状态写盘用:先备份会话日志,再原子写
220
+ * target(缺省 false 时只做备份守卫)。任何备份失败都拒绝落盘。
221
+ */
222
+ export function guardedWrite(input = {}) {
223
+ const sessionPath = String(input.sessionPath ?? '').trim();
224
+ if (sessionPath === '') {
225
+ throw backupError(BACKUP_ERROR_CODE, 'guardedWrite 缺少 sessionPath:无法确认备份,拒写');
226
+ }
227
+ const backup = assertBackupReady(sessionPath, {
228
+ date: input.date ?? new Date(),
229
+ sourceBuf: input.sourceBuf ?? null,
230
+ sha256: input.sha256 ?? null,
231
+ size: input.size ?? null,
232
+ });
233
+ const target = String(input.path ?? input.cardPath ?? '').trim();
234
+ if (target === '') return { ok: true, backup, written: false };
235
+ if (typeof input.writer === 'function') {
236
+ return { ok: true, backup, written: input.writer(backup) };
237
+ }
238
+ const file = path.isAbsolute(target) ? target : path.resolve(input.memoryRoot ?? process.cwd(), target);
239
+ const content = String(input.content ?? '');
240
+ const dir = path.dirname(file);
241
+ try {
242
+ fs.mkdirSync(dir, { recursive: true });
243
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
244
+ fs.writeFileSync(tmp, content, 'utf8');
245
+ fs.renameSync(tmp, file);
246
+ } catch (error) {
247
+ throw asBackupError(error, file);
248
+ }
249
+ return { ok: true, backup, written: true, path: file, bytes: Buffer.byteLength(content, 'utf8') };
250
+ }
251
+
252
+ /** 写前守卫 4:writeWithBackup = guardedWrite 的可注入 writer 形态(旧名兼容)。 */
253
+ export function writeWithBackup(input = {}, writer = null) {
254
+ const opts = writer ? { ...input, writer } : input;
255
+ return guardedWrite(opts);
256
+ }
257
+
258
+ /**
259
+ * 保留上限(7 份):只删本会话自己的 .bak-* 副本,不碰 ledger 与其他文件。
260
+ * 删除前写 gate-log(备份可回滚,删的是重复副本);默认 dryRun=false 由调用方显式开启。
261
+ */
262
+ export function pruneBackups({ sessionPath, memoryRoot = null, keep = BACKUP_KEEP, now = new Date(), dryRun = false } = {}) {
263
+ const session = String(sessionPath ?? '').trim();
264
+ if (session === '') return { ok: false, error: 'session-path-missing', removed: [], kept: 0 };
265
+ const backups = listBackups(session);
266
+ const keepN = Math.max(1, Math.floor(Number(keep) || BACKUP_KEEP));
267
+ const excess = backups.slice(0, Math.max(0, backups.length - keepN));
268
+ const removed = [];
269
+ for (const item of excess) {
270
+ if (dryRun) {
271
+ removed.push({ file: item.file, dryRun: true });
272
+ continue;
273
+ }
274
+ try {
275
+ fs.unlinkSync(item.file);
276
+ removed.push({ file: item.file });
277
+ } catch (error) {
278
+ return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
279
+ }
280
+ }
281
+ // ledger 里只保留现存副本,避免下次读到幽灵记录。
282
+ if (!dryRun && removed.length > 0) {
283
+ try {
284
+ const ledger = readLedger(session);
285
+ const present = new Set(listBackups(session).map((item) => item.file));
286
+ ledger.backups = ledger.backups.filter((entry) => present.has(entry.file));
287
+ writeLedger(session, ledger);
288
+ } catch (error) {
289
+ return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
290
+ }
291
+ }
292
+ if (removed.length > 0 && memoryRoot) {
293
+ try {
294
+ appendGateLog(memoryRoot, {
295
+ gate: 'backup.prune',
296
+ decision: 'ok',
297
+ reason: 'backup.prune',
298
+ evidence: removed.map((item) => path.basename(item.file)),
299
+ at: (now instanceof Date ? now : new Date(now ?? Date.now())).toISOString(),
300
+ sessionId: null,
301
+ turn: null,
302
+ });
303
+ } catch {
304
+ // gate-log 写失败不回滚删除(副本已不在,账可事后补)
305
+ }
306
+ }
307
+ return { ok: true, removed, kept: backups.length - removed.length, dryRun, keep: keepN };
308
+ }
309
+
310
+ export { pruneBackups as cleanupBackups, pruneBackups as enforceBackupRetention, pruneBackups as retainBackups, pruneBackups as trimBackups };