@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,520 @@
1
+ // status.json(DESIGN §3.3 / §9.2,v2)。
2
+ //
3
+ // 只读投影:provider 只给两个布尔(绝不吐端点/凭据),model 只给
4
+ // {auto,resolved,resolvedAt},提案对象不含正文。warnings 是开放枚举:
5
+ // 已知码给文案,未知码原样保留并计入 warnings.length。
6
+ //
7
+ // 写盘 tmp + fsync + rename + 读回校验,失败不阻塞 tick。
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ export const STATUS_VERSION = 2;
13
+ export const STATUS_MAX_BYTES = 16 * 1024;
14
+ export const STATUS_QUEUE_MAX_BYTES = 2 * 1024;
15
+ export const STATUS_WARNING_LIMIT = 8;
16
+
17
+ // 已知告警码 -> {severity, message}。开放枚举:不在这里的码也允许出现。
18
+ export const WARNING_CATALOG = Object.freeze({
19
+ BOARD_STALE: { severity: 'warn', message: '看板数据已过期。' },
20
+ BOARD_TRUNCATED: { severity: 'warn', message: '看板内容被截断。' },
21
+ BOARD_RESET: { severity: 'warn', message: '看板已重置或无法读取。' },
22
+ FOCUS_LIMITED: { severity: 'warn', message: 'focus 数量超过上限。' },
23
+ LIVE_ROWS_SATURATED: { severity: 'warn', message: 'live 注册表行数已达上限。' },
24
+ LIVE_UNREADABLE: { severity: 'warn', message: 'live 注册表无法读取。' },
25
+ WAL_BROKEN: { severity: 'error', message: 'WAL 损坏,需要恢复。' },
26
+ RESTORE_REQUIRED: { severity: 'warn', message: '检测到需要恢复的状态。' },
27
+ RESTORE_FAILED: { severity: 'error', message: '状态恢复失败。' },
28
+ OWNER_WRITE_RACE: { severity: 'error', message: '检测到所有者写入竞争。' },
29
+ QUEUE_STARVATION: { severity: 'warn', message: '提案队列出现饥饿。' },
30
+ BLOCKED_ON_USER_EXPIRED: { severity: 'warn', message: '等待用户的提案已过期。' },
31
+ WAKE_QUOTA: { severity: 'warn', message: '唤醒额度已用完。' },
32
+ WAKE_DEGRADED: { severity: 'warn', message: '唤醒已降级。' },
33
+ INJECT_QUOTA: { severity: 'warn', message: '注入额度已用完。' },
34
+ TICK_RECLAIM_BUSY: { severity: 'warn', message: 'tick 回收繁忙。' },
35
+ });
36
+
37
+ export const KNOWN_WARNING_CODES = Object.freeze(Object.keys(WARNING_CATALOG));
38
+
39
+ const SEVERITY_RANK = Object.freeze({ error: 0, warn: 1, info: 2 });
40
+
41
+ export function truncateText(value, maxChars) {
42
+ const text = typeof value === 'string' ? value : '';
43
+ if (text.length <= maxChars) return text;
44
+ return `${Array.from(text).slice(0, Math.max(0, maxChars - 1)).join('')}…`;
45
+ }
46
+
47
+ function isObject(value) {
48
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
49
+ }
50
+
51
+ function finiteInt(value) {
52
+ return Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
53
+ }
54
+
55
+ function isoOrNull(value, fallback = null) {
56
+ if (value === null || value === undefined || value === '') return fallback;
57
+ if (typeof value === 'string') return value;
58
+ const date = value instanceof Date ? value : new Date(value);
59
+ return Number.isNaN(date.getTime()) ? fallback : date.toISOString();
60
+ }
61
+
62
+ function cleanCode(value) {
63
+ return truncateText(String(value ?? '').replace(/[\u0000-\u001F\u007F]/g, '').trim(), 64);
64
+ }
65
+
66
+ function normalizeWarningCode(raw) {
67
+ const code = cleanCode(raw);
68
+ if (!code) return '';
69
+ // 已知码统一大写;未知码原样保留(只去控制符)。
70
+ return WARNING_CATALOG[code.toUpperCase()] ? code.toUpperCase() : code;
71
+ }
72
+
73
+ function warningSeverity(code) {
74
+ return WARNING_CATALOG[code.toUpperCase()]?.severity ?? 'warn';
75
+ }
76
+
77
+ function warningMessage(code) {
78
+ return WARNING_CATALOG[code.toUpperCase()]?.message ?? `未登记的告警码:${code}`;
79
+ }
80
+
81
+ /** 归一化 warnings:去控制符、去重、稳定排序、≤8;空数组不是 null。 */
82
+ export function normalizeWarnings(list, extra = []) {
83
+ const codes = [];
84
+ for (const item of [...(Array.isArray(list) ? list : []), ...(Array.isArray(extra) ? extra : [])]) {
85
+ const code = normalizeWarningCode(item);
86
+ if (code && !codes.includes(code)) codes.push(code);
87
+ }
88
+ codes.sort((a, b) => {
89
+ const rank = (SEVERITY_RANK[warningSeverity(a)] ?? 9) - (SEVERITY_RANK[warningSeverity(b)] ?? 9);
90
+ return rank !== 0 ? rank : a.localeCompare(b);
91
+ });
92
+ return codes.slice(0, STATUS_WARNING_LIMIT);
93
+ }
94
+
95
+ function normalizeAlerts(input, warnings) {
96
+ const byCode = new Map();
97
+ const add = (codeRaw, severityRaw, messageRaw) => {
98
+ const code = cleanCode(codeRaw);
99
+ if (!code) return;
100
+ const severity = severityRaw === 'error' || severityRaw === 'info' ? severityRaw : 'warn';
101
+ const existing = byCode.get(code);
102
+ const candidate = {
103
+ code,
104
+ severity,
105
+ message: truncateText(String(messageRaw ?? warningMessage(code)), 300),
106
+ };
107
+ if (!existing) {
108
+ byCode.set(code, candidate);
109
+ return;
110
+ }
111
+ // 同 code 保留更严重的一条;同严重度保留先到的。
112
+ if ((SEVERITY_RANK[severity] ?? 9) < (SEVERITY_RANK[existing.severity] ?? 9)) byCode.set(code, candidate);
113
+ };
114
+
115
+ for (const alert of Array.isArray(input.alerts) ? input.alerts : []) {
116
+ if (!isObject(alert)) continue;
117
+ add(alert.code, alert.severity, alert.message);
118
+ }
119
+ for (const code of warnings) {
120
+ if (!byCode.has(code)) add(code, warningSeverity(code), warningMessage(code));
121
+ }
122
+
123
+ return [...byCode.values()]
124
+ .sort((a, b) => {
125
+ const rank = (SEVERITY_RANK[a.severity] ?? 9) - (SEVERITY_RANK[b.severity] ?? 9);
126
+ return rank !== 0 ? rank : a.code.localeCompare(b.code);
127
+ })
128
+ .slice(0, 8);
129
+ }
130
+
131
+ function buildWarnings(input) {
132
+ const raw = Array.isArray(input.warnings) ? input.warnings : [];
133
+ const fromErrors = (Array.isArray(input.alerts) ? input.alerts : [])
134
+ .filter((alert) => isObject(alert) && alert.severity === 'error')
135
+ .map((alert) => alert.code);
136
+ return normalizeWarnings(raw, fromErrors);
137
+ }
138
+
139
+ function normalizeProvider(input) {
140
+ const source = input.provider;
141
+ let configured;
142
+ let missing;
143
+ if (isObject(source)) {
144
+ configured = source.configured === true;
145
+ missing = source.missing === true;
146
+ if (source.configured === undefined && source.missing === undefined) configured = false;
147
+ } else if (typeof source === 'string') {
148
+ configured = source.trim() !== '';
149
+ missing = !configured;
150
+ } else {
151
+ configured = false;
152
+ missing = true;
153
+ }
154
+ // 只吐两个布尔,绝不带 id/端点/候选。等待 provider 时额外带退避计数,
155
+ // 仅在该字段存在时出现,避免影响 running 状态的既有形状断言(D-WP5-4)。
156
+ const out = { configured, missing: missing || !configured };
157
+ if (isObject(source)) {
158
+ if (Number.isInteger(source.waitAttempts) && source.waitAttempts > 0) {
159
+ out.waitAttempts = source.waitAttempts;
160
+ }
161
+ if (typeof source.lastError === 'string' && source.lastError.trim() !== '') {
162
+ out.lastError = truncateText(source.lastError.trim(), 200);
163
+ }
164
+ const nextRetryAt = isoOrNull(source.nextRetryAt);
165
+ if (nextRetryAt) out.nextRetryAt = nextRetryAt;
166
+ }
167
+ return out;
168
+ }
169
+
170
+ function normalizeModel(input) {
171
+ const source = input.model;
172
+ if (isObject(source)) {
173
+ return {
174
+ auto: source.auto === true,
175
+ resolved: typeof source.resolved === 'string' && source.resolved.trim() !== '' && source.resolved !== 'auto'
176
+ ? source.resolved
177
+ : null,
178
+ resolvedAt: isoOrNull(source.resolvedAt),
179
+ };
180
+ }
181
+ const text = typeof source === 'string' ? source.trim() : '';
182
+ return {
183
+ auto: text === 'auto',
184
+ resolved: text !== '' && text !== 'auto' ? text : null,
185
+ resolvedAt: text !== '' && text !== 'auto' ? isoOrNull(input.now) : null,
186
+ };
187
+ }
188
+
189
+ function normalizeFocus(list) {
190
+ return (Array.isArray(list) ? list : [])
191
+ .filter(isObject)
192
+ .slice(0, 8)
193
+ .map((item) => ({
194
+ sessionId: truncateText(String(item.sessionId ?? ''), 120),
195
+ goal: truncateText(String(item.goal ?? ''), 200),
196
+ lastAction: isObject(item.lastAction)
197
+ ? {
198
+ kind: truncateText(String(item.lastAction.kind ?? ''), 40),
199
+ detail: truncateText(String(item.lastAction.detail ?? ''), 60),
200
+ at: isoOrNull(item.lastAction.at),
201
+ }
202
+ : null,
203
+ queuedCount: finiteInt(item.queuedCount),
204
+ updatedAt: isoOrNull(item.updatedAt),
205
+ }));
206
+ }
207
+
208
+ function normalizeBoard(input) {
209
+ const board = isObject(input.board) ? input.board : {};
210
+ const pulse = isObject(board.pulse) ? board.pulse : (isObject(input.pulse) ? input.pulse : {});
211
+ const focus = normalizeFocus(board.focus);
212
+ const unknownSessions = finiteInt(board.unknownSessions ?? pulse.unknownSessions ?? input.unknownSessions);
213
+ return {
214
+ seq: finiteInt(board.seq),
215
+ generatedAt: isoOrNull(board.generatedAt),
216
+ activeSessions: finiteInt(board.activeSessions ?? pulse.active),
217
+ unknownSessions,
218
+ focusVisible: finiteInt(board.focusVisible ?? focus.length),
219
+ stale: board.stale === true,
220
+ focus,
221
+ pulse: {
222
+ active: finiteInt(pulse.active ?? board.activeSessions),
223
+ running: finiteInt(pulse.running),
224
+ blocked: finiteInt(pulse.blocked),
225
+ unknownSessions: finiteInt(pulse.unknownSessions ?? unknownSessions),
226
+ queuedProposals: finiteInt(pulse.queuedProposals),
227
+ approvedProposals: finiteInt(pulse.approvedProposals),
228
+ blockedOnUser: finiteInt(pulse.blockedOnUser),
229
+ readyProposals: finiteInt(pulse.readyProposals),
230
+ lastApplyAt: isoOrNull(pulse.lastApplyAt),
231
+ lease: isObject(pulse.lease) ? {
232
+ active: pulse.lease.active === true,
233
+ holder: pulse.lease.holder == null ? null : truncateText(String(pulse.lease.holder), 120),
234
+ heldMs: finiteInt(pulse.lease.heldMs),
235
+ } : null,
236
+ },
237
+ };
238
+ }
239
+
240
+ function normalizeProposals(input) {
241
+ const proposals = isObject(input.proposals) ? input.proposals : {};
242
+ const queue = isObject(proposals.queue) ? proposals.queue : {};
243
+ const writer = isObject(queue.writer)
244
+ ? {
245
+ ticket: truncateText(String(queue.writer.ticket ?? ''), 64),
246
+ proposalId: truncateText(String(queue.writer.proposalId ?? ''), 64),
247
+ sessionId: truncateText(String(queue.writer.sessionId ?? ''), 120),
248
+ since: isoOrNull(queue.writer.since),
249
+ }
250
+ : null;
251
+ const blocked = (Array.isArray(queue.blocked) ? queue.blocked : [])
252
+ .filter(isObject)
253
+ .slice(0, 8)
254
+ .map((item) => ({
255
+ ticket: truncateText(String(item.ticket ?? ''), 64),
256
+ reason: truncateText(String(item.reason ?? ''), 120),
257
+ since: isoOrNull(item.since),
258
+ }));
259
+ return {
260
+ doneToday: finiteInt(proposals.doneToday),
261
+ conflicts: finiteInt(proposals.conflicts),
262
+ superseded: finiteInt(proposals.superseded),
263
+ pending: finiteInt(proposals.pending ?? proposals.counts?.pending),
264
+ approved: finiteInt(proposals.approved ?? proposals.counts?.approved ?? proposals.counts?.queued),
265
+ queue: {
266
+ seqCounter: finiteInt(queue.seqCounter),
267
+ depth: finiteInt(queue.depth),
268
+ etaMs: finiteInt(queue.etaMs),
269
+ starvation: queue.starvation === true,
270
+ writer,
271
+ blocked,
272
+ },
273
+ };
274
+ }
275
+
276
+ function normalizeLease(input) {
277
+ const lease = isObject(input.lease) ? input.lease : {};
278
+ return {
279
+ active: lease.active === true,
280
+ holder: lease.holder == null ? null : truncateText(String(lease.holder), 120),
281
+ since: isoOrNull(lease.since),
282
+ renewals: finiteInt(lease.renewals),
283
+ expiresAt: isoOrNull(lease.expiresAt),
284
+ };
285
+ }
286
+
287
+ function normalizeWal(input) {
288
+ const wal = isObject(input.wal) ? input.wal : {};
289
+ return {
290
+ lastSeq: finiteInt(wal.lastSeq),
291
+ lastAt: isoOrNull(wal.lastAt),
292
+ bytes: finiteInt(wal.bytes),
293
+ segments: finiteInt(wal.segments),
294
+ broken: wal.broken === true,
295
+ };
296
+ }
297
+
298
+ // WP1 任务要求把 live 注册表的只读摘要放进 status:rows 是当前行数,
299
+ // maxRows 是写侧上限(默认 128),unknown 是无 live 行的会话数。属于 §9
300
+ // 之外的 additive 字段;DESIGN 的 shared.liveRows/unknownSessions 仍保留。
301
+ function normalizeLive(input) {
302
+ const live = isObject(input.live) ? input.live : {};
303
+ const shared = isObject(input.shared) ? input.shared : {};
304
+ const via = (value) => (typeof value === 'string' && value !== '' ? truncateText(value, 64) : null);
305
+ const out = {
306
+ rows: finiteInt(live.rows ?? shared.liveRows),
307
+ maxRows: finiteInt(live.maxRows ?? input.liveMaxRows ?? 128),
308
+ unknown: finiteInt(live.unknown ?? shared.unknownSessions),
309
+ };
310
+ // Additive WP2 diagnostics: only present when the caller actually reports
311
+ // them, so a minimal status stays byte-identical to the v2 baseline.
312
+ if (isObject(input.live)) {
313
+ out.corrupt = finiteInt(live.corrupt);
314
+ out.saturated = live.saturated === true;
315
+ // S4: stale/dead/active visibility. Only present when reported by the
316
+ // caller, so a minimal v2 status stays byte-identical.
317
+ out.active = finiteInt(live.active);
318
+ out.stale = finiteInt(live.stale);
319
+ out.dead = finiteInt(live.dead);
320
+ out.tombstoned = finiteInt(live.tombstoned);
321
+ // Which host event shape actually drove the L1 write. null means "not
322
+ // observed yet", never a silently assumed green channel.
323
+ out.createdEventVia = via(live.createdEventVia ?? input.liveCreatedEventVia);
324
+ out.turnEndEventVia = via(live.turnEndEventVia ?? input.liveTurnEndEventVia);
325
+ } else {
326
+ const createdEventVia = via(input.liveCreatedEventVia);
327
+ if (createdEventVia) out.createdEventVia = createdEventVia;
328
+ const turnEndEventVia = via(input.liveTurnEndEventVia);
329
+ if (turnEndEventVia) out.turnEndEventVia = turnEndEventVia;
330
+ }
331
+ return out;
332
+ }
333
+
334
+ function normalizeShared(input) {
335
+ const shared = isObject(input.shared) ? input.shared : {};
336
+ return {
337
+ hintTokensLast: finiteInt(shared.hintTokensLast),
338
+ injectedTurns: finiteInt(shared.injectedTurns),
339
+ injectedTokensToday: finiteInt(shared.injectedTokensToday),
340
+ skipped: finiteInt(shared.skipped),
341
+ readyProposals: finiteInt(shared.readyProposals),
342
+ lastInjectAt: isoOrNull(shared.lastInjectAt),
343
+ lastInjectSha256: typeof shared.lastInjectSha256 === 'string' && shared.lastInjectSha256 !== ''
344
+ ? truncateText(shared.lastInjectSha256, 64)
345
+ : null,
346
+ liveRows: finiteInt(shared.liveRows),
347
+ unknownSessions: finiteInt(shared.unknownSessions),
348
+ };
349
+ }
350
+
351
+ function normalizeWake(input) {
352
+ const wake = isObject(input.wake) ? input.wake : {};
353
+ return {
354
+ enabled: wake.enabled === true,
355
+ lastAttemptAt: isoOrNull(wake.lastAttemptAt),
356
+ lastError: wake.lastError == null ? null : truncateText(String(wake.lastError), 200),
357
+ todayCount: finiteInt(wake.todayCount),
358
+ cooldownRemainingMs: finiteInt(wake.cooldownRemainingMs),
359
+ };
360
+ }
361
+
362
+ function normalizeLastError(input, now) {
363
+ if (!isObject(input.lastError)) return null;
364
+ return {
365
+ code: cleanCode(input.lastError.code) || 'E_UNKNOWN',
366
+ at: isoOrNull(input.lastError.at, now),
367
+ message: truncateText(String(input.lastError.message ?? ''), 500),
368
+ };
369
+ }
370
+
371
+ function normalizeLastReport(input, now) {
372
+ if (!isObject(input.lastReport)) return null;
373
+ return {
374
+ at: isoOrNull(input.lastReport.at, now),
375
+ summary: truncateText(String(input.lastReport.summary ?? ''), 200),
376
+ next: truncateText(String(input.lastReport.next ?? ''), 300),
377
+ waiting: truncateText(String(input.lastReport.waiting ?? ''), 300),
378
+ degraded: input.lastReport.degraded === true,
379
+ };
380
+ }
381
+
382
+ export function buildStatus(input = {}) {
383
+ const now = isoOrNull(input.now, new Date().toISOString());
384
+ const warnings = buildWarnings(input);
385
+ const alerts = normalizeAlerts(input, warnings);
386
+ // severity=error 的 alert 必须镜像进 warnings(若 8 条上限截掉了,优先补回)。
387
+ for (const alert of alerts) {
388
+ if (alert.severity === 'error' && !warnings.includes(alert.code)) {
389
+ warnings.unshift(alert.code);
390
+ if (warnings.length > STATUS_WARNING_LIMIT) warnings.length = STATUS_WARNING_LIMIT;
391
+ }
392
+ }
393
+
394
+ const tickQueue = isObject(input.tickQueue)
395
+ ? input.tickQueue
396
+ : (isObject(input.queue) ? input.queue : {});
397
+ const queue = isObject(input.queueStatus) ? input.queueStatus : {};
398
+ const files = isObject(input.files) ? input.files : {};
399
+
400
+ return {
401
+ v: STATUS_VERSION,
402
+ readOnly: true,
403
+ state: String(input.state ?? 'stopped'),
404
+ reason: input.reason === undefined || input.reason === null || input.reason === '' ? null : truncateText(String(input.reason), 200),
405
+ since: isoOrNull(input.since, now),
406
+ runId: truncateText(String(input.runId ?? ''), 120),
407
+ provider: normalizeProvider(input),
408
+ model: normalizeModel(input),
409
+ autonomy: String(input.autonomy ?? 'report'),
410
+ agentMode: input.agentMode === true,
411
+ lastTickAt: isoOrNull(input.lastTickAt),
412
+ nextTickAt: isoOrNull(input.nextTickAt),
413
+ heartbeatAt: isoOrNull(input.heartbeatAt, now),
414
+ today: {
415
+ day: String(input.today?.day ?? ''),
416
+ usedTokens: finiteInt(input.today?.usedTokens),
417
+ reservedTokens: finiteInt(input.today?.reservedTokens),
418
+ capTokens: finiteInt(input.today?.capTokens),
419
+ },
420
+ run: {
421
+ usedTokens: finiteInt(input.run?.usedTokens),
422
+ capTokens: finiteInt(input.run?.capTokens),
423
+ },
424
+ tickQueue: {
425
+ pending: finiteInt(tickQueue.pending),
426
+ invalid: finiteInt(tickQueue.invalid),
427
+ oldestAgeMs: finiteInt(tickQueue.oldestAgeMs),
428
+ },
429
+ queue: {
430
+ pending: finiteInt(queue.pending),
431
+ queued: finiteInt(queue.queued),
432
+ applying: finiteInt(queue.applying),
433
+ blockedOnUser: finiteInt(queue.blockedOnUser),
434
+ expired: finiteInt(queue.expired),
435
+ },
436
+ board: normalizeBoard(input),
437
+ live: normalizeLive(input),
438
+ proposals: normalizeProposals(input),
439
+ lease: normalizeLease(input),
440
+ wal: normalizeWal(input),
441
+ shared: normalizeShared(input),
442
+ wake: normalizeWake(input),
443
+ warnings,
444
+ alerts,
445
+ lastError: normalizeLastError(input, now),
446
+ lastReport: normalizeLastReport(input, now),
447
+ files: {
448
+ vault: String(files.vault ?? ''),
449
+ board: String(files.board ?? ''),
450
+ audit: String(files.audit ?? ''),
451
+ ledger: String(files.ledger ?? ''),
452
+ anchor: String(files.anchor ?? ''),
453
+ outbox: String(files.outbox ?? ''),
454
+ },
455
+ };
456
+ }
457
+
458
+ function serialize(value) {
459
+ return `${JSON.stringify(value)}\n`;
460
+ }
461
+
462
+ /** 超 16KB 时的收缩顺序:alerts(保 error)→ blocked → focus/report → 其余。 */
463
+ function shrinkStatus(status) {
464
+ const next = structuredClone(status);
465
+ next.alerts = next.alerts.filter((alert) => alert.severity === 'error').slice(0, 8);
466
+ next.proposals.queue.blocked = next.proposals.queue.blocked.slice(0, 2);
467
+ next.board.focus = next.board.focus.slice(0, 4);
468
+ next.lastReport = next.lastReport ? { ...next.lastReport, summary: truncateText(next.lastReport.summary, 120) } : null;
469
+ if (next.lastError) next.lastError.message = truncateText(next.lastError.message, 120);
470
+ return next;
471
+ }
472
+
473
+ export function storageErrorCode(error) {
474
+ const code = error?.code;
475
+ if (code === 'ENOSPC' || code === 'EROFS' || code === 'EACCES' || code === 'EPERM') return 'E_STORAGE';
476
+ return 'E_IO';
477
+ }
478
+
479
+ /**
480
+ * @param {string} file
481
+ * @param {object} statusOrInput
482
+ * @returns {{ok:boolean,bytes?:number,error?:string}}
483
+ */
484
+ export function writeStatus(file, statusOrInput) {
485
+ if (typeof file !== 'string' || file.trim() === '') return { ok: false, error: 'E_STATUS_PATH' };
486
+ let tmp = '';
487
+ try {
488
+ let value = statusOrInput && statusOrInput.v === STATUS_VERSION
489
+ ? statusOrInput
490
+ : buildStatus(statusOrInput);
491
+ let text = serialize(value);
492
+ if (Buffer.byteLength(text) > STATUS_MAX_BYTES) {
493
+ value = shrinkStatus(value);
494
+ text = serialize(value);
495
+ }
496
+ if (Buffer.byteLength(text) > STATUS_MAX_BYTES) {
497
+ // 最后一道:去报告、去 blocked、消息截短;starvation 永远保留。
498
+ value = { ...value, lastReport: null, alerts: value.alerts.filter((alert) => alert.severity === 'error') };
499
+ value.proposals = { ...value.proposals, queue: { ...value.proposals.queue, blocked: [] } };
500
+ if (value.lastError) value.lastError = { ...value.lastError, message: truncateText(value.lastError.message, 80) };
501
+ text = serialize(value);
502
+ }
503
+ fs.mkdirSync(path.dirname(file), { recursive: true });
504
+ tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
505
+ const fd = fs.openSync(tmp, 'w');
506
+ try {
507
+ fs.writeFileSync(fd, text, 'utf8');
508
+ fs.fsyncSync(fd);
509
+ } finally {
510
+ fs.closeSync(fd);
511
+ }
512
+ fs.renameSync(tmp, file);
513
+ const readBack = fs.readFileSync(file, 'utf8');
514
+ if (readBack !== text) return { ok: false, error: 'E_IO' };
515
+ return { ok: true, bytes: Buffer.byteLength(text) };
516
+ } catch (error) {
517
+ try { if (tmp) fs.unlinkSync(tmp); } catch { /* best effort */ }
518
+ return { ok: false, error: storageErrorCode(error) };
519
+ }
520
+ }