@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,227 @@
1
+ // src/util/redact.js — S1:凭据类敏感原文 scrub(answer-audit / D2 tool-output 写入前)。
2
+ //
3
+ // 口径(审计报告 P0-2):
4
+ // * 只处理"凭据类"模式(token / api key / password / Bearer / 私钥块 / cookie /
5
+ // AWS / GCP / npm / GitHub / Slack / HuggingFace / JWT / 连接串口令);
6
+ // * 命中替换为 `[REDACTED:<type>]`,原文不落盘、不进日志;
7
+ // * 保留可审计用途:原文 sha256 + 长度 + 命中类型(由调用方写进 metadata);
8
+ // * 纯函数、无 IO,前后端共用安全。
9
+
10
+ import crypto from 'node:crypto';
11
+
12
+ export const REDACT_SCHEMA = 'redact/v1';
13
+
14
+ /**
15
+ * Pattern list. Order matters: the private-key block must run before the
16
+ * generic `api_key: "..."` assignment so a PEM body cannot be partially
17
+ * matched by an inner token pattern.
18
+ */
19
+ export const REDACTION_PATTERNS = Object.freeze([
20
+ {
21
+ type: 'private-key-block',
22
+ re: /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]{0,16384}?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/g,
23
+ },
24
+ {
25
+ type: 'openai-key',
26
+ re: /\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{16,}\b/g,
27
+ },
28
+ {
29
+ type: 'anthropic-key',
30
+ re: /\bsk-ant-[A-Za-z0-9_-]{16,}\b/g,
31
+ },
32
+ {
33
+ type: 'github-token',
34
+ re: /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g,
35
+ },
36
+ {
37
+ type: 'slack-token',
38
+ re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
39
+ },
40
+ {
41
+ type: 'aws-access-key',
42
+ re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
43
+ },
44
+ {
45
+ type: 'aws-secret-key',
46
+ re: /\baws_?secret_?access_?key\b\s*[:=]\s*['"]?[A-Za-z0-9/+=]{32,}['"]?/gi,
47
+ },
48
+ {
49
+ type: 'google-api-key',
50
+ re: /\bAIza[0-9A-Za-z_-]{35}\b/g,
51
+ },
52
+ {
53
+ type: 'npm-token',
54
+ re: /\bnpm_[A-Za-z0-9]{30,}\b/g,
55
+ },
56
+ {
57
+ type: 'huggingface-token',
58
+ re: /\bhf_[A-Za-z0-9]{20,}\b/g,
59
+ },
60
+ {
61
+ type: 'jwt',
62
+ re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
63
+ },
64
+ {
65
+ type: 'bearer-token',
66
+ re: /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,
67
+ },
68
+ {
69
+ type: 'basic-auth',
70
+ re: /\bBasic\s+[A-Za-z0-9+/=]{16,}/g,
71
+ },
72
+ {
73
+ type: 'password-assignment',
74
+ re: /\b(?:password|passwd|pwd)\b\s*[:=]\s*(?:"[^"\n]{4,}"|'[^'\n]{4,}'|[^\s"',;]{6,})/gi,
75
+ },
76
+ {
77
+ type: 'api-key-assignment',
78
+ re: /\b(?:api[_-]?key|apikey|secret[_-]?key|client[_-]?secret|access[_-]?token|refresh[_-]?token|auth[_-]?token|authorization[_-]?key)\b\s*[:=]\s*(?:"[^"\n]{8,}"|'[^'\n]{8,}'|[A-Za-z0-9._~+/=-]{12,})/gi,
79
+ },
80
+ {
81
+ type: 'cookie',
82
+ re: /\b(?:cookie|set-cookie)\b\s*[:=]\s*[^\n;]{8,}/gi,
83
+ },
84
+ {
85
+ type: 'url-credentials',
86
+ re: /\b[a-z][a-z0-9+.-]*:\/\/[^:\s/]+:[^@\s/]+@[^\s]+/gi,
87
+ },
88
+ ]);
89
+
90
+ export const DEFAULT_REDACTION = Object.freeze({
91
+ enabled: true,
92
+ auditRetentionDays: 30,
93
+ toolOutputRetentionDays: 90,
94
+ });
95
+
96
+ /** Stable sha256 of the exact text handed in (hex). */
97
+ export function sha256Hex(text) {
98
+ return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
99
+ }
100
+
101
+ function emptyHits() {
102
+ const out = {};
103
+ return out;
104
+ }
105
+
106
+ function addHit(hits, type) {
107
+ hits[type] = (hits[type] ?? 0) + 1;
108
+ }
109
+
110
+ function hitsToArray(hits) {
111
+ return Object.entries(hits)
112
+ .map(([type, count]) => ({ type, count }))
113
+ .sort((a, b) => a.type.localeCompare(b.type));
114
+ }
115
+
116
+ /**
117
+ * Scrub one string.
118
+ *
119
+ * @param {string} text
120
+ * @param {{patterns?:Array, enabled?:boolean}} [options]
121
+ * @returns {{text:string,hits:Array<{type:string,count:number}>,hitCount:number,
122
+ * originalSha256:string, originalLength:number, redactedLength:number,
123
+ * changed:boolean}}
124
+ */
125
+ export function scrubText(text, options = {}) {
126
+ const source = typeof text === 'string' ? text : String(text ?? '');
127
+ const enabled = options.enabled !== false;
128
+ const patterns = Array.isArray(options.patterns) ? options.patterns : REDACTION_PATTERNS;
129
+ const originalSha256 = sha256Hex(source);
130
+ if (!enabled || source === '') {
131
+ return { text: source, hits: [], hitCount: 0, originalSha256, originalLength: source.length, redactedLength: source.length, changed: false };
132
+ }
133
+ const hits = emptyHits();
134
+ let output = source;
135
+ for (const pattern of patterns) {
136
+ if (!pattern || !(pattern.re instanceof RegExp)) continue;
137
+ pattern.re.lastIndex = 0;
138
+ output = output.replace(pattern.re, () => {
139
+ addHit(hits, pattern.type);
140
+ return `[REDACTED:${pattern.type}]`;
141
+ });
142
+ }
143
+ const list = hitsToArray(hits);
144
+ return {
145
+ text: output,
146
+ hits: list,
147
+ hitCount: list.reduce((sum, entry) => sum + entry.count, 0),
148
+ originalSha256,
149
+ originalLength: source.length,
150
+ redactedLength: output.length,
151
+ changed: output !== source,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Deep-scrub every string value inside a JSON-serializable value (keys kept).
157
+ * Returns a structurally-cloned value plus aggregate hits and the sha256 of the
158
+ * original serialized tree (for audit correlation).
159
+ */
160
+ export function scrubJsonValue(value, options = {}) {
161
+ const enabled = options.enabled !== false;
162
+ const hits = emptyHits();
163
+ let hitCount = 0;
164
+ let originalSerialized = '';
165
+ try {
166
+ originalSerialized = JSON.stringify(value);
167
+ } catch {
168
+ originalSerialized = String(value);
169
+ }
170
+ const originalSha256 = sha256Hex(originalSerialized);
171
+ const originalLength = originalSerialized.length;
172
+
173
+ const walk = (input, depth) => {
174
+ if (depth > 32) return input;
175
+ if (typeof input === 'string') {
176
+ const result = scrubText(input, options);
177
+ for (const hit of result.hits) { hits[hit.type] = (hits[hit.type] ?? 0) + hit.count; }
178
+ hitCount += result.hitCount;
179
+ return result.text;
180
+ }
181
+ if (Array.isArray(input)) return input.map((entry) => walk(entry, depth + 1));
182
+ if (input && typeof input === 'object') {
183
+ const out = {};
184
+ for (const [key, entry] of Object.entries(input)) out[key] = walk(entry, depth + 1);
185
+ return out;
186
+ }
187
+ return input;
188
+ };
189
+
190
+ const scrubbed = enabled ? walk(value, 0) : value;
191
+ const list = hitsToArray(hits);
192
+ let redactedSerialized = '';
193
+ try {
194
+ redactedSerialized = JSON.stringify(scrubbed);
195
+ } catch {
196
+ redactedSerialized = '';
197
+ }
198
+ return {
199
+ value: scrubbed,
200
+ enabled,
201
+ changed: hitCount > 0,
202
+ hits: list,
203
+ hitCount,
204
+ originalSha256,
205
+ originalLength,
206
+ redactedLength: redactedSerialized.length,
207
+ };
208
+ }
209
+
210
+ /** Redaction metadata block to persist in audit rows / sidecar files. */
211
+ export function redactionMetadata(result, { retentionDays = null, at = null } = {}) {
212
+ const meta = {
213
+ schema: REDACT_SCHEMA,
214
+ applied: result?.enabled !== false && (result?.hitCount ?? 0) > 0,
215
+ hits: Array.isArray(result?.hits) ? result.hits : [],
216
+ hitCount: Number.isInteger(result?.hitCount) ? result.hitCount : 0,
217
+ originalSha256: typeof result?.originalSha256 === 'string' ? result.originalSha256 : null,
218
+ originalLength: Number.isInteger(result?.originalLength) ? result.originalLength : null,
219
+ redactedLength: Number.isInteger(result?.redactedLength) ? result.redactedLength : null,
220
+ };
221
+ if (Number.isInteger(retentionDays) && retentionDays > 0) {
222
+ meta.retentionDays = retentionDays;
223
+ const base = at ? Date.parse(at) : Date.now();
224
+ if (Number.isFinite(base)) meta.retainUntil = new Date(base + retentionDays * 24 * 60 * 60 * 1000).toISOString();
225
+ }
226
+ return meta;
227
+ }
@@ -0,0 +1,148 @@
1
+ // src/util/stale-locks.js — S1:陈旧锁清理(启动 / doctor 各跑一次)。
2
+ //
3
+ // 覆盖审计报告 P1-10 列出的两类遗留锁:
4
+ // * `<...>.lock`(append / capture 的租约文件);
5
+ // * `<...>.lock.tmp-*`、`router.lock.tmp-*`(崩溃留下的临时锁)。
6
+ // 判定:文件 mtime 超过 `staleMs`(默认 30 分钟)即视为陈旧;删除前解析 JSON 租约,
7
+ // 若租约 expiresAt 仍在未来则保留(避免误删正在续期的持有者)。每次删除写一行审计
8
+ // 到 `.longlive/audit/lock-cleanup.jsonl`(经由 append-store,带 fsync),失败只告警。
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ import { appendJsonLine } from './append-store.js';
14
+
15
+ export const LOCK_CLEANUP_SCHEMA = 'lock-cleanup/v1';
16
+ export const LOCK_CLEANUP_AUDIT = path.join('.longlive', 'audit', 'lock-cleanup.jsonl');
17
+ export const DEFAULT_STALE_LOCK_MS = 30 * 60 * 1000;
18
+
19
+ const LOCK_FILE_RE = /(?:^|[\\/])(?:[^\\/]+\.lock|router\.lock\.tmp-[^\\/]+|[^\\/]+\.lock\.tmp-[^\\/]+)$/;
20
+
21
+ function envStaleMs(env) {
22
+ const minutes = Number(env?.DSH_LONGLIVE_STALE_LOCK_MINUTES);
23
+ if (Number.isFinite(minutes) && minutes > 0) return minutes * 60 * 1000;
24
+ return DEFAULT_STALE_LOCK_MS;
25
+ }
26
+
27
+ function walkLockFiles(root, out = [], depth = 0) {
28
+ if (depth > 8) return out;
29
+ let entries = [];
30
+ try {
31
+ entries = fs.readdirSync(root, { withFileTypes: true });
32
+ } catch {
33
+ return out;
34
+ }
35
+ for (const entry of entries) {
36
+ const abs = path.join(root, entry.name);
37
+ if (entry.isDirectory()) {
38
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
39
+ walkLockFiles(abs, out, depth + 1);
40
+ } else if (entry.isFile() && LOCK_FILE_RE.test(entry.name)) {
41
+ out.push(abs);
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** Candidate lock files: the `.longlive` subtree plus top-level lock files. */
48
+ function collectLockCandidates(memoryRoot) {
49
+ const root = path.resolve(memoryRoot);
50
+ const out = [];
51
+ const longlive = path.join(root, '.longlive');
52
+ if (fs.existsSync(longlive)) walkLockFiles(longlive, out);
53
+ let entries = [];
54
+ try {
55
+ entries = fs.readdirSync(root, { withFileTypes: true });
56
+ } catch {
57
+ entries = [];
58
+ }
59
+ for (const entry of entries) {
60
+ if (entry.isFile() && LOCK_FILE_RE.test(entry.name)) out.push(path.join(root, entry.name));
61
+ }
62
+ return [...new Set(out)];
63
+ }
64
+
65
+ function readLease(file) {
66
+ try {
67
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
68
+ return value && typeof value === 'object' ? value : null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Delete stale lock/tmp-lock files under `<memoryRoot>/.longlive` (plus the
76
+ * memory root itself for legacy layouts). Never throws.
77
+ *
78
+ * @param {{memoryRoot:string, now?:Function, staleMs?:number, env?:object,
79
+ * logger?:object|Function, audit?:boolean}} options
80
+ * @returns {{ok:boolean, scanned:number, removed:Array, kept:Array, errors:Array}}
81
+ */
82
+ export function cleanupStaleLocks(options = {}) {
83
+ const staleMs = Number.isFinite(Number(options.staleMs)) && Number(options.staleMs) > 0
84
+ ? Number(options.staleMs)
85
+ : envStaleMs(options.env ?? process.env);
86
+ const now = (() => {
87
+ try {
88
+ const value = typeof options.now === 'function' ? options.now() : (options.now ?? Date.now());
89
+ const date = value instanceof Date ? value : new Date(value);
90
+ return Number.isNaN(date.getTime()) ? Date.now() : date.getTime();
91
+ } catch {
92
+ return Date.now();
93
+ }
94
+ })();
95
+ const result = { ok: true, scanned: 0, removed: [], kept: [], errors: [] };
96
+ const memoryRoot = typeof options.memoryRoot === 'string' ? options.memoryRoot.trim() : '';
97
+ if (memoryRoot === '') return { ...result, ok: false, code: 'E_NO_MEMORY_ROOT' };
98
+
99
+ const candidates = collectLockCandidates(path.resolve(memoryRoot));
100
+ result.scanned = candidates.length;
101
+ const auditRows = [];
102
+ for (const file of candidates) {
103
+ let stat;
104
+ try {
105
+ stat = fs.statSync(file);
106
+ } catch {
107
+ continue;
108
+ }
109
+ const ageMs = Math.max(0, now - stat.mtimeMs);
110
+ if (ageMs < staleMs) {
111
+ result.kept.push({ file: path.relative(memoryRoot, file).split(path.sep).join('/'), ageMs, reason: 'fresh' });
112
+ continue;
113
+ }
114
+ const lease = readLease(file);
115
+ const expiresAt = Number(lease?.expiresAt ?? 0);
116
+ if (Number.isFinite(expiresAt) && expiresAt > now) {
117
+ result.kept.push({ file: path.relative(memoryRoot, file).split(path.sep).join('/'), ageMs, reason: 'lease-active', expiresAt });
118
+ continue;
119
+ }
120
+ try {
121
+ fs.rmSync(file, { force: true });
122
+ const rel = path.relative(memoryRoot, file).split(path.sep).join('/');
123
+ result.removed.push({ file: rel, ageMs, holder: lease?.holder ?? null, pid: lease?.pid ?? null });
124
+ auditRows.push({
125
+ schema: LOCK_CLEANUP_SCHEMA,
126
+ at: new Date(now).toISOString(),
127
+ action: 'remove-stale-lock',
128
+ file: rel,
129
+ ageMs,
130
+ holder: lease?.holder ?? null,
131
+ pid: lease?.pid ?? null,
132
+ });
133
+ try {
134
+ options.logger?.warn?.(`[lock-cleanup] 清理陈旧锁:${rel}(age=${Math.round(ageMs / 1000)}s)`);
135
+ } catch { /* logging must not fail cleanup */ }
136
+ } catch (error) {
137
+ result.errors.push({ file: path.relative(memoryRoot, file).split(path.sep).join('/'), error: String(error?.message ?? error) });
138
+ result.ok = false;
139
+ }
140
+ }
141
+ if (options.audit !== false && auditRows.length > 0) {
142
+ const auditFile = path.join(path.resolve(memoryRoot), LOCK_CLEANUP_AUDIT);
143
+ for (const row of auditRows) {
144
+ appendJsonLine({ file: auditFile, row, label: 'lock-cleanup', healthRoot: memoryRoot, now: options.now, logger: options.logger });
145
+ }
146
+ }
147
+ return result;
148
+ }
package/src/version.js ADDED
@@ -0,0 +1,99 @@
1
+ // Single source of truth for the package version.
2
+ //
3
+ // The version is stated exactly once: `package.json#version`. Everything else
4
+ // (the packer, the acceptance suite, release checks) reads it through this
5
+ // module. A second literal anywhere in the tree is how 0.7.1 kept shipping as
6
+ // "expected version" long after package.json moved on, so `validateVersion`
7
+ // rejects anything that is not a plain MAJOR.MINOR.PATCH release tag and the
8
+ // callers refuse to build rather than guess.
9
+ //
10
+ // Only Node built-ins are used: the package has no dependencies.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ /** Repository/package root, resolved from this file, never from the cwd. */
17
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
18
+ export const PACKAGE_JSON = path.join(PACKAGE_ROOT, 'package.json');
19
+
20
+ /** Plain release versions, plus the `-rc.N` release-candidate suffix: no `v`
21
+ * prefix, no build metadata, no other prerelease identifiers. */
22
+ export const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-rc\.(?:0|[1-9]\d*))?$/;
23
+
24
+ export const VERSION_CODES = Object.freeze({
25
+ PACKAGE_UNREADABLE: 'PACKAGE_JSON_UNREADABLE',
26
+ VERSION_INVALID: 'BAD_PACKAGE_VERSION',
27
+ });
28
+
29
+ function versionError(code, message, cause) {
30
+ const error = new Error(message);
31
+ error.code = code;
32
+ if (cause !== undefined) error.cause = cause;
33
+ return error;
34
+ }
35
+
36
+ /**
37
+ * Validate a claimed version. Returns the exact string so callers record what
38
+ * they checked instead of re-deriving it.
39
+ *
40
+ * `where` only decorates the error message (e.g. "package.json").
41
+ */
42
+ export function validateVersion(value, where = 'package.json') {
43
+ if (typeof value !== 'string' || value.trim() === '') {
44
+ throw versionError(
45
+ VERSION_CODES.VERSION_INVALID,
46
+ `${where}: version must be a non-empty string, got ${JSON.stringify(value)}`,
47
+ );
48
+ }
49
+ if (!VERSION_PATTERN.test(value)) {
50
+ throw versionError(
51
+ VERSION_CODES.VERSION_INVALID,
52
+ `${where}: invalid version ${JSON.stringify(value)} — expected MAJOR.MINOR.PATCH ` +
53
+ '(for example 0.7.2) or MAJOR.MINOR.PATCH-rc.N (for example 0.8.0-rc.3); ' +
54
+ 'build metadata and other prerelease tags are not accepted by the packer',
55
+ );
56
+ }
57
+ return value;
58
+ }
59
+
60
+ /** Read and parse `<root>/package.json`; never falls back to another file. */
61
+ export function readPackageManifest(root = PACKAGE_ROOT) {
62
+ const file = path.join(path.resolve(root), 'package.json');
63
+ let text;
64
+ try {
65
+ text = fs.readFileSync(file, 'utf8');
66
+ } catch (error) {
67
+ throw versionError(
68
+ VERSION_CODES.PACKAGE_UNREADABLE,
69
+ `cannot read ${file} (${error?.code ?? error?.message})`,
70
+ error,
71
+ );
72
+ }
73
+ try {
74
+ const parsed = JSON.parse(text);
75
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
76
+ throw new Error('package.json must contain a JSON object');
77
+ }
78
+ return parsed;
79
+ } catch (error) {
80
+ throw versionError(
81
+ VERSION_CODES.PACKAGE_UNREADABLE,
82
+ `cannot parse ${file}: ${error?.message ?? String(error)}`,
83
+ error,
84
+ );
85
+ }
86
+ }
87
+
88
+ /** The validated version of the package rooted at `root`. */
89
+ export function readPackageVersion(root = PACKAGE_ROOT) {
90
+ const manifest = readPackageManifest(root);
91
+ return validateVersion(manifest.version, path.join(path.resolve(root), 'package.json'));
92
+ }
93
+
94
+ /**
95
+ * The version this checkout ships. Import-time resolution is deliberate: a
96
+ * broken or malformed package.json must fail the packer and the suite loudly
97
+ * instead of silently packing "undefined".
98
+ */
99
+ export const VERSION = readPackageVersion(PACKAGE_ROOT);
@@ -0,0 +1,100 @@
1
+ /**
2
+ * pre-step 容器 fixture —— 复刻真实 Cordis 的 waterfall 合成语义。
3
+ *
4
+ * 依据(asar 解包的宿主代码):
5
+ * - `@deepseek-ai/cordis` src/events.ts:234-242
6
+ * const cbs = this.dispatch('waterfall', args)
7
+ * const inner = args.pop()
8
+ * const next = () => (cbs.shift() ?? inner)(...args)
9
+ * args.push(next); return next()
10
+ * - 同文件 :255 `const method = options.prepend ? 'unshift' : 'push'`
11
+ * - 宿主 `dsh-agent-loop/lib/index.js:902-926`:
12
+ * const claimed = this.inbox.claim(target, position.turn)
13
+ * dispatch.waterfall('agent/pre-step', { messages: claimed, ... }, () =>
14
+ * ({ kind: 'enter', messages: context === undefined ? claimed : [...claimed, context] }))
15
+ *
16
+ * 注意:listener 收到的是 `(payload, next)`,且所有 listener 共用同一个 next
17
+ * 闭包;inner 闭包引用的是同一个 claimed 数组。所以 identity-router 在
18
+ * `next()` 之前原地把开机卡插到第一条真实 user 之后,内层才看得到。v3 起开机卡
19
+ * 不再 unshift 到最前(TurnNavigator 取该轮第一个 kind==='user' 节点当 tooltip)。
20
+ *
21
+ * 这个 fixture 不是手拼顺序数组:测试只给输入消息 + runtime context,顺序完全由
22
+ * 注册语义和插件代码合成。
23
+ */
24
+
25
+ export class PreStepBus {
26
+ constructor() {
27
+ /** @type {Map<string, Function[]>} */
28
+ this.hooks = new Map();
29
+ }
30
+
31
+ on(name, listener, options = {}) {
32
+ if (typeof listener !== 'function') throw new TypeError(`listener for ${name} must be a function`);
33
+ const list = this.hooks.get(name) ?? [];
34
+ const prepend = typeof options === 'boolean' ? options : options?.prepend === true;
35
+ if (prepend) list.unshift(listener);
36
+ else list.push(listener);
37
+ this.hooks.set(name, list);
38
+ return () => {
39
+ const index = list.indexOf(listener);
40
+ if (index !== -1) list.splice(index, 1);
41
+ return index !== -1;
42
+ };
43
+ }
44
+
45
+ /** 真实 Cordis waterfall:外层先跑,next 共享。 */
46
+ async waterfall(name, payload, inner) {
47
+ const cbs = [...(this.hooks.get(name) ?? [])];
48
+ const next = () => {
49
+ const cb = cbs.shift() ?? inner;
50
+ return cb(payload, next);
51
+ };
52
+ return next();
53
+ }
54
+
55
+ /**
56
+ * 合成一次 pre-step,返回宿主最终会消费的 decision 和 claimed 数组。
57
+ * @param {{messages:object[], agent?:object, turn?:number, step?:number, context?:object}} input
58
+ */
59
+ async compose({ messages, agent, turn = 1, step = 1, context } = {}) {
60
+ const claimed = Array.isArray(messages) ? [...messages] : [];
61
+ const inner = () => (context === undefined
62
+ ? { kind: 'enter', messages: claimed }
63
+ : { kind: 'enter', messages: [...claimed, context] });
64
+ const decision = await this.waterfall(
65
+ 'agent/pre-step',
66
+ { messages: claimed, agent, turn, step },
67
+ inner,
68
+ );
69
+ return { decision, claimed };
70
+ }
71
+
72
+ /** 给 session/event 之类的普通事件用。 */
73
+ async emit(name, ...args) {
74
+ for (const listener of [...(this.hooks.get(name) ?? [])]) {
75
+ await listener(...args);
76
+ }
77
+ }
78
+ }
79
+
80
+ /** 与宿主 createUserMessage 同形的最小工厂(冻结消息,防插件原地改消息)。 */
81
+ export function makeUserMessageFactory(prefix = 'msg') {
82
+ let seq = 0;
83
+ return ({ content, source }) => {
84
+ seq += 1;
85
+ return Object.freeze({
86
+ role: 'user',
87
+ content,
88
+ source,
89
+ id: `${prefix}-${seq}`,
90
+ });
91
+ };
92
+ }
93
+
94
+ export function textMessage(text, { role = 'user', source = { kind: 'user' }, id } = {}) {
95
+ return { role, content: [{ type: 'text', text }], source, ...(id ? { id } : {}) };
96
+ }
97
+
98
+ export function noopLogger() {
99
+ return { warn() {}, info() {}, error() {} };
100
+ }
@@ -0,0 +1,97 @@
1
+ // P1 runtime witness. Runs the plugin's own tools inside a throwaway home and
2
+ // records EVERY file the fs layer is asked to open, so "this code never reads
3
+ // the credential file" is observed rather than asserted from source text.
4
+ //
5
+ // The parent (run.mjs) plants a decoy credential file in the fake home, sets
6
+ // HOME/USERPROFILE/DSH_HOME at it, then requires: (a) the canary read below is
7
+ // in the witness list — proof the witness is live, not silently unpatched —
8
+ // and (b) nothing the tools touched is the credential file or the real home.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const reads = [];
14
+ const calls = [];
15
+
16
+ // The fs layer accepts a path string, a Buffer, a file-descriptor number, or a
17
+ // WHATWG URL — and Node's own ESM loader passes a URL when it reads a module
18
+ // through our patched readFileSync. `path.resolve(String(url))` turns
19
+ // `file:///C:/x/y.js` into `<cwd>\file:\C:\x\y.js`: a path that does not
20
+ // exist, and that shares the real home's prefix whenever the package is
21
+ // installed under ~/.dsh. Normalise URLs to real file paths first, or the
22
+ // witness reports a phantom "the tools touched the real ~/.dsh".
23
+ const toPath = (file) => {
24
+ if (typeof file === 'number') return `<fd ${file}>`;
25
+ if (file instanceof URL) {
26
+ try { return fileURLToPath(file); } catch { return String(file); }
27
+ }
28
+ if (Buffer.isBuffer(file)) return file.toString();
29
+ const text = String(file);
30
+ if (text.startsWith('file:')) {
31
+ try { return fileURLToPath(new URL(text)); } catch { return text; }
32
+ }
33
+ try { return path.resolve(text); } catch { return text; }
34
+ };
35
+
36
+ const original = {
37
+ readFileSync: fs.readFileSync,
38
+ openSync: fs.openSync,
39
+ readFile: fs.readFile,
40
+ createReadStream: fs.createReadStream,
41
+ };
42
+
43
+ // Keep every wrapper bound to the ORIGINAL implementation: no wrapper may call
44
+ // another wrapper, or the same read would be recorded twice.
45
+ fs.readFileSync = function witnessReadFileSync(file, ...rest) {
46
+ reads.push(toPath(file));
47
+ return original.readFileSync.call(fs, file, ...rest);
48
+ };
49
+ fs.openSync = function witnessOpenSync(file, ...rest) {
50
+ reads.push(toPath(file));
51
+ return original.openSync.call(fs, file, ...rest);
52
+ };
53
+ fs.readFile = function witnessReadFile(file, ...rest) {
54
+ reads.push(toPath(file));
55
+ return original.readFile.call(fs, file, ...rest);
56
+ };
57
+ fs.createReadStream = function witnessCreateReadStream(file, ...rest) {
58
+ reads.push(toPath(file));
59
+ return original.createReadStream.call(fs, file, ...rest);
60
+ };
61
+
62
+ const home = process.env.P1_PROBE_HOME;
63
+ if (!home) {
64
+ console.error('P1_PROBE_HOME is required');
65
+ process.exit(2);
66
+ }
67
+ const memRoot = path.join(home, 'memory');
68
+ const sessionFile = path.join(home, 'sessions', '--p1--', 'session-p1', 'session.v4.jsonl.zstd');
69
+
70
+ // Canary: a read the witness MUST see. If this path is missing from `reads`,
71
+ // the instrumentation failed and the credential check below would be vacuous.
72
+ fs.readFileSync(path.join(home, 'canary.txt'), 'utf8');
73
+
74
+ const tools = await import('../src/tools.js');
75
+ const plugin = await import('../src/index.js');
76
+
77
+ const run = (name, fn) => {
78
+ try {
79
+ const value = fn();
80
+ calls.push({ name, ok: true, status: value?.status ?? null, code: value?.code ?? null });
81
+ return value;
82
+ } catch (error) {
83
+ calls.push({ name, ok: false, thrown: String(error?.message ?? error) });
84
+ return null;
85
+ }
86
+ };
87
+
88
+ run('sessionHealth(list)', () => tools.sessionHealth({}, { home }));
89
+ run('sessionHealth(latest)', () => tools.sessionHealth({ session: 'latest' }, { home }));
90
+ run('sessionHealth(sessionPath)', () => tools.sessionHealth({ sessionPath: sessionFile }, { home }));
91
+ run('sessionBackupPlan(dry)', () => tools.sessionBackupPlan({ sessionPath: sessionFile, dryRun: true }, { home }));
92
+ run('sessionWake', () => tools.sessionWake({}, { memRoot }));
93
+ run('leaseAcquire', () => tools.leaseAcquire({ holder: 'p1-probe', ttlSec: 30 }, { memRoot }));
94
+
95
+ const payload = { reads, calls, inject: plugin.inject };
96
+ // One JSON line on the last line of stdout: the parent parses this, nothing else.
97
+ console.log('P1_WITNESS ' + JSON.stringify(payload));