@jjh32456/dsh-longlive 1.6.8 → 1.8.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 (288) hide show
  1. package/CHANGELOG.md +69 -1539
  2. package/LICENSE +1 -1
  3. package/QUICKSTART.md +33 -12
  4. package/README.en.md +17 -7
  5. package/README.md +29 -10
  6. package/SPEC.md +5 -5
  7. package/cordis.patch.yml +17 -12
  8. package/docs/ANSWER-GUARD.md +92 -0
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +1 -1
  11. package/docs/AUTO-RECALL.md +15 -9
  12. package/docs/CONFIG.md +143 -37
  13. package/docs/ERRORS.md +17 -5
  14. package/docs/FAQ.md +7 -7
  15. package/docs/FEATURES.md +66 -29
  16. package/docs/MIGRATION-1.6.0.md +2 -2
  17. package/docs/OPERATIONS.md +6 -6
  18. package/docs/PANEL-INTEGRATION.md +6 -0
  19. package/docs/PRIVACY.md +88 -0
  20. package/docs/QUICKSTART.md +5 -5
  21. package/docs/README.en.md +3 -2
  22. package/docs/RESIDENT-WATCHER.md +1 -1
  23. package/docs/SESSION-WATCH.md +6 -6
  24. package/docs/TROUBLESHOOTING.md +4 -4
  25. package/package.json +42 -117
  26. package/runbook.md +2 -2
  27. package/scripts/backfill-auto-cards.mjs +98 -0
  28. package/scripts/install-surgery-task.ps1 +5 -2
  29. package/scripts/lib/session-watch-fixture.mjs +1 -1
  30. package/scripts/longlive-doctor.mjs +6 -0
  31. package/scripts/migrate-180.mjs +163 -0
  32. package/scripts/recall-index-build.mjs +128 -0
  33. package/scripts/session-watch-drill.mjs +1 -1
  34. package/scripts/surgery-run.cmd +1 -1
  35. package/scripts/unattended-surgery.ps1 +5 -2
  36. package/scripts/verify-card-anchors.mjs +138 -0
  37. package/src/actions/audit.js +125 -0
  38. package/src/actions/evidence.js +122 -0
  39. package/src/actions/fs.js +162 -0
  40. package/src/activity/index.js +129 -18
  41. package/src/activity/model.js +11 -1
  42. package/src/activity/store.js +22 -3
  43. package/src/activity/thinking.js +176 -0
  44. package/src/adapters/constants.js +11 -0
  45. package/src/adapters/engram/data/aliases.json +51 -0
  46. package/src/adapters/engram/data/policy.json +8 -0
  47. package/src/adapters/engram/data/routing-rules.json +546 -0
  48. package/src/adapters/engram/index.js +235 -0
  49. package/src/adapters/registry.js +315 -0
  50. package/src/answer/audit.js +193 -0
  51. package/src/answer/evidence.js +30 -0
  52. package/src/answer/guard.js +1370 -0
  53. package/src/answer/index.js +1067 -0
  54. package/src/answer/query.js +111 -0
  55. package/src/answer/second-hop.mjs +101 -0
  56. package/src/auto-truncate.js +1 -1
  57. package/src/config.js +145 -48
  58. package/src/deps.js +6 -4
  59. package/src/features.js +158 -8
  60. package/src/identity/index.js +13 -5
  61. package/src/identity/inject-position.js +2 -2
  62. package/src/index.js +97 -7
  63. package/src/lifecycle/gap-clocks.js +328 -0
  64. package/src/lifecycle/index.js +269 -0
  65. package/src/memory/activity-capture.js +229 -0
  66. package/src/memory/anchors.js +194 -0
  67. package/src/memory/audit-records.js +222 -0
  68. package/src/memory/auto-cards.js +401 -0
  69. package/src/memory/capture.js +442 -0
  70. package/src/memory/card-anchors.js +203 -0
  71. package/src/memory/conflicts.js +106 -0
  72. package/src/memory/decay.js +311 -0
  73. package/src/memory/distill.js +471 -0
  74. package/src/memory/event-index.js +917 -0
  75. package/src/memory/evidence-chain.js +295 -0
  76. package/src/memory/evidence.js +145 -0
  77. package/src/memory/filter-runner.js +1 -1
  78. package/src/memory/filter.js +5 -1
  79. package/src/memory/forget-v2.js +410 -0
  80. package/src/memory/forget.js +71 -0
  81. package/src/memory/frames-activation.js +247 -0
  82. package/src/memory/fts-query.js +174 -0
  83. package/src/memory/governance.js +604 -0
  84. package/src/memory/index.js +1 -0
  85. package/src/memory/l2-gate.js +169 -0
  86. package/src/memory/lock.js +121 -0
  87. package/src/memory/migrate.js +139 -0
  88. package/src/memory/recall-v2.js +223 -0
  89. package/src/memory/recall.js +65 -2
  90. package/src/memory/records.js +425 -0
  91. package/src/memory/retention.js +128 -0
  92. package/src/memory/review.js +124 -0
  93. package/src/memory/trust.js +88 -0
  94. package/src/memory/version-chain.js +264 -0
  95. package/src/memory/wal.js +137 -0
  96. package/src/memory/working-frame.js +516 -0
  97. package/src/metrics/classify.mjs +5 -3
  98. package/src/metrics/index.mjs +21 -1
  99. package/src/metrics/prestep-latency.mjs +300 -0
  100. package/src/metrics/store.mjs +25 -0
  101. package/src/policy-profile.js +18 -3
  102. package/src/recall/anaphora.mjs +87 -0
  103. package/src/recall/cards.mjs +7 -0
  104. package/src/recall/embedding.mjs +8 -8
  105. package/src/recall/entities.mjs +112 -0
  106. package/src/recall/index.js +235 -19
  107. package/src/recall/inject-order.mjs +10 -8
  108. package/src/recall/privacy.mjs +1 -1
  109. package/src/recall/recall-core.mjs +116 -10
  110. package/src/recall/shared-visibility.js +302 -0
  111. package/src/recall/time-normalizer.mjs +196 -0
  112. package/src/role/activation.js +191 -0
  113. package/src/role/attention.js +318 -0
  114. package/src/role/base.js +36 -0
  115. package/src/role/channels.js +423 -0
  116. package/src/role/index.js +425 -0
  117. package/src/role/interfaces.js +115 -0
  118. package/src/role/personality.js +370 -0
  119. package/src/role/readers.js +151 -0
  120. package/src/role/relationships.js +477 -0
  121. package/src/role/store.js +202 -0
  122. package/src/role/writeprotect.js +373 -0
  123. package/src/router/aliases.json +176 -25
  124. package/src/router/background/agent-runner.mjs +1 -1
  125. package/src/router/background/anchor.mjs +1 -1
  126. package/src/router/background/audit.mjs +2 -2
  127. package/src/router/background/budget-ledger.mjs +2 -2
  128. package/src/router/background/host-sim.mjs +1 -1
  129. package/src/router/background/memory.mjs +4 -4
  130. package/src/router/background/queue.mjs +1 -1
  131. package/src/router/background/retry.mjs +1 -1
  132. package/src/router/background/router.mjs +1 -1
  133. package/src/router/background/stream.mjs +1 -1
  134. package/src/router/background/tool-policy.mjs +1 -1
  135. package/src/router/design-headings.json +5 -5
  136. package/src/router/face/config.mjs +1 -1
  137. package/src/router/face/identity.mjs +3 -3
  138. package/src/router/judge.mjs +8 -7
  139. package/src/router/policies/generic.json +21 -4
  140. package/src/router/route.js +109 -22
  141. package/src/router/router.mjs +10 -6
  142. package/src/router/routing-rules.json +260 -445
  143. package/src/router/run-sim.mjs +8 -8
  144. package/src/router/runtime.js +23 -12
  145. package/src/router/service/config.mjs +5 -5
  146. package/src/router/service/context.mjs +1 -1
  147. package/src/router/service/queue.mjs +1 -1
  148. package/src/router/shadow.mjs +4 -3
  149. package/src/surgery-recovery.js +2 -2
  150. package/src/tool-output.js +2 -2
  151. package/src/tools.js +39 -7
  152. package/src/truncate-visible.js +2 -2
  153. package/src/ui/actions.js +1312 -0
  154. package/src/ui/panel-api.js +367 -0
  155. package/src/ui/panel-auth.js +251 -0
  156. package/src/ui/panel-integrity.js +243 -0
  157. package/src/ui/routes-readonly.js +695 -0
  158. package/src/ui/routes.js +3 -0
  159. package/docs/DEV.md +0 -279
  160. package/docs/PRESENCE-BUS-WIRING.md +0 -491
  161. package/docs/PRESENCE-BUS.md +0 -694
  162. package/docs/SURGERY.md +0 -186
  163. package/scripts/mark-core-cards.mjs +0 -289
  164. package/scripts/pack.mjs +0 -392
  165. package/scripts/router-proposals.mjs +0 -386
  166. package/src/router/fixtures/M1.json +0 -16
  167. package/src/router/fixtures/M2.json +0 -16
  168. package/src/router/fixtures/M3.json +0 -20
  169. package/src/router/fixtures/M4.json +0 -20
  170. package/src/router/fixtures/M5.json +0 -45
  171. package/src/router/fixtures/M6.json +0 -53
  172. package/src/router/fixtures/M7.json +0 -46
  173. package/src/router/fixtures/S1.json +0 -20
  174. package/src/router/fixtures/S2.json +0 -23
  175. package/src/router/fixtures/S3.json +0 -20
  176. package/src/router/fixtures/S4.json +0 -34
  177. package/src/router/fixtures/S5.json +0 -43
  178. package/src/router/fixtures/S6.json +0 -47
  179. package/src/router/fixtures/T1.json +0 -23
  180. package/src/router/fixtures/T2.json +0 -16
  181. package/src/router/fixtures/T3.json +0 -19
  182. package/src/router/fixtures/T4.json +0 -16
  183. package/src/router/fixtures/X1.json +0 -17
  184. package/src/router/fixtures/X2.json +0 -20
  185. package/src/router/gen-design-headings.mjs +0 -107
  186. package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
  187. package/test/activity-realtime.test.mjs +0 -959
  188. package/test/activity-stream.test.mjs +0 -512
  189. package/test/auto-recall.test.mjs +0 -474
  190. package/test/auto-truncate.test.mjs +0 -931
  191. package/test/autobind.test.mjs +0 -399
  192. package/test/bus.test.mjs +0 -1572
  193. package/test/cli-guard.test.mjs +0 -198
  194. package/test/conclusion.test.mjs +0 -408
  195. package/test/config-schema.test.mjs +0 -210
  196. package/test/d6-output.test.mjs +0 -194
  197. package/test/d6.test.mjs +0 -395
  198. package/test/deps.test.mjs +0 -342
  199. package/test/doctor-setup.test.mjs +0 -297
  200. package/test/embedding-recall.test.mjs +0 -347
  201. package/test/feature-flags.test.mjs +0 -585
  202. package/test/filter-shadow.test.mjs +0 -170
  203. package/test/fixtures/activity-append-child.mjs +0 -29
  204. package/test/fixtures/baseline-0.8.0-registration.json +0 -556
  205. package/test/fixtures/d6-header-tools.json +0 -1
  206. package/test/fixtures/lock-child.mjs +0 -67
  207. package/test/fixtures/pre-step-container.mjs +0 -100
  208. package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
  209. package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
  210. package/test/fixtures/profile-session-longlive-config.json +0 -20
  211. package/test/fixtures/proposal-cas-child.mjs +0 -66
  212. package/test/host-engine-status.test.mjs +0 -307
  213. package/test/hot-truncate.test.mjs +0 -1349
  214. package/test/identity-card-marker.test.mjs +0 -307
  215. package/test/identity-router/run.mjs +0 -721
  216. package/test/integration-pre-step.test.mjs +0 -553
  217. package/test/live.test.mjs +0 -1023
  218. package/test/maintenance-schedule.test.mjs +0 -538
  219. package/test/memory.test.mjs +0 -2828
  220. package/test/metrics.test.mjs +0 -478
  221. package/test/orchestrator.test.mjs +0 -266
  222. package/test/p1_probe.mjs +0 -97
  223. package/test/packaging.test.mjs +0 -184
  224. package/test/portability.test.mjs +0 -343
  225. package/test/rc4-regressions.test.mjs +0 -562
  226. package/test/rc5-regressions.test.mjs +0 -197
  227. package/test/rc6-chinese.test.mjs +0 -394
  228. package/test/router-1100/apply-off.test.mjs +0 -175
  229. package/test/router-1100/budget-reconcile.test.mjs +0 -215
  230. package/test/router-1100/config-context.test.mjs +0 -211
  231. package/test/router-1100/helpers.mjs +0 -129
  232. package/test/router-1100/hint-envelope.test.mjs +0 -150
  233. package/test/router-1100/lock-crossproc.test.mjs +0 -206
  234. package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
  235. package/test/router-1100/router-apply.test.mjs +0 -372
  236. package/test/router-1100/router-fixb.test.mjs +0 -602
  237. package/test/router-1100/router-proposals.test.mjs +0 -405
  238. package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
  239. package/test/router-1100/router-security-cr.test.mjs +0 -333
  240. package/test/router-1100/service-lifecycle.test.mjs +0 -220
  241. package/test/router-1100/tools-contract.test.mjs +0 -164
  242. package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
  243. package/test/router-1100/v6-contract.test.mjs +0 -158
  244. package/test/router-1100/v6b-contract.test.mjs +0 -293
  245. package/test/router-1100/v6c-contract.test.mjs +0 -249
  246. package/test/router-1100/wal-rotation.test.mjs +0 -375
  247. package/test/router-1100/wp1-config.test.mjs +0 -170
  248. package/test/router-1100/wp1-default-off.test.mjs +0 -77
  249. package/test/router-1100/wp1-model-status.test.mjs +0 -90
  250. package/test/router-1100/wp1-status.test.mjs +0 -220
  251. package/test/router-1100/wp1-tools.test.mjs +0 -146
  252. package/test/router-1100/wp5-cli.test.mjs +0 -240
  253. package/test/router-1100/wp5-model-auto.test.mjs +0 -418
  254. package/test/router-1100/wp6-merge.test.mjs +0 -386
  255. package/test/router-1100/wp6-wake.test.mjs +0 -502
  256. package/test/router-background/audit.test.mjs +0 -37
  257. package/test/router-background/budget-ledger.test.mjs +0 -330
  258. package/test/router-background/cross-process.test.mjs +0 -222
  259. package/test/router-background/fixtures/cross-child.mjs +0 -85
  260. package/test/router-background/fixtures/real-shapes.mjs +0 -239
  261. package/test/router-background/router.test.mjs +0 -1076
  262. package/test/router-background/stream-retry.test.mjs +0 -358
  263. package/test/router-background/tool-agent.test.mjs +0 -384
  264. package/test/router-face/bridge.test.mjs +0 -169
  265. package/test/router-face/face.test.mjs +0 -316
  266. package/test/router-failclosed.test.mjs +0 -466
  267. package/test/router-identity.test.mjs +0 -384
  268. package/test/router-l1-l2.contract.test.mjs +0 -1075
  269. package/test/router-memory-tools.test.mjs +0 -262
  270. package/test/router-policy.test.mjs +0 -225
  271. package/test/router-runtime.test.mjs +0 -438
  272. package/test/router-shadow.test.mjs +0 -287
  273. package/test/router.test.mjs +0 -903
  274. package/test/run-rc.mjs +0 -315
  275. package/test/run.mjs +0 -2469
  276. package/test/safety-defaults.test.mjs +0 -181
  277. package/test/seeded-load.test.mjs +0 -436
  278. package/test/session-original.test.mjs +0 -338
  279. package/test/state-truth.test.mjs +0 -937
  280. package/test/surgery-recovery.test.mjs +0 -936
  281. package/test/t7_drive.mjs +0 -151
  282. package/test/tool-output.test.mjs +0 -393
  283. package/test/tool-schema.test.mjs +0 -177
  284. package/test/tools_contract.test.mjs +0 -716
  285. package/test/truncate-visible.test.mjs +0 -1150
  286. package/test/ui-flags.test.mjs +0 -477
  287. package/test/v4-hardening.test.mjs +0 -427
  288. package/test/version-consistency.test.mjs +0 -286
@@ -0,0 +1,328 @@
1
+ // src/lifecycle/gap-clocks.js — M2-B / PLAN §2.7(Lead 2026-11-07 修订版,双时钟)
2
+ //
3
+ // 两个**独立**的一等记忆,不许合并:
4
+ // memory-gap(记忆写入空窗)= bootAt − 记忆内容文件最后写入时间
5
+ // 白名单:topics/*.md、journal/*.md、handover/*.md、flow/**/*.md、STATE.md、
6
+ // .longlive/records.jsonl、.longlive/distill/*.jsonl
7
+ // 排除:.longlive/{hot-truncate,router,filter,live,board,bridge,tool-output}、
8
+ // sessions/、外部记忆库、logs/、backups/、index/(逐文件 stat,绝不用目录 mtime)
9
+ // 整秒口径:floorSec(bootAt) − floorSec(lastContentWriteAt)
10
+ // host-gap(宿主中断)= bootAt − 上次生命周期记录(缺失时退化为上一会话最后**事件**)
11
+ // 端点写死:floorSec(bootAt) − floorSec(lastSessionEventAt),标 uncertain:true
12
+ //
13
+ // 11-06 用例 #1(fixture 写死,单测断言):
14
+ // bootAt = 2026-11-06T20:36:24.799+08:00(c045 createdAt)
15
+ // lastWrite = 2026-11-06T14:10:33.351+08:00(handover/2026-11-06-发布计划.md)
16
+ // memoryGap = 23,151,448 ms(精确)/ 23,151 s(floor)= 6 小时 25 分 51 秒
17
+ // lastSessionEventAt = 2026-11-06T20:28:59.113+08:00(e219 job/registered seq=13051)
18
+ // hostGap = 445,000 ms(floor 口径)= 7 分 25 秒
19
+ //
20
+ // 本模块是纯函数 + 只读扫描,不写任何文件(写 journal/事件由 lifecycle/index.js 负责)。
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+
25
+ import { parseSession } from '../codec.js';
26
+
27
+ export const MS_MINUTE = 60_000;
28
+ export const HOST_GAP_WARN_MS = 3 * MS_MINUTE;
29
+ export const MEMORY_GAP_WARN_MS = 30 * MS_MINUTE;
30
+
31
+ /** memory-gap 内容白名单(rel 前缀,统一 `/` 分隔,相对 memoryRoot)。 */
32
+ export const MEMORY_CONTENT_PATTERNS = Object.freeze([
33
+ /^topics\/[^/]+\.md$/,
34
+ /^journal\/[^/]+\.md$/,
35
+ /^handover\/[^/]+\.md$/,
36
+ /^flow\/.*\.md$/,
37
+ /^STATE\.md$/,
38
+ /^\.longlive\/records\.jsonl$/,
39
+ /^\.longlive\/distill\/[^/]+\.jsonl$/,
40
+ ]);
41
+
42
+ export function isMemoryContentRel(rel) {
43
+ const normalized = String(rel ?? '').replace(/\\/g, '/').replace(/^\.\//, '');
44
+ if (normalized === '' || normalized.split('/').includes('..')) return false;
45
+ return MEMORY_CONTENT_PATTERNS.some((pattern) => pattern.test(normalized));
46
+ }
47
+
48
+ export function floorSec(ms) {
49
+ return Math.floor(Number(ms) / 1000);
50
+ }
51
+
52
+ /** 中文时长文本(验收用固定格式:X 小时 Y 分 Z 秒 / Y 分 Z 秒 / Z 秒)。 */
53
+ export function formatGapText(ms) {
54
+ const total = Math.max(0, Math.round(Number(ms) / 1000));
55
+ const hours = Math.floor(total / 3600);
56
+ const minutes = Math.floor((total % 3600) / 60);
57
+ const seconds = total % 60;
58
+ if (hours > 0) return `${hours} 小时 ${minutes} 分 ${seconds} 秒`;
59
+ if (minutes > 0) return `${minutes} 分 ${seconds} 秒`;
60
+ return `${seconds} 秒`;
61
+ }
62
+
63
+ function walkFiles(root, relBase = '', out = []) {
64
+ let entries = [];
65
+ try {
66
+ entries = fs.readdirSync(root, { withFileTypes: true });
67
+ } catch {
68
+ return out;
69
+ }
70
+ for (const entry of entries) {
71
+ const full = path.join(root, entry.name);
72
+ const rel = relBase === '' ? entry.name : `${relBase}/${entry.name}`;
73
+ if (entry.isDirectory()) walkFiles(full, rel, out);
74
+ else if (entry.isFile()) out.push(rel);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * Last memory-content write strictly before bootAt (multi-file whitelist, per-file stat).
81
+ * @returns {{atMs:number, rel:string, sources:Array<{rel:string, mtimeMs:number}>}|null}
82
+ */
83
+ export function resolveMemoryWriteAt({ memoryRoot, bootAtMs }) {
84
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') return null;
85
+ const boot = Number(bootAtMs);
86
+ if (!Number.isFinite(boot)) return null;
87
+ let candidates = [];
88
+ try {
89
+ candidates = walkFiles(path.resolve(memoryRoot));
90
+ } catch {
91
+ return null;
92
+ }
93
+ const sources = [];
94
+ for (const rel of candidates) {
95
+ if (!isMemoryContentRel(rel)) continue;
96
+ let stat = null;
97
+ try {
98
+ stat = fs.statSync(path.join(memoryRoot, rel));
99
+ } catch {
100
+ continue;
101
+ }
102
+ if (!stat.isFile() || stat.mtimeMs >= boot) continue;
103
+ sources.push({ rel, mtimeMs: stat.mtimeMs });
104
+ }
105
+ if (sources.length === 0) return null;
106
+ sources.sort((a, b) => b.mtimeMs - a.mtimeMs || a.rel.localeCompare(b.rel));
107
+ return { atMs: sources[0].mtimeMs, rel: sources[0].rel, sources: sources.slice(0, 8) };
108
+ }
109
+
110
+ /**
111
+ * Last session event strictly before bootAt, across the newest N session logs.
112
+ * Used as the honest fallback when no lifecycle record exists (uncertain:true).
113
+ */
114
+ export function resolveLastSessionEventAt({ sessionRoots, bootAtMs, limitSessions = 8 }) {
115
+ const boot = Number(bootAtMs);
116
+ const roots = (Array.isArray(sessionRoots) ? sessionRoots : [sessionRoots]).filter(Boolean);
117
+ const logs = [];
118
+ const stack = roots.map((root) => path.resolve(String(root)));
119
+ const seen = new Set();
120
+ while (stack.length > 0) {
121
+ const dir = stack.pop();
122
+ if (seen.has(dir)) continue;
123
+ seen.add(dir);
124
+ let entries = [];
125
+ try {
126
+ entries = fs.readdirSync(dir, { withFileTypes: true });
127
+ } catch {
128
+ continue;
129
+ }
130
+ for (const entry of entries) {
131
+ const full = path.join(dir, entry.name);
132
+ if (entry.isDirectory()) stack.push(full);
133
+ else if (entry.isFile() && entry.name === 'session.v4.jsonl.zstd') {
134
+ try {
135
+ logs.push({ file: full, mtimeMs: fs.statSync(full).mtimeMs });
136
+ } catch {
137
+ /* skip unreadable log */
138
+ }
139
+ }
140
+ }
141
+ }
142
+ if (logs.length === 0) return null;
143
+ logs.sort((a, b) => b.mtimeMs - a.mtimeMs);
144
+ let best = null;
145
+ for (const log of logs.slice(0, limitSessions)) {
146
+ let parsed = null;
147
+ try {
148
+ parsed = parseSession(fs.readFileSync(log.file));
149
+ } catch {
150
+ continue;
151
+ }
152
+ for (const event of parsed.events) {
153
+ const at = Number(event?.time);
154
+ if (!Number.isFinite(at) || at >= boot) continue;
155
+ if (best === null || at > best.atMs) best = { atMs: at, rel: log.file };
156
+ }
157
+ }
158
+ return best;
159
+ }
160
+
161
+ function countActivityEvidence({ memoryRoot, fromMs, toMs }) {
162
+ const out = { toolOutputs: 0, boardRows: 0, sessionEvents: 0 };
163
+ // tool-output:窗口内落盘的 tool-output 归档(实测 3 个为用例 #1 的升级证据)
164
+ const toolDir = path.join(memoryRoot, '.longlive', 'tool-output');
165
+ for (const rel of walkFiles(toolDir)) {
166
+ try {
167
+ const stat = fs.statSync(path.join(toolDir, rel));
168
+ if (stat.isFile() && stat.mtimeMs > fromMs && stat.mtimeMs <= toMs) out.toolOutputs += 1;
169
+ } catch {
170
+ /* skip */
171
+ }
172
+ }
173
+ // board 行:窗口内的活动流行(按行内 at/ts 时间戳,缺时间戳的行不计)
174
+ const boardFile = path.join(memoryRoot, '.longlive', 'board', 'activity.jsonl');
175
+ try {
176
+ for (const line of fs.readFileSync(boardFile, 'utf8').split('\n')) {
177
+ if (line.trim() === '') continue;
178
+ let row = null;
179
+ try {
180
+ row = JSON.parse(line);
181
+ } catch {
182
+ continue;
183
+ }
184
+ const at = Number(row?.at ?? row?.ts ?? row?.time);
185
+ if (Number.isFinite(at) && at > fromMs && at <= toMs) out.boardRows += 1;
186
+ }
187
+ } catch {
188
+ /* no board */
189
+ }
190
+ return out;
191
+ }
192
+
193
+ /** Compute both clocks (separate objects, never merged). */
194
+ export function computeGaps(options = {}) {
195
+ const memoryRoot = typeof options.memoryRoot === 'string' ? path.resolve(options.memoryRoot) : '';
196
+ const bootRaw = typeof options.bootAt === 'string' || typeof options.bootAt === 'number'
197
+ ? new Date(options.bootAt).getTime()
198
+ : Number(options.bootAtMs);
199
+ const bootAtMs = Number.isFinite(bootRaw) ? bootRaw : Date.now();
200
+ const sessionRoots = Array.isArray(options.sessionRoots) ? options.sessionRoots : [];
201
+ const lifecycle = options.lifecycle ?? null;
202
+
203
+ // ---- memory-gap ----
204
+ const memoryWrite = options.memoryWriteAt !== undefined
205
+ ? (options.memoryWriteAt === null ? null : { atMs: Number(options.memoryWriteAt), rel: 'injected', sources: [] })
206
+ : resolveMemoryWriteAt({ memoryRoot, bootAtMs });
207
+ let memoryGap;
208
+ if (memoryWrite === null || !Number.isFinite(memoryWrite.atMs)) {
209
+ memoryGap = {
210
+ kind: 'unknown',
211
+ gapMs: null,
212
+ gapSec: null,
213
+ gapText: 'unknown',
214
+ from: null,
215
+ to: new Date(bootAtMs).toISOString(),
216
+ sources: [],
217
+ activityEvidence: null,
218
+ uncertain: true,
219
+ };
220
+ } else {
221
+ const gapMsExact = bootAtMs - memoryWrite.atMs;
222
+ const gapSec = floorSec(bootAtMs) - floorSec(memoryWrite.atMs);
223
+ const evidence = options.activityEvidence ?? countActivityEvidence({
224
+ memoryRoot,
225
+ fromMs: memoryWrite.atMs,
226
+ toMs: bootAtMs,
227
+ });
228
+ const activityCount = evidence.toolOutputs + evidence.boardRows + Number(evidence.sessionEvents ?? 0);
229
+ const warn = gapSec * 1000 >= MEMORY_GAP_WARN_MS;
230
+ memoryGap = {
231
+ kind: warn && activityCount > 0 ? 'active-no-memory' : (warn ? 'gap' : 'ok'),
232
+ gapMs: gapMsExact, // exact ms (fixture: 23,151,448)
233
+ gapSec, // floor endpoints (fixture: 23,151)
234
+ gapText: formatGapText(gapSec * 1000),
235
+ from: new Date(memoryWrite.atMs).toISOString(),
236
+ to: new Date(bootAtMs).toISOString(),
237
+ sources: memoryWrite.sources,
238
+ source: memoryWrite.rel,
239
+ activityEvidence: evidence,
240
+ activityCount,
241
+ warn,
242
+ uncertain: false,
243
+ };
244
+ }
245
+
246
+ // ---- host-gap ----
247
+ let hostFrom = null;
248
+ let hostSource = null;
249
+ let prevExitForm = lifecycle?.prevExitForm ?? 'unknown';
250
+ let uncertain = false;
251
+ if (Number.isFinite(options.lastSessionEventAtMs)) {
252
+ hostFrom = Number(options.lastSessionEventAtMs);
253
+ hostSource = options.lastSessionEventSource ?? 'injected-session-event';
254
+ uncertain = true;
255
+ } else if (lifecycle && Number.isFinite(lifecycle.lastShutdownAtMs)) {
256
+ hostFrom = Number(lifecycle.lastShutdownAtMs);
257
+ hostSource = 'lifecycle:shutdown';
258
+ } else if (lifecycle && Number.isFinite(lifecycle.lastActivityAtMs)) {
259
+ hostFrom = Number(lifecycle.lastActivityAtMs);
260
+ hostSource = 'lifecycle:lastActivity';
261
+ uncertain = true;
262
+ } else if (sessionRoots.length > 0) {
263
+ const lastEvent = resolveLastSessionEventAt({ sessionRoots, bootAtMs });
264
+ if (lastEvent !== null) {
265
+ hostFrom = lastEvent.atMs;
266
+ hostSource = 'session-last-event';
267
+ uncertain = true;
268
+ }
269
+ }
270
+ let hostGap;
271
+ if (hostFrom === null || !Number.isFinite(hostFrom)) {
272
+ hostGap = {
273
+ kind: 'unknown',
274
+ gapMs: null,
275
+ gapSec: null,
276
+ gapText: 'unknown',
277
+ from: null,
278
+ to: new Date(bootAtMs).toISOString(),
279
+ source: 'unknown',
280
+ prevExitForm,
281
+ uncertain: true,
282
+ };
283
+ } else {
284
+ // floor 端点口径(fixture: 445,000ms / 445s)
285
+ const gapSec = Math.max(0, floorSec(bootAtMs) - floorSec(hostFrom));
286
+ hostGap = {
287
+ kind: gapSec * 1000 >= HOST_GAP_WARN_MS ? 'gap' : 'ok',
288
+ gapMs: gapSec * 1000,
289
+ rawGapMs: Math.max(0, bootAtMs - hostFrom),
290
+ gapSec,
291
+ gapText: formatGapText(gapSec * 1000),
292
+ from: new Date(hostFrom).toISOString(),
293
+ to: new Date(bootAtMs).toISOString(),
294
+ source: hostSource,
295
+ prevExitForm,
296
+ warn: gapSec * 1000 >= HOST_GAP_WARN_MS,
297
+ uncertain,
298
+ };
299
+ }
300
+
301
+ return {
302
+ schema: 'gap-clocks/v1',
303
+ bootAt: new Date(bootAtMs).toISOString(),
304
+ memoryGap,
305
+ hostGap,
306
+ // 双钟分别记录、不合并(用例 #1:23,151,448 ms vs 445,000 ms)
307
+ merged: false,
308
+ };
309
+ }
310
+
311
+ /** Render the two boot-card lines (each ≤80 chars; host line is droppable). */
312
+ export function renderGapLines(gaps) {
313
+ const lines = [];
314
+ if (gaps?.memoryGap?.kind !== 'unknown') {
315
+ const time = gaps.memoryGap.from?.slice(11, 19) ?? '?';
316
+ const evidence = gaps.memoryGap.activityEvidence;
317
+ const activityText = evidence && (evidence.toolOutputs + evidence.boardRows) > 0
318
+ ? ` · 期间活动证据 ${evidence.toolOutputs + evidence.boardRows} 个`
319
+ : '';
320
+ lines.push(`▍记忆空窗 ${gaps.memoryGap.gapText}(上次记忆写入 ${time}${activityText})`.slice(0, 80));
321
+ }
322
+ if (gaps?.hostGap?.kind !== 'unknown') {
323
+ const from = gaps.hostGap.from?.slice(11, 19) ?? '?';
324
+ const to = gaps.hostGap.to?.slice(11, 19) ?? '?';
325
+ lines.push(`▍宿主中断 ${gaps.hostGap.gapText}(${from} → ${to} · 上次退出:${gaps.hostGap.prevExitForm ?? '未知'})`.slice(0, 80));
326
+ }
327
+ return lines;
328
+ }
@@ -0,0 +1,269 @@
1
+ // src/lifecycle/index.js — M2-B / PLAN §2.7:宿主生命周期入账 + 双时钟空窗补记
2
+ //
3
+ // 启动时(memoryV2.enabled=true 且 host 支持):
4
+ // 1) 读上次 boot.json / shutdown.json → 判定 prevExitForm(clean|crash|unknown);
5
+ // 2) computeGaps() 算 host-gap / memory-gap(分别记录、不合并);
6
+ // 3) 追加 `.longlive/board/lifecycle.jsonl` 事件行;
7
+ // 4) 原子写本次 boot.json(tmp→rename);
8
+ // 5) 通过 capture 把两钟写进 journal(幂等 cap key)+ 索引 lifecycle 事件;
9
+ // 6) 注册退出钩子写 shutdown.json(exit form 的唯一可靠来源)。
10
+ // 任何异常只告警、不阻断插件加载(与 surgery-recovery 同款)。
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { createCapture, writeFileAtomic } from '../memory/capture.js';
16
+ import { acquireLease, releaseLease } from '../memory/lock.js';
17
+ import { computeGaps, renderGapLines } from './gap-clocks.js';
18
+
19
+ export const LIFECYCLE_SCHEMA = 'host-lifecycle/v1';
20
+
21
+ function nowMs(now) {
22
+ const value = typeof now === 'function' ? now() : new Date();
23
+ return value instanceof Date ? value.getTime() : Number(value);
24
+ }
25
+
26
+ function readJsonSafe(file) {
27
+ try {
28
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
29
+ return value && typeof value === 'object' ? value : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ function pidAlive(pid) {
36
+ if (!Number.isInteger(pid) || pid <= 0) return false;
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ } catch (error) {
41
+ if (error?.code === 'ESRCH') return false;
42
+ return true; // EPERM etc: cannot prove dead -> treat as alive (conservative)
43
+ }
44
+ }
45
+
46
+ export function lifecyclePaths(memoryRoot) {
47
+ const root = path.resolve(String(memoryRoot ?? ''));
48
+ const bridge = path.join(root, '.longlive', 'bridge');
49
+ return {
50
+ root,
51
+ bridge,
52
+ boot: path.join(bridge, 'boot.json'),
53
+ shutdown: path.join(bridge, 'shutdown.json'),
54
+ lifecycleLog: path.join(root, '.longlive', 'board', 'lifecycle.jsonl'),
55
+ lock: path.join(root, '.longlive', 'memory', 'lifecycle.lock'),
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Create the host lifecycle recorder.
61
+ *
62
+ * @param {object} options
63
+ * @param {string} options.memoryRoot
64
+ * @param {() => Date} [options.now]
65
+ * @param {string[]} [options.sessionRoots]
66
+ * @param {object} [options.capture] injected createCapture() (tests)
67
+ * @param {string} [options.holder]
68
+ */
69
+ export function createHostLifecycle(options = {}) {
70
+ const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
71
+ if (memoryRoot === '') throw new Error('E_MEMORY_ROOT: lifecycle requires memoryRoot');
72
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
73
+ const paths = lifecyclePaths(memoryRoot);
74
+ const sessionRoots = Array.isArray(options.sessionRoots) ? options.sessionRoots : [];
75
+ const holder = options.holder ?? `lifecycle-${process.pid}`;
76
+ const capture = options.capture ?? createCapture({ memoryRoot, now, sessionRoots, holder });
77
+
78
+ function withLease(fn) {
79
+ fs.mkdirSync(path.dirname(paths.lock), { recursive: true });
80
+ const lease = acquireLease(paths.lock, { holder, now });
81
+ try {
82
+ return fn();
83
+ } finally {
84
+ releaseLease(paths.lock, lease.holder);
85
+ }
86
+ }
87
+
88
+ function appendLifecycleLine(line) {
89
+ fs.mkdirSync(path.dirname(paths.lifecycleLog), { recursive: true });
90
+ fs.appendFileSync(paths.lifecycleLog, `${JSON.stringify({ schema: LIFECYCLE_SCHEMA, ...line })}\n`, 'utf8');
91
+ }
92
+
93
+ function prevExitFormOf(prevBoot, prevShutdown) {
94
+ if (prevShutdown && Number.isFinite(Number(prevShutdown.at))
95
+ && (!prevBoot || Number(prevShutdown.at) >= Number(prevBoot.bootAt ?? 0))) return 'clean';
96
+ if (prevBoot && Number.isInteger(prevBoot.pid) && !pidAlive(prevBoot.pid)) return 'crash';
97
+ return 'unknown';
98
+ }
99
+
100
+ /**
101
+ * Record a boot: prevExitForm + gap clocks + boot.json.
102
+ * Returns { ok, boot, gaps, lines, journal, lifecycleEvent }.
103
+ */
104
+ function recordBoot(input = {}) {
105
+ const bootAtMs = Number.isFinite(input.bootAt) ? input.bootAt : nowMs(now);
106
+ const prevBoot = readJsonSafe(paths.boot);
107
+ const prevShutdown = readJsonSafe(paths.shutdown);
108
+ const prevExitForm = prevExitFormOf(prevBoot, prevShutdown);
109
+ const gaps = computeGaps({
110
+ memoryRoot,
111
+ bootAtMs,
112
+ sessionRoots,
113
+ lifecycle: {
114
+ prevExitForm,
115
+ lastShutdownAtMs: Number(prevShutdown?.at) > 0 ? Number(prevShutdown.at) : undefined,
116
+ lastActivityAtMs: Number(prevBoot?.lastActivityAt) > 0 ? Number(prevBoot.lastActivityAt) : undefined,
117
+ },
118
+ });
119
+ const boot = {
120
+ schema: LIFECYCLE_SCHEMA,
121
+ event: 'boot',
122
+ at: nowMs(now),
123
+ bootAt: bootAtMs,
124
+ pid: Number.isInteger(input.pid) ? input.pid : process.pid,
125
+ prevExitForm,
126
+ prevBootAt: Number(prevBoot?.bootAt) > 0 ? Number(prevBoot.bootAt) : null,
127
+ hostVersion: input.hostVersion ?? options.hostVersion ?? null,
128
+ pluginVersion: input.pluginVersion ?? options.pluginVersion ?? null,
129
+ hostGap: { gapMs: gaps.hostGap.gapMs, gapText: gaps.hostGap.gapText, uncertain: gaps.hostGap.uncertain },
130
+ memoryGap: { gapMs: gaps.memoryGap.gapMs, gapSec: gaps.memoryGap.gapSec, gapText: gaps.memoryGap.gapText, kind: gaps.memoryGap.kind },
131
+ };
132
+ let journal = null;
133
+ try {
134
+ journal = capture.captureMemoryGap({ gaps });
135
+ } catch (error) {
136
+ journal = { ok: false, code: 'E_GAP_CAPTURE', message: String(error?.message ?? error) };
137
+ }
138
+ let lifecycleEvent = null;
139
+ try {
140
+ lifecycleEvent = capture.captureLifecycleEvent({
141
+ event: 'boot',
142
+ at: boot.at,
143
+ key: `boot:${bootAtMs}`,
144
+ text: `prevExitForm=${prevExitForm} hostGap=${gaps.hostGap.gapText} memoryGap=${gaps.memoryGap.gapText}`,
145
+ data: { pid: boot.pid, bootAt: bootAtMs },
146
+ });
147
+ } catch (error) {
148
+ lifecycleEvent = { ok: false, code: 'E_LIFECYCLE_CAPTURE', message: String(error?.message ?? error) };
149
+ }
150
+ const writeResult = withLease(() => {
151
+ appendLifecycleLine(boot);
152
+ writeFileAtomic(paths.boot, `${JSON.stringify({
153
+ bootAt: bootAtMs,
154
+ pid: boot.pid,
155
+ hostVersion: boot.hostVersion,
156
+ pluginVersion: boot.pluginVersion,
157
+ prevExitForm,
158
+ lastActivityAt: boot.at,
159
+ }, null, 2)}\n`);
160
+ return { ok: true };
161
+ });
162
+ return {
163
+ ok: true,
164
+ boot,
165
+ gaps,
166
+ lines: renderGapLines(gaps),
167
+ journal,
168
+ lifecycleEvent,
169
+ write: writeResult,
170
+ bootPath: paths.boot,
171
+ lifecycleLog: paths.lifecycleLog,
172
+ };
173
+ }
174
+
175
+ /** Record a clean shutdown (exit form evidence). Best effort: never throws. */
176
+ function recordShutdown(input = {}) {
177
+ const at = Number.isFinite(input.at) ? input.at : nowMs(now);
178
+ const record = { schema: LIFECYCLE_SCHEMA, event: 'shutdown', at, pid: Number.isInteger(input.pid) ? input.pid : process.pid, form: input.form ?? 'clean' };
179
+ let written = false;
180
+ try {
181
+ withLease(() => {
182
+ writeFileAtomic(paths.shutdown, `${JSON.stringify(record, null, 2)}\n`);
183
+ appendLifecycleLine(record);
184
+ written = true;
185
+ });
186
+ } catch {
187
+ written = false;
188
+ }
189
+ try {
190
+ capture.captureLifecycleEvent({ event: 'shutdown', at, key: `shutdown:${at}`, text: `form=${record.form}`, data: { pid: record.pid } });
191
+ } catch {
192
+ /* best effort */
193
+ }
194
+ return { ok: written, record, shutdownPath: paths.shutdown };
195
+ }
196
+
197
+ function history(input = {}) {
198
+ const limit = Number.isInteger(input.limit) ? Math.min(Math.max(input.limit, 1), 200) : 20;
199
+ const rows = [];
200
+ let text = '';
201
+ try {
202
+ text = fs.readFileSync(paths.lifecycleLog, 'utf8');
203
+ } catch {
204
+ return { ok: true, items: [], total: 0 };
205
+ }
206
+ for (const line of text.split('\n')) {
207
+ if (line.trim() === '') continue;
208
+ try {
209
+ rows.push(JSON.parse(line));
210
+ } catch {
211
+ /* skip corrupt line */
212
+ }
213
+ }
214
+ return { ok: true, items: rows.slice(-limit), total: rows.length };
215
+ }
216
+
217
+ return { memoryRoot, paths, recordBoot, recordShutdown, history };
218
+ }
219
+
220
+ /**
221
+ * Host wiring entry point (called from src/index.js only when memoryV2 is on).
222
+ * Never throws: a lifecycle failure must not block plugin loading.
223
+ */
224
+ export function registerHostLifecycle(ctx = {}, options = {}) {
225
+ const result = { ok: false, code: null, gaps: null, lines: [], handle: null };
226
+ try {
227
+ const memoryRoot = options.memoryRoot ?? options.memoryRootOf?.() ?? '';
228
+ if (typeof memoryRoot !== 'string' || memoryRoot === '') {
229
+ result.code = 'E_MEMORY_ROOT';
230
+ return result;
231
+ }
232
+ const lifecycle = createHostLifecycle({
233
+ memoryRoot,
234
+ now: options.now,
235
+ sessionRoots: Array.isArray(options.sessionRoots) ? options.sessionRoots : undefined,
236
+ hostVersion: options.hostVersion,
237
+ pluginVersion: options.pluginVersion,
238
+ });
239
+ const boot = lifecycle.recordBoot({
240
+ bootAt: options.bootAt,
241
+ hostVersion: options.hostVersion,
242
+ pluginVersion: options.pluginVersion,
243
+ });
244
+ if (options.registerExitHook === true) {
245
+ try {
246
+ process.once('exit', () => {
247
+ try {
248
+ lifecycle.recordShutdown({ form: 'clean' });
249
+ } catch {
250
+ /* exit hooks must never throw */
251
+ }
252
+ });
253
+ } catch {
254
+ /* best effort */
255
+ }
256
+ }
257
+ Object.assign(result, {
258
+ ok: true,
259
+ gaps: boot.gaps,
260
+ lines: boot.lines,
261
+ handle: { lifecycle, boot },
262
+ });
263
+ return result;
264
+ } catch (error) {
265
+ result.code = error?.code ?? 'E_LIFECYCLE';
266
+ result.message = String(error?.message ?? error);
267
+ return result;
268
+ }
269
+ }