@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
package/src/live.js ADDED
@@ -0,0 +1,1603 @@
1
+ // Live session registry — the "正在" table (0.5.0).
2
+ //
3
+ // One JSON file per session under `<memoryRoot>/.longlive/live/<sessionId>.json`.
4
+ // The location is deliberate: topics/ and journal/ are scanned by memory_index,
5
+ // and the store root belongs to hand-written cards, so a registry row must not
6
+ // land in either. `.longlive/` already owns plugin state (memory-state.json,
7
+ // backups/, reports/), and `live/` is hidden from every memory_* tool.
8
+ //
9
+ // The file is a snapshot, not a log. A writer declares one of five states
10
+ // (idle | running | waiting | blocked | stale); a reader computes what is
11
+ // actually true. Liveness is heartbeat-first:
12
+ // running the heartbeat is within one ttl, whatever the recorded pid says.
13
+ // record.pid is the *writer's* pid, not the session's, so it can
14
+ // never overturn a fresh heartbeat.
15
+ // stale the heartbeat is older than 2 x ttlMs (strictly older)
16
+ // dead the heartbeat is older than 4 x ttlMs, or the row is from this
17
+ // host and its pid is definitively gone. pid evidence only
18
+ // accelerates death; it never decides it on its own.
19
+ // corrupt the file cannot be read, parsed, or no longer has the shape
20
+ // A fresh heartbeat therefore always wins, including when another process wrote
21
+ // the row and that writer has already exited.
22
+ //
23
+ // Writes are atomic: a unique tmp file in the same directory, a read-back of
24
+ // the tmp, then rename over the target. A writer that dies half-way leaves the
25
+ // old complete file (or no file) and at worst an orphan tmp that listing
26
+ // ignores. Concurrent writers each rename their own complete file, so the last
27
+ // rename wins and the target is never a mixture of two payloads.
28
+ //
29
+ // Prune is dry-run by default and requires confirm:"PRUNE". Before deleting it
30
+ // re-reads the row and deletes only a row that is still dead/corrupt AND whose
31
+ // bytes did not change since it became a candidate. A row carrying blocked_on
32
+ // is never deleted automatically; it is reported under `skipped` instead.
33
+ // Corrupt rows carry no trustworthy host, so they are the one cross-host case
34
+ // prune may remove. Remote rows that are merely dead are left alone. The same
35
+ // run reports (and, with confirm, removes) orphan *.tmp-* files older than an
36
+ // hour and empty directory placeholders that block a session id.
37
+ //
38
+ // All registry paths are checked after realpath(): the live directory and every
39
+ // row must resolve inside <memoryRoot>, so a junction or symlink cannot redirect
40
+ // a write outside it. liveGet refuses a symlinked row outright.
41
+
42
+ import fs from 'node:fs';
43
+ import os from 'node:os';
44
+ import path from 'node:path';
45
+ import crypto from 'node:crypto';
46
+
47
+ import {
48
+ memoryError, memoryRootFromConfig, resolveInside, relativePath,
49
+ realPathProbe, isInsideRoot,
50
+ } from './memory/paths.js';
51
+
52
+ export const LIVE_SCHEMA_VERSION = 1;
53
+ export const LIVE_DIR = path.join('.longlive', 'live');
54
+ export const LIVE_TOMBSTONE_FILE = 'tombstones.jsonl';
55
+ export const LIVE_CONFIRM = 'PRUNE';
56
+ export const LIVE_SWEEP_CONFIRM = 'SWEEP';
57
+ export const GOAL_MAX_CHARS = 80;
58
+ export const DEFAULT_TTL_MS = 60_000;
59
+ export const MIN_TTL_MS = 1_000;
60
+ export const MAX_TTL_MS = 86_400_000;
61
+ // Bounded queue/detail payloads: a registry row is a glance, not a backlog dump.
62
+ export const MAX_QUEUED_ITEMS = 200;
63
+ export const MAX_QUEUED_ITEM_CHARS = 300;
64
+ export const LAST_ACTION_DETAIL_MAX_CHARS = 500;
65
+ // Orphaned tmp files younger than this may still belong to a live writer.
66
+ export const TMP_MAX_AGE_MS = 60 * 60 * 1000;
67
+
68
+ /** States a writer may declare. `stale` is legal here and also computed on read. */
69
+ export const DECLARED_STATES = Object.freeze(['idle', 'running', 'waiting', 'blocked', 'stale']);
70
+ /** States only a reader can decide; a writer must never store them. */
71
+ export const COMPUTED_STATES = Object.freeze(['dead', 'corrupt']);
72
+ export const EFFECTIVE_STATES = Object.freeze([...DECLARED_STATES, ...COMPUTED_STATES]);
73
+
74
+ /** The exact keys of a stored row, in order. Nothing else is written. */
75
+ export const LIVE_RECORD_FIELDS = Object.freeze([
76
+ 'schemaVersion',
77
+ 'sessionId',
78
+ 'pid',
79
+ 'host',
80
+ 'startedAt',
81
+ 'updatedAt',
82
+ 'heartbeatAt',
83
+ 'ttlMs',
84
+ 'state',
85
+ 'turn',
86
+ 'goal',
87
+ // R3: the clock of the *goal*, not of the row. A heartbeat touch must never
88
+ // move it (see liveTouch), and the board renders focus.updatedAt from it.
89
+ 'goalUpdatedAt',
90
+ 'blocked_on',
91
+ 'queued',
92
+ 'last_action',
93
+ ]);
94
+
95
+ export const LIVE_CODES = Object.freeze({
96
+ BAD_ARGUMENT: 'E_BAD_ARGUMENT',
97
+ ROOT_UNSET: 'E_MEMORY_ROOT_UNSET',
98
+ PATH_OUTSIDE_ROOT: 'E_PATH_OUTSIDE_ROOT',
99
+ CORRUPT: 'E_LIVE_CORRUPT',
100
+ CONFIRM_REQUIRED: 'E_CONFIRM_REQUIRED',
101
+ WRITE: 'E_LIVE_WRITE',
102
+ // Reading through a case alias is ambiguous on NTFS: one file, several
103
+ // spellings. Writers normalise; readers must name the canonical id.
104
+ NOT_CANONICAL: 'E_SESSION_ID_NOT_CANONICAL',
105
+ // Something that is not a regular file occupies the row path (directory,
106
+ // device, FIFO). Writing would fail or replace the wrong object.
107
+ DIR_PLACEHOLDER: 'E_LIVE_ROW_BLOCKED',
108
+ });
109
+
110
+ // A session id becomes a file name, so it is constrained, not sanitised: a
111
+ // value that looks like a path is refused rather than rewritten into something
112
+ // the caller did not ask for.
113
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
114
+
115
+ function bad(message) {
116
+ return memoryError(LIVE_CODES.BAD_ARGUMENT, message);
117
+ }
118
+
119
+ function isPlainObject(value) {
120
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;
121
+ const proto = Object.getPrototypeOf(value);
122
+ return proto === Object.prototype || proto === null;
123
+ }
124
+
125
+ function argumentType(value) {
126
+ if (value === null) return 'null';
127
+ if (Array.isArray(value)) return 'array';
128
+ return typeof value;
129
+ }
130
+
131
+ /** Tool-entry gate: args and config must be explicit plain objects. */
132
+ function assertEntry(name, args, config) {
133
+ if (!isPlainObject(args)) {
134
+ throw bad(`${name} 的 args 必须是普通对象,收到 ${argumentType(args)}`);
135
+ }
136
+ if (!isPlainObject(config)) {
137
+ throw bad(`${name} 的 config 必须是普通对象,收到 ${argumentType(config)}`);
138
+ }
139
+ }
140
+
141
+ function currentHostname() {
142
+ const name = os.hostname();
143
+ return typeof name === 'string' && name.trim() !== '' ? name.trim() : 'unknown-host';
144
+ }
145
+
146
+ /** Host stamps are case-insensitive, like the OS names they came from. */
147
+ function hostsMatch(a, b) {
148
+ return typeof a === 'string' && typeof b === 'string'
149
+ && a.trim() !== '' && a.trim().toLowerCase() === b.trim().toLowerCase();
150
+ }
151
+
152
+ function nowMs(config = {}) {
153
+ const raw = config?.now;
154
+ if (raw instanceof Date) {
155
+ const ms = raw.getTime();
156
+ if (Number.isFinite(ms)) return ms;
157
+ }
158
+ if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
159
+ return Date.now();
160
+ }
161
+
162
+ function isoTime(ms) {
163
+ return new Date(ms).toISOString();
164
+ }
165
+
166
+ function parseTime(value) {
167
+ if (typeof value !== 'string' || value.trim() === '') return null;
168
+ const ms = Date.parse(value);
169
+ return Number.isFinite(ms) ? ms : null;
170
+ }
171
+
172
+ /**
173
+ * True when `pid` is an existing process. Signal 0 only probes; it never
174
+ * terminates anything. EPERM means the process exists but belongs to another
175
+ * user, which still counts as alive.
176
+ */
177
+ export function pidAlive(pid) {
178
+ if (!Number.isInteger(pid) || pid <= 0) return false;
179
+ try {
180
+ process.kill(pid, 0);
181
+ return true;
182
+ } catch (error) {
183
+ return error?.code === 'EPERM';
184
+ }
185
+ }
186
+
187
+ /** Validate and normalise a session id before it can become a file name. */
188
+ export function normalizeSessionId(value, label = 'sessionId') {
189
+ if (typeof value !== 'string' || value.trim() === '') {
190
+ throw bad(`${label} 必须是非空字符串,收到 ${value === undefined ? 'undefined' : JSON.stringify(value)}`);
191
+ }
192
+ const id = value.trim();
193
+ if (id.includes('\0')) throw bad(`${label} 不能包含 NUL 字符`);
194
+ if (path.isAbsolute(id) || /[\\/]/.test(id) || id === '..' || id.split(/[\\/]+/).includes('..')) {
195
+ throw memoryError(
196
+ LIVE_CODES.PATH_OUTSIDE_ROOT,
197
+ `拒绝越界 ${label}:${JSON.stringify(id)} — 只允许写在 <memoryRoot>/.longlive/live 里`,
198
+ );
199
+ }
200
+ if (!SESSION_ID_RE.test(id)) {
201
+ throw bad(`${label} 只允许字母、数字与 . _ -(1..128 位,首字符是字母或数字),收到 ${JSON.stringify(id)}`);
202
+ }
203
+ // NTFS is case-insensitive, so `S-A` and `s-a` are one file. Canonicalise to
204
+ // lowercase before the id ever becomes a name: one session, one row, no
205
+ // duplicate-looking aliases that decode as "corrupt".
206
+ return id.toLowerCase();
207
+ }
208
+
209
+ /**
210
+ * Lexical resolveInside already refuses `..`, but a junction or symlink can
211
+ * still point the live directory outside the root. Every registry path is
212
+ * therefore resolved again through the shared memory-layer probe and compared
213
+ * against the real root.
214
+ */
215
+ function assertRealInside(root, target, label) {
216
+ let realRoot;
217
+ try {
218
+ // Use the same native realpath probe as the memory layer: the JS fallback
219
+ // can hand back an 8.3 short name (ADMINI~1) while the target probe returns
220
+ // the long form, which would look like an escape on Windows.
221
+ realRoot = realPathProbe(root);
222
+ } catch (error) {
223
+ throw memoryError(
224
+ LIVE_CODES.ROOT_UNSET,
225
+ `无法解析 memoryRoot 的真实路径:${root}(${error?.code ?? error?.message})`,
226
+ error,
227
+ );
228
+ }
229
+ let realTarget;
230
+ try {
231
+ realTarget = realPathProbe(target);
232
+ } catch (error) {
233
+ throw memoryError(
234
+ LIVE_CODES.PATH_OUTSIDE_ROOT,
235
+ `无法校验 ${label} 的真实路径:${target}(${error?.code ?? error?.message})`,
236
+ error,
237
+ );
238
+ }
239
+ if (!isInsideRoot(realRoot, realTarget)) {
240
+ throw memoryError(
241
+ LIVE_CODES.PATH_OUTSIDE_ROOT,
242
+ `拒绝越界 ${label}:${target} 的真实路径 ${realTarget} 不在 ${realRoot} 之内`,
243
+ );
244
+ }
245
+ return realTarget;
246
+ }
247
+
248
+ /** `<memoryRoot>/.longlive/live` (no mkdir; lexical + realpath guarded). */
249
+ export function liveDir(root) {
250
+ const dir = resolveInside(root, LIVE_DIR);
251
+ assertRealInside(root, dir, '活体目录');
252
+ return dir;
253
+ }
254
+
255
+ /** Absolute path of one session's row; id and realpath are validated first. */
256
+ export function liveFile(root, sessionId) {
257
+ const id = normalizeSessionId(sessionId);
258
+ const file = resolveInside(root, path.join(LIVE_DIR, `${id}.json`));
259
+ assertRealInside(root, file, '活体记录');
260
+ return file;
261
+ }
262
+
263
+ /** Append-only tombstone/audit ledger for removed or swept L1 rows. */
264
+ export function liveTombstoneFile(root) {
265
+ return resolveInside(root, path.join(LIVE_DIR, LIVE_TOMBSTONE_FILE));
266
+ }
267
+
268
+ function appendLiveTombstones(root, rows, now) {
269
+ if (!Array.isArray(rows) || rows.length === 0) return [];
270
+ const file = liveTombstoneFile(root);
271
+ fs.mkdirSync(path.dirname(file), { recursive: true });
272
+ const at = isoTime(typeof now === 'number' ? now : Date.now());
273
+ const written = [];
274
+ const lines = rows.map((row) => {
275
+ const entry = {
276
+ schema: 'live-tombstone/v1',
277
+ at,
278
+ sessionId: row.sessionId ?? null,
279
+ effectiveState: row.effectiveState ?? null,
280
+ reason: row.reason ?? 'dead-row-cleanup',
281
+ heartbeatAt: row.heartbeatAt ?? null,
282
+ ttlMs: row.ttlMs ?? null,
283
+ heartbeatAgeMs: row.heartbeatAgeMs ?? null,
284
+ host: row.host ?? null,
285
+ sha256: row.sha256 ?? null,
286
+ fileRel: row.fileRel ?? null,
287
+ row: row.row ?? null,
288
+ };
289
+ written.push(entry);
290
+ return JSON.stringify(entry);
291
+ });
292
+ fs.appendFileSync(file, `${lines.join('\n')}\n`, 'utf8');
293
+ return written;
294
+ }
295
+
296
+ /** Read-only health snapshot: stale/dead counts + tombstone backlog. */
297
+ export function liveHealth(rootOrConfig, config = {}) {
298
+ const root = typeof rootOrConfig === 'string' ? rootOrConfig : memoryRootFromConfig(rootOrConfig ?? config);
299
+ const now = typeof rootOrConfig === 'string' ? nowMs(config) : nowMs(rootOrConfig ?? config);
300
+ const listed = liveList({ includeDead: true }, { memoryRoot: root, now });
301
+ const entries = Array.isArray(listed.entries) ? listed.entries : [];
302
+ const stale = entries.filter((entry) => entry.effectiveState === 'stale');
303
+ const dead = entries.filter((entry) => entry.effectiveState === 'dead');
304
+ let tombstones = 0;
305
+ try {
306
+ const text = fs.readFileSync(liveTombstoneFile(root), 'utf8');
307
+ tombstones = text.split('\n').filter((line) => line.trim() !== '').length;
308
+ } catch { /* no ledger yet */ }
309
+ return {
310
+ ok: true,
311
+ root,
312
+ dir: listed.dir,
313
+ total: entries.length,
314
+ active: entries.filter((entry) => ['idle', 'running', 'waiting', 'blocked'].includes(entry.effectiveState)).length,
315
+ stale: stale.length,
316
+ dead: dead.length,
317
+ corrupt: entries.filter((entry) => entry.effectiveState === 'corrupt').length,
318
+ tombstoned: tombstones,
319
+ staleIds: stale.map((entry) => entry.sessionId),
320
+ deadIds: dead.map((entry) => entry.sessionId),
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Startup-safe sweep: mark stale in the health view and move dead same-host
326
+ * rows to the append-only tombstone ledger before unlinking them. Remote rows
327
+ * are never swept; dry-run is the default.
328
+ */
329
+ export function liveSweep(args = {}, config = {}) {
330
+ const root = memoryRootFromConfig(config);
331
+ const now = nowMs(config);
332
+ const real = args.confirm === LIVE_SWEEP_CONFIRM || args.autoCleanup === true;
333
+ const health = liveHealth(root, { now });
334
+ const listed = liveList({ includeDead: true }, { memoryRoot: root, now });
335
+ const entries = Array.isArray(listed.entries) ? listed.entries : [];
336
+ const candidates = entries.filter((entry) => entry.effectiveState === 'dead' && entry.sameHost === true && entry.file);
337
+ const removed = [];
338
+ const tombstoned = [];
339
+ if (real) {
340
+ for (const entry of candidates) {
341
+ let text = '';
342
+ let sha = null;
343
+ try {
344
+ const bytes = fs.readFileSync(entry.file);
345
+ text = bytes.toString('utf8');
346
+ sha = crypto.createHash('sha256').update(bytes).digest('hex');
347
+ } catch { continue; }
348
+ const row = { ...entry, sha256: sha };
349
+ try { tombstoned.push(...appendLiveTombstones(root, [row], now)); } catch { continue; }
350
+ try {
351
+ fs.unlinkSync(entry.file);
352
+ removed.push(entry.sessionId);
353
+ } catch { /* tombstone is already durable; report as not removed */ }
354
+ }
355
+ }
356
+ return {
357
+ ok: true,
358
+ status: real ? 'swept' : 'dry-run',
359
+ dryRun: !real,
360
+ confirmRequired: LIVE_SWEEP_CONFIRM,
361
+ ...health,
362
+ candidates: candidates.map((entry) => entry.sessionId),
363
+ removed,
364
+ tombstoned: tombstoned.length,
365
+ };
366
+ }
367
+
368
+ // --------------------------------------------------------------------- write
369
+
370
+ let tmpSeq = 0;
371
+
372
+ function tmpPathFor(file) {
373
+ tmpSeq += 1;
374
+ return `${file}.tmp-${process.pid}-${tmpSeq}-${crypto.randomBytes(4).toString('hex')}`;
375
+ }
376
+
377
+ /** Synchronous sleep for the Windows rename retry only. */
378
+ function sleepSync(ms) {
379
+ try {
380
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
381
+ } catch {
382
+ /* no Atomics on this runtime: retry immediately */
383
+ }
384
+ }
385
+
386
+ // On Windows a rename over a target another process has open can fail with
387
+ // EPERM/EBUSY for a moment. Retrying a few times is a real fix, not a mask:
388
+ // the rename itself is still all-or-nothing.
389
+ function renameWithRetry(from, to) {
390
+ const retryable = new Set(['EPERM', 'EACCES', 'EBUSY']);
391
+ for (let attempt = 0; ; attempt += 1) {
392
+ try {
393
+ fs.renameSync(from, to);
394
+ return;
395
+ } catch (error) {
396
+ if (!retryable.has(error?.code) || attempt >= 4) throw error;
397
+ sleepSync(5 * (attempt + 1));
398
+ }
399
+ }
400
+ }
401
+
402
+ function writeFailure(file, error) {
403
+ if (error?.code === LIVE_CODES.WRITE) return error;
404
+ return memoryError(
405
+ LIVE_CODES.WRITE,
406
+ `写入活体记录失败:${file}(${error?.code ?? error?.message ?? 'unknown'})`,
407
+ error,
408
+ );
409
+ }
410
+
411
+ /**
412
+ * Write `text` to `file` atomically: tmp + tmp read-back + rename + read-back.
413
+ * If the read-back after the rename shows a complete JSON object that is not
414
+ * ours, another writer won the race and that is the contract (last complete
415
+ * file wins), so the write is reported as superseded instead of rolled back.
416
+ * Anything else (including a half-written tmp) restores the previous bytes and
417
+ * throws E_LIVE_WRITE.
418
+ */
419
+ function writeLiveText(file, text) {
420
+ let prior = null;
421
+ try {
422
+ prior = fs.readFileSync(file);
423
+ } catch (error) {
424
+ if (error?.code !== 'ENOENT') prior = null;
425
+ }
426
+ const tmp = tmpPathFor(file);
427
+ let renamed = false;
428
+ try {
429
+ fs.writeFileSync(tmp, text, 'utf8');
430
+ const staged = fs.readFileSync(tmp, 'utf8');
431
+ if (staged !== text) {
432
+ throw memoryError(LIVE_CODES.WRITE, `临时文件内容不完整:${tmp}`);
433
+ }
434
+ renameWithRetry(tmp, file);
435
+ renamed = true;
436
+ const readBack = fs.readFileSync(file, 'utf8');
437
+ if (readBack !== text) {
438
+ let completeForeign = false;
439
+ try {
440
+ const other = JSON.parse(readBack.replace(/^\uFEFF/, ''));
441
+ completeForeign = isPlainObject(other) && typeof other.sessionId === 'string';
442
+ } catch {
443
+ completeForeign = false;
444
+ }
445
+ if (!completeForeign) {
446
+ throw memoryError(LIVE_CODES.WRITE, `写入后读回的不是完整 JSON:${file}`);
447
+ }
448
+ return { sha256: sha256Text(text), bytes: Buffer.byteLength(text, 'utf8'), superseded: true };
449
+ }
450
+ } catch (error) {
451
+ try {
452
+ if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
453
+ } catch {
454
+ /* best effort: the error that matters is the one being rethrown */
455
+ }
456
+ if (renamed) {
457
+ try {
458
+ if (prior != null) fs.writeFileSync(file, prior);
459
+ else if (fs.existsSync(file)) fs.unlinkSync(file);
460
+ } catch {
461
+ /* best effort: never mask the write error */
462
+ }
463
+ }
464
+ throw writeFailure(file, error);
465
+ }
466
+ return {
467
+ sha256: sha256Text(text),
468
+ bytes: Buffer.byteLength(text, 'utf8'),
469
+ superseded: false,
470
+ };
471
+ }
472
+
473
+ function sha256Text(text) {
474
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
475
+ }
476
+
477
+ // ---------------------------------------------------------------------- read
478
+
479
+ /**
480
+ * Parse one row. Returns `{ok:true, record}` with exactly LIVE_RECORD_FIELDS,
481
+ * or `{ok:false, reason}` for anything that cannot be trusted. This never
482
+ * throws: corrupt rows are data for the reader, not an exception.
483
+ */
484
+ function decodeRecord(text, expectedSessionId) {
485
+ let raw;
486
+ try {
487
+ raw = JSON.parse(text.replace(/^\uFEFF/, ''));
488
+ } catch (error) {
489
+ return { ok: false, reason: `JSON 解析失败:${error.message}` };
490
+ }
491
+ if (!isPlainObject(raw)) return { ok: false, reason: '顶层不是 JSON 对象' };
492
+ // Case-insensitive on purpose: NTFS maps S-A.json and s-a.json to one file,
493
+ // and rows written before the lowercase canonicalisation may still carry the
494
+ // mixed-case id. They are the same session, not a corrupt row.
495
+ if (typeof raw.sessionId !== 'string'
496
+ || raw.sessionId.trim().toLowerCase() !== expectedSessionId.toLowerCase()) {
497
+ return {
498
+ ok: false,
499
+ reason: `sessionId 缺失或与文件名不一致:文件名 ${expectedSessionId},记录 ${JSON.stringify(raw.sessionId)}`,
500
+ };
501
+ }
502
+ if (!Number.isInteger(raw.schemaVersion) || raw.schemaVersion < 1) {
503
+ return { ok: false, reason: `schemaVersion 无效:${JSON.stringify(raw.schemaVersion)}` };
504
+ }
505
+ if (typeof raw.state !== 'string' || !DECLARED_STATES.includes(raw.state)) {
506
+ return { ok: false, reason: `state 无效:${JSON.stringify(raw.state)}` };
507
+ }
508
+ if (!Number.isInteger(raw.pid) || raw.pid <= 0) {
509
+ return { ok: false, reason: `pid 无效:${JSON.stringify(raw.pid)}` };
510
+ }
511
+ if (typeof raw.host !== 'string' || raw.host.trim() === '') {
512
+ return { ok: false, reason: 'host 缺失或不是字符串' };
513
+ }
514
+ if (!Number.isInteger(raw.ttlMs) || raw.ttlMs <= 0) {
515
+ return { ok: false, reason: `ttlMs 无效:${JSON.stringify(raw.ttlMs)}` };
516
+ }
517
+ const heartbeatMs = parseTime(raw.heartbeatAt) ?? parseTime(raw.updatedAt);
518
+ if (heartbeatMs == null) {
519
+ return { ok: false, reason: 'heartbeatAt/updatedAt 不是可解析的时间' };
520
+ }
521
+ const updatedMs = parseTime(raw.updatedAt) ?? heartbeatMs;
522
+ const startedMs = parseTime(raw.startedAt) ?? heartbeatMs;
523
+ // R3 additive field: rows written before this version simply have no goal
524
+ // clock; keep it as '' (unknown) instead of inventing one from heartbeatAt.
525
+ const goalUpdatedMs = parseTime(raw.goalUpdatedAt);
526
+ if (!Array.isArray(raw.queued) || !raw.queued.every((item) => typeof item === 'string')) {
527
+ return { ok: false, reason: 'queued 必须是字符串数组' };
528
+ }
529
+ return {
530
+ ok: true,
531
+ record: {
532
+ schemaVersion: raw.schemaVersion,
533
+ sessionId: raw.sessionId,
534
+ pid: raw.pid,
535
+ host: raw.host,
536
+ startedAt: isoTime(startedMs),
537
+ updatedAt: isoTime(updatedMs),
538
+ heartbeatAt: isoTime(heartbeatMs),
539
+ ttlMs: raw.ttlMs,
540
+ state: raw.state,
541
+ turn: Number.isInteger(raw.turn) && raw.turn >= 0 ? raw.turn : 0,
542
+ goal: typeof raw.goal === 'string' ? raw.goal : '',
543
+ goalUpdatedAt: goalUpdatedMs != null ? isoTime(goalUpdatedMs) : '',
544
+ blocked_on: typeof raw.blocked_on === 'string' ? raw.blocked_on : '',
545
+ queued: [...raw.queued],
546
+ last_action: normalizeLastAction(raw.last_action, updatedMs),
547
+ },
548
+ };
549
+ }
550
+
551
+ function normalizeLastAction(value, fallbackMs) {
552
+ if (!isPlainObject(value)) return null;
553
+ return {
554
+ at: parseTime(value.at) != null ? value.at : isoTime(fallbackMs),
555
+ kind: typeof value.kind === 'string' ? value.kind : '',
556
+ detail: typeof value.detail === 'string' ? value.detail : '',
557
+ };
558
+ }
559
+
560
+ /** Reader-side truth for one valid row. Never mutates the file. */
561
+ function liveEntry(record, { file, root, now, hostname }) {
562
+ const heartbeatMs = parseTime(record.heartbeatAt);
563
+ const sameHost = record.host.trim().toLowerCase() === hostname.trim().toLowerCase();
564
+ // Only a local pid can be probed. A remote row ages by heartbeat alone.
565
+ const alive = sameHost ? pidAlive(record.pid) : null;
566
+ const age = now - heartbeatMs;
567
+ const fresh = age <= record.ttlMs;
568
+ let effectiveState;
569
+ if (fresh) {
570
+ // Heartbeat-first: a row refreshed within one ttl is alive. The pid is the
571
+ // writer's, not the session's, so a dead pid must not overturn this.
572
+ effectiveState = 'running';
573
+ } else if (age > 4 * record.ttlMs) {
574
+ // The writer has been silent for four lifetimes: no pid evidence needed.
575
+ effectiveState = 'dead';
576
+ } else if (alive === false) {
577
+ // A local pid that is definitively gone only accelerates death; it never
578
+ // decides it while the heartbeat is still fresh (handled above).
579
+ effectiveState = 'dead';
580
+ } else if (age > 2 * record.ttlMs) {
581
+ effectiveState = 'stale';
582
+ } else {
583
+ effectiveState = record.state;
584
+ }
585
+ return {
586
+ sessionId: record.sessionId,
587
+ file,
588
+ fileRel: relativePath(root, file),
589
+ effectiveState,
590
+ state: record.state,
591
+ pid: record.pid,
592
+ host: record.host,
593
+ startedAt: record.startedAt,
594
+ updatedAt: record.updatedAt,
595
+ heartbeatAt: record.heartbeatAt,
596
+ ttlMs: record.ttlMs,
597
+ heartbeatAgeMs: age,
598
+ sameHost,
599
+ pidAlive: alive,
600
+ turn: record.turn,
601
+ goal: record.goal,
602
+ // R3: the goal write clock (ISO) or null when the row never declared one.
603
+ // Never derived from heartbeatAt — that is exactly the lie R3 fixes.
604
+ goalUpdatedAt: record.goalUpdatedAt === '' ? null : record.goalUpdatedAt,
605
+ blocked_on: record.blocked_on,
606
+ queued: record.queued,
607
+ last_action: record.last_action,
608
+ corrupt: false,
609
+ corruptReason: null,
610
+ };
611
+ }
612
+
613
+ /** Stable shape for a row that cannot be read; every field is present but null. */
614
+ function corruptEntry({ sessionId, file, root, reason, hostHint = null, hostname = null }) {
615
+ const host = typeof hostHint === 'string' && hostHint.trim() !== '' ? hostHint.trim() : null;
616
+ return {
617
+ sessionId,
618
+ file,
619
+ fileRel: relativePath(root, file),
620
+ effectiveState: 'corrupt',
621
+ state: null,
622
+ pid: null,
623
+ host,
624
+ startedAt: null,
625
+ updatedAt: null,
626
+ heartbeatAt: null,
627
+ ttlMs: null,
628
+ heartbeatAgeMs: null,
629
+ sameHost: host == null || hostname == null ? null : hostsMatch(host, hostname),
630
+ pidAlive: null,
631
+ turn: null,
632
+ goal: '',
633
+ goalUpdatedAt: null,
634
+ blocked_on: '',
635
+ queued: [],
636
+ last_action: null,
637
+ corrupt: true,
638
+ corruptReason: reason,
639
+ };
640
+ }
641
+
642
+ /**
643
+ * Best-effort host stamp from a corrupt row. A half-written JSON object still
644
+ * usually carries its host; extracting it lets prune tell a local orphan from
645
+ * a row another machine may still own. This is a hint for protection only —
646
+ * it is never trusted as proof of liveness.
647
+ */
648
+ function hostHintFromText(text) {
649
+ try {
650
+ const raw = JSON.parse(text.replace(/^\uFEFF/, ''));
651
+ if (isPlainObject(raw) && typeof raw.host === 'string' && raw.host.trim() !== '') {
652
+ return raw.host.trim();
653
+ }
654
+ } catch {
655
+ // Fall through to the field regex for truncated/half-written JSON.
656
+ }
657
+ const match = /"host"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(text);
658
+ if (!match) return null;
659
+ try {
660
+ const decoded = JSON.parse(`"${match[1]}"`);
661
+ return typeof decoded === 'string' && decoded.trim() !== '' ? decoded.trim() : null;
662
+ } catch {
663
+ return null;
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Every row in the live directory. A missing directory is an empty registry.
669
+ * Corrupt rows are returned, never thrown; a directory that cannot be read at
670
+ * all is E_LIVE_CORRUPT because the list cannot be answered honestly.
671
+ */
672
+ function scanEntries(root, { now, hostname }) {
673
+ const dir = liveDir(root);
674
+ let dirents;
675
+ try {
676
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
677
+ } catch (error) {
678
+ if (error?.code === 'ENOENT') return { dir, entries: [], hashes: new Map() };
679
+ throw memoryError(
680
+ LIVE_CODES.CORRUPT,
681
+ `读不到活体目录:${dir}(${error?.code ?? error?.message})`,
682
+ error,
683
+ );
684
+ }
685
+ const entries = [];
686
+ // The exact bytes each row had when it was scanned. Prune keeps this hash so
687
+ // it can prove the row did not change while it was being considered.
688
+ const hashes = new Map();
689
+ for (const dirent of dirents) {
690
+ if (!dirent.isFile()) continue; // no symlinks, no directories
691
+ const name = dirent.name;
692
+ if (!name.endsWith('.json')) continue; // orphan .tmp-* files stay invisible
693
+ const sessionId = name.slice(0, -'.json'.length);
694
+ if (!SESSION_ID_RE.test(sessionId)) continue; // not a registry file
695
+ const file = path.join(dir, name);
696
+ let text;
697
+ try {
698
+ text = fs.readFileSync(file, 'utf8');
699
+ } catch (error) {
700
+ entries.push(corruptEntry({
701
+ sessionId, file, root, reason: `读取失败:${error?.code ?? error?.message}`,
702
+ }));
703
+ continue;
704
+ }
705
+ hashes.set(file, sha256Text(text));
706
+ const decoded = decodeRecord(text, sessionId);
707
+ if (!decoded.ok) {
708
+ entries.push(corruptEntry({
709
+ sessionId, file, root, reason: decoded.reason,
710
+ hostHint: hostHintFromText(text), hostname,
711
+ }));
712
+ continue;
713
+ }
714
+ entries.push(liveEntry(decoded.record, { file, root, now, hostname }));
715
+ }
716
+ entries.sort((a, b) => {
717
+ const at = parseTime(a.updatedAt);
718
+ const bt = parseTime(b.updatedAt);
719
+ if (at != null && bt != null && at !== bt) return bt - at;
720
+ if (at != null && bt == null) return -1;
721
+ if (at == null && bt != null) return 1;
722
+ return a.sessionId.localeCompare(b.sessionId);
723
+ });
724
+ return { dir, entries, hashes };
725
+ }
726
+
727
+ function countStates(entries) {
728
+ const counts = Object.fromEntries(EFFECTIVE_STATES.map((state) => [state, 0]));
729
+ for (const entry of entries) counts[entry.effectiveState] += 1;
730
+ counts.total = entries.length;
731
+ return counts;
732
+ }
733
+
734
+ function entrySummary(entry) {
735
+ return {
736
+ sessionId: entry.sessionId,
737
+ effectiveState: entry.effectiveState,
738
+ host: entry.host,
739
+ pid: entry.pid,
740
+ };
741
+ }
742
+
743
+ // ------------------------------------------------------------------- argument
744
+
745
+ function optionalString(value, name) {
746
+ if (value === undefined) return undefined;
747
+ if (typeof value !== 'string') {
748
+ throw bad(`${name} 必须是字符串,收到 ${argumentType(value)}`);
749
+ }
750
+ return value;
751
+ }
752
+
753
+ function requireString(value, name) {
754
+ if (typeof value !== 'string') {
755
+ throw bad(`${name} 必须是字符串,收到 ${argumentType(value)}`);
756
+ }
757
+ return value;
758
+ }
759
+
760
+ function optionalInteger(value, name, { min, max } = {}) {
761
+ if (value === undefined) return undefined;
762
+ if (!Number.isInteger(value)) {
763
+ throw bad(`${name} 必须是整数,收到 ${JSON.stringify(value)}`);
764
+ }
765
+ if (min !== undefined && value < min) throw bad(`${name} 必须 >= ${min},收到 ${value}`);
766
+ if (max !== undefined && value > max) throw bad(`${name} 必须 <= ${max},收到 ${value}`);
767
+ return value;
768
+ }
769
+
770
+ function requireBoolean(value, name) {
771
+ if (typeof value !== 'boolean') {
772
+ throw bad(`${name} 必须是布尔值,收到 ${argumentType(value)}`);
773
+ }
774
+ return value;
775
+ }
776
+
777
+ function optionalBoolean(value, name, fallback = false) {
778
+ if (value === undefined) return fallback;
779
+ return requireBoolean(value, name);
780
+ }
781
+
782
+ function optionalQueued(value) {
783
+ if (value === undefined) return undefined;
784
+ if (!Array.isArray(value)) {
785
+ throw bad(`queued 必须是字符串数组,收到 ${argumentType(value)}`);
786
+ }
787
+ for (const [index, item] of value.entries()) {
788
+ if (typeof item !== 'string') {
789
+ throw bad(`queued[${index}] 必须是字符串,收到 ${argumentType(item)}`);
790
+ }
791
+ }
792
+ return value;
793
+ }
794
+
795
+ function optionalLastAction(value, now) {
796
+ if (value === undefined) return undefined;
797
+ if (!isPlainObject(value)) {
798
+ throw bad(`last_action 必须是 {at, kind, detail} 对象,收到 ${argumentType(value)}`);
799
+ }
800
+ const at = value.at === undefined
801
+ ? isoTime(now)
802
+ : (parseTime(requireString(value.at, 'last_action.at')) != null
803
+ ? value.at
804
+ : (() => { throw bad(`last_action.at 不是可解析的时间:${JSON.stringify(value.at)}`); })());
805
+ return {
806
+ at,
807
+ kind: value.kind === undefined ? '' : requireString(value.kind, 'last_action.kind'),
808
+ detail: value.detail === undefined ? '' : requireString(value.detail, 'last_action.detail'),
809
+ };
810
+ }
811
+
812
+ function requireState(value) {
813
+ if (value === undefined) throw bad(`state 必填,可选值:${DECLARED_STATES.join(' | ')}`);
814
+ if (typeof value !== 'string') throw bad(`state 必须是字符串,收到 ${argumentType(value)}`);
815
+ const state = value.trim().toLowerCase();
816
+ if (!DECLARED_STATES.includes(state)) {
817
+ throw bad(`state 无效:${JSON.stringify(value)},可选值:${DECLARED_STATES.join(' | ')}`);
818
+ }
819
+ return state;
820
+ }
821
+
822
+ /** Keep a goal to GOAL_MAX_CHARS code points; the result says it was cut. */
823
+ function fitGoal(goal) {
824
+ const chars = Array.from(goal);
825
+ if (chars.length <= GOAL_MAX_CHARS) {
826
+ return { value: goal, truncated: false, chars: chars.length };
827
+ }
828
+ return {
829
+ value: chars.slice(0, GOAL_MAX_CHARS).join(''),
830
+ truncated: true,
831
+ chars: chars.length,
832
+ };
833
+ }
834
+
835
+ /** Trim a string to `max` code points; report whether anything was cut. */
836
+ function clipChars(value, max) {
837
+ const chars = Array.from(value);
838
+ if (chars.length <= max) return { value, clipped: false, chars: chars.length };
839
+ return { value: chars.slice(0, max).join(''), clipped: true, chars: chars.length };
840
+ }
841
+
842
+ /**
843
+ * Bound a queued list: at most MAX_QUEUED_ITEMS entries, each at most
844
+ * MAX_QUEUED_ITEM_CHARS code points. The drop counts are reported, never silent.
845
+ */
846
+ function boundQueued(value, fallback) {
847
+ const input = value ?? fallback ?? [];
848
+ const kept = input.slice(0, MAX_QUEUED_ITEMS);
849
+ let clippedItems = 0;
850
+ const items = kept.map((item) => {
851
+ const clip = clipChars(item, MAX_QUEUED_ITEM_CHARS);
852
+ if (clip.clipped) clippedItems += 1;
853
+ return clip.value;
854
+ });
855
+ return {
856
+ value: items,
857
+ input: input.length,
858
+ dropped: Math.max(0, input.length - items.length),
859
+ clippedItems,
860
+ truncated: input.length > items.length || clippedItems > 0,
861
+ };
862
+ }
863
+
864
+ /** Bound last_action.detail; the row still carries a complete, usable action. */
865
+ function boundLastAction(action, now, created, state) {
866
+ const base = action ?? {
867
+ at: isoTime(now),
868
+ kind: created ? 'create' : 'update',
869
+ detail: `state=${state}`,
870
+ };
871
+ const detail = clipChars(base.detail ?? '', LAST_ACTION_DETAIL_MAX_CHARS);
872
+ return {
873
+ value: { at: base.at, kind: base.kind, detail: detail.value },
874
+ truncated: detail.clipped,
875
+ chars: detail.chars,
876
+ };
877
+ }
878
+
879
+ function resolveSessionId(args, config) {
880
+ if (args.sessionId !== undefined) return normalizeSessionId(args.sessionId);
881
+ let fromConfig = typeof config.sessionId === 'string' && config.sessionId.trim() !== ''
882
+ ? config.sessionId
883
+ : null;
884
+ // An explicit `config.sessionId` is a caller decision (e.g. a scheduled job
885
+ // acting on a named row); it must not be registered as "this writer's own".
886
+ const explicitConfig = fromConfig != null;
887
+ if (fromConfig == null && typeof config.currentSessionId === 'function') {
888
+ try {
889
+ // Pass `exec` through: the resolver uses the explicit caller Agent from
890
+ // the tool execution, falling back to the initiator chain.
891
+ const current = config.currentSessionId(config.exec);
892
+ if (typeof current === 'string' && current.trim() !== '') fromConfig = current;
893
+ } catch {
894
+ fromConfig = null;
895
+ }
896
+ }
897
+ if (fromConfig == null) {
898
+ throw bad('无法确定当前会话 id:传 sessionId,或让宿主提供当前会话 id');
899
+ }
900
+ const id = normalizeSessionId(fromConfig, 'currentSessionId');
901
+ // Auto-bind: a row written without an explicit id belongs to the caller, so
902
+ // the heartbeat manager may keep refreshing this id later. Best effort — a
903
+ // failed hook must never fail the write that already succeeded.
904
+ if (!explicitConfig && typeof config.onAutoSessionId === 'function') {
905
+ try {
906
+ config.onAutoSessionId(id);
907
+ } catch {
908
+ /* binding is optional */
909
+ }
910
+ }
911
+ return id;
912
+ }
913
+
914
+ // --------------------------------------------------------------------- tools
915
+
916
+ /**
917
+ * A row path must be a regular file or absent. A directory (or a symlink)
918
+ * sitting on the exact path would make every write fail late with a generic
919
+ * rename error, so refuse it up front and name the obstacle.
920
+ */
921
+ function assertRowSlotWritable(file) {
922
+ let stat;
923
+ try {
924
+ stat = fs.lstatSync(file);
925
+ } catch (error) {
926
+ if (error?.code === 'ENOENT') return;
927
+ throw memoryError(
928
+ LIVE_CODES.WRITE,
929
+ `无法检查活体记录位置:${file}(${error?.code ?? error?.message})`,
930
+ error,
931
+ );
932
+ }
933
+ if (stat.isSymbolicLink()) {
934
+ throw memoryError(
935
+ LIVE_CODES.DIR_PLACEHOLDER,
936
+ `活体记录位置是符号链接,拒绝写入:${file} — 删除链接后重试`,
937
+ );
938
+ }
939
+ if (!stat.isFile()) {
940
+ throw memoryError(
941
+ LIVE_CODES.DIR_PLACEHOLDER,
942
+ `活体记录位置被${stat.isDirectory() ? '目录' : '非普通文件'}占用:${file}`
943
+ + ' — 先移走它(空目录可交给 session_live_prune 清理),再写入',
944
+ );
945
+ }
946
+ }
947
+
948
+ /**
949
+ * session_live_update — write or patch this session's row.
950
+ * Omitted optional fields keep their previous value, except `blocked_on`,
951
+ * which is cleared whenever the new state is not `blocked`.
952
+ */
953
+ export function liveUpdate(args = {}, config = {}) {
954
+ assertEntry('session_live_update', args, config);
955
+ const root = memoryRootFromConfig(config);
956
+ const sessionId = resolveSessionId(args, config);
957
+ const state = requireState(args.state);
958
+ const turn = optionalInteger(args.turn, 'turn', { min: 0 });
959
+ const goalInput = optionalString(args.goal, 'goal');
960
+ const blockedInput = optionalString(args.blocked_on, 'blocked_on');
961
+ const queuedInput = optionalQueued(args.queued);
962
+ const ttlInput = optionalInteger(args.ttlMs, 'ttlMs', { min: MIN_TTL_MS, max: MAX_TTL_MS });
963
+ const now = nowMs(config);
964
+ const lastActionInput = optionalLastAction(args.last_action, now);
965
+ const fit = goalInput === undefined ? null : fitGoal(goalInput);
966
+
967
+ const file = liveFile(root, sessionId);
968
+ assertRowSlotWritable(file);
969
+ const prior = readPrior(file, sessionId);
970
+ const base = prior.record;
971
+ const created = base == null;
972
+ const goal = fit ? fit.value : (base?.goal ?? '');
973
+ // R3: `goalUpdatedAt` is the goal's own clock. Only a write that supplies a
974
+ // goal stamps it; patches and heartbeat touches keep the previous value, so
975
+ // "目标 30 分钟没更新" can be told apart from "心跳 5 秒前刚动过".
976
+ const goalUpdatedAt = goalInput !== undefined
977
+ ? isoTime(now)
978
+ : (base?.goalUpdatedAt ?? '');
979
+ // blocked_on describes a blocked session; anything else clears it, so a
980
+ // running row cannot keep advertising an obstacle nobody is waiting on.
981
+ const priorBlockedOn = base?.blocked_on ?? '';
982
+ const incomingBlockedOn = blockedInput !== undefined ? blockedInput : priorBlockedOn;
983
+ const blockedOn = state === 'blocked' ? incomingBlockedOn : '';
984
+ const blockedOnCleared = state !== 'blocked' && incomingBlockedOn.length > 0;
985
+ // Both patches are bounded so one row cannot grow into a backlog dump.
986
+ const queued = boundQueued(queuedInput, base?.queued ?? []);
987
+ const lastAction = boundLastAction(lastActionInput ?? base?.last_action, now, created, state);
988
+ const record = {
989
+ schemaVersion: LIVE_SCHEMA_VERSION,
990
+ sessionId,
991
+ pid: process.pid,
992
+ host: currentHostname(),
993
+ startedAt: base?.startedAt ?? isoTime(now),
994
+ updatedAt: isoTime(now),
995
+ heartbeatAt: isoTime(now),
996
+ ttlMs: ttlInput ?? base?.ttlMs ?? DEFAULT_TTL_MS,
997
+ state,
998
+ turn: turn ?? base?.turn ?? 0,
999
+ goal,
1000
+ goalUpdatedAt,
1001
+ blocked_on: blockedOn,
1002
+ queued: queued.value,
1003
+ last_action: lastAction.value,
1004
+ };
1005
+
1006
+ const dir = liveDir(root);
1007
+ try {
1008
+ fs.mkdirSync(dir, { recursive: true });
1009
+ } catch (error) {
1010
+ throw memoryError(
1011
+ LIVE_CODES.WRITE,
1012
+ `创建活体目录失败:${dir}(${error?.code ?? error?.message})`,
1013
+ error,
1014
+ );
1015
+ }
1016
+ const text = `${JSON.stringify(record, null, 2)}\n`;
1017
+ const write = writeLiveText(file, text);
1018
+ const entry = liveEntry(record, { file, root, now, hostname: currentHostname() });
1019
+
1020
+ return {
1021
+ ok: true,
1022
+ status: 'written',
1023
+ created,
1024
+ sessionId,
1025
+ file,
1026
+ fileRel: entry.fileRel,
1027
+ sha256: write.sha256,
1028
+ bytes: write.bytes,
1029
+ superseded: write.superseded,
1030
+ state,
1031
+ effectiveState: entry.effectiveState,
1032
+ ttlMs: record.ttlMs,
1033
+ goalTruncated: fit?.truncated === true,
1034
+ goalChars: fit?.chars ?? Array.from(goal).length,
1035
+ goalLimit: GOAL_MAX_CHARS,
1036
+ queuedTruncated: queued.truncated,
1037
+ queuedInput: queued.input,
1038
+ queuedCount: queued.value.length,
1039
+ queuedLimit: MAX_QUEUED_ITEMS,
1040
+ queuedItemLimit: MAX_QUEUED_ITEM_CHARS,
1041
+ lastActionDetailTruncated: lastAction.truncated,
1042
+ lastActionDetailChars: lastAction.chars,
1043
+ lastActionDetailLimit: LAST_ACTION_DETAIL_MAX_CHARS,
1044
+ blockedOnCleared,
1045
+ repairedCorrupt: prior.reason,
1046
+ record,
1047
+ message:
1048
+ `${created ? '已创建' : '已更新'} ${entry.fileRel}:state=${state}, effectiveState=${entry.effectiveState}, ` +
1049
+ `pid=${record.pid}, ttl=${record.ttlMs}ms` +
1050
+ (fit?.truncated ? `;goal 超过 ${GOAL_MAX_CHARS} 字,已截断(原 ${fit.chars} 字)` : '') +
1051
+ (queued.truncated
1052
+ ? `;queued 超过上限(最多 ${MAX_QUEUED_ITEMS} 项、每项 ${MAX_QUEUED_ITEM_CHARS} 字),输入 ${queued.input} 项,保留 ${queued.value.length} 项`
1053
+ : '') +
1054
+ (lastAction.truncated ? `;last_action.detail 超过 ${LAST_ACTION_DETAIL_MAX_CHARS} 字,已截断` : '') +
1055
+ (blockedOnCleared ? ';state 不是 blocked,blocked_on 已清空' : '') +
1056
+ (write.superseded ? ';并发写入中另一份完整记录最后落盘(last-writer-wins)' : '') +
1057
+ (prior.reason ? `;覆盖了损坏的旧记录(${prior.reason})` : ''),
1058
+ };
1059
+ }
1060
+
1061
+ /**
1062
+ * Refresh one *existing* row's liveness stamps — the write behind auto-heartbeat.
1063
+ *
1064
+ * This is deliberately narrower than `liveUpdate`:
1065
+ * - it never creates a row (`status:'absent'` instead), so merely running a
1066
+ * longlive tool does not fabricate a session row;
1067
+ * - it never repairs/lists corrupt rows (`status:'corrupt'`, bytes untouched);
1068
+ * - it preserves `state`, `goal`, `goalUpdatedAt`, `blocked_on`, `queued`,
1069
+ * `turn`, `startedAt` and `ttlMs`: heartbeat says "this writer is still
1070
+ * here", not "state changed". In particular the goal's own clock must not
1071
+ * move, or the board could no longer tell a stale goal from a live one;
1072
+ * - `lastAction:false` keeps `last_action` exactly as-is (the timer tick);
1073
+ * otherwise only the action stamp is replaced, bounded like every other write.
1074
+ */
1075
+ export function liveTouch(sessionId, config = {}) {
1076
+ const root = memoryRootFromConfig(config);
1077
+ const id = normalizeSessionId(sessionId);
1078
+ const file = liveFile(root, id);
1079
+ assertRowSlotWritable(file);
1080
+ const prior = readPrior(file, id);
1081
+ if (prior.record == null) {
1082
+ if (prior.reason == null) {
1083
+ return {
1084
+ ok: false,
1085
+ status: 'absent',
1086
+ sessionId: id,
1087
+ file,
1088
+ message: `没有 ${id} 的活体记录,未新建(自动心跳只刷新已存在的行)`,
1089
+ };
1090
+ }
1091
+ return {
1092
+ ok: false,
1093
+ status: 'corrupt',
1094
+ sessionId: id,
1095
+ file,
1096
+ reason: prior.reason,
1097
+ message: `活体记录无法解析,未覆盖:${prior.reason}`,
1098
+ };
1099
+ }
1100
+
1101
+ const now = nowMs(config);
1102
+ const base = prior.record;
1103
+ const keepAction = config.lastAction === false;
1104
+ const action = keepAction
1105
+ ? base.last_action
1106
+ : {
1107
+ at: isoTime(now),
1108
+ kind: typeof config.kind === 'string' && config.kind.trim() !== ''
1109
+ ? config.kind.trim()
1110
+ : 'heartbeat',
1111
+ detail: clipChars(
1112
+ typeof config.detail === 'string' ? config.detail : '',
1113
+ LAST_ACTION_DETAIL_MAX_CHARS,
1114
+ ).value,
1115
+ };
1116
+ const record = {
1117
+ ...base,
1118
+ pid: process.pid,
1119
+ host: currentHostname(),
1120
+ updatedAt: isoTime(now),
1121
+ heartbeatAt: isoTime(now),
1122
+ last_action: action,
1123
+ };
1124
+ const text = `${JSON.stringify(record, null, 2)}\n`;
1125
+ const write = writeLiveText(file, text);
1126
+ const entry = liveEntry(record, { file, root, now, hostname: currentHostname() });
1127
+ return {
1128
+ ok: true,
1129
+ status: 'touched',
1130
+ sessionId: id,
1131
+ file,
1132
+ fileRel: entry.fileRel,
1133
+ sha256: write.sha256,
1134
+ bytes: write.bytes,
1135
+ superseded: write.superseded,
1136
+ state: record.state,
1137
+ effectiveState: entry.effectiveState,
1138
+ record,
1139
+ message: `已刷新 ${entry.fileRel}:heartbeatAt=${record.heartbeatAt}, pid=${record.pid}, state=${record.state}`,
1140
+ };
1141
+ }
1142
+
1143
+ /** session_live_list — every row with its computed effectiveState. */
1144
+ export function liveList(args = {}, config = {}) {
1145
+ assertEntry('session_live_list', args, config);
1146
+ const root = memoryRootFromConfig(config);
1147
+ const includeDead = optionalBoolean(args.includeDead, 'includeDead', false);
1148
+ const now = nowMs(config);
1149
+ const hostname = currentHostname();
1150
+ const { dir, entries } = scanEntries(root, { now, hostname });
1151
+ const counts = countStates(entries);
1152
+ const deadEntries = entries.filter((entry) => entry.effectiveState === 'dead');
1153
+ const visible = includeDead
1154
+ ? entries
1155
+ : entries.filter((entry) => entry.effectiveState !== 'dead');
1156
+ return {
1157
+ ok: true,
1158
+ status: 'listed',
1159
+ root,
1160
+ dir,
1161
+ includeDead,
1162
+ scanned: entries.length,
1163
+ count: visible.length,
1164
+ hiddenDead: deadEntries.length,
1165
+ counts,
1166
+ entries: visible,
1167
+ message:
1168
+ `活体表:${visible.length} 条` +
1169
+ (includeDead ? '' : `(隐藏 dead ${deadEntries.length} 条)`) +
1170
+ `;running ${counts.running}, idle ${counts.idle}, waiting ${counts.waiting}, ` +
1171
+ `blocked ${counts.blocked}, stale ${counts.stale}, dead ${counts.dead}, corrupt ${counts.corrupt}`,
1172
+ };
1173
+ }
1174
+
1175
+ /** session_live_get — one row by id, same computed state as the list. */
1176
+ export function liveGet(args = {}, config = {}) {
1177
+ assertEntry('session_live_get', args, config);
1178
+ const root = memoryRootFromConfig(config);
1179
+ const sessionId = normalizeSessionId(args.sessionId);
1180
+ // NTFS maps S-ALI / s-ali / S-Ali to the same file, so a read through an
1181
+ // alias cannot tell the caller which session it actually got. Writers
1182
+ // normalise silently; readers must name the canonical id.
1183
+ if (args.sessionId !== sessionId) {
1184
+ const error = memoryError(
1185
+ LIVE_CODES.NOT_CANONICAL,
1186
+ `sessionId 不是规范形式:收到 ${JSON.stringify(args.sessionId)},应为 ${JSON.stringify(sessionId)}`
1187
+ + '(NTFS 上大小写/空白别名指向同一文件)',
1188
+ );
1189
+ error.canonical = sessionId;
1190
+ throw error;
1191
+ }
1192
+ const now = nowMs(config);
1193
+ const hostname = currentHostname();
1194
+ const file = liveFile(root, sessionId);
1195
+ // A symlinked row could be retargeted between the realpath check and the
1196
+ // read. liveGet is a lookup, not a follower: refuse the link itself.
1197
+ let stat;
1198
+ try {
1199
+ stat = fs.lstatSync(file);
1200
+ } catch (error) {
1201
+ if (error?.code === 'ENOENT') {
1202
+ return {
1203
+ ok: false,
1204
+ status: 'absent',
1205
+ found: false,
1206
+ sessionId,
1207
+ file,
1208
+ fileRel: relativePath(root, file),
1209
+ message: `没有 ${sessionId} 的活体记录`,
1210
+ };
1211
+ }
1212
+ throw memoryError(
1213
+ LIVE_CODES.CORRUPT,
1214
+ `读取活体记录失败:${file}(${error?.code ?? error?.message})`,
1215
+ error,
1216
+ );
1217
+ }
1218
+ if (stat.isSymbolicLink()) {
1219
+ throw memoryError(LIVE_CODES.CORRUPT, `拒绝跟随符号链接的活体记录:${file}`);
1220
+ }
1221
+ if (!stat.isFile()) {
1222
+ throw memoryError(LIVE_CODES.CORRUPT, `活体记录不是普通文件:${file}`);
1223
+ }
1224
+ let text;
1225
+ try {
1226
+ text = fs.readFileSync(file, 'utf8');
1227
+ } catch (error) {
1228
+ throw memoryError(
1229
+ LIVE_CODES.CORRUPT,
1230
+ `读取活体记录失败:${file}(${error?.code ?? error?.message})`,
1231
+ error,
1232
+ );
1233
+ }
1234
+ const decoded = decodeRecord(text, sessionId);
1235
+ if (!decoded.ok) {
1236
+ throw memoryError(LIVE_CODES.CORRUPT, `活体记录损坏:${file} — ${decoded.reason}`);
1237
+ }
1238
+ const live = liveEntry(decoded.record, { file, root, now, hostname });
1239
+ return {
1240
+ ok: true,
1241
+ status: 'ok',
1242
+ found: true,
1243
+ sessionId,
1244
+ file,
1245
+ fileRel: live.fileRel,
1246
+ live,
1247
+ message: `${sessionId}: ${live.effectiveState}`,
1248
+ };
1249
+ }
1250
+
1251
+ /**
1252
+ * Non-row clutter in the live directory: orphan tmp files left by a SIGKILLed
1253
+ * writer, empty directory placeholders that block a session id, and symlinks
1254
+ * (reported, never followed or deleted).
1255
+ */
1256
+ function scanPruneExtras(root, dir, now) {
1257
+ let dirents;
1258
+ try {
1259
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
1260
+ } catch (error) {
1261
+ if (error?.code === 'ENOENT') return [];
1262
+ throw memoryError(
1263
+ LIVE_CODES.CORRUPT,
1264
+ `读不到活体目录:${dir}(${error?.code ?? error?.message})`,
1265
+ error,
1266
+ );
1267
+ }
1268
+ const extras = [];
1269
+ for (const dirent of dirents) {
1270
+ const file = path.join(dir, dirent.name);
1271
+ const fileRel = relativePath(root, file);
1272
+ if (dirent.isSymbolicLink()) {
1273
+ extras.push({
1274
+ kind: 'symlink',
1275
+ file,
1276
+ fileRel,
1277
+ action: 'report',
1278
+ reason: '符号链接:不跟随、不自动删除',
1279
+ });
1280
+ continue;
1281
+ }
1282
+ if (dirent.isDirectory()) {
1283
+ let empty = false;
1284
+ try {
1285
+ empty = fs.readdirSync(file).length === 0;
1286
+ } catch {
1287
+ empty = false;
1288
+ }
1289
+ extras.push({
1290
+ kind: 'directory',
1291
+ file,
1292
+ fileRel,
1293
+ empty,
1294
+ action: empty ? 'delete' : 'report',
1295
+ reason: empty
1296
+ ? '空目录占位:可删除'
1297
+ : '非空目录占位:只报告,不递归删除',
1298
+ });
1299
+ continue;
1300
+ }
1301
+ if (!dirent.name.includes('.tmp-')) continue;
1302
+ let ageMs = null;
1303
+ try {
1304
+ ageMs = now - fs.lstatSync(file).mtimeMs;
1305
+ } catch {
1306
+ ageMs = null;
1307
+ }
1308
+ const old = ageMs != null && ageMs > TMP_MAX_AGE_MS;
1309
+ extras.push({
1310
+ kind: 'tmp',
1311
+ file,
1312
+ fileRel,
1313
+ ageMs,
1314
+ action: old ? 'delete' : 'report',
1315
+ reason: old
1316
+ ? `遗留 tmp 文件超过 ${Math.round(TMP_MAX_AGE_MS / 60000)} 分钟,可删除`
1317
+ : 'tmp 文件仍新:可能属于正在写入的进程,保留',
1318
+ });
1319
+ }
1320
+ return extras;
1321
+ }
1322
+
1323
+ /**
1324
+ * session_live_prune — delete still-dead/corrupt rows whose bytes did not
1325
+ * change, plus old orphan tmp files and empty directory placeholders.
1326
+ * Dry-run unless confirm:"PRUNE"; dryRun:true forces a preview even then.
1327
+ */
1328
+ export function livePrune(args = {}, config = {}) {
1329
+ assertEntry('session_live_prune', args, config);
1330
+ const root = memoryRootFromConfig(config);
1331
+ const dryRunFlag = args.dryRun === undefined ? undefined : requireBoolean(args.dryRun, 'dryRun');
1332
+ const confirm = args.confirm === undefined ? undefined : requireString(args.confirm, 'confirm');
1333
+ const confirmed = confirm === LIVE_CONFIRM;
1334
+ if (dryRunFlag === false && !confirmed) {
1335
+ throw memoryError(
1336
+ LIVE_CODES.CONFIRM_REQUIRED,
1337
+ `真正清理需要 confirm:"${LIVE_CONFIRM}";当前 confirm=${JSON.stringify(confirm)}`,
1338
+ );
1339
+ }
1340
+ const real = confirmed && dryRunFlag !== true;
1341
+ const now = nowMs(config);
1342
+ const hostname = currentHostname();
1343
+ const { dir, entries, hashes } = scanEntries(root, { now, hostname });
1344
+ const extras = scanPruneExtras(root, dir, now);
1345
+
1346
+ // Legal row candidates: a dead row with a confirmed same host, or a corrupt
1347
+ // row that does not carry another machine's host stamp. A corrupt row with a
1348
+ // remote host hint is protected: its bytes still may belong to a live remote
1349
+ // session, and corruptness alone is not proof of abandonment.
1350
+ // Each candidate carries the exact byte hash seen while scanning and the
1351
+ // preservation fields (blocked_on / queued / startedAt) so a delete decision
1352
+ // never silently loses them.
1353
+ const rowCandidate = (entry) => ({
1354
+ sessionId: entry.sessionId,
1355
+ effectiveState: entry.effectiveState,
1356
+ host: entry.host,
1357
+ pid: entry.pid,
1358
+ file: entry.file,
1359
+ fileRel: entry.fileRel,
1360
+ sha256: hashes.get(entry.file) ?? null,
1361
+ blocked_on: entry.blocked_on ?? '',
1362
+ queued: Array.isArray(entry.queued) ? entry.queued : [],
1363
+ startedAt: entry.startedAt ?? null,
1364
+ goal: entry.goal ?? '',
1365
+ reason: entry.effectiveState === 'corrupt'
1366
+ ? `corrupt:${entry.corruptReason}`
1367
+ : `dead:同 host 且 pid ${entry.pid} 不存在`,
1368
+ });
1369
+ const candidates = entries
1370
+ .filter((entry) => {
1371
+ if (entry.effectiveState === 'corrupt') return entry.sameHost !== false;
1372
+ if (entry.effectiveState === 'dead') return entry.sameHost === true;
1373
+ return false;
1374
+ })
1375
+ .map(rowCandidate);
1376
+
1377
+ // blocked_on is never dropped silently: such a row is skipped, not deleted,
1378
+ // and the skip is visible in the result.
1379
+ const protectedRows = candidates.filter((candidate) => candidate.blocked_on !== '');
1380
+ const deletableRows = candidates.filter((candidate) => candidate.blocked_on === '');
1381
+ const remoteCorruptSkips = entries
1382
+ .filter((entry) => entry.effectiveState === 'corrupt' && entry.sameHost === false)
1383
+ .map((entry) => ({
1384
+ ...rowCandidate(entry),
1385
+ reason: `corrupt 行带远端 host ${entry.host}:跨 host 不可判定,保留`,
1386
+ }));
1387
+ const wouldDelete = [
1388
+ ...deletableRows.map((candidate) => ({
1389
+ kind: 'row', sessionId: candidate.sessionId, file: candidate.file, fileRel: candidate.fileRel,
1390
+ })),
1391
+ ...extras
1392
+ .filter((extra) => extra.action === 'delete')
1393
+ .map((extra) => ({ kind: extra.kind, file: extra.file, fileRel: extra.fileRel })),
1394
+ ];
1395
+
1396
+ if (!real) {
1397
+ const candidateIds = new Set(candidates.map((candidate) => candidate.sessionId));
1398
+ return {
1399
+ ok: true,
1400
+ status: 'dry-run',
1401
+ dryRun: true,
1402
+ confirmRequired: LIVE_CONFIRM,
1403
+ root,
1404
+ dir,
1405
+ scanned: entries.length,
1406
+ candidates,
1407
+ wouldDelete,
1408
+ deleted: [],
1409
+ failed: [],
1410
+ tombstoned: [],
1411
+ skipped: [
1412
+ ...protectedRows.map((candidate) => ({
1413
+ ...candidate,
1414
+ reason: 'blocked_on 非空:自动删除会静默丢弃阻塞信息,保留',
1415
+ })),
1416
+ ...remoteCorruptSkips,
1417
+ ],
1418
+ placeholders: extras.filter((extra) => extra.kind !== 'tmp'),
1419
+ tmpFiles: extras.filter((extra) => extra.kind === 'tmp'),
1420
+ kept: entries.filter((entry) => !candidateIds.has(entry.sessionId)).map(entrySummary),
1421
+ message:
1422
+ `dry-run:扫描 ${entries.length} 条,可清理 ${wouldDelete.length} 项(dead/本机 corrupt 行 + 陈旧 tmp/空目录);` +
1423
+ (protectedRows.length ? `blocked_on 保护 ${protectedRows.length} 条;` : '') +
1424
+ (remoteCorruptSkips.length ? `远端 host 的 corrupt 行保护 ${remoteCorruptSkips.length} 条;` : '') +
1425
+ `加 confirm:"${LIVE_CONFIRM}" 才真删` +
1426
+ (confirmed ? '(dryRun:true 是显式预览,不删除)' : ''),
1427
+ };
1428
+ }
1429
+
1430
+ const deleted = [];
1431
+ const failed = [];
1432
+ const tombstoned = [];
1433
+ const skipped = [
1434
+ ...protectedRows.map((candidate) => ({
1435
+ ...candidate,
1436
+ reason: 'blocked_on 非空:自动删除会静默丢弃阻塞信息,保留',
1437
+ })),
1438
+ ...remoteCorruptSkips,
1439
+ ];
1440
+
1441
+ for (const candidate of deletableRows) {
1442
+ // Re-read and re-judge immediately before unlinking. A row that changed
1443
+ // since it became a candidate is never removed on stale evidence.
1444
+ let text;
1445
+ try {
1446
+ text = fs.readFileSync(candidate.file, 'utf8');
1447
+ } catch (error) {
1448
+ if (error?.code === 'ENOENT') {
1449
+ skipped.push({ ...candidate, reason: '删除前记录已不存在' });
1450
+ } else {
1451
+ failed.push({
1452
+ ...candidate,
1453
+ code: error?.code ?? LIVE_CODES.WRITE,
1454
+ error: String(error?.message ?? error),
1455
+ });
1456
+ }
1457
+ continue;
1458
+ }
1459
+ if (candidate.sha256 != null && sha256Text(text) !== candidate.sha256) {
1460
+ skipped.push({ ...candidate, reason: '删除前内容已变化,重新判定后保留' });
1461
+ continue;
1462
+ }
1463
+ const decoded = decodeRecord(text, candidate.sessionId);
1464
+ if (decoded.ok) {
1465
+ const current = liveEntry(decoded.record, {
1466
+ file: candidate.file, root, now, hostname,
1467
+ });
1468
+ if ((current.blocked_on ?? '') !== '') {
1469
+ skipped.push({ ...candidate, reason: '删除前出现 blocked_on,保留' });
1470
+ continue;
1471
+ }
1472
+ const stillGone = current.effectiveState === 'corrupt'
1473
+ || (current.effectiveState === 'dead' && current.sameHost === true);
1474
+ if (!stillGone) {
1475
+ skipped.push({ ...candidate, reason: `重新判定为 ${current.effectiveState},不再删除` });
1476
+ continue;
1477
+ }
1478
+ } else {
1479
+ // Still corrupt: re-extract the host stamp from the bytes read right now.
1480
+ // Evidence that changed from "host unknown" to "another host" protects it.
1481
+ const hint = hostHintFromText(text);
1482
+ if (hint != null && !hostsMatch(hint, hostname)) {
1483
+ skipped.push({ ...candidate, reason: `删除前重读发现远端 host ${hint},保留` });
1484
+ continue;
1485
+ }
1486
+ }
1487
+ try {
1488
+ // Archive first: a crash between tombstone and unlink leaves a replayable
1489
+ // audit row; a crash before tombstone leaves the row untouched.
1490
+ try {
1491
+ tombstoned.push(...appendLiveTombstones(root, [{ ...candidate, sha256: sha256Text(text) }], now));
1492
+ } catch { /* the row is still recoverable from its file */ }
1493
+ fs.unlinkSync(candidate.file);
1494
+ deleted.push(candidate);
1495
+ } catch (error) {
1496
+ if (error?.code === 'ENOENT') {
1497
+ skipped.push({ ...candidate, reason: '删除前记录已不存在' });
1498
+ } else {
1499
+ failed.push({
1500
+ ...candidate,
1501
+ code: error?.code ?? LIVE_CODES.WRITE,
1502
+ error: String(error?.message ?? error),
1503
+ });
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ // Extras are re-checked at delete time: only still-old tmp files and still-
1509
+ // empty directories are removed. A non-empty directory is only reported.
1510
+ const placeholders = [];
1511
+ const tmpFiles = [];
1512
+ const extrasDeleted = [];
1513
+ for (const extra of extras) {
1514
+ if (extra.kind === 'tmp') {
1515
+ if (extra.action !== 'delete') {
1516
+ tmpFiles.push(extra);
1517
+ continue;
1518
+ }
1519
+ try {
1520
+ const ageMs = now - fs.lstatSync(extra.file).mtimeMs;
1521
+ if (!(ageMs > TMP_MAX_AGE_MS)) {
1522
+ tmpFiles.push({ ...extra, action: 'report', reason: 'tmp 文件仍新,保留' });
1523
+ continue;
1524
+ }
1525
+ fs.unlinkSync(extra.file);
1526
+ tmpFiles.push({ ...extra, action: 'deleted' });
1527
+ extrasDeleted.push({ ...extra, action: 'deleted' });
1528
+ } catch (error) {
1529
+ if (error?.code === 'ENOENT') {
1530
+ tmpFiles.push({ ...extra, action: 'gone' });
1531
+ } else {
1532
+ tmpFiles.push({ ...extra, action: 'report', reason: `删除失败:${error?.code ?? error?.message}` });
1533
+ }
1534
+ }
1535
+ continue;
1536
+ }
1537
+ if (extra.kind === 'symlink') {
1538
+ placeholders.push(extra);
1539
+ continue;
1540
+ }
1541
+ // directory
1542
+ if (extra.action !== 'delete') {
1543
+ placeholders.push(extra);
1544
+ continue;
1545
+ }
1546
+ try {
1547
+ if (fs.readdirSync(extra.file).length !== 0) {
1548
+ placeholders.push({ ...extra, action: 'report', reason: '删除时目录已非空,只报告' });
1549
+ continue;
1550
+ }
1551
+ fs.rmdirSync(extra.file);
1552
+ placeholders.push({ ...extra, action: 'deleted' });
1553
+ extrasDeleted.push({ ...extra, action: 'deleted' });
1554
+ } catch (error) {
1555
+ if (error?.code === 'ENOENT') {
1556
+ placeholders.push({ ...extra, action: 'gone' });
1557
+ } else {
1558
+ placeholders.push({ ...extra, action: 'report', reason: `删除失败:${error?.code ?? error?.message}` });
1559
+ }
1560
+ }
1561
+ }
1562
+
1563
+ const goneIds = new Set([...deleted, ...failed].map((item) => item.sessionId));
1564
+ return {
1565
+ ok: true,
1566
+ status: 'pruned',
1567
+ dryRun: false,
1568
+ confirmRequired: LIVE_CONFIRM,
1569
+ root,
1570
+ dir,
1571
+ scanned: entries.length,
1572
+ candidates,
1573
+ wouldDelete: [],
1574
+ deleted,
1575
+ failed,
1576
+ tombstoned,
1577
+ skipped,
1578
+ placeholders,
1579
+ tmpFiles,
1580
+ kept: entries.filter((entry) => !goneIds.has(entry.sessionId)).map(entrySummary),
1581
+ message:
1582
+ `已清理 ${deleted.length} 条(仍 dead/corrupt 且字节未变)` +
1583
+ (extrasDeleted.length ? `,另清理 ${extrasDeleted.length} 项陈旧 tmp/空目录` : '') +
1584
+ (skipped.length ? `,跳过 ${skipped.length} 条(内容变化、blocked_on 或远端 host)` : '') +
1585
+ (failed.length ? `,失败 ${failed.length} 条` : '') +
1586
+ `;删除前内容变化、blocked_on 非空、跨 host 的 dead/corrupt 行与 pid 仍存活的记录一律未动`,
1587
+ };
1588
+ }
1589
+
1590
+ /** Read the previous row for a patch; a corrupt prior is reported, not fatal. */
1591
+ function readPrior(file, sessionId) {
1592
+ let text;
1593
+ try {
1594
+ text = fs.readFileSync(file, 'utf8');
1595
+ } catch (error) {
1596
+ if (error?.code === 'ENOENT') return { record: null, reason: null };
1597
+ return { record: null, reason: `读取失败:${error?.code ?? error?.message}` };
1598
+ }
1599
+ const decoded = decodeRecord(text, sessionId);
1600
+ return decoded.ok
1601
+ ? { record: decoded.record, reason: null }
1602
+ : { record: null, reason: decoded.reason };
1603
+ }