@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,307 @@
1
+ // src/metrics/prestep-latency.mjs — B3 时延责任归因(pre-step 编排器 observability)
2
+ //
3
+ // 目的:把「思考/回忆时间(t_question → t_evidence_ready)」拆成可归因的阶段:
4
+ // boot(开机卡)/ shared(共享活动流)/ working(工作帧)/ recall(召回编排)/
5
+ // inject(消息合并入 messages)/ budget(召回预算裁剪)
6
+ // 另记 degradations[]:gate 跳过 / embedding 回退 / 零命中 / 预算裁剪 / 异常 fail-open。
7
+ //
8
+ // 契约:**纯计时、零行为变化**。所有入口都吞异常并返回 no-op 计时器;metrics 未启用时
9
+ // 完全不写盘、不创建目录(registerMetrics 在入口调用 configurePrestepLatency)。
10
+ // 落盘:<memoryRoot>/.longlive/metrics/prestep.jsonl,每轮一行(sessionId+turn 幂等)。
11
+ // 面板/基准读取:readPrestepRows();面板接线走 store.mjs#readPrestepSummary()。
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ import { appendJsonLine } from '../util/append-store.js';
17
+
18
+ export const PRESTEP_LATENCY_SCHEMA = 'prestep-latency/v1';
19
+ export const PRESTEP_SUMMARY_SCHEMA = 'prestep-summary/v1';
20
+ export const PRESTEP_FILE_NAME = 'prestep.jsonl';
21
+ export const PRESTEP_PHASES = Object.freeze(['boot', 'shared', 'working', 'recall', 'inject', 'budget', 'guard', 'proactive', 'handoff']);
22
+ export const PRESTEP_DEGRADES = Object.freeze([
23
+ 'gate-skip', 'embedding-fallback', 'zero-hit', 'budget-trim', 'error', 'factory-unavailable', 'frame-skip',
24
+ 'handoff-skip',
25
+ ]);
26
+
27
+ const state = {
28
+ enabled: false,
29
+ memoryRoot: '',
30
+ now: () => new Date(),
31
+ pending: new Map(), // key -> entry
32
+ finalized: new Map(), // key -> at (idempotency; bounded)
33
+ };
34
+ const MAX_ENTRIES = 2048;
35
+
36
+ function roundMs(value) {
37
+ return Number.isFinite(value) ? Math.round(value * 1000) / 1000 : null;
38
+ }
39
+ function nowMs() {
40
+ if (typeof process.hrtime?.bigint === 'function') return process.hrtime.bigint();
41
+ return BigInt(Date.now()) * 1_000_000n;
42
+ }
43
+ function elapsedMs(start) {
44
+ if (start === null) return null;
45
+ try {
46
+ return Number(nowMs() - start) / 1e6;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function safeSessionId(sessionId) {
52
+ return typeof sessionId === 'string' && sessionId.trim() !== '' ? sessionId.trim() : 'unknown';
53
+ }
54
+ function safeTurn(turn) {
55
+ return Number.isFinite(Number(turn)) ? Number(turn) : null;
56
+ }
57
+ function turnKey(sessionId, turn) {
58
+ return `${safeSessionId(sessionId)}:${safeTurn(turn) === null ? '?' : safeTurn(turn)}`;
59
+ }
60
+ function prestepFile(memoryRoot) {
61
+ const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? path.resolve(memoryRoot.trim()) : '';
62
+ return root === '' ? '' : path.join(root, '.longlive', 'metrics', PRESTEP_FILE_NAME);
63
+ }
64
+ function trimMap(map) {
65
+ while (map.size > MAX_ENTRIES) {
66
+ const first = map.keys().next().value;
67
+ map.delete(first);
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Called once by metrics registration. `enabled:false` makes every helper a no-op
73
+ * with zero disk IO; changing memoryRoot resets in-flight turn state.
74
+ */
75
+ export function configurePrestepLatency(options = {}) {
76
+ const memoryRoot = typeof options.memoryRoot === 'string' ? options.memoryRoot.trim() : '';
77
+ if (memoryRoot !== state.memoryRoot) {
78
+ state.pending.clear();
79
+ state.finalized.clear();
80
+ }
81
+ state.enabled = options.enabled === true && memoryRoot !== '';
82
+ state.memoryRoot = memoryRoot;
83
+ state.now = typeof options.now === 'function' ? options.now : () => new Date();
84
+ return { enabled: state.enabled, memoryRoot: state.memoryRoot };
85
+ }
86
+
87
+ export function prestepLatencyEnabled() {
88
+ return state.enabled === true;
89
+ }
90
+
91
+ export function resetPrestepLatencyForTests() {
92
+ state.pending.clear();
93
+ state.finalized.clear();
94
+ state.enabled = false;
95
+ state.memoryRoot = '';
96
+ }
97
+
98
+ function getEntry(sessionId, turn) {
99
+ const key = turnKey(sessionId, turn);
100
+ let entry = state.pending.get(key);
101
+ if (!entry) {
102
+ entry = {
103
+ key,
104
+ sessionId: safeSessionId(sessionId),
105
+ turn: safeTurn(turn),
106
+ startedAt: state.now().toISOString(),
107
+ phases: Object.fromEntries(PRESTEP_PHASES.map((name) => [name, null])),
108
+ degrades: [],
109
+ meta: {},
110
+ };
111
+ state.pending.set(key, entry);
112
+ trimMap(state.pending);
113
+ }
114
+ return entry;
115
+ }
116
+
117
+ /** Open a phase timer; always safe to call. */
118
+ export function startPrestepPhase(sessionId, turn, phase) {
119
+ if (!state.enabled || !PRESTEP_PHASES.includes(phase)) return { end() {} };
120
+ let start = null;
121
+ try {
122
+ const entry = getEntry(sessionId, turn);
123
+ start = nowMs();
124
+ return {
125
+ end(detail = null) {
126
+ if (start === null) return;
127
+ const ms = elapsedMs(start);
128
+ start = null;
129
+ if (!Number.isFinite(ms)) return;
130
+ try {
131
+ entry.phases[phase] = roundMs(ms);
132
+ if (detail !== null && typeof detail === 'object') {
133
+ for (const [name, value] of Object.entries(detail)) {
134
+ if (name === 'degrades' && Array.isArray(value)) continue;
135
+ entry.meta[name] = value;
136
+ }
137
+ }
138
+ } catch { /* timing must never break a turn */ }
139
+ },
140
+ };
141
+ } catch {
142
+ return { end() {} };
143
+ }
144
+ }
145
+
146
+ /** Record one degradation reason for this turn (unknown session/turn just creates the entry). */
147
+ export function notePrestepDegrade(sessionId, turn, input = {}) {
148
+ if (!state.enabled) return false;
149
+ try {
150
+ const entry = getEntry(sessionId, turn);
151
+ const kind = typeof input.kind === 'string' && input.kind !== '' ? input.kind : 'error';
152
+ entry.degrades.push({
153
+ kind,
154
+ phase: typeof input.phase === 'string' && PRESTEP_PHASES.includes(input.phase) ? input.phase : null,
155
+ detail: input.detail === undefined ? null : String(input.detail),
156
+ });
157
+ if (entry.degrades.length > 32) entry.degrades.splice(0, entry.degrades.length - 32);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ /** Merge metadata into this turn's row (e.g. budget tokens, injected paths). */
165
+ export function setPrestepMeta(sessionId, turn, meta = {}) {
166
+ if (!state.enabled || meta === null || typeof meta !== 'object') return false;
167
+ try {
168
+ Object.assign(getEntry(sessionId, turn).meta, meta);
169
+ return true;
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+
175
+ function dominantOf(phases) {
176
+ let name = null;
177
+ let ms = -1;
178
+ for (const key of PRESTEP_PHASES) {
179
+ const value = phases[key];
180
+ if (Number.isFinite(value) && value > ms) {
181
+ name = key;
182
+ ms = value;
183
+ }
184
+ }
185
+ return { dominant: name, dominantMs: ms >= 0 ? roundMs(ms) : null };
186
+ }
187
+
188
+ /**
189
+ * Write one row (idempotent per session:turn) and clear pending state.
190
+ * Safe to call from any pre-step handler / metrics turn-end fallback.
191
+ */
192
+ export function finalizePrestepTurn(sessionId, turn, options = {}) {
193
+ if (!state.enabled) return null;
194
+ const key = turnKey(sessionId, turn);
195
+ if (state.finalized.has(key)) return null;
196
+ let entry = state.pending.get(key);
197
+ if (!entry) entry = getEntry(sessionId, turn);
198
+ state.pending.delete(key);
199
+ state.finalized.set(key, state.now().toISOString());
200
+ trimMap(state.finalized);
201
+
202
+ let ms = 0;
203
+ let counted = 0;
204
+ for (const name of PRESTEP_PHASES) {
205
+ if (Number.isFinite(entry.phases[name])) {
206
+ ms += entry.phases[name];
207
+ counted += 1;
208
+ }
209
+ }
210
+ const { dominant, dominantMs } = dominantOf(entry.phases);
211
+ const row = {
212
+ schema: PRESTEP_LATENCY_SCHEMA,
213
+ at: state.now().toISOString(),
214
+ sessionId: entry.sessionId,
215
+ turn: entry.turn,
216
+ phases: { ...entry.phases },
217
+ dominant,
218
+ dominantMs,
219
+ ms: counted === 0 ? null : roundMs(ms),
220
+ countedPhases: counted,
221
+ degrades: entry.degrades,
222
+ meta: entry.meta,
223
+ };
224
+ const file = prestepFile(typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== '' ? options.memoryRoot : state.memoryRoot);
225
+ if (file === '') return null;
226
+ const healthRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== '' ? options.memoryRoot : state.memoryRoot;
227
+ const written = appendJsonLine({
228
+ file,
229
+ row,
230
+ label: 'metrics.prestep',
231
+ healthRoot,
232
+ now: () => state.now(),
233
+ quarantineDir: path.join(String(healthRoot ?? ''), '.longlive', 'quarantine'),
234
+ });
235
+ if (!written.ok) return null;
236
+ return row;
237
+ }
238
+
239
+ /** Read raw rows, newest last. Corrupt lines skipped; never throws. */
240
+ export function readPrestepRows(options = {}) {
241
+ const file = prestepFile(options.memoryRoot);
242
+ if (file === '') return { ok: false, code: 'E_MEMORY_ROOT_UNSET', path: '', rows: [], total: 0, skipped: 0 };
243
+ let text;
244
+ try {
245
+ text = fs.readFileSync(file, 'utf8');
246
+ } catch (error) {
247
+ if (error?.code === 'ENOENT') return { ok: true, path: file, rows: [], total: 0, skipped: 0, exists: false };
248
+ return { ok: false, code: 'E_PRESTEP_READ', path: file, rows: [], total: 0, skipped: 0, message: String(error?.message ?? error) };
249
+ }
250
+ const rows = [];
251
+ let skipped = 0;
252
+ for (const line of text.split('\n')) {
253
+ const trimmed = line.trim();
254
+ if (trimmed === '') continue;
255
+ try {
256
+ const row = JSON.parse(trimmed);
257
+ if (row && typeof row === 'object' && row.schema === PRESTEP_LATENCY_SCHEMA) rows.push(row);
258
+ else skipped += 1;
259
+ } catch {
260
+ skipped += 1;
261
+ }
262
+ }
263
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
264
+ const kept = limit > 0 ? rows.slice(-limit) : rows;
265
+ return { ok: true, path: file, exists: true, rows: kept, total: rows.length, skipped };
266
+ }
267
+
268
+ function avg(values) {
269
+ if (values.length === 0) return null;
270
+ return roundMs(values.reduce((sum, value) => sum + value, 0) / values.length);
271
+ }
272
+ function p50(values) {
273
+ if (values.length === 0) return null;
274
+ const sorted = [...values].sort((a, b) => a - b);
275
+ return roundMs(sorted[Math.floor((sorted.length - 1) / 2)]);
276
+ }
277
+
278
+ /** Deterministic summary for the panel (#9 write-health `prestep` field) / benchmarks. */
279
+ export function summarizePrestepRows(rows = []) {
280
+ const phases = {};
281
+ for (const name of PRESTEP_PHASES) {
282
+ const values = [];
283
+ for (const row of rows) {
284
+ const value = row?.phases?.[name];
285
+ if (Number.isFinite(value)) values.push(value);
286
+ }
287
+ phases[name] = { count: values.length, avgMs: avg(values), p50Ms: p50(values), maxMs: values.length > 0 ? roundMs(Math.max(...values)) : null };
288
+ }
289
+ const dominantCounts = {};
290
+ const degradeCounts = {};
291
+ let lastAt = null;
292
+ for (const row of rows) {
293
+ if (typeof row.dominant === 'string' && row.dominant !== '') dominantCounts[row.dominant] = (dominantCounts[row.dominant] ?? 0) + 1;
294
+ for (const item of Array.isArray(row.degrades) ? row.degrades : []) {
295
+ if (typeof item?.kind === 'string') degradeCounts[item.kind] = (degradeCounts[item.kind] ?? 0) + 1;
296
+ }
297
+ if (typeof row.at === 'string' && (lastAt === null || row.at > lastAt)) lastAt = row.at;
298
+ }
299
+ return {
300
+ schema: PRESTEP_SUMMARY_SCHEMA,
301
+ count: rows.length,
302
+ lastAt,
303
+ phases,
304
+ dominantCounts,
305
+ degradeCounts,
306
+ };
307
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * D4 — the turn ledger on disk.
3
+ *
4
+ * Layout:
5
+ * <memoryRoot>/.longlive/metrics/turns.jsonl one JSON object per line
6
+ * <memoryRoot>/.longlive/metrics/state.json cumulative calibration state
7
+ *
8
+ * Every write is best-effort and returns `{ok:false,code}` instead of throwing:
9
+ * a metrics failure must never break a turn (D1: over-budget is a record, not
10
+ * an error).
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { appendJsonLine } from '../util/append-store.js';
16
+ import { summarizeRows, clampFactor, DEFAULT_FACTOR, DEFAULT_KEEP_TURNS } from './measure.mjs';
17
+ import { PRESTEP_FILE_NAME, readPrestepRows, summarizePrestepRows } from './prestep-latency.mjs';
18
+
19
+ export const METRICS_DIR_NAME = 'metrics';
20
+ export const TURNS_FILE_NAME = 'turns.jsonl';
21
+ export const STATE_FILE_NAME = 'state.json';
22
+ export const PRESTEP_FILE = PRESTEP_FILE_NAME;
23
+ export const LEDGER_VERSION = 1;
24
+
25
+ export function metricsDir(memoryRoot) {
26
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') return '';
27
+ return path.join(path.resolve(memoryRoot), '.longlive', METRICS_DIR_NAME);
28
+ }
29
+
30
+ export function ledgerPath(memoryRoot) {
31
+ const dir = metricsDir(memoryRoot);
32
+ return dir === '' ? '' : path.join(dir, TURNS_FILE_NAME);
33
+ }
34
+
35
+ export function calibrationPath(memoryRoot) {
36
+ const dir = metricsDir(memoryRoot);
37
+ return dir === '' ? '' : path.join(dir, STATE_FILE_NAME);
38
+ }
39
+
40
+ export function prestepLedgerPath(memoryRoot) {
41
+ const dir = metricsDir(memoryRoot);
42
+ return dir === '' ? '' : path.join(dir, PRESTEP_FILE_NAME);
43
+ }
44
+
45
+ /**
46
+ * B3: read the pre-step latency ledger (`.longlive/metrics/prestep.jsonl`).
47
+ * Best-effort, never throws; corrupt lines are counted in `skipped`.
48
+ */
49
+ export function readPrestepLedger(options = {}) {
50
+ return readPrestepRows({ memoryRoot: options.memoryRoot, limit: options.limit });
51
+ }
52
+
53
+ /**
54
+ * B3: deterministic pre-step latency summary for the panel.
55
+ * Activity-writer A6 wiring: add `prestep: readPrestepSummary({ memoryRoot })` to the
56
+ * #9 write-health reader response (see B3 handoff), no new route id needed.
57
+ */
58
+ export function readPrestepSummary(options = {}) {
59
+ const rows = readPrestepRows({ memoryRoot: options.memoryRoot, limit: options.limit }).rows;
60
+ return summarizePrestepRows(rows);
61
+ }
62
+
63
+ /** Append one row. Never throws. S1: 单写锁 + fsync + 坏行隔离(append-store)。 */
64
+ export function appendTurnRow(row, options = {}) {
65
+ const memoryRoot = options.memoryRoot;
66
+ const file = ledgerPath(memoryRoot);
67
+ if (file === '') return { ok: false, code: 'E_MEMORY_ROOT_UNSET', path: '' };
68
+ if (row === null || typeof row !== 'object') return { ok: false, code: 'E_INVALID_ROW', path: file };
69
+ const written = appendJsonLine({
70
+ file,
71
+ row,
72
+ label: 'metrics.turns',
73
+ healthRoot: memoryRoot,
74
+ now: options.now,
75
+ quarantineDir: path.join(path.resolve(String(memoryRoot)), '.longlive', 'quarantine'),
76
+ });
77
+ if (!written.ok) {
78
+ return { ok: false, code: written.code === 'E_APPEND_LOCKED' ? 'E_LEDGER_LOCKED' : 'E_LEDGER_WRITE', path: file, message: written.error?.message ?? written.code ?? 'append failed' };
79
+ }
80
+ return { ok: true, path: file, bytes: written.bytes };
81
+ }
82
+
83
+ function compareAt(a, b) {
84
+ const left = typeof a === 'string' ? a : '';
85
+ const right = typeof b === 'string' ? b : '';
86
+ return left.localeCompare(right);
87
+ }
88
+
89
+ /**
90
+ * Read the ledger. Corrupt lines are counted and skipped, never fatal.
91
+ *
92
+ * @param {object} options
93
+ * @param {string} options.memoryRoot
94
+ * @param {string} [options.sessionId] exact match
95
+ * @param {number} [options.limit] keep the newest N rows (0/undefined = all)
96
+ * @param {string} [options.since] ISO lower bound (inclusive)
97
+ * @param {string} [options.until] ISO upper bound (inclusive)
98
+ * @returns {{ok:boolean,path:string,exists:boolean,rows:object[],total:number,skipped:number,bytes:number,code?:string}}
99
+ */
100
+ export function readTurnLedger(options = {}) {
101
+ const memoryRoot = options.memoryRoot;
102
+ const file = ledgerPath(memoryRoot);
103
+ if (file === '') {
104
+ return { ok: false, code: 'E_MEMORY_ROOT_UNSET', path: '', exists: false, rows: [], total: 0, skipped: 0, bytes: 0 };
105
+ }
106
+ let text;
107
+ try {
108
+ text = fs.readFileSync(file, 'utf8');
109
+ } catch (error) {
110
+ if (error?.code === 'ENOENT') {
111
+ return { ok: true, path: file, exists: false, rows: [], total: 0, skipped: 0, bytes: 0 };
112
+ }
113
+ return { ok: false, code: 'E_LEDGER_READ', path: file, exists: false, rows: [], total: 0, skipped: 0, bytes: 0, message: String(error?.message ?? error) };
114
+ }
115
+
116
+ const sessionId = typeof options.sessionId === 'string' && options.sessionId !== '' ? options.sessionId : '';
117
+ const since = typeof options.since === 'string' ? options.since : '';
118
+ const until = typeof options.until === 'string' ? options.until : '';
119
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
120
+
121
+ let skipped = 0;
122
+ const rows = [];
123
+ for (const line of text.split(/\r?\n/)) {
124
+ const trimmed = line.trim();
125
+ if (trimmed === '') continue;
126
+ let row;
127
+ try {
128
+ row = JSON.parse(trimmed);
129
+ } catch {
130
+ skipped += 1;
131
+ continue;
132
+ }
133
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) {
134
+ skipped += 1;
135
+ continue;
136
+ }
137
+ if (sessionId !== '' && row.sessionId !== sessionId) continue;
138
+ if (since !== '' && compareAt(row.at, since) < 0) continue;
139
+ if (until !== '' && compareAt(row.at, until) > 0) continue;
140
+ rows.push(row);
141
+ }
142
+
143
+ const total = rows.length;
144
+ const kept = limit > 0 && rows.length > limit ? rows.slice(rows.length - limit) : rows;
145
+ return {
146
+ ok: true,
147
+ path: file,
148
+ exists: true,
149
+ rows: kept,
150
+ total,
151
+ skipped,
152
+ bytes: Buffer.byteLength(text, 'utf8'),
153
+ };
154
+ }
155
+
156
+ /** Compact rollup for router_status / the panel. */
157
+ export function readMetricsSummary(options = {}) {
158
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 500;
159
+ const ledger = readTurnLedger({ ...options, limit });
160
+ if (ledger.ok !== true) {
161
+ return {
162
+ ok: false,
163
+ code: ledger.code ?? 'E_LEDGER_READ',
164
+ path: ledger.path ?? '',
165
+ available: false,
166
+ summary: summarizeRows([]),
167
+ };
168
+ }
169
+ return {
170
+ ok: true,
171
+ path: ledger.path,
172
+ exists: ledger.exists,
173
+ available: ledger.rows.length > 0,
174
+ skipped: ledger.skipped,
175
+ summary: summarizeRows(ledger.rows),
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Calibration state. `factor` starts at 1.0 (documented /3.5 estimate) and
181
+ * is the ratio of all observed actual input to all observed raw estimates:
182
+ * factor = clamp(0.5, 2, (actualSum + actual) / (rawSum + raw))
183
+ * This is a cumulative ratio, not an EWMA: one sample already corrects the
184
+ * systematic bias, and later samples only refine it.
185
+ */
186
+ export function readCalibration(memoryRoot) {
187
+ const file = calibrationPath(memoryRoot);
188
+ const fallback = {
189
+ v: LEDGER_VERSION,
190
+ factor: DEFAULT_FACTOR,
191
+ samples: 0,
192
+ rawSum: 0,
193
+ actualSum: 0,
194
+ keepTurns: DEFAULT_KEEP_TURNS,
195
+ updatedAt: null,
196
+ };
197
+ if (file === '') return { ok: false, code: 'E_MEMORY_ROOT_UNSET', path: '', exists: false, ...fallback };
198
+ try {
199
+ const text = fs.readFileSync(file, 'utf8');
200
+ const parsed = JSON.parse(text);
201
+ if (parsed === null || typeof parsed !== 'object') throw new Error('state is not an object');
202
+ return {
203
+ ok: true,
204
+ path: file,
205
+ exists: true,
206
+ v: LEDGER_VERSION,
207
+ factor: clampFactor(parsed.factor),
208
+ samples: Number.isInteger(parsed.samples) && parsed.samples >= 0 ? parsed.samples : 0,
209
+ rawSum: Number.isFinite(parsed.rawSum) && parsed.rawSum >= 0 ? parsed.rawSum : 0,
210
+ actualSum: Number.isFinite(parsed.actualSum) && parsed.actualSum >= 0 ? parsed.actualSum : 0,
211
+ keepTurns: Number.isInteger(parsed.keepTurns) && parsed.keepTurns > 0 ? parsed.keepTurns : DEFAULT_KEEP_TURNS,
212
+ updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : null,
213
+ };
214
+ } catch (error) {
215
+ if (error?.code === 'ENOENT') return { ok: true, path: file, exists: false, ...fallback };
216
+ return { ok: false, code: 'E_STATE_READ', path: file, exists: true, message: String(error?.message ?? error), ...fallback };
217
+ }
218
+ }
219
+
220
+ /** Atomic state write (tmp -> rename), best-effort. */
221
+ export function writeCalibration(memoryRoot, state = {}) {
222
+ const file = calibrationPath(memoryRoot);
223
+ if (file === '') return { ok: false, code: 'E_MEMORY_ROOT_UNSET', path: '' };
224
+ const payload = {
225
+ v: LEDGER_VERSION,
226
+ factor: clampFactor(state.factor),
227
+ samples: Number.isInteger(state.samples) && state.samples >= 0 ? state.samples : 0,
228
+ rawSum: Number.isFinite(state.rawSum) && state.rawSum >= 0 ? state.rawSum : 0,
229
+ actualSum: Number.isFinite(state.actualSum) && state.actualSum >= 0 ? state.actualSum : 0,
230
+ keepTurns: Number.isInteger(state.keepTurns) && state.keepTurns > 0 ? state.keepTurns : DEFAULT_KEEP_TURNS,
231
+ updatedAt: typeof state.updatedAt === 'string' && state.updatedAt !== '' ? state.updatedAt : new Date().toISOString(),
232
+ };
233
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
234
+ try {
235
+ fs.mkdirSync(path.dirname(file), { recursive: true });
236
+ fs.writeFileSync(tmp, `${JSON.stringify(payload)}\n`, 'utf8');
237
+ fs.renameSync(tmp, file);
238
+ return { ok: true, path: file, state: payload };
239
+ } catch (error) {
240
+ try { fs.unlinkSync(tmp); } catch { /* best effort */ }
241
+ return { ok: false, code: 'E_STATE_WRITE', path: file, message: String(error?.message ?? error) };
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Optional A2 compatibility: read `focus[].lastConclusion` from
247
+ * `<memoryRoot>/.longlive/router/board.json`. Today the field does not exist,
248
+ * so this returns '' — a future board can start feeding the conclusion layer
249
+ * without a schema change here.
250
+ */
251
+ export function readLastConclusion({ memoryRoot, sessionId } = {}) {
252
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') return '';
253
+ const file = path.join(path.resolve(memoryRoot), '.longlive', 'router', 'board.json');
254
+ let board;
255
+ try {
256
+ board = JSON.parse(fs.readFileSync(file, 'utf8'));
257
+ } catch {
258
+ return '';
259
+ }
260
+ const focus = Array.isArray(board?.focus) ? board.focus : [];
261
+ const row = (sessionId && focus.find((item) => item?.sessionId === sessionId))
262
+ ?? focus.find((item) => typeof item?.lastConclusion === 'string' && item.lastConclusion.trim() !== '');
263
+ return row !== null && typeof row?.lastConclusion === 'string' ? row.lastConclusion.trim() : '';
264
+ }