@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,1446 @@
1
+ // Cross-session message bus — prototype (dependency-free, Node >= 18).
2
+ //
3
+ // Storage layout (one bus root, shared by every session of one profile):
4
+ //
5
+ // <root>/
6
+ // aliases.json { "reviewer": "session-bob" }
7
+ // roles.json { "team": ["session-bob", "session-carol"] }
8
+ // writer.lock single-writer lease for identity/handover files
9
+ // inbox/<session-id>/
10
+ // <message-id>.json pending envelope; immutable after creation
11
+ // acked/<message-id>.json acknowledged (kept for duplicate-ack replay)
12
+ // dead/<message-id>.*.json corrupt / foreign-host messages, quarantined
13
+ //
14
+ // Delivery is at-least-once: poll() never removes a message, ack() does. A
15
+ // sender that supplies dedupKey gets a deterministic id, so a retry after a
16
+ // timeout cannot create a second copy. TTL is evaluated on the receiver side.
17
+ //
18
+ // All operations stay below the realpath of the bus root; symlinked
19
+ // directories and message files are rejected, and ids are limited to the same
20
+ // charset the longlive live registry accepts (lowercased).
21
+
22
+ import fs from 'node:fs';
23
+ import os from 'node:os';
24
+ import path from 'node:path';
25
+ import crypto from 'node:crypto';
26
+
27
+ export const BUS_SCHEMA_VERSION = 1;
28
+ export const KINDS = Object.freeze(['note', 'task', 'reply', 'handover', 'control']);
29
+ export const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
30
+ export const MAX_TTL_MS = 7 * 24 * 60 * 60 * 1000;
31
+ export const DEFAULT_MAX_BODY_CHARS = 8192;
32
+ export const DEFAULT_MAX_PENDING = 1000;
33
+ // Writer lease TTL: 1_800_000 ms = 30 minutes. This constant is the single
34
+ // source of truth for the default; DESIGN.md §13.1 and WIRING.md §8 quote the
35
+ // same value in ms, and a test asserts the three stay in sync.
36
+ export const DEFAULT_WRITER_TTL_MS = 1_800_000;
37
+ export const WRITER_SCHEMA_VERSION = 2;
38
+ export const DEFAULT_LIMIT = 100;
39
+ export const MAX_LIMIT = 1000;
40
+ // A sender whose clock is ahead by more than this is refused (E_BAD_CLOCK), and
41
+ // a receiver quarantines any envelope whose ts is this far in its own future.
42
+ // 300_000 ms = 5 minutes, enough for ordinary NTP slew, small enough that a
43
+ // poisoned cursor cannot hide real traffic for long.
44
+ export const DEFAULT_MAX_CLOCK_SKEW_MS = 300_000;
45
+
46
+ // The commit lock serializes writer.lock readers/writers across processes. It
47
+ // only ever exists for the duration of one synchronous critical section; a
48
+ // crashed process leaves it behind and the next caller steals it after
49
+ // COMMIT_LOCK_STALE_MS (or immediately when the recorded pid is provably dead).
50
+ const COMMIT_LOCK_STALE_MS = 30_000;
51
+ const COMMIT_LOCK_TIMEOUT_MS = 15_000;
52
+ // Same-process reentrancy: fencedWrite holds the commit lock while it calls a
53
+ // test hook / JSON.stringify, and a hook may synchronously call claimWriter.
54
+ // JavaScript is single-threaded, so an inner call cannot interleave with the
55
+ // outer critical section; skipping the file lock avoids a self-deadlock while
56
+ // the outer revalidation still catches a takeover.
57
+ const commitLocksHeldByProcess = new Set();
58
+
59
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
60
+ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
61
+ const MESSAGE_ID_RE = /^m-[a-z0-9]+(?:-[a-z0-9]+)*$/;
62
+ const RESERVED_BASENAMES = new Set([
63
+ 'con', 'prn', 'aux', 'nul',
64
+ 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
65
+ 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9',
66
+ ]);
67
+
68
+ let localSeq = 0;
69
+
70
+ function busError(code, message) {
71
+ const error = new Error(message);
72
+ error.code = code;
73
+ // Marks an intentional bus-level error (as opposed to an fs error whose code
74
+ // also happens to start with "E"). Commit paths rethrow only these.
75
+ error.busError = true;
76
+ return error;
77
+ }
78
+
79
+ function isPlainObject(value) {
80
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
81
+ }
82
+
83
+ /**
84
+ * Ack policy for the wiring layer.
85
+ *
86
+ * Host `turn/end` events are appended from a `finally` block, so they also fire
87
+ * for failed turns (`reason.kind === 'error' | 'aborted'`). The bus has no
88
+ * un-ack / requeue, so acking there would consume a message the model never got
89
+ * to process. Only a turn whose reason is exactly `completed` may ack; a
90
+ * missing or unknown reason fails closed and the message is redelivered on the
91
+ * next `agent/pre-step`.
92
+ *
93
+ * Call this only inside the `turn/end` branch of `session/event` (WIRING §5.2).
94
+ */
95
+ export function shouldAckOnTurnEnd(event) {
96
+ if (!isPlainObject(event) || event.type !== 'turn/end') return false;
97
+ const reason = isPlainObject(event.data) ? event.data.reason : undefined;
98
+ return isPlainObject(reason) && reason.kind === 'completed';
99
+ }
100
+
101
+ /**
102
+ * Merge the ids this pre-step injected with ids left over from an earlier
103
+ * turn's failed ack.
104
+ *
105
+ * WIRING §3.2 and §5.1: `record.pendingAckIds` is a retry queue, not a
106
+ * "messages shown this turn" register. Overwriting it on the next pre-step
107
+ * would silently drop ids whose turn/end ack failed, and those messages would
108
+ * be redelivered forever (bus ack has no expiry other than TTL). The union
109
+ * keeps the old ids first, preserves order, and drops duplicates so repeated
110
+ * `ack(id)` calls stay idempotent.
111
+ *
112
+ * @param {unknown} previous pending ids from the last turn
113
+ * @param {unknown} included ids injected into the card just now
114
+ * @returns {string[]}
115
+ */
116
+ export function mergePendingAckIds(previous, included) {
117
+ const merged = [];
118
+ const seen = new Set();
119
+ for (const list of [previous, included]) {
120
+ if (!Array.isArray(list)) continue;
121
+ for (const id of list) {
122
+ if (typeof id !== 'string' || id.length === 0 || seen.has(id)) continue;
123
+ seen.add(id);
124
+ merged.push(id);
125
+ }
126
+ }
127
+ return merged;
128
+ }
129
+
130
+ function codePointLength(value) {
131
+ return Array.from(value).length;
132
+ }
133
+
134
+ function clampInt(value, fallback, min, max) {
135
+ const number = Number(value);
136
+ if (!Number.isFinite(number)) return fallback;
137
+ return Math.min(max, Math.max(min, Math.floor(number)));
138
+ }
139
+
140
+ function normalizeHost(value) {
141
+ if (typeof value !== 'string') throw busError('E_BAD_HOST', 'host must be a string');
142
+ const host = value.trim();
143
+ if (!host || host.length > 255) throw busError('E_BAD_HOST', 'host must be 1..255 chars');
144
+ if (/[\u0000-\u001f/\\]/.test(host)) throw busError('E_BAD_HOST', 'host contains control chars or path separators');
145
+ return host;
146
+ }
147
+
148
+ export function normalizeSessionId(value, label = 'sessionId') {
149
+ if (typeof value !== 'string') {
150
+ throw busError('E_BAD_SESSION_ID', `${label} must be a string`);
151
+ }
152
+ const id = value.trim();
153
+ if (!id) throw busError('E_BAD_SESSION_ID', `${label} must not be empty`);
154
+ if (id.includes('\u0000')) {
155
+ throw busError('E_PATH_OUTSIDE_ROOT', `${label} must not contain NUL`);
156
+ }
157
+ if (path.isAbsolute(id) || id === '.' || id === '..' || /[\\/]/.test(id)) {
158
+ throw busError('E_PATH_OUTSIDE_ROOT', `${label} must not be a path: ${value}`);
159
+ }
160
+ if (!SESSION_ID_RE.test(id)) {
161
+ throw busError('E_BAD_SESSION_ID', `${label} is not a valid session id: ${value}`);
162
+ }
163
+ const canonical = id.toLowerCase();
164
+ if (canonical.endsWith('.') || canonical.endsWith(' ')) {
165
+ throw busError('E_BAD_SESSION_ID', `${label} must not end with a dot or space`);
166
+ }
167
+ const base = canonical.split('.')[0];
168
+ if (RESERVED_BASENAMES.has(base)) {
169
+ throw busError('E_BAD_SESSION_ID', `${label} is a Windows reserved name: ${value}`);
170
+ }
171
+ return canonical;
172
+ }
173
+
174
+ function normalizeAlias(value) {
175
+ if (typeof value !== 'string') throw busError('E_BAD_ALIAS', 'alias must be a string');
176
+ const alias = value.trim();
177
+ if (!ALIAS_RE.test(alias)) throw busError('E_BAD_ALIAS', `invalid alias: ${value}`);
178
+ return alias.toLowerCase();
179
+ }
180
+
181
+ function newMessageId(now) {
182
+ localSeq = (localSeq + 1) % 0xffffff;
183
+ const time = Math.floor(now).toString(36).padStart(9, '0');
184
+ const seq = localSeq.toString(36).padStart(4, '0');
185
+ const pid = (process.pid % 0xfffffff).toString(36).padStart(6, '0');
186
+ const random = crypto.randomBytes(3).toString('hex');
187
+ return `m-${time}-${seq}-${pid}-${random}`;
188
+ }
189
+
190
+ function dedupMessageId(from, to, dedupKey) {
191
+ const hash = crypto.createHash('sha256').update(`${from}\u0000${to}\u0000${dedupKey}`, 'utf8').digest('hex');
192
+ return `m-${hash.slice(0, 32)}`;
193
+ }
194
+
195
+ function timestampFromMessageId(id) {
196
+ const time = id.split('-')[1] || '';
197
+ if (time.length !== 9) return null;
198
+ const parsed = Number.parseInt(time, 36);
199
+ return Number.isFinite(parsed) ? parsed : null;
200
+ }
201
+
202
+ function resolveRoot(input) {
203
+ if (typeof input !== 'string' || !input.trim()) {
204
+ throw busError('E_ROOT_REQUIRED', 'createBus requires a non-empty root path');
205
+ }
206
+ if (/^\\\\/.test(input.trim())) {
207
+ throw busError('E_UNC_NOT_ALLOWED', 'bus root must be a local path, not a UNC share');
208
+ }
209
+ return path.resolve(input.trim());
210
+ }
211
+
212
+ function isPermissionError(error) {
213
+ return error?.code === 'EACCES' || error?.code === 'EPERM' || error?.code === 'EROFS';
214
+ }
215
+
216
+ function ensureRoot(root) {
217
+ try {
218
+ fs.mkdirSync(root, { recursive: true });
219
+ } catch (error) {
220
+ // m3 (rc.2): a read-only root is a permission problem, not a malformed
221
+ // path. Keep failing hard, but say EPERM so callers can tell it apart.
222
+ if (isPermissionError(error)) {
223
+ throw busError('EPERM', `bus root is not writable: ${root}: ${error.code || error.message}`);
224
+ }
225
+ throw busError('E_BAD_ROOT', `cannot create bus root ${root}: ${error.code || error.message}`);
226
+ }
227
+ let real;
228
+ try {
229
+ real = fs.realpathSync.native(root);
230
+ } catch (error) {
231
+ // A directory that exists but cannot be resolved is usually an ACL/EPERM
232
+ // problem, not a bad path (0.9.0-rc.3: real read-only root diagnostic).
233
+ if (isPermissionError(error)) {
234
+ throw busError('EPERM', `bus root is not readable: ${root}: ${error.code || error.message}`);
235
+ }
236
+ throw busError('E_BAD_ROOT', `cannot resolve bus root ${root}: ${error.code || error.message}`);
237
+ }
238
+ if (/^\\\\/.test(real)) {
239
+ throw busError('E_UNC_NOT_ALLOWED', 'bus root resolves to a UNC share');
240
+ }
241
+ let stat;
242
+ try {
243
+ stat = fs.lstatSync(real);
244
+ } catch (error) {
245
+ if (isPermissionError(error)) {
246
+ throw busError('EPERM', `bus root is not accessible: ${root}: ${error.code || error.message}`);
247
+ }
248
+ throw busError('E_BAD_ROOT', `cannot inspect bus root ${root}: ${error.code || error.message}`);
249
+ }
250
+ if (!stat.isDirectory()) throw busError('E_BAD_ROOT', `bus root is not a directory: ${real}`);
251
+ return real;
252
+ }
253
+
254
+ function assertInside(root, target) {
255
+ const relative = path.relative(root, target);
256
+ if (relative === '') return;
257
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
258
+ throw busError('E_PATH_OUTSIDE_ROOT', `path escapes bus root: ${target}`);
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Resolve the nearest existing ancestor of `target` with realpath, then append
264
+ * the still-missing segments. `assertInside` alone is lexical: an NTFS junction
265
+ * inside the root can point anywhere, so the real path is what must stay in.
266
+ */
267
+ function realpathNearestExisting(target) {
268
+ let current = target;
269
+ const missing = [];
270
+ for (;;) {
271
+ try {
272
+ return { real: fs.realpathSync.native(current), missing };
273
+ } catch (error) {
274
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') {
275
+ if (isPermissionError(error)) {
276
+ throw busError('EPERM', `cannot resolve ${current}: ${error.code || error.message}`);
277
+ }
278
+ throw busError('E_PATH_OUTSIDE_ROOT', `cannot resolve ${current}: ${error.code || error.message}`);
279
+ }
280
+ const parent = path.dirname(current);
281
+ if (parent === current) {
282
+ throw busError('E_PATH_OUTSIDE_ROOT', `cannot resolve path: ${target}`);
283
+ }
284
+ missing.unshift(path.basename(current));
285
+ current = parent;
286
+ }
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Strong path jail for anything the bus is about to create or write:
292
+ * 1. lexical check against the real root (fast rejection of `..`/absolute);
293
+ * 2. reject Windows alternate data streams (`file.json:payload`);
294
+ * 3. realpath the nearest existing ancestor (a junction anywhere above the
295
+ * target resolves to its real location) and require it to be inside root;
296
+ * 4. refuse to write through a symlink/junction at the target itself.
297
+ * Missing tail segments are appended lexically after the real ancestor was
298
+ * proven inside, so a not-yet-created parent can still be validated.
299
+ */
300
+ function assertRealInsideRoot(root, target) {
301
+ assertInside(root, target);
302
+ const relative = path.relative(root, target);
303
+ for (const segment of relative.split(path.sep)) {
304
+ if (segment.includes(':')) {
305
+ throw busError('E_PATH_OUTSIDE_ROOT', `path contains an alternate data stream: ${target}`);
306
+ }
307
+ }
308
+ const { real, missing } = realpathNearestExisting(target);
309
+ assertInside(root, real);
310
+ const resolved = missing.length === 0 ? real : path.join(real, ...missing);
311
+ assertInside(root, resolved);
312
+ try {
313
+ if (fs.lstatSync(target).isSymbolicLink()) {
314
+ throw busError('E_PATH_OUTSIDE_ROOT', `refusing to write through a symlink: ${target}`);
315
+ }
316
+ } catch (error) {
317
+ if (error.code !== 'ENOENT') throw error;
318
+ }
319
+ return resolved;
320
+ }
321
+
322
+ function ensureDirInside(root, dir) {
323
+ // Check before mkdir: `mkdirSync(recursive)` through a junction ancestor would
324
+ // create directories outside the root and only fail afterwards.
325
+ assertRealInsideRoot(root, dir);
326
+ try {
327
+ fs.mkdirSync(dir, { recursive: true });
328
+ } catch (error) {
329
+ if (isPermissionError(error)) {
330
+ throw busError('EPERM', `cannot create ${dir}: ${error.code || error.message}`);
331
+ }
332
+ throw busError('E_BAD_ROOT', `cannot create ${dir}: ${error.code || error.message}`);
333
+ }
334
+ let stat;
335
+ try {
336
+ stat = fs.lstatSync(dir);
337
+ } catch (error) {
338
+ if (isPermissionError(error)) {
339
+ throw busError('EPERM', `cannot inspect ${dir}: ${error.code || error.message}`);
340
+ }
341
+ throw busError('E_BAD_ROOT', `cannot inspect ${dir}: ${error.code || error.message}`);
342
+ }
343
+ if (stat.isSymbolicLink()) throw busError('E_PATH_OUTSIDE_ROOT', `refusing symlinked directory: ${dir}`);
344
+ if (!stat.isDirectory()) throw busError('E_PATH_OUTSIDE_ROOT', `not a directory: ${dir}`);
345
+ let real;
346
+ try {
347
+ real = fs.realpathSync.native(dir);
348
+ } catch (error) {
349
+ if (isPermissionError(error)) {
350
+ throw busError('EPERM', `cannot resolve ${dir}: ${error.code || error.message}`);
351
+ }
352
+ throw busError('E_BAD_ROOT', `cannot resolve ${dir}: ${error.code || error.message}`);
353
+ }
354
+ assertInside(root, real);
355
+ return real;
356
+ }
357
+
358
+ function readJsonFile(file) {
359
+ let text;
360
+ try {
361
+ text = fs.readFileSync(file, 'utf8');
362
+ } catch (error) {
363
+ return { ok: false, error: error.code || 'EREAD' };
364
+ }
365
+ try {
366
+ return { ok: true, value: JSON.parse(text.replace(/^\uFEFF/, '')) };
367
+ } catch {
368
+ return { ok: false, error: 'EPARSE' };
369
+ }
370
+ }
371
+
372
+ function sleepSync(ms) {
373
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
374
+ }
375
+
376
+ function renameWithRetry(from, to) {
377
+ for (let attempt = 0; attempt < 5; attempt += 1) {
378
+ try {
379
+ fs.renameSync(from, to);
380
+ return;
381
+ } catch (error) {
382
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(error.code) || attempt === 4) throw error;
383
+ sleepSync(5);
384
+ }
385
+ }
386
+ }
387
+
388
+ function atomicWriteJson(target, value) {
389
+ const dir = path.dirname(target);
390
+ const temp = path.join(dir, `.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
391
+ const text = `${JSON.stringify(value, null, 2)}\n`;
392
+ let fd;
393
+ try {
394
+ fd = fs.openSync(temp, 'wx');
395
+ fs.writeFileSync(fd, text, 'utf8');
396
+ try {
397
+ fs.fsyncSync(fd);
398
+ } catch {
399
+ // fsync is best effort; rename still gives atomic visibility.
400
+ }
401
+ fs.closeSync(fd);
402
+ fd = undefined;
403
+ renameWithRetry(temp, target);
404
+ return { ok: true, exists: false };
405
+ } catch (error) {
406
+ if (fd !== undefined) {
407
+ try { fs.closeSync(fd); } catch { /* ignore */ }
408
+ }
409
+ try {
410
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
411
+ } catch { /* ignore */ }
412
+ // A concurrent writer may have created the target first. Caller re-reads it.
413
+ if (fs.existsSync(target)) return { ok: true, exists: true };
414
+ throw busError('E_WRITE', `cannot write ${target}: ${error.code || error.message}`);
415
+ }
416
+ }
417
+
418
+ function pidAlive(pid) {
419
+ if (!Number.isInteger(pid) || pid <= 0) return false;
420
+ try {
421
+ process.kill(pid, 0);
422
+ return true;
423
+ } catch (error) {
424
+ return error.code === 'EPERM';
425
+ }
426
+ }
427
+
428
+ function validateEnvelope(value, recipient, maxBodyChars, expectedId) {
429
+ if (!isPlainObject(value)) return { ok: false, reason: 'not-object' };
430
+ if (value.v !== BUS_SCHEMA_VERSION) return { ok: false, reason: 'bad-version' };
431
+ if (typeof value.id !== 'string' || !MESSAGE_ID_RE.test(value.id)) return { ok: false, reason: 'bad-id' };
432
+ // The filename is the address of the message: ack(id) can only find an
433
+ // envelope whose id matches its file name. A mismatch is never deliverable
434
+ // (it would be permanently un-ackable), so quarantine it instead.
435
+ if (expectedId !== undefined && value.id !== expectedId) return { ok: false, reason: 'id-mismatch' };
436
+ let from;
437
+ try {
438
+ from = normalizeSessionId(value.from, 'from');
439
+ } catch {
440
+ return { ok: false, reason: 'bad-from' };
441
+ }
442
+ if (value.to !== recipient) return { ok: false, reason: 'wrong-recipient' };
443
+ if (!KINDS.includes(value.kind)) return { ok: false, reason: 'bad-kind' };
444
+ if (typeof value.body !== 'string' || value.body.length === 0) return { ok: false, reason: 'bad-body' };
445
+ if (codePointLength(value.body) > maxBodyChars) return { ok: false, reason: 'body-too-large' };
446
+ if (!Number.isFinite(value.ts) || value.ts <= 0) return { ok: false, reason: 'bad-ts' };
447
+ if (!Number.isFinite(value.ttl) || value.ttl <= 0 || value.ttl > MAX_TTL_MS) {
448
+ return { ok: false, reason: 'bad-ttl' };
449
+ }
450
+ if (typeof value.host !== 'string' || !value.host.trim()) return { ok: false, reason: 'bad-host' };
451
+ if (value.dedupKey !== undefined) {
452
+ if (typeof value.dedupKey !== 'string' || value.dedupKey.length === 0
453
+ || codePointLength(value.dedupKey) > 128) {
454
+ return { ok: false, reason: 'bad-dedup-key' };
455
+ }
456
+ }
457
+ return {
458
+ ok: true,
459
+ message: {
460
+ v: BUS_SCHEMA_VERSION,
461
+ id: value.id,
462
+ from,
463
+ to: recipient,
464
+ kind: value.kind,
465
+ body: value.body,
466
+ ts: value.ts,
467
+ ttl: value.ttl,
468
+ host: value.host,
469
+ ...(value.dedupKey === undefined ? {} : { dedupKey: value.dedupKey }),
470
+ },
471
+ };
472
+ }
473
+
474
+ function deriveMemoryRoot(root) {
475
+ const bus = path.basename(root).toLowerCase();
476
+ const longlive = path.basename(path.dirname(root)).toLowerCase();
477
+ if (bus === 'bus' && longlive === '.longlive') {
478
+ return path.dirname(path.dirname(root));
479
+ }
480
+ return null;
481
+ }
482
+
483
+ function resolveMemoryRootOption(value) {
484
+ if (value === undefined || value === null) return null;
485
+ if (typeof value !== 'string' || !value.trim()) throw busError('E_BAD_ROOT', 'memoryRoot must be a path');
486
+ return path.resolve(value.trim());
487
+ }
488
+
489
+ /**
490
+ * Create a bus handle bound to one session.
491
+ *
492
+ * @param {object} options
493
+ * @param {string} options.root bus root (required)
494
+ * @param {string} [options.sessionId] this session's canonical id
495
+ * @param {string} [options.host] local hostname, default os.hostname()
496
+ * @param {string} [options.memoryRoot] memory root used to find .longlive/live
497
+ * @param {string} [options.liveDir] override the live registry directory
498
+ * @param {() => number} [options.now] clock injection (tests / deterministic)
499
+ * @param {number} [options.maxBodyChars] default 8192 code points
500
+ * @param {number} [options.maxPending] default 1000 messages per inbox
501
+ */
502
+ export function createBus(options = {}) {
503
+ const root = ensureRoot(resolveRoot(options.root));
504
+ const sessionId = options.sessionId === undefined || options.sessionId === null
505
+ ? null
506
+ : normalizeSessionId(options.sessionId);
507
+ const host = normalizeHost(options.host ?? os.hostname());
508
+ const hostKey = host.toLowerCase();
509
+ const clock = typeof options.now === 'function' ? options.now : () => Date.now();
510
+ const maxBodyChars = clampInt(options.maxBodyChars, DEFAULT_MAX_BODY_CHARS, 1, 1_000_000);
511
+ const maxPending = clampInt(options.maxPending, DEFAULT_MAX_PENDING, 1, 100_000);
512
+ const maxClockSkewMs = clampInt(options.maxClockSkewMs, DEFAULT_MAX_CLOCK_SKEW_MS, 0, MAX_TTL_MS);
513
+ // Wall clock used only for the "sender clock is far in the future" guard. A
514
+ // test can pin it; production always uses Date.now(). The injected `now()` is
515
+ // still the logical clock for envelopes, leases and TTL.
516
+ const referenceClock = typeof options.referenceNow === 'function' ? options.referenceNow : () => Date.now();
517
+ // Test seam. `hooks.afterSerialize` runs inside the fencedWrite commit lock,
518
+ // after JSON.stringify and before the temp file/rename; production code must
519
+ // not pass it. It exists so the TOCTOU takeover can be injected
520
+ // deterministically instead of relying on a sleeping toJSON.
521
+ const testHooks = isPlainObject(options.hooks) ? options.hooks : {};
522
+ const memoryRoot = resolveMemoryRootOption(options.memoryRoot) ?? deriveMemoryRoot(root);
523
+ const liveDir = options.liveDir !== undefined
524
+ ? path.resolve(String(options.liveDir))
525
+ : memoryRoot
526
+ ? path.join(memoryRoot, '.longlive', 'live')
527
+ : null;
528
+
529
+ function nowMs() {
530
+ const value = Number(clock());
531
+ if (!Number.isFinite(value)) throw busError('E_BAD_CLOCK', 'now() must return a finite number');
532
+ return Math.floor(value);
533
+ }
534
+
535
+ function referenceNowMs() {
536
+ let value;
537
+ try {
538
+ value = Number(referenceClock());
539
+ } catch {
540
+ return null;
541
+ }
542
+ return Number.isFinite(value) ? Math.floor(value) : null;
543
+ }
544
+
545
+ function runHook(name, info) {
546
+ const hook = testHooks[name];
547
+ if (typeof hook === 'function') hook(info);
548
+ }
549
+
550
+ function inboxPath(recipient) {
551
+ return path.join(root, 'inbox', recipient);
552
+ }
553
+
554
+ function ensureInbox(recipient) {
555
+ return ensureDirInside(root, inboxPath(recipient));
556
+ }
557
+
558
+ function loadAddressBook(name) {
559
+ const file = path.join(root, name);
560
+ const read = readJsonFile(file);
561
+ if (!read.ok) {
562
+ if (read.error === 'ENOENT') return {};
563
+ throw busError('E_BAD_ADDRESS_BOOK', `cannot read ${name}: ${read.error}`);
564
+ }
565
+ if (!isPlainObject(read.value)) throw busError('E_BAD_ADDRESS_BOOK', `${name} must contain a JSON object`);
566
+ return read.value;
567
+ }
568
+
569
+ function resolveTargets(to) {
570
+ if (typeof to !== 'string' || !to.trim()) throw busError('E_BAD_TARGET', 'to must be a non-empty string');
571
+ const raw = to.trim();
572
+ const seen = new Set();
573
+ const targets = [];
574
+ const push = (id, via) => {
575
+ if (seen.has(id)) return;
576
+ seen.add(id);
577
+ targets.push({ sessionId: id, via });
578
+ };
579
+
580
+ if (raw.startsWith('@')) {
581
+ const name = normalizeAlias(raw.slice(1));
582
+ const aliases = loadAddressBook('aliases.json');
583
+ const foundKey = Object.keys(aliases).find((key) => key.toLowerCase() === name);
584
+ if (!foundKey) throw busError('E_UNKNOWN_TARGET', `unknown alias: ${raw}`);
585
+ const value = aliases[foundKey];
586
+ const id = typeof value === 'string' ? value : isPlainObject(value) ? value.sessionId : null;
587
+ if (typeof id !== 'string') throw busError('E_BAD_ADDRESS_BOOK', `alias ${name} must map to a session id string`);
588
+ push(normalizeSessionId(id, `alias ${name}`), `@${name}`);
589
+ return targets;
590
+ }
591
+
592
+ if (raw.startsWith('#')) {
593
+ const role = normalizeAlias(raw.slice(1));
594
+ const roles = loadAddressBook('roles.json');
595
+ const foundKey = Object.keys(roles).find((key) => key.toLowerCase() === role);
596
+ if (!foundKey || !Array.isArray(roles[foundKey]) || roles[foundKey].length === 0) {
597
+ throw busError('E_UNKNOWN_TARGET', `unknown or empty role: ${raw}`);
598
+ }
599
+ for (const member of roles[foundKey]) {
600
+ if (typeof member !== 'string') throw busError('E_BAD_ADDRESS_BOOK', `role ${role} members must be strings`);
601
+ push(normalizeSessionId(member, `role ${role}`), `#${role}`);
602
+ }
603
+ return targets;
604
+ }
605
+
606
+ push(normalizeSessionId(raw, 'to'), 'id');
607
+ return targets;
608
+ }
609
+
610
+ function peerState(recipient, at) {
611
+ if (!liveDir) return { state: 'unknown', live: false };
612
+ const file = path.join(liveDir, `${recipient}.json`);
613
+ let stat;
614
+ try {
615
+ stat = fs.lstatSync(file);
616
+ } catch (error) {
617
+ return { state: error.code === 'ENOENT' ? 'missing' : 'corrupt', live: false };
618
+ }
619
+ if (stat.isSymbolicLink() || !stat.isFile()) return { state: 'corrupt', live: true };
620
+ const read = readJsonFile(file);
621
+ if (!read.ok) return { state: 'corrupt', live: true };
622
+ const row = read.value;
623
+ const heartbeat = Date.parse(row.heartbeatAt ?? row.updatedAt ?? '');
624
+ const ttl = Number(row.ttlMs);
625
+ if (!Number.isFinite(heartbeat) || !Number.isFinite(ttl) || ttl <= 0) {
626
+ return { state: 'corrupt', live: true };
627
+ }
628
+ const rowHost = typeof row.host === 'string' ? row.host.trim().toLowerCase() : '';
629
+ const remote = rowHost !== '' && rowHost !== hostKey;
630
+ const age = at - heartbeat;
631
+ if (remote) {
632
+ if (age > 4 * ttl) return { state: 'dead', remote: true, live: true };
633
+ if (age > 2 * ttl) return { state: 'stale', remote: true, live: true };
634
+ return { state: 'fresh', remote: true, live: true };
635
+ }
636
+ // Liveness on this host is decided by the pid first: a fresh heartbeat is
637
+ // just a timestamp and can be forged (or left behind by a crash), while a
638
+ // dead pid is positive evidence that nobody is reading the mailbox. If the
639
+ // heartbeat check ran first, a forged fresh row would mask the dead pid and
640
+ // send() would deliver into a mailbox nobody will ever poll.
641
+ if (!pidAlive(Number(row.pid))) {
642
+ return { state: 'dead', reason: 'pid', remote: false, live: true };
643
+ }
644
+ if (age <= ttl) return { state: 'fresh', declared: row.state, live: true };
645
+ if (age > 4 * ttl) return { state: 'dead', reason: 'heartbeat', remote: false, live: true };
646
+ if (age > 2 * ttl) return { state: 'stale', remote: false, live: true };
647
+ return { state: 'stale', declared: row.state, remote: false, live: true };
648
+ }
649
+
650
+ function countPending(dir) {
651
+ let count = 0;
652
+ let entries;
653
+ try {
654
+ entries = fs.readdirSync(dir, { withFileTypes: true });
655
+ } catch {
656
+ return 0;
657
+ }
658
+ for (const entry of entries) {
659
+ if (entry.isFile() && entry.name.endsWith('.json') && !entry.name.startsWith('.')) count += 1;
660
+ }
661
+ return count;
662
+ }
663
+
664
+ function quarantine(dir, file, reason) {
665
+ try {
666
+ const dead = ensureDirInside(root, path.join(dir, 'dead'));
667
+ const base = path.basename(file).replace(/\.json$/i, '');
668
+ let target = path.join(dead, `${base}.${reason}.json`);
669
+ if (fs.existsSync(target)) {
670
+ target = path.join(dead, `${base}.${reason}.${Date.now().toString(36)}.json`);
671
+ }
672
+ fs.renameSync(file, target);
673
+ } catch {
674
+ // Quarantine is best effort; the original file remains and is reported.
675
+ }
676
+ }
677
+
678
+ function send(args = {}) {
679
+ const from = normalizeSessionId(args.from ?? sessionId, 'from');
680
+ if (sessionId && from !== sessionId) {
681
+ throw busError('E_FROM_MISMATCH', `bus is bound to ${sessionId}, cannot send as ${from}`);
682
+ }
683
+ if (typeof args.body !== 'string' || args.body.length === 0) {
684
+ throw busError('E_BAD_BODY', 'body must be a non-empty string');
685
+ }
686
+ if (codePointLength(args.body) > maxBodyChars) {
687
+ throw busError('E_BODY_TOO_LARGE', `body exceeds ${maxBodyChars} code points`);
688
+ }
689
+ const kind = args.kind ?? 'note';
690
+ if (!KINDS.includes(kind)) throw busError('E_BAD_KIND', `kind must be one of ${KINDS.join(', ')}`);
691
+ const ttl = args.ttl === undefined ? DEFAULT_TTL_MS : Number(args.ttl);
692
+ if (!Number.isFinite(ttl) || ttl <= 0 || ttl > MAX_TTL_MS) {
693
+ throw busError('E_BAD_TTL', `ttl must be > 0 and <= ${MAX_TTL_MS}`);
694
+ }
695
+ let dedupKey;
696
+ if (args.dedupKey !== undefined) {
697
+ if (typeof args.dedupKey !== 'string' || args.dedupKey.length === 0
698
+ || codePointLength(args.dedupKey) > 128) {
699
+ throw busError('E_BAD_DEDUP_KEY', 'dedupKey must be a non-empty string of <= 128 code points');
700
+ }
701
+ dedupKey = args.dedupKey;
702
+ }
703
+
704
+ const targets = resolveTargets(args.to);
705
+ const direct = !targets[0].via.startsWith('#');
706
+ const allowDead = args.allowDead === true;
707
+ const ts = nowMs();
708
+ // A non-positive timestamp produces envelopes that are already expired
709
+ // (poll drops `at > ts + ttl`) and breaks cursor math, so reject it at the
710
+ // sender instead of writing a poison message.
711
+ if (!Number.isFinite(ts) || ts <= 0) {
712
+ throw busError('E_BAD_CLOCK', `now() must be a positive finite millisecond timestamp (got ${ts})`);
713
+ }
714
+ // A clock that is far ahead would mint a message no peer can see until the
715
+ // skew elapses (P14): the receiver quarantines it and any cursor derived
716
+ // from it jumps over real traffic. Refuse to write it in the first place.
717
+ // `now()` is injectable and therefore can be wrong; Date.now() is the
718
+ // independent wall-clock reference for this guard.
719
+ const reference = referenceNowMs();
720
+ if (reference !== null && ts > reference + maxClockSkewMs) {
721
+ throw busError(
722
+ 'E_BAD_CLOCK',
723
+ `timestamp ${ts} is ${ts - reference}ms ahead of the wall clock; maxClockSkewMs=${maxClockSkewMs}`,
724
+ );
725
+ }
726
+ const results = [];
727
+ const skipped = [];
728
+
729
+ for (const target of targets) {
730
+ const recipient = target.sessionId;
731
+ const id = dedupKey ? dedupMessageId(from, recipient, dedupKey) : newMessageId(ts);
732
+ const dir = ensureInbox(recipient);
733
+ const file = path.join(dir, `${id}.json`);
734
+ const ackedFile = path.join(dir, 'acked', `${id}.json`);
735
+
736
+ // Dedup means "this dedupKey was already accepted", not "a pending copy
737
+ // exists". A retry after the receiver acked must not resurrect the id:
738
+ // the acked copy is the tombstone. Otherwise ack-then-retry recreated the
739
+ // inbox file, and a later ack saw the acked copy, returned already:true
740
+ // and left the new inbox copy pending forever (un-ackable until TTL).
741
+ if (dedupKey && !fs.existsSync(file) && fs.existsSync(ackedFile)) {
742
+ const prior = readJsonFile(ackedFile);
743
+ if (!prior.ok) throw busError('E_CORRUPT_TARGET', `acked message is unreadable: ${id}`);
744
+ if (prior.value.body !== args.body || prior.value.kind !== kind) {
745
+ throw busError('E_DEDUP_CONFLICT', `dedupKey ${dedupKey} was already acked with a different body/kind`);
746
+ }
747
+ results.push({ to: recipient, id, deduped: true, acked: true, path: ackedFile });
748
+ continue;
749
+ }
750
+
751
+ if (fs.existsSync(file)) {
752
+ const existing = readJsonFile(file);
753
+ if (!existing.ok) throw busError('E_CORRUPT_TARGET', `existing message is unreadable: ${id}`);
754
+ const value = existing.value;
755
+ if (value.body !== args.body || value.kind !== kind) {
756
+ throw busError('E_DEDUP_CONFLICT', `dedupKey ${dedupKey} already used with a different body/kind`);
757
+ }
758
+ results.push({ to: recipient, id, deduped: true, path: file });
759
+ continue;
760
+ }
761
+
762
+ const peer = peerState(recipient, ts);
763
+ if (peer.remote) {
764
+ if (direct) throw busError('E_REMOTE_HOST', `recipient ${recipient} lives on another host`);
765
+ skipped.push({ to: recipient, reason: 'remote-host' });
766
+ continue;
767
+ }
768
+ if (peer.state === 'dead' && !allowDead) {
769
+ if (direct) throw busError('E_PEER_DEAD', `recipient ${recipient} is dead`);
770
+ skipped.push({ to: recipient, reason: 'dead' });
771
+ continue;
772
+ }
773
+ if (countPending(dir) >= maxPending) {
774
+ if (direct) throw busError('E_BACKLOG_FULL', `inbox ${recipient} has ${maxPending} pending messages`);
775
+ skipped.push({ to: recipient, reason: 'backlog' });
776
+ continue;
777
+ }
778
+
779
+ const envelope = {
780
+ v: BUS_SCHEMA_VERSION,
781
+ id,
782
+ from,
783
+ to: recipient,
784
+ kind,
785
+ body: args.body,
786
+ ts,
787
+ ttl,
788
+ host,
789
+ ...(dedupKey === undefined ? {} : { dedupKey }),
790
+ };
791
+ const write = atomicWriteJson(file, envelope);
792
+ if (write.exists) {
793
+ // Our pre-check can lose a race with a receiver that acked the old copy
794
+ // between then and the write. The acked tombstone wins.
795
+ if (dedupKey && fs.existsSync(ackedFile)) {
796
+ try { fs.unlinkSync(file); } catch { /* already gone */ }
797
+ results.push({ to: recipient, id, deduped: true, acked: true, path: ackedFile });
798
+ continue;
799
+ }
800
+ const again = readJsonFile(file);
801
+ if (!again.ok) throw busError('E_CORRUPT_TARGET', `racing message is unreadable: ${id}`);
802
+ if (again.value.body !== args.body || again.value.kind !== kind) {
803
+ throw busError('E_DEDUP_CONFLICT', `dedupKey ${dedupKey} already used with a different body/kind`);
804
+ }
805
+ results.push({ to: recipient, id, deduped: true, path: file });
806
+ } else if (dedupKey && fs.existsSync(ackedFile)) {
807
+ // Close the ack-vs-retry race: ack may have moved the previous copy to
808
+ // acked/ after the pre-check. Drop the fresh inbox copy we just wrote.
809
+ try { fs.unlinkSync(file); } catch { /* ack already removed it */ }
810
+ results.push({ to: recipient, id, deduped: true, acked: true, path: ackedFile });
811
+ } else {
812
+ results.push({ to: recipient, id, deduped: false, peerState: peer.state, path: file });
813
+ }
814
+ }
815
+
816
+ if (results.length === 0) {
817
+ throw busError('E_NO_LIVE_RECIPIENTS', 'no live recipient accepted the message');
818
+ }
819
+ return {
820
+ ok: true,
821
+ id: results[0].id,
822
+ from,
823
+ results,
824
+ skipped,
825
+ ...(skipped.length > 0 ? { partial: true } : {}),
826
+ };
827
+ }
828
+
829
+ function resolveCursor(since, dir) {
830
+ if (since === undefined || since === null) return { ts: -Infinity, id: '' };
831
+ if (typeof since === 'number' && Number.isFinite(since)) return { ts: since, id: '' };
832
+ if (typeof since !== 'string') throw busError('E_BAD_SINCE', 'since must be a number, ISO time, or message id');
833
+ const text = since.trim();
834
+ if (!text) throw busError('E_BAD_SINCE', 'since must not be empty');
835
+ if (/^\d+$/.test(text)) return { ts: Number(text), id: '' };
836
+ const parsed = Date.parse(text);
837
+ if (Number.isFinite(parsed)) return { ts: parsed, id: '' };
838
+ if (MESSAGE_ID_RE.test(text)) {
839
+ for (const sub of ['', 'acked']) {
840
+ const read = readJsonFile(path.join(dir, sub, `${text}.json`));
841
+ if (read.ok && Number.isFinite(read.value.ts)) return { ts: read.value.ts, id: text };
842
+ }
843
+ const fromId = timestampFromMessageId(text);
844
+ if (fromId !== null) return { ts: fromId, id: text };
845
+ throw busError('E_BAD_SINCE', `cannot resolve message id: ${text}`);
846
+ }
847
+ throw busError('E_BAD_SINCE', 'since must be a number, ISO time, or message id');
848
+ }
849
+
850
+ function poll(args = {}) {
851
+ const recipient = normalizeSessionId(args.sessionId ?? sessionId, 'sessionId');
852
+ const dir = inboxPath(recipient);
853
+ if (!fs.existsSync(dir)) {
854
+ return {
855
+ ok: true, sessionId: recipient, messages: [], cursor: args.since ?? null,
856
+ scanned: 0, expired: 0, corrupt: 0, foreignHost: 0, futureTs: 0,
857
+ futureCursor: false, hasMore: false,
858
+ };
859
+ }
860
+ const stat = fs.lstatSync(dir);
861
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
862
+ throw busError('E_PATH_OUTSIDE_ROOT', `inbox is not a real directory: ${dir}`);
863
+ }
864
+ assertInside(root, fs.realpathSync.native(dir));
865
+
866
+ const limit = clampInt(args.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
867
+ const at = nowMs();
868
+ const cursor = resolveCursor(args.since, dir);
869
+ // A cursor must never sit in the future: a single message with a poisoned
870
+ // ts would otherwise make every later (real) message invisible. Reset the
871
+ // filter to "replay everything pending" rather than clamping to `at`:
872
+ // clamping forward would silently drop messages that are already queued
873
+ // (at-least-once delivery; ack is idempotent, so a replay is safe).
874
+ const futureCursor = Number.isFinite(cursor.ts) && cursor.ts > at + maxClockSkewMs;
875
+ if (futureCursor) {
876
+ cursor.ts = -Infinity;
877
+ cursor.id = '';
878
+ }
879
+ let scanned = 0;
880
+ let expired = 0;
881
+ let corrupt = 0;
882
+ let foreignHost = 0;
883
+ let futureTs = 0;
884
+ const found = [];
885
+
886
+ for (const name of fs.readdirSync(dir)) {
887
+ if (!name.endsWith('.json') || name.startsWith('.')) continue;
888
+ const file = path.join(dir, name);
889
+ let fileStat;
890
+ try {
891
+ fileStat = fs.lstatSync(file);
892
+ } catch {
893
+ continue;
894
+ }
895
+ if (!fileStat.isFile() || fileStat.isSymbolicLink()) continue;
896
+ scanned += 1;
897
+ const read = readJsonFile(file);
898
+ if (!read.ok) {
899
+ corrupt += 1;
900
+ quarantine(dir, file, 'corrupt');
901
+ continue;
902
+ }
903
+ const expectedId = name.slice(0, -'.json'.length);
904
+ const valid = validateEnvelope(read.value, recipient, maxBodyChars, expectedId);
905
+ if (!valid.ok) {
906
+ corrupt += 1;
907
+ quarantine(dir, file, valid.reason === 'id-mismatch' ? 'id-mismatch' : 'corrupt');
908
+ continue;
909
+ }
910
+ const message = valid.message;
911
+ if (message.host.trim().toLowerCase() !== hostKey) {
912
+ foreignHost += 1;
913
+ quarantine(dir, file, 'foreign');
914
+ continue;
915
+ }
916
+ // A timestamp far in the receiver's future is a clock-skew attack, not a
917
+ // deliverable message: quarantine it so it cannot enter `found` (and so
918
+ // cannot become the next cursor), but do not let it hide the inbox.
919
+ if (message.ts > at + maxClockSkewMs) {
920
+ futureTs += 1;
921
+ quarantine(dir, file, 'future-ts');
922
+ continue;
923
+ }
924
+ if (at > message.ts + message.ttl) {
925
+ expired += 1;
926
+ try { fs.unlinkSync(file); } catch { /* best effort */ }
927
+ continue;
928
+ }
929
+ if (message.ts > cursor.ts || (message.ts === cursor.ts && message.id > cursor.id)) {
930
+ found.push(message);
931
+ }
932
+ }
933
+
934
+ found.sort((a, b) => a.ts - b.ts || a.id.localeCompare(b.id));
935
+ const messages = found.slice(0, limit);
936
+ // A message may legitimately be up to maxClockSkewMs (5 min) ahead of this
937
+ // receiver's clock. Returning its id as the cursor would then hide every
938
+ // later message with a smaller ts forever (P24): id cursors compare (ts,id),
939
+ // and a smaller ts can never beat the ahead-of-clock ts. Clamp the cursor to
940
+ // `at` instead, so the next poll replays the ahead-of-clock message
941
+ // (at-least-once) together with anything that arrived with a normal ts.
942
+ const cursorClamped = messages.some((message) => message.ts > at);
943
+ return {
944
+ ok: true,
945
+ sessionId: recipient,
946
+ messages,
947
+ cursor: messages.length > 0
948
+ ? (cursorClamped ? at : messages[messages.length - 1].id)
949
+ : (futureCursor ? at : (args.since ?? null)),
950
+ scanned,
951
+ expired,
952
+ corrupt,
953
+ foreignHost,
954
+ futureTs,
955
+ futureCursor,
956
+ hasMore: found.length > messages.length,
957
+ };
958
+ }
959
+
960
+ function ack(id) {
961
+ if (!sessionId) throw busError('E_NO_SESSION', 'ack requires a bus bound to a sessionId');
962
+ if (typeof id !== 'string' || !MESSAGE_ID_RE.test(id)) {
963
+ throw busError('E_BAD_MESSAGE_ID', `invalid message id: ${id}`);
964
+ }
965
+ const dir = inboxPath(sessionId);
966
+ if (!fs.existsSync(dir)) return { ok: false, code: 'E_NOT_FOUND', id };
967
+ const ackedDir = ensureDirInside(root, path.join(dir, 'acked'));
968
+ const source = path.join(dir, `${id}.json`);
969
+ const target = path.join(ackedDir, `${id}.json`);
970
+ // A copy may exist in both places after a crash between "target written"
971
+ // and "source removed" (or when a dedup retry raced an ack). Once the
972
+ // acked copy exists the message is consumed; leaving the inbox copy behind
973
+ // would make it permanently pending while every ack returns already:true.
974
+ const dropSource = () => {
975
+ try { fs.unlinkSync(source); } catch { /* already gone */ }
976
+ };
977
+ if (fs.existsSync(target)) {
978
+ dropSource();
979
+ return { ok: true, already: true, id };
980
+ }
981
+ try {
982
+ fs.renameSync(source, target);
983
+ return { ok: true, already: false, id };
984
+ } catch (error) {
985
+ if (fs.existsSync(target)) {
986
+ dropSource();
987
+ return { ok: true, already: true, id };
988
+ }
989
+ if (error.code === 'ENOENT') return { ok: false, code: 'E_NOT_FOUND', id };
990
+ throw busError('E_ACK_FAILED', `cannot ack ${id}: ${error.code || error.message}`);
991
+ }
992
+ }
993
+
994
+ function writerFile() {
995
+ return path.join(root, 'writer.lock');
996
+ }
997
+
998
+ function writerSeqFile() {
999
+ return path.join(root, 'writer.seq');
1000
+ }
1001
+
1002
+ function readWriterSeq() {
1003
+ const read = readJsonFile(writerSeqFile());
1004
+ if (!read.ok) return 0;
1005
+ const token = Number(read.value?.token);
1006
+ return Number.isSafeInteger(token) && token > 0 ? token : 0;
1007
+ }
1008
+
1009
+ function rememberToken(token) {
1010
+ // writer.seq is a best-effort fence counter: it closes the window where the
1011
+ // old lock is already unlinked but a stale writer has not yet tried to
1012
+ // write. Identity itself comes from (holder, token, nonce) in the lock, so
1013
+ // losing a seq write cannot let an old holder back in.
1014
+ try { atomicWriteJson(writerSeqFile(), { schemaVersion: 1, token }); } catch { /* best effort */ }
1015
+ }
1016
+
1017
+ function nextToken(record) {
1018
+ return Math.max(readWriterSeq(), Number(record?.token) || 0) + 1;
1019
+ }
1020
+
1021
+ function writeLockRecord(record) {
1022
+ const file = writerFile();
1023
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.${crypto.randomBytes(4).toString('hex')}.tmp`;
1024
+ const fd = fs.openSync(tmp, 'wx');
1025
+ try {
1026
+ fs.writeFileSync(fd, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
1027
+ try { fs.fsyncSync(fd); } catch { /* best effort */ }
1028
+ } finally {
1029
+ fs.closeSync(fd);
1030
+ }
1031
+ try {
1032
+ renameWithRetry(tmp, file);
1033
+ } finally {
1034
+ try { fs.unlinkSync(tmp); } catch { /* renamed */ }
1035
+ }
1036
+ }
1037
+
1038
+ function commitLockFile() {
1039
+ return path.join(root, 'writer.commit.lock');
1040
+ }
1041
+
1042
+ /**
1043
+ * Serialize every writer.lock mutation (claim/renew/release) and every
1044
+ * fenced commit with an O_EXCL lock file. The lock file carries the owner pid
1045
+ * and host so a crash can be recovered deterministically: a same-host dead pid
1046
+ * is stolen immediately, an unreadable/foreign lock after COMMIT_LOCK_STALE_MS.
1047
+ *
1048
+ * Reentrancy is deliberate: fencedWrite calls a test hook (and JSON.stringify,
1049
+ * which may run user toJSON) while holding the lock, and that code may
1050
+ * synchronously call claimWriter. JS is single-threaded, so the inner call
1051
+ * cannot interleave with the outer critical section; the outer commit still
1052
+ * revalidates the lease before renaming.
1053
+ */
1054
+ function withCommitLock(fn) {
1055
+ if (commitLocksHeldByProcess.has(root)) return fn();
1056
+ const lockFile = commitLockFile();
1057
+ // Per-acquisition identity. Stale reclaim unlinks this file and a new owner
1058
+ // recreates it; the old holder must be able to tell "still mine" from
1059
+ // "someone else's" before removing it (red-team P09).
1060
+ const ownerId = crypto.randomUUID();
1061
+ const deadline = Date.now() + COMMIT_LOCK_TIMEOUT_MS;
1062
+ let fd;
1063
+ for (;;) {
1064
+ try {
1065
+ fd = fs.openSync(lockFile, 'wx');
1066
+ break;
1067
+ } catch (error) {
1068
+ if (error.code !== 'EEXIST') {
1069
+ throw busError('E_LEASE_WRITE', `cannot create writer commit lock: ${error.code || error.message}`);
1070
+ }
1071
+ let stale = false;
1072
+ try {
1073
+ const read = readJsonFile(lockFile);
1074
+ if (read.ok) {
1075
+ const sameHost = String(read.value?.host ?? '').toLowerCase() === hostKey;
1076
+ if (sameHost && !pidAlive(Number(read.value?.pid))) stale = true;
1077
+ }
1078
+ if (!stale) stale = (Date.now() - fs.statSync(lockFile).mtimeMs) > COMMIT_LOCK_STALE_MS;
1079
+ } catch {
1080
+ // The owner is mid-create or just released; retry below.
1081
+ stale = false;
1082
+ }
1083
+ if (stale) {
1084
+ try { fs.unlinkSync(lockFile); } catch { /* raced */ }
1085
+ continue;
1086
+ }
1087
+ if (Date.now() >= deadline) {
1088
+ throw busError('E_LEASE_WRITE', 'writer commit lock is busy; another fenced write did not finish');
1089
+ }
1090
+ sleepSync(4);
1091
+ }
1092
+ }
1093
+ try {
1094
+ fs.writeFileSync(fd, `${JSON.stringify({
1095
+ pid: process.pid,
1096
+ host,
1097
+ at: new Date().toISOString(),
1098
+ ownerId,
1099
+ })}\n`, 'utf8');
1100
+ try { fs.fsyncSync(fd); } catch { /* best effort */ }
1101
+ } catch (error) {
1102
+ try { fs.closeSync(fd); } catch { /* ignore */ }
1103
+ try { fs.unlinkSync(lockFile); } catch { /* ignore */ }
1104
+ throw busError('E_LEASE_WRITE', `cannot initialize writer commit lock: ${error.code || error.message}`);
1105
+ }
1106
+ fs.closeSync(fd);
1107
+ commitLocksHeldByProcess.add(root);
1108
+ try {
1109
+ return fn();
1110
+ } finally {
1111
+ commitLocksHeldByProcess.delete(root);
1112
+ releaseCommitLock(lockFile, ownerId);
1113
+ }
1114
+ }
1115
+
1116
+ /**
1117
+ * Remove the commit lock only if this acquisition still owns it.
1118
+ *
1119
+ * Ownership can be lost inside the critical section: a reclaim may see our
1120
+ * mtime as older than COMMIT_LOCK_STALE_MS (slow hook, suspended process) or
1121
+ * read our pid as dead, unlink the file and install its own record. A blind
1122
+ * unlink in the finally would then delete the *new* owner's lock while that
1123
+ * process is still writing, letting a third writer in (P09). Comparing the
1124
+ * random ownerId closes that window; a lock we cannot prove is ours is left
1125
+ * to the normal stale-reclaim path (30s / dead pid), never removed here.
1126
+ */
1127
+ function releaseCommitLock(lockFile, ownerId) {
1128
+ const read = readJsonFile(lockFile);
1129
+ if (!read.ok || read.value?.ownerId !== ownerId) return;
1130
+ try { fs.unlinkSync(lockFile); } catch { /* raced with reclaim/removal */ }
1131
+ }
1132
+
1133
+ /**
1134
+ * Read writer.lock fresh and prove this call still owns the lease. Runs
1135
+ * before serialization and again immediately before the rename; the second
1136
+ * read is the one that closes the P13 TOCTOU window.
1137
+ */
1138
+ function checkWriterLease(holder, args) {
1139
+ const read = readJsonFile(writerFile());
1140
+ if (!read.ok) throw busError('E_LEASE_LOST', 'no writer lease; claimWriter first');
1141
+ const record = read.value;
1142
+ const at = nowMs();
1143
+ const expires = Date.parse(record.expiresAt);
1144
+ if (!Number.isFinite(expires) || expires <= at) {
1145
+ throw busError('E_LEASE_LOST', 'writer lease has expired');
1146
+ }
1147
+ if (record.holder !== holder || args.token !== record.token) {
1148
+ throw busError('E_LEASE_LOST', 'writer lease belongs to another acquisition (fencing token mismatch)');
1149
+ }
1150
+ if (typeof args.nonce !== 'string' || args.nonce.length === 0 || args.nonce !== record.nonce) {
1151
+ throw busError('E_LEASE_AUTH', 'writer nonce mismatch');
1152
+ }
1153
+ if (String(record.host ?? '').toLowerCase() === hostKey && !pidAlive(Number(record.pid))) {
1154
+ throw busError('E_LEASE_LOST', 'writer process is gone');
1155
+ }
1156
+ return record;
1157
+ }
1158
+
1159
+ function writerStatus() {
1160
+ const read = readJsonFile(writerFile());
1161
+ if (!read.ok) {
1162
+ return { ok: true, held: false, corrupt: read.error !== 'ENOENT' };
1163
+ }
1164
+ const record = read.value;
1165
+ const expires = Date.parse(record.expiresAt);
1166
+ const sameHost = String(record.host ?? '').toLowerCase() === hostKey;
1167
+ const alive = !sameHost || pidAlive(Number(record.pid));
1168
+ return {
1169
+ ok: true,
1170
+ held: Number.isFinite(expires) && expires > nowMs() && alive,
1171
+ holder: record.holder,
1172
+ token: record.token,
1173
+ expiresAt: record.expiresAt,
1174
+ ...(alive ? {} : { reason: 'pid' }),
1175
+ };
1176
+ }
1177
+
1178
+ function claimWriter(args = {}) {
1179
+ const holder = normalizeSessionId(args.holder ?? sessionId, 'holder');
1180
+ if (sessionId && holder !== sessionId) {
1181
+ throw busError('E_FROM_MISMATCH', `bus is bound to ${sessionId}, cannot claim as ${holder}`);
1182
+ }
1183
+ const ttl = clampInt(args.ttlMs, DEFAULT_WRITER_TTL_MS, 1000, 86_400_000);
1184
+ return withCommitLock(() => {
1185
+ const file = writerFile();
1186
+ const at = nowMs();
1187
+
1188
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1189
+ const token = nextToken();
1190
+ const nonce = crypto.randomBytes(16).toString('hex');
1191
+ const payload = {
1192
+ schemaVersion: WRITER_SCHEMA_VERSION,
1193
+ holder,
1194
+ nonce,
1195
+ token,
1196
+ pid: process.pid,
1197
+ host,
1198
+ acquiredAt: new Date(at).toISOString(),
1199
+ expiresAt: new Date(at + ttl).toISOString(),
1200
+ ttlMs: ttl,
1201
+ };
1202
+ try {
1203
+ const fd = fs.openSync(file, 'wx');
1204
+ try {
1205
+ fs.writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
1206
+ try { fs.fsyncSync(fd); } catch { /* best effort */ }
1207
+ } finally {
1208
+ fs.closeSync(fd);
1209
+ }
1210
+ rememberToken(token);
1211
+ return { ok: true, holder, token, nonce, expiresAt: payload.expiresAt, created: true };
1212
+ } catch (error) {
1213
+ if (error.code !== 'EEXIST') {
1214
+ throw busError('E_LEASE_WRITE', `cannot create writer lock: ${error.code || error.message}`);
1215
+ }
1216
+ const read = readJsonFile(file);
1217
+ let stale;
1218
+ if (read.ok) {
1219
+ const record = read.value;
1220
+ const expires = Date.parse(record.expiresAt);
1221
+ const sameHost = String(record.host ?? '').toLowerCase() === hostKey;
1222
+ stale = !Number.isFinite(expires) || expires <= at || (sameHost && !pidAlive(Number(record.pid)));
1223
+ if (!stale) {
1224
+ if (record.holder === holder) {
1225
+ // Same-holder re-claim is a renewal, but it still has to prove
1226
+ // it owns this acquisition. Without the acquisition nonce, any
1227
+ // process that can read the lock (or guess the session id)
1228
+ // could extend the lease and receive the nonce back (P08).
1229
+ if (typeof args.nonce !== 'string' || args.nonce.length === 0) {
1230
+ return { ok: false, holder, reason: 'auth', code: 'E_NONCE_REQUIRED' };
1231
+ }
1232
+ if (args.nonce !== record.nonce) {
1233
+ return { ok: false, holder, reason: 'auth', code: 'E_LEASE_AUTH' };
1234
+ }
1235
+ const refreshed = {
1236
+ ...record,
1237
+ ttlMs: ttl,
1238
+ expiresAt: new Date(at + ttl).toISOString(),
1239
+ };
1240
+ writeLockRecord(refreshed);
1241
+ return {
1242
+ ok: true, holder, token: record.token, nonce: record.nonce,
1243
+ expiresAt: refreshed.expiresAt, created: false, renewed: true,
1244
+ };
1245
+ }
1246
+ return { ok: false, holder: record.holder, expiresAt: record.expiresAt, reason: 'held' };
1247
+ }
1248
+ // Stale lock: advance the fence counter past the dead holder before
1249
+ // unlinking, so the next acquisition's token is strictly larger.
1250
+ rememberToken(nextToken(record));
1251
+ } else {
1252
+ let old = true;
1253
+ try { old = (at - fs.statSync(file).mtimeMs) > ttl; } catch { old = true; }
1254
+ if (!old) return { ok: false, reason: 'corrupt' };
1255
+ }
1256
+ try { fs.unlinkSync(file); } catch { /* another process may have won */ }
1257
+ }
1258
+ }
1259
+ return { ok: false, reason: 'race' };
1260
+ });
1261
+ }
1262
+
1263
+ function renewWriter(args = {}) {
1264
+ const holder = normalizeSessionId(args.holder ?? sessionId, 'holder');
1265
+ if (sessionId && holder !== sessionId) {
1266
+ throw busError('E_FROM_MISMATCH', `bus is bound to ${sessionId}, cannot renew as ${holder}`);
1267
+ }
1268
+ return withCommitLock(() => {
1269
+ if (typeof args.nonce !== 'string' || args.nonce.length === 0) {
1270
+ return { ok: false, reason: 'bad-nonce' };
1271
+ }
1272
+ const read = readJsonFile(writerFile());
1273
+ if (!read.ok) return { ok: false, reason: 'no-lock' };
1274
+ const record = read.value;
1275
+ if (record.holder !== holder) return { ok: false, reason: 'not-holder', holder: record.holder };
1276
+ if (args.nonce !== record.nonce) return { ok: false, reason: 'bad-nonce' };
1277
+ if (args.token !== undefined && args.token !== record.token) {
1278
+ return { ok: false, reason: 'stale-token' };
1279
+ }
1280
+ const at = nowMs();
1281
+ const expires = Date.parse(record.expiresAt);
1282
+ if (!Number.isFinite(expires) || expires <= at) {
1283
+ return { ok: false, reason: 'expired', code: 'E_LEASE_LOST' };
1284
+ }
1285
+ if (String(record.host ?? '').toLowerCase() === hostKey && !pidAlive(Number(record.pid))) {
1286
+ return { ok: false, reason: 'pid', code: 'E_LEASE_LOST' };
1287
+ }
1288
+ const ttl = clampInt(args.ttlMs, Number(record.ttlMs) || DEFAULT_WRITER_TTL_MS, 1000, 86_400_000);
1289
+ const refreshed = { ...record, ttlMs: ttl, expiresAt: new Date(at + ttl).toISOString() };
1290
+ writeLockRecord(refreshed);
1291
+ return {
1292
+ ok: true, renewed: true, holder, token: record.token, nonce: record.nonce,
1293
+ expiresAt: refreshed.expiresAt,
1294
+ };
1295
+ });
1296
+ }
1297
+
1298
+ function releaseWriter(args = {}) {
1299
+ const holder = normalizeSessionId(args.holder ?? sessionId, 'holder');
1300
+ if (sessionId && holder !== sessionId) {
1301
+ throw busError('E_FROM_MISMATCH', `bus is bound to ${sessionId}, cannot release as ${holder}`);
1302
+ }
1303
+ return withCommitLock(() => {
1304
+ const read = readJsonFile(writerFile());
1305
+ if (!read.ok) return { ok: true, released: false, reason: 'no-lock' };
1306
+ const record = read.value;
1307
+ if (record.holder !== holder) {
1308
+ return { ok: false, released: false, reason: 'not-holder', holder: record.holder };
1309
+ }
1310
+ // The nonce is issued once per acquisition and returned only in that
1311
+ // claimWriter result: knowing the session id is not enough to release or
1312
+ // steal another acquisition's lease.
1313
+ if (typeof args.nonce !== 'string' || args.nonce.length === 0 || args.nonce !== record.nonce) {
1314
+ return { ok: false, released: false, reason: 'bad-nonce' };
1315
+ }
1316
+ if (args.token !== undefined && args.token !== record.token) {
1317
+ return { ok: false, released: false, reason: 'stale-token' };
1318
+ }
1319
+ try {
1320
+ fs.unlinkSync(writerFile());
1321
+ return { ok: true, released: true, holder, token: record.token };
1322
+ } catch (error) {
1323
+ if (error.code === 'ENOENT') return { ok: true, released: false, reason: 'no-lock' };
1324
+ throw busError('E_LEASE_WRITE', `cannot release writer lock: ${error.code || error.message}`);
1325
+ }
1326
+ });
1327
+ }
1328
+
1329
+ function fencedWrite(args = {}) {
1330
+ const holder = normalizeSessionId(args.holder ?? sessionId, 'holder');
1331
+ if (sessionId && holder !== sessionId) {
1332
+ throw busError('E_FROM_MISMATCH', `bus is bound to ${sessionId}, cannot write as ${holder}`);
1333
+ }
1334
+ if (typeof args.file !== 'string' || args.file.trim().length === 0) {
1335
+ throw busError('E_BAD_PATH', 'fencedWrite requires a file path');
1336
+ }
1337
+ if (args.value === undefined) throw busError('E_BAD_VALUE', 'fencedWrite requires a value');
1338
+ const target = path.isAbsolute(args.file)
1339
+ ? path.resolve(args.file)
1340
+ : path.resolve(root, args.file);
1341
+ // The root is lexically "inside" itself, so the jail below would accept it
1342
+ // while `dirname(target)` is the root's *parent*: the commit temp file would
1343
+ // be created outside the jail and only the rename would fail (P17). The root
1344
+ // and any existing directory are not file targets; refuse them up front.
1345
+ if (target === root) {
1346
+ throw busError('E_BAD_PATH', 'fencedWrite target must not be the bus root itself');
1347
+ }
1348
+ let targetStat = null;
1349
+ try {
1350
+ targetStat = fs.lstatSync(target);
1351
+ } catch (error) {
1352
+ if (error.code !== 'ENOENT') {
1353
+ throw busError('E_PATH_OUTSIDE_ROOT', `cannot inspect fencedWrite target: ${error.code || error.message}`);
1354
+ }
1355
+ }
1356
+ if (targetStat && targetStat.isDirectory()) {
1357
+ throw busError('E_BAD_PATH', `fencedWrite target is a directory: ${target}`);
1358
+ }
1359
+ // Real path jail: assertInside is lexical, so a junction inside the root
1360
+ // would still let the write land outside. Resolve the nearest existing
1361
+ // ancestor and refuse anything whose real location escapes (P12).
1362
+ assertRealInsideRoot(root, target);
1363
+
1364
+ // Everything below runs under one cross-process commit lock. The lock is
1365
+ // acquired before the first lease read, so a concurrent claimWriter cannot
1366
+ // change the lease between the checks and the rename. The lease is checked
1367
+ // again after JSON.stringify (which may run user toJSON code) and
1368
+ // immediately before the rename (P13).
1369
+ return withCommitLock(() => {
1370
+ const initial = checkWriterLease(holder, args);
1371
+
1372
+ let text;
1373
+ try {
1374
+ const serialized = JSON.stringify(args.value, null, 2);
1375
+ if (typeof serialized !== 'string') {
1376
+ throw busError('E_BAD_VALUE', 'fencedWrite value is not JSON-serializable');
1377
+ }
1378
+ text = `${serialized}\n`;
1379
+ } catch (error) {
1380
+ if (error && error.busError) throw error;
1381
+ throw busError('E_BAD_VALUE', `fencedWrite value is not JSON-serializable: ${error?.message ?? error}`);
1382
+ }
1383
+
1384
+ runHook('afterSerialize', { file: target, holder, token: initial.token });
1385
+
1386
+ // Serialization can take arbitrarily long (toJSON). If the lease expired
1387
+ // or another acquisition took over in that window, abort before any byte
1388
+ // reaches a temp file.
1389
+ checkWriterLease(holder, args);
1390
+ // Re-resolve the real path inside the lock: the first check ran before
1391
+ // the lock, and a junction could have been swapped in meanwhile.
1392
+ assertRealInsideRoot(root, target);
1393
+
1394
+ const dir = path.dirname(target);
1395
+ // target === root is rejected above, so dirname(target) is the root or
1396
+ // deeper; assert it anyway so a temp file can never be created outside
1397
+ // the jail even if that guard is ever loosened (P17).
1398
+ assertInside(root, dir);
1399
+ const temp = path.join(dir, `.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
1400
+ let fd;
1401
+ try {
1402
+ fd = fs.openSync(temp, 'wx');
1403
+ fs.writeFileSync(fd, text, 'utf8');
1404
+ try { fs.fsyncSync(fd); } catch { /* fsync is best effort */ }
1405
+ fs.closeSync(fd);
1406
+ fd = undefined;
1407
+
1408
+ // Final gate, after the temp file is durable and immediately before the
1409
+ // rename. claim/renew/release share the commit lock, so no other
1410
+ // process can slip a takeover in between this read and renameWithRetry.
1411
+ const finalRecord = checkWriterLease(holder, args);
1412
+ renameWithRetry(temp, target);
1413
+ return { ok: true, file: target, holder, token: finalRecord.token };
1414
+ } catch (error) {
1415
+ if (fd !== undefined) {
1416
+ try { fs.closeSync(fd); } catch { /* ignore */ }
1417
+ }
1418
+ try {
1419
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
1420
+ } catch { /* ignore */ }
1421
+ if (error && error.busError) throw error;
1422
+ throw busError('E_WRITE', `cannot write ${target}: ${error?.code || error?.message || error}`);
1423
+ }
1424
+ });
1425
+ }
1426
+
1427
+ return {
1428
+ root,
1429
+ sessionId,
1430
+ host,
1431
+ liveDir,
1432
+ maxBodyChars,
1433
+ maxPending,
1434
+ send,
1435
+ poll,
1436
+ ack,
1437
+ peerState: (recipient, at = nowMs()) => peerState(normalizeSessionId(recipient, 'recipient'), at),
1438
+ claimWriter,
1439
+ renewWriter,
1440
+ releaseWriter,
1441
+ writerStatus,
1442
+ fencedWrite,
1443
+ };
1444
+ }
1445
+
1446
+ export default createBus;