daftari 3.17.0 → 3.19.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 (318) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +3 -3
  3. package/dist/access/rbac.d.ts.map +1 -1
  4. package/dist/access/rbac.js +3 -1
  5. package/dist/access/rbac.js.map +1 -1
  6. package/dist/asof/git-read.d.ts.map +1 -1
  7. package/dist/asof/git-read.js +11 -9
  8. package/dist/asof/git-read.js.map +1 -1
  9. package/dist/asof/index.d.ts.map +1 -1
  10. package/dist/asof/index.js +3 -1
  11. package/dist/asof/index.js.map +1 -1
  12. package/dist/asof/report.d.ts.map +1 -1
  13. package/dist/asof/report.js +5 -3
  14. package/dist/asof/report.js.map +1 -1
  15. package/dist/asof/snapshot.d.ts +4 -3
  16. package/dist/asof/snapshot.d.ts.map +1 -1
  17. package/dist/asof/snapshot.js +44 -24
  18. package/dist/asof/snapshot.js.map +1 -1
  19. package/dist/board/ledger.d.ts.map +1 -1
  20. package/dist/board/ledger.js +1 -0
  21. package/dist/board/ledger.js.map +1 -1
  22. package/dist/board/sources/index.d.ts.map +1 -1
  23. package/dist/board/sources/index.js +2 -1
  24. package/dist/board/sources/index.js.map +1 -1
  25. package/dist/board/sources/lint.d.ts.map +1 -1
  26. package/dist/board/sources/lint.js +3 -1
  27. package/dist/board/sources/lint.js.map +1 -1
  28. package/dist/board/sources/staleness.d.ts +1 -0
  29. package/dist/board/sources/staleness.d.ts.map +1 -1
  30. package/dist/board/sources/staleness.js +101 -9
  31. package/dist/board/sources/staleness.js.map +1 -1
  32. package/dist/board/sources/staleness.test.js +27 -0
  33. package/dist/board/sources/staleness.test.js.map +1 -1
  34. package/dist/board/types.d.ts +7 -0
  35. package/dist/board/types.d.ts.map +1 -1
  36. package/dist/cli.d.ts.map +1 -1
  37. package/dist/cli.js +9 -2
  38. package/dist/cli.js.map +1 -1
  39. package/dist/consolidate/constants.d.ts.map +1 -1
  40. package/dist/consolidate/constants.js +6 -1
  41. package/dist/consolidate/constants.js.map +1 -1
  42. package/dist/consolidate/index.d.ts.map +1 -1
  43. package/dist/consolidate/index.js +1 -1
  44. package/dist/consolidate/index.js.map +1 -1
  45. package/dist/court/index.d.ts.map +1 -1
  46. package/dist/court/index.js +8 -1
  47. package/dist/court/index.js.map +1 -1
  48. package/dist/curation/chains.d.ts +21 -0
  49. package/dist/curation/chains.d.ts.map +1 -0
  50. package/dist/curation/chains.js +151 -0
  51. package/dist/curation/chains.js.map +1 -0
  52. package/dist/curation/governance-journals.d.ts +2 -0
  53. package/dist/curation/governance-journals.d.ts.map +1 -0
  54. package/dist/curation/governance-journals.js +36 -0
  55. package/dist/curation/governance-journals.js.map +1 -0
  56. package/dist/curation/grounding.d.ts +42 -0
  57. package/dist/curation/grounding.d.ts.map +1 -0
  58. package/dist/curation/grounding.js +247 -0
  59. package/dist/curation/grounding.js.map +1 -0
  60. package/dist/curation/lint-page.d.ts +22 -0
  61. package/dist/curation/lint-page.d.ts.map +1 -0
  62. package/dist/curation/lint-page.js +97 -0
  63. package/dist/curation/lint-page.js.map +1 -0
  64. package/dist/curation/lint-voice.d.ts.map +1 -1
  65. package/dist/curation/lint-voice.js +16 -11
  66. package/dist/curation/lint-voice.js.map +1 -1
  67. package/dist/curation/lint.d.ts +7 -1
  68. package/dist/curation/lint.d.ts.map +1 -1
  69. package/dist/curation/lint.js +85 -25
  70. package/dist/curation/lint.js.map +1 -1
  71. package/dist/curation/provenance.d.ts.map +1 -1
  72. package/dist/curation/provenance.js.map +1 -1
  73. package/dist/curation/question-candidates.d.ts +27 -0
  74. package/dist/curation/question-candidates.d.ts.map +1 -0
  75. package/dist/curation/question-candidates.js +151 -0
  76. package/dist/curation/question-candidates.js.map +1 -0
  77. package/dist/curation/questions.d.ts +9 -0
  78. package/dist/curation/questions.d.ts.map +1 -0
  79. package/dist/curation/questions.js +44 -0
  80. package/dist/curation/questions.js.map +1 -0
  81. package/dist/curation/review-log.d.ts +36 -0
  82. package/dist/curation/review-log.d.ts.map +1 -0
  83. package/dist/curation/review-log.js +195 -0
  84. package/dist/curation/review-log.js.map +1 -0
  85. package/dist/curation/review-stats.d.ts +39 -0
  86. package/dist/curation/review-stats.d.ts.map +1 -0
  87. package/dist/curation/review-stats.js +222 -0
  88. package/dist/curation/review-stats.js.map +1 -0
  89. package/dist/curation/review-throughput.d.ts +1 -0
  90. package/dist/curation/review-throughput.d.ts.map +1 -1
  91. package/dist/curation/review-throughput.js +1 -1
  92. package/dist/curation/review-throughput.js.map +1 -1
  93. package/dist/curation/shadow.d.ts.map +1 -1
  94. package/dist/curation/shadow.js +2 -0
  95. package/dist/curation/shadow.js.map +1 -1
  96. package/dist/curation/source-refs.d.ts +7 -0
  97. package/dist/curation/source-refs.d.ts.map +1 -1
  98. package/dist/curation/source-refs.js +46 -1
  99. package/dist/curation/source-refs.js.map +1 -1
  100. package/dist/curation/staged-actions.d.ts +12 -3
  101. package/dist/curation/staged-actions.d.ts.map +1 -1
  102. package/dist/curation/staged-actions.js +206 -46
  103. package/dist/curation/staged-actions.js.map +1 -1
  104. package/dist/curation/staleness.d.ts +6 -0
  105. package/dist/curation/staleness.d.ts.map +1 -1
  106. package/dist/curation/staleness.js +41 -0
  107. package/dist/curation/staleness.js.map +1 -1
  108. package/dist/curation/structural.d.ts.map +1 -1
  109. package/dist/curation/structural.js +6 -4
  110. package/dist/curation/structural.js.map +1 -1
  111. package/dist/curation/supersede-chains.d.ts +10 -0
  112. package/dist/curation/supersede-chains.d.ts.map +1 -0
  113. package/dist/curation/supersede-chains.js +95 -0
  114. package/dist/curation/supersede-chains.js.map +1 -0
  115. package/dist/curation/tension-blast.d.ts +5 -1
  116. package/dist/curation/tension-blast.d.ts.map +1 -1
  117. package/dist/curation/tension-blast.js +56 -9
  118. package/dist/curation/tension-blast.js.map +1 -1
  119. package/dist/curation/tension.d.ts +4 -1
  120. package/dist/curation/tension.d.ts.map +1 -1
  121. package/dist/curation/tension.js +48 -18
  122. package/dist/curation/tension.js.map +1 -1
  123. package/dist/curation/tier0.d.ts +3 -1
  124. package/dist/curation/tier0.d.ts.map +1 -1
  125. package/dist/curation/tier0.js +7 -3
  126. package/dist/curation/tier0.js.map +1 -1
  127. package/dist/curation/vault-docs.js +4 -4
  128. package/dist/curation/vault-docs.js.map +1 -1
  129. package/dist/distill/citation-check.d.ts +29 -0
  130. package/dist/distill/citation-check.d.ts.map +1 -0
  131. package/dist/distill/citation-check.js +109 -0
  132. package/dist/distill/citation-check.js.map +1 -0
  133. package/dist/distill/cli.d.ts +1 -1
  134. package/dist/distill/cli.d.ts.map +1 -1
  135. package/dist/distill/cli.js +127 -16
  136. package/dist/distill/cli.js.map +1 -1
  137. package/dist/distill/cost.d.ts +7 -3
  138. package/dist/distill/cost.d.ts.map +1 -1
  139. package/dist/distill/cost.js.map +1 -1
  140. package/dist/distill/extract.d.ts +38 -1
  141. package/dist/distill/extract.d.ts.map +1 -1
  142. package/dist/distill/extract.js +48 -6
  143. package/dist/distill/extract.js.map +1 -1
  144. package/dist/distill/index.d.ts +1 -1
  145. package/dist/distill/index.d.ts.map +1 -1
  146. package/dist/distill/index.js +1 -1
  147. package/dist/distill/index.js.map +1 -1
  148. package/dist/distill/propose.d.ts.map +1 -1
  149. package/dist/distill/propose.js +23 -0
  150. package/dist/distill/propose.js.map +1 -1
  151. package/dist/distill/receipt-store.d.ts.map +1 -1
  152. package/dist/distill/receipt-store.js +4 -3
  153. package/dist/distill/receipt-store.js.map +1 -1
  154. package/dist/distill/state.d.ts +39 -0
  155. package/dist/distill/state.d.ts.map +1 -1
  156. package/dist/distill/state.js +84 -7
  157. package/dist/distill/state.js.map +1 -1
  158. package/dist/eval/index.js.map +1 -1
  159. package/dist/eval/llm-openrouter.d.ts.map +1 -1
  160. package/dist/eval/llm-openrouter.js +6 -4
  161. package/dist/eval/llm-openrouter.js.map +1 -1
  162. package/dist/eval/llm.d.ts +2 -0
  163. package/dist/eval/llm.d.ts.map +1 -1
  164. package/dist/eval/llm.js +29 -4
  165. package/dist/eval/llm.js.map +1 -1
  166. package/dist/eval/tool-surface.d.ts.map +1 -1
  167. package/dist/eval/tool-surface.js +4 -1
  168. package/dist/eval/tool-surface.js.map +1 -1
  169. package/dist/federation/classification.d.ts.map +1 -1
  170. package/dist/federation/classification.js +4 -0
  171. package/dist/federation/classification.js.map +1 -1
  172. package/dist/federation/mounts.d.ts.map +1 -1
  173. package/dist/federation/mounts.js +3 -2
  174. package/dist/federation/mounts.js.map +1 -1
  175. package/dist/fence/detect.js +1 -1
  176. package/dist/fence/detect.js.map +1 -1
  177. package/dist/frontmatter/schema.d.ts.map +1 -1
  178. package/dist/frontmatter/schema.js +20 -0
  179. package/dist/frontmatter/schema.js.map +1 -1
  180. package/dist/frontmatter/types.d.ts +4 -1
  181. package/dist/frontmatter/types.d.ts.map +1 -1
  182. package/dist/frontmatter/types.js +3 -0
  183. package/dist/frontmatter/types.js.map +1 -1
  184. package/dist/import/langgraph-store.d.ts +2 -1
  185. package/dist/import/langgraph-store.d.ts.map +1 -1
  186. package/dist/import/langgraph-store.js +23 -4
  187. package/dist/import/langgraph-store.js.map +1 -1
  188. package/dist/index.d.ts +1 -1
  189. package/dist/index.d.ts.map +1 -1
  190. package/dist/index.js +27 -10
  191. package/dist/index.js.map +1 -1
  192. package/dist/integrations/distill.d.ts.map +1 -1
  193. package/dist/integrations/distill.js +5 -3
  194. package/dist/integrations/distill.js.map +1 -1
  195. package/dist/interview/index.d.ts.map +1 -1
  196. package/dist/interview/index.js +7 -1
  197. package/dist/interview/index.js.map +1 -1
  198. package/dist/interview/questions.d.ts +1 -1
  199. package/dist/interview/questions.d.ts.map +1 -1
  200. package/dist/interview/questions.js +6 -39
  201. package/dist/interview/questions.js.map +1 -1
  202. package/dist/interview/transcript.d.ts +2 -0
  203. package/dist/interview/transcript.d.ts.map +1 -1
  204. package/dist/interview/transcript.js +19 -5
  205. package/dist/interview/transcript.js.map +1 -1
  206. package/dist/lifecycle/lock.d.ts +19 -4
  207. package/dist/lifecycle/lock.d.ts.map +1 -1
  208. package/dist/lifecycle/lock.js +760 -171
  209. package/dist/lifecycle/lock.js.map +1 -1
  210. package/dist/okf/import.d.ts.map +1 -1
  211. package/dist/okf/import.js +15 -3
  212. package/dist/okf/import.js.map +1 -1
  213. package/dist/search/amended-by.d.ts +45 -0
  214. package/dist/search/amended-by.d.ts.map +1 -0
  215. package/dist/search/amended-by.js +62 -0
  216. package/dist/search/amended-by.js.map +1 -0
  217. package/dist/search/hybrid.d.ts +5 -0
  218. package/dist/search/hybrid.d.ts.map +1 -1
  219. package/dist/search/hybrid.js.map +1 -1
  220. package/dist/search/reindex.d.ts +2 -0
  221. package/dist/search/reindex.d.ts.map +1 -1
  222. package/dist/search/reindex.js +44 -12
  223. package/dist/search/reindex.js.map +1 -1
  224. package/dist/search/watcher.d.ts +2 -1
  225. package/dist/search/watcher.d.ts.map +1 -1
  226. package/dist/search/watcher.js +11 -19
  227. package/dist/search/watcher.js.map +1 -1
  228. package/dist/serve/index.d.ts.map +1 -1
  229. package/dist/serve/index.js +21 -10
  230. package/dist/serve/index.js.map +1 -1
  231. package/dist/serve/session.d.ts +3 -1
  232. package/dist/serve/session.d.ts.map +1 -1
  233. package/dist/serve/session.js +32 -4
  234. package/dist/serve/session.js.map +1 -1
  235. package/dist/server.d.ts.map +1 -1
  236. package/dist/server.js +10 -1
  237. package/dist/server.js.map +1 -1
  238. package/dist/sleep/cycle.d.ts +2 -0
  239. package/dist/sleep/cycle.d.ts.map +1 -1
  240. package/dist/sleep/cycle.js +65 -35
  241. package/dist/sleep/cycle.js.map +1 -1
  242. package/dist/sleep/index.d.ts.map +1 -1
  243. package/dist/sleep/index.js +1 -1
  244. package/dist/sleep/index.js.map +1 -1
  245. package/dist/sleep/report.d.ts.map +1 -1
  246. package/dist/sleep/report.js +3 -2
  247. package/dist/sleep/report.js.map +1 -1
  248. package/dist/storage/index-db.d.ts +28 -1
  249. package/dist/storage/index-db.d.ts.map +1 -1
  250. package/dist/storage/index-db.js +82 -23
  251. package/dist/storage/index-db.js.map +1 -1
  252. package/dist/storage/local.d.ts +6 -2
  253. package/dist/storage/local.d.ts.map +1 -1
  254. package/dist/storage/local.js +45 -7
  255. package/dist/storage/local.js.map +1 -1
  256. package/dist/storage/sync.d.ts +1 -0
  257. package/dist/storage/sync.d.ts.map +1 -1
  258. package/dist/storage/sync.js +31 -6
  259. package/dist/storage/sync.js.map +1 -1
  260. package/dist/tools/board.d.ts +1 -0
  261. package/dist/tools/board.d.ts.map +1 -1
  262. package/dist/tools/board.js +27 -2
  263. package/dist/tools/board.js.map +1 -1
  264. package/dist/tools/board.test.js +4 -2
  265. package/dist/tools/board.test.js.map +1 -1
  266. package/dist/tools/chains.d.ts +11 -0
  267. package/dist/tools/chains.d.ts.map +1 -0
  268. package/dist/tools/chains.js +133 -0
  269. package/dist/tools/chains.js.map +1 -0
  270. package/dist/tools/curation.d.ts +6 -1
  271. package/dist/tools/curation.d.ts.map +1 -1
  272. package/dist/tools/curation.js +114 -69
  273. package/dist/tools/curation.js.map +1 -1
  274. package/dist/tools/erase.d.ts.map +1 -1
  275. package/dist/tools/erase.js +14 -19
  276. package/dist/tools/erase.js.map +1 -1
  277. package/dist/tools/positions.d.ts.map +1 -1
  278. package/dist/tools/positions.js +4 -2
  279. package/dist/tools/positions.js.map +1 -1
  280. package/dist/tools/question-candidates.d.ts +11 -0
  281. package/dist/tools/question-candidates.d.ts.map +1 -0
  282. package/dist/tools/question-candidates.js +205 -0
  283. package/dist/tools/question-candidates.js.map +1 -0
  284. package/dist/tools/read.d.ts +5 -0
  285. package/dist/tools/read.d.ts.map +1 -1
  286. package/dist/tools/read.js +39 -12
  287. package/dist/tools/read.js.map +1 -1
  288. package/dist/tools/receipt.d.ts +4 -0
  289. package/dist/tools/receipt.d.ts.map +1 -1
  290. package/dist/tools/receipt.js +262 -22
  291. package/dist/tools/receipt.js.map +1 -1
  292. package/dist/tools/search.d.ts.map +1 -1
  293. package/dist/tools/search.js +53 -4
  294. package/dist/tools/search.js.map +1 -1
  295. package/dist/tools/staged-actions.d.ts +2 -1
  296. package/dist/tools/staged-actions.d.ts.map +1 -1
  297. package/dist/tools/staged-actions.js +152 -46
  298. package/dist/tools/staged-actions.js.map +1 -1
  299. package/dist/tools/write.d.ts +15 -2
  300. package/dist/tools/write.d.ts.map +1 -1
  301. package/dist/tools/write.js +747 -89
  302. package/dist/tools/write.js.map +1 -1
  303. package/dist/utils/config.d.ts +10 -2
  304. package/dist/utils/config.d.ts.map +1 -1
  305. package/dist/utils/config.js +61 -1
  306. package/dist/utils/config.js.map +1 -1
  307. package/dist/utils/git.d.ts +1 -0
  308. package/dist/utils/git.d.ts.map +1 -1
  309. package/dist/utils/git.js +18 -0
  310. package/dist/utils/git.js.map +1 -1
  311. package/dist/utils/vault-gitignore.d.ts +1 -1
  312. package/dist/utils/vault-gitignore.d.ts.map +1 -1
  313. package/dist/utils/vault-gitignore.js +25 -9
  314. package/dist/utils/vault-gitignore.js.map +1 -1
  315. package/dist/view/board-page.test.js +1 -1
  316. package/dist/view/board-page.test.js.map +1 -1
  317. package/package.json +3 -1
  318. package/templates/config.yaml +18 -3
@@ -1,35 +1,231 @@
1
1
  // Process-level lockfile for a vault. Prevents two daftari processes from
2
2
  // running against the same vault concurrently and corrupting the shared
3
3
  // index.db. See docs/superpowers/plans/2026-05-20-process-lockfile.md (#52).
4
- import { execFileSync } from "node:child_process";
5
- import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
4
+ //
5
+ // Lease lock (istf). Liveness is a renewed lease, not "is this pid a daftari
6
+ // process?". A vault can be shared across machines (a FUSE-mounted Cowork
7
+ // folder seen from several VMs, a network share), where the holder's pid means
8
+ // nothing to us and pid reuse is routine, and Windows has no `ps` at all. So:
9
+ // - The holder id is host identity + pid + a random nonce (hostId(), below).
10
+ // - The holder renews every heartbeatMs (default HEARTBEAT_MS) by rewriting
11
+ // its OWN side file, process.lock.hb-<nonce>. process.lock itself is
12
+ // written once, at the claim, and never rewritten — so a holder that
13
+ // stalls and resumes can never overwrite a successor's lock.
14
+ // - Another process may take over only once the lease has lapsed: no renewal
15
+ // for leaseMs (default LEASE_MS = 10 heartbeats). Expiry is judged on the
16
+ // holder's own recorded heartbeatMs/leaseMs, so a future change of the
17
+ // defaults never misjudges an older holder.
18
+ // - A lease that LOOKS lapsed by our wall clock is still watched for one
19
+ // more renewal window before it is broken: a holder whose clock runs
20
+ // behind ours, or that just woke from sleep, renews and is seen as live.
21
+ // - Same-host fast path: if the holder is on this host and its pid is dead
22
+ // (`process.kill(pid, 0)` — cross-platform, never `ps`), the lock is stale
23
+ // after one renewal window (2 heartbeats + 250ms) with no renewal, instead
24
+ // of the full lease. Never at once: sandboxes can share a host id, and a
25
+ // holder that renews in that window is treated as foreign.
26
+ // - A same-host holder is SIGTERMed (the stdio takeover, or serve
27
+ // --takeover) only after its heartbeat is SEEN to advance: a live pid alone
28
+ // may be a recycled one belonging to an unrelated process.
29
+ // - A holder that finds its lock is no longer its own (taken over while it
30
+ // was stalled) stops renewing and reports the lost lease; the servers shut
31
+ // down on it rather than keep writing as a second writer.
32
+ // Takeover is atomic: the claim is always an O_EXCL create. Breakers of one
33
+ // stale lock are serialized by an O_EXCL succession claim keyed by its bytes;
34
+ // the single winner removes it by an atomic rename to a private name and
35
+ // checks what it moved — if that is not the lock judged stale, it is put back
36
+ // with an O_EXCL create that never overwrites. Release takes the same claim.
37
+ // Lock-file transitions depend on no clock; only recovering a crashed
38
+ // breaker's claim uses a local timeout.
39
+ //
40
+ // Accepted residual (decision 2026-10-26): with only O_EXCL and rename — no
41
+ // compare-and-swap, no OS lock — a few steps remain check-then-act (e.g. a
42
+ // breaker's re-check of the heartbeat, then its rename). The window is
43
+ // microseconds wide and needs a process to stall or crash exactly inside it.
44
+ // If it is hit, two processes can hold the vault at once, but the one whose
45
+ // lock is gone notices at its next renewal and shuts down: overlap is bounded
46
+ // by one heartbeat (HEARTBEAT_MS) plus its shutdown drain.
47
+ import { createHash, randomBytes } from "node:crypto";
48
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, renameSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
49
+ import { hostname, networkInterfaces, tmpdir } from "node:os";
6
50
  import { join } from "node:path";
7
51
  import { setTimeout as sleep } from "node:timers/promises";
8
52
  import { err, ok } from "../frontmatter/types.js";
53
+ // Renew every 2s; the lease lapses after 20s without a renewal (10 missed
54
+ // heartbeats). 10x absorbs event-loop stalls (a synchronous SQLite batch),
55
+ // GC pauses and slow writes on a FUSE or network mount without a live holder
56
+ // being judged dead, while a crashed holder on another machine frees the vault
57
+ // within ~20s. Same-host crashes do not wait at all (dead-pid fast path).
58
+ export const HEARTBEAT_MS = 2_000;
59
+ export const LEASE_MS = 10 * HEARTBEAT_MS;
60
+ // Exit code for a holder that shuts down because its lease was taken over.
61
+ // Non-zero so a supervisor (systemd, launchd, pm2) sees the loss; 75 is
62
+ // EX_TEMPFAIL: the vault was busy, try again later.
63
+ export const EXIT_LEASE_LOST = 75;
64
+ // A lockfile that stays unparseable this long is not one being written.
65
+ const UNREADABLE_GRACE_MS = 1_000;
9
66
  function lockPath(vaultRoot) {
10
67
  return join(vaultRoot, ".daftari", "process.lock");
11
68
  }
12
- export function readLockfile(vaultRoot) {
69
+ // A nonce names a side file, so a foreign lockfile must not be able to steer
70
+ // that path anywhere (no separators, no "..").
71
+ const NONCE_RE = /^[A-Za-z0-9_-]{1,64}$/;
72
+ function heartbeatPath(vaultRoot, nonce) {
73
+ return NONCE_RE.test(nonce) ? join(vaultRoot, ".daftari", `process.lock.hb-${nonce}`) : null;
74
+ }
75
+ // The holder's latest renewal: its heartbeat side file, or — before the first
76
+ // renewal, or for a lock without one — the claim time recorded in the lock.
77
+ export function lastHeartbeat(vaultRoot, lock) {
78
+ const path = lock.nonce === undefined ? null : heartbeatPath(vaultRoot, lock.nonce);
79
+ if (path !== null) {
80
+ const raw = readOptional(path);
81
+ if (raw) {
82
+ try {
83
+ const hb = JSON.parse(raw);
84
+ if (hb.nonce === lock.nonce && typeof hb.heartbeatAt === "string")
85
+ return hb.heartbeatAt;
86
+ }
87
+ catch {
88
+ // mid-replace or garbage: fall back to the claim time
89
+ }
90
+ }
91
+ }
92
+ return lock.heartbeatAt;
93
+ }
94
+ function readOptional(path) {
95
+ try {
96
+ return readFileSync(path, "utf-8").trim();
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ // Host identity: hostname, plus on Linux the kernel boot id and the pid
103
+ // namespace. The pid namespace matters: sandboxes inside one VM (and
104
+ // containers on one kernel) share a boot id but not a pid space, so a pid
105
+ // read from another namespace says nothing about liveness here. macOS and
106
+ // Windows expose no boot id without a subprocess, so there the hostname is
107
+ // paired with the machine's hardware (MAC) addresses — see isSameHost.
108
+ let cachedHostId;
109
+ export function hostId() {
110
+ if (cachedHostId !== undefined)
111
+ return cachedHostId;
112
+ const parts = [hostname()];
113
+ const boot = readOptional("/proc/sys/kernel/random/boot_id");
114
+ if (boot)
115
+ parts.push(`boot=${boot}`);
116
+ try {
117
+ parts.push(`pidns=${readlinkSync("/proc/self/ns/pid")}`);
118
+ }
119
+ catch {
120
+ // Not Linux (or /proc unavailable): hostname + MACs only.
121
+ }
122
+ cachedHostId = parts.join("|");
123
+ return cachedHostId;
124
+ }
125
+ let cachedMacs;
126
+ export function hostMacs() {
127
+ if (cachedMacs !== undefined)
128
+ return cachedMacs;
129
+ const macs = new Set();
130
+ for (const list of Object.values(networkInterfaces())) {
131
+ for (const nic of list ?? []) {
132
+ if (!nic.internal && nic.mac && nic.mac !== "00:00:00:00:00:00")
133
+ macs.add(nic.mac);
134
+ }
135
+ }
136
+ cachedMacs = [...macs].sort();
137
+ return cachedMacs;
138
+ }
139
+ // Same host = same host id AND at least one hardware address in common.
140
+ // Intersection rather than equality: a VPN or a docker bridge coming up
141
+ // between two starts must not turn this machine into "another machine". No
142
+ // addresses on either side (a VM without a non-internal NIC) is unknown, so
143
+ // NOT same host. Even a true answer is only a hint: same-host shortcuts still
144
+ // wait one renewal window (see judge).
145
+ function isSameHost(prior) {
146
+ if (prior.host !== hostId())
147
+ return false;
148
+ const theirs = prior.macs ?? [];
149
+ const ours = hostMacs();
150
+ // No hardware addresses on either side is missing evidence, not a match.
151
+ if (theirs.length === 0 || ours.length === 0)
152
+ return false;
153
+ if (!theirs.some((m) => ours.includes(m)))
154
+ return false;
155
+ // And the holder's marker must be in OUR temp dir. Sandboxes that clone a
156
+ // host id do not share a /tmp, so this ties the pid we would test (or
157
+ // signal) to a process that really ran here.
158
+ const marker = prior.nonce === undefined ? null : holderMarkerPath(prior.nonce);
159
+ return marker !== null && existsSync(marker);
160
+ }
161
+ // A per-holder file in the OS temp dir, written at the claim and removed on
162
+ // release. Exported for tests.
163
+ export function holderMarkerPath(nonce) {
164
+ return NONCE_RE.test(nonce) ? join(tmpdir(), `daftari-lock-holder-${nonce}`) : null;
165
+ }
166
+ function writeHolderMarker(nonce) {
167
+ const path = holderMarkerPath(nonce);
168
+ if (path === null)
169
+ return;
170
+ try {
171
+ writeFileSync(path, String(process.pid), "utf-8");
172
+ }
173
+ catch {
174
+ // without a marker we are simply "another host" to local contenders
175
+ }
176
+ }
177
+ function removeHolderMarker(nonce) {
178
+ const path = holderMarkerPath(nonce);
179
+ if (path === null)
180
+ return;
181
+ try {
182
+ unlinkSync(path);
183
+ }
184
+ catch {
185
+ // never written
186
+ }
187
+ }
188
+ function parseLock(raw) {
13
189
  try {
14
- const raw = readFileSync(lockPath(vaultRoot), "utf-8");
15
190
  const parsed = JSON.parse(raw);
16
191
  if (typeof parsed === "object" &&
17
192
  parsed !== null &&
18
193
  parsed.daftari === true &&
19
194
  typeof parsed.pid === "number") {
20
- return ok(parsed);
195
+ return parsed;
21
196
  }
22
- return ok(null);
197
+ return null;
23
198
  }
24
- catch (e) {
25
- const errno = e;
26
- if (errno.code === "ENOENT")
27
- return ok(null);
28
- if (e instanceof SyntaxError)
29
- return ok(null);
30
- return err(errno);
199
+ catch {
200
+ return null;
201
+ }
202
+ }
203
+ // Raw lockfile content, null when absent. Windows can refuse to open a file
204
+ // that is being atomically replaced at that instant (EPERM/EBUSY); a short
205
+ // retry rides that out instead of failing the acquire.
206
+ function readRaw(path) {
207
+ for (let i = 0;; i++) {
208
+ try {
209
+ return ok(readFileSync(path, "utf-8"));
210
+ }
211
+ catch (e) {
212
+ const errno = e;
213
+ if (errno.code === "ENOENT")
214
+ return ok(null);
215
+ if ((errno.code === "EPERM" || errno.code === "EBUSY") && i < 5)
216
+ continue;
217
+ return err(errno);
218
+ }
31
219
  }
32
220
  }
221
+ export function readLockfile(vaultRoot) {
222
+ const raw = readRaw(lockPath(vaultRoot));
223
+ if (!raw.ok)
224
+ return raw;
225
+ if (raw.value === null)
226
+ return ok(null);
227
+ return ok(parseLock(raw.value));
228
+ }
33
229
  export function writeLockfile(vaultRoot, data) {
34
230
  try {
35
231
  mkdirSync(join(vaultRoot, ".daftari"), { recursive: true });
@@ -40,9 +236,9 @@ export function writeLockfile(vaultRoot, data) {
40
236
  return err(e);
41
237
  }
42
238
  }
43
- // `kill(pid, 0)` is the POSIX way to test process liveness without delivering
44
- // a signal. ESRCH = no such process; EPERM = exists but not ours (still alive
45
- // for our purposes — someone else owns it but it exists).
239
+ // `kill(pid, 0)` tests process liveness without delivering a signal, on POSIX
240
+ // and on Windows. ESRCH = no such process; EPERM = exists but not ours (still
241
+ // alive for our purposes). Meaningful only for a pid on THIS host.
46
242
  export function isProcessAlive(pid) {
47
243
  try {
48
244
  process.kill(pid, 0);
@@ -53,64 +249,6 @@ export function isProcessAlive(pid) {
53
249
  return errno.code === "EPERM";
54
250
  }
55
251
  }
56
- // Best-effort check that PID belongs to a daftari process running THIS vault.
57
- // Protects against PID recycling — if the original daftari died and the OS
58
- // reassigned its PID to e.g. vim, we must NOT SIGTERM the unrelated process.
59
- //
60
- // The vault path must appear in the command line as a WHOLE path token, not as
61
- // a bare substring. A plain `includes(vaultRoot)` check has two dangerous
62
- // false-positive modes, both of which end in SIGTERM against the wrong process
63
- // on the stdio takeover path (acquireLock below):
64
- // - prefix aliasing: vault "/x/v" substring-matches a daftari serving
65
- // "/x/v2", so a start against "/x/v" would kill the "/x/v2" server.
66
- // - PID recycling into an unrelated process whose argv holds a path INSIDE
67
- // the vault, e.g. `vim /x/v/notes.md` — we'd SIGTERM the editor.
68
- // A match is accepted only when the occurrence of vaultRoot is followed by a
69
- // token boundary: end-of-string, whitespace, or a lone trailing slash (a
70
- // "/x/v/" invocation). Every occurrence the old substring check accepted for
71
- // THIS vault still matches (the holder's own `--vault <resolved-path>` is
72
- // followed by a space or the end), so this adds no new false-negatives — which
73
- // matters because failing to recognize a live holder would overwrite its lock
74
- // and let two processes double-write index.db, the exact corruption the lock
75
- // exists to prevent.
76
- export function commandLineTargetsVault(commandLine, vaultRoot) {
77
- if (vaultRoot.length === 0)
78
- return false;
79
- for (let at = commandLine.indexOf(vaultRoot); at !== -1; at = commandLine.indexOf(vaultRoot, at + 1)) {
80
- const tail = commandLine.slice(at + vaultRoot.length);
81
- // end-of-string | starts with whitespace | a lone trailing slash then a boundary
82
- if (tail === "" || /^\s/.test(tail) || /^\/(\s|$)/.test(tail))
83
- return true;
84
- }
85
- return false;
86
- }
87
- // Best-effort check that PID belongs to a daftari process running THIS vault.
88
- // Protects against PID recycling — if the original daftari died and the OS
89
- // reassigned its PID to e.g. vim, we must NOT SIGTERM the unrelated process.
90
- //
91
- // Uses `ps -p PID -o command=` which is POSIX-portable. Both invocation modes
92
- // store `vaultRoot = resolve(vaultArg)` and pass it on argv as `--vault
93
- // <path>`, so the resolved path is the identity token we match (see
94
- // commandLineTargetsVault for the boundary rule). We deliberately do NOT match
95
- // on the substring "daftari" anywhere in the output, because the daftari repo's
96
- // own path contains that string and would falsely match any node process whose
97
- // cwd or argv includes the repo root (e.g. vitest workers).
98
- export function isDaftariProcess(pid, vaultRoot) {
99
- if (!isProcessAlive(pid))
100
- return false;
101
- try {
102
- const out = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
103
- encoding: "utf-8",
104
- stdio: ["ignore", "pipe", "ignore"],
105
- }).trim();
106
- if (out.length === 0)
107
- return false;
108
- return commandLineTargetsVault(out, vaultRoot);
109
- }
110
- catch {
111
- return false;
112
- }
113
- }
114
252
  // Wait until pid exits or until timeoutMs elapses. Returns true if pid is
115
253
  // gone. Polled with setTimeout so we don't peg a CPU core during the grace
116
254
  // window.
@@ -127,12 +265,11 @@ async function waitForExit(pid, timeoutMs) {
127
265
  const SIGTERM_GRACE_MS = 3000;
128
266
  // Atomic O_EXCL create. Returns ok(true) if we created the lockfile (sole
129
267
  // owner), ok(false) on EEXIST (caller must read and resolve).
130
- function tryCreateExclusive(vaultRoot, data) {
268
+ function tryCreateExclusive(path, content) {
131
269
  try {
132
- mkdirSync(join(vaultRoot, ".daftari"), { recursive: true });
133
- const fd = openSync(lockPath(vaultRoot), "wx");
270
+ const fd = openSync(path, "wx");
134
271
  try {
135
- writeSync(fd, JSON.stringify(data, null, 2));
272
+ writeSync(fd, content);
136
273
  }
137
274
  finally {
138
275
  closeSync(fd);
@@ -151,37 +288,471 @@ function tryCreateExclusive(vaultRoot, data) {
151
288
  // (O_EXCL), returns a definitive refusal, or removes a defunct lock and retries;
152
289
  // the bound stops two simultaneous stdio takeovers from ping-ponging forever.
153
290
  const MAX_ACQUIRE_ATTEMPTS = 5;
154
- // Remove the lockfile iff it still holds exactly `expected` (same pid AND
155
- // startedAt). Used to reclaim a defunct lock without a plain in-place overwrite:
156
- // if a competing acquirer replaced it with its own valid lock in the race
157
- // window, the content differs and we leave it untouched, so acquireLock
158
- // re-evaluates it as a live contender instead of clobbering it — which would
159
- // reintroduce the two-writers-one-vault corruption the lock exists to prevent.
160
- // The atomic claim is the tryCreateExclusive that follows on the next loop
161
- // iteration; this only avoids deleting a lock that is demonstrably not the
162
- // stale one we inspected.
291
+ function sameLock(a, b) {
292
+ return (a.pid === b.pid &&
293
+ a.startedAt === b.startedAt &&
294
+ a.nonce === b.nonce &&
295
+ a.heartbeatAt === b.heartbeatAt);
296
+ }
297
+ // Remove the lockfile iff it still holds `expected` — a parsed lock (same
298
+ // pid, startedAt, nonce, claim time) or the exact raw bytes of an unreadable
299
+ // one. Returns true if it removed it.
300
+ //
301
+ // The check and the removal are one atomic step: rename the file to a name
302
+ // only we know, then look at what we moved. If it is not `expected` (a
303
+ // competing acquirer replaced the stale lock in the race window), put it back
304
+ // with link(), which fails rather than overwrite should yet another lock have
305
+ // appeared meanwhile — in which case the displaced owner finds its lock gone
306
+ // at its next renewal and stops (see startHeartbeat). A plain read-then-unlink
307
+ // here could delete a competitor's fresh lock.
163
308
  export function removeLockIfUnchanged(vaultRoot, expected) {
164
- const current = readLockfile(vaultRoot);
165
- if (!current.ok || current.value === null)
166
- return;
167
- if (current.value.pid !== expected.pid || current.value.startedAt !== expected.startedAt) {
309
+ const path = lockPath(vaultRoot);
310
+ const isExpected = (raw) => {
311
+ if (typeof expected === "string")
312
+ return raw === expected.trim();
313
+ const parsed = parseLock(raw);
314
+ return parsed !== null && sameLock(parsed, expected);
315
+ };
316
+ // Cheap pre-check: never even move a lock that is visibly not ours to move.
317
+ const before = readOptional(path);
318
+ if (before === null || !isExpected(before))
319
+ return false;
320
+ const grave = `${path}.gone-${randomBytes(8).toString("hex")}`;
321
+ try {
322
+ renameSync(path, grave);
323
+ }
324
+ catch {
325
+ return false; // already gone (or unmovable) — the next exclusive create decides
326
+ }
327
+ const movedRaw = readOptional(grave) ?? "";
328
+ const moved = parseLock(movedRaw);
329
+ if (!isExpected(movedRaw)) {
330
+ restoreLock(grave, path, movedRaw);
331
+ return false;
332
+ }
333
+ try {
334
+ unlinkSync(grave);
335
+ }
336
+ catch {
337
+ // leftover side file; harmless and gitignored
338
+ }
339
+ if (moved?.nonce !== undefined)
340
+ removeHolderMarker(moved.nonce);
341
+ const hb = moved?.nonce === undefined ? null : heartbeatPath(vaultRoot, moved.nonce);
342
+ if (hb !== null) {
343
+ try {
344
+ unlinkSync(hb);
345
+ }
346
+ catch {
347
+ // no heartbeat file yet
348
+ }
349
+ }
350
+ return true;
351
+ }
352
+ // Put a lock we moved by mistake back, never overwriting a newer one: an
353
+ // O_EXCL create of the same bytes (works on every filesystem, unlike link()).
354
+ // Owners recognise their lock by its content (nonce), not its inode.
355
+ function restoreLock(grave, path, raw) {
356
+ tryCreateExclusive(path, raw);
357
+ try {
358
+ unlinkSync(grave);
359
+ }
360
+ catch {
361
+ // leftover side file; harmless and gitignored
362
+ }
363
+ }
364
+ // A succession claim is held for the microseconds it takes to verify and
365
+ // move one stale lock. One that sits unchanged this long — by our own
366
+ // observation, never by comparing clocks — belongs to a breaker that crashed.
367
+ const CLAIM_STALE_MS = 10_000;
368
+ // Break a lock judged stale. Breakers of the same stale lock are serialized
369
+ // by an O_EXCL succession claim keyed by that lock's exact bytes, so only one
370
+ // of them ever moves it (racing breakers would otherwise move each other's
371
+ // fresh locks). A crashed breaker's claim is escalated by O_EXCL-claiming the
372
+ // next level, never by deleting it, so recovery cannot itself race. Waiting
373
+ // out a claim happens here, not in the acquire retry budget, so a fresh
374
+ // process can always recover a claim abandoned by a crash. Returns true if
375
+ // this call removed the lock.
376
+ function claimPath(vaultRoot, raw, level) {
377
+ const key = createHash("sha256").update(raw.trim()).digest("hex").slice(0, 24);
378
+ return `${lockPath(vaultRoot)}.succ-${key}-${level}`;
379
+ }
380
+ function dropClaims(vaultRoot, raw, upToLevel) {
381
+ for (let level = upToLevel; level >= 0; level--) {
382
+ try {
383
+ unlinkSync(claimPath(vaultRoot, raw, level));
384
+ }
385
+ catch {
386
+ // already gone
387
+ }
388
+ }
389
+ }
390
+ function claimBody() {
391
+ return JSON.stringify({ host: hostId(), pid: process.pid, at: new Date().toISOString() });
392
+ }
393
+ // `beatAtJudgment` is the holder's heartbeat as read BEFORE the stale verdict
394
+ // (the caller passes it in; re-reading it here would adopt a renewal that
395
+ // landed after the verdict as the baseline and miss it). Its process.lock
396
+ // bytes never change, so a renewal shows only in its heartbeat file: if that
397
+ // moves from the judged value before we remove the lock, the holder is alive
398
+ // and we must not. Exported for tests.
399
+ export async function breakStale(vaultRoot, raw, beatAtJudgment) {
400
+ const judged = parseLock(raw);
401
+ const renewed = () => judged !== null && lastHeartbeat(vaultRoot, judged) !== beatAtJudgment;
402
+ for (let level = 0; level < 8; level++) {
403
+ const claim = claimPath(vaultRoot, raw, level);
404
+ const created = tryCreateExclusive(claim, claimBody());
405
+ if (!created.ok)
406
+ return false;
407
+ if (created.value) {
408
+ try {
409
+ if (renewed())
410
+ return false; // live after all: re-evaluate
411
+ return removeLockIfUnchanged(vaultRoot, raw);
412
+ }
413
+ finally {
414
+ // Done with these bytes either way. Drop our claim and the abandoned
415
+ // ones we escalated past, so a later breaker of the same (still
416
+ // current) lock is not stalled behind a finished claim, and repeated
417
+ // aborts cannot use up the escalation levels.
418
+ dropClaims(vaultRoot, raw, level);
419
+ }
420
+ }
421
+ const claimant = readOptional(claim);
422
+ if (claimant === null)
423
+ return false; // finished just now: re-evaluate
424
+ if (!claimantIsDead(claimant)) {
425
+ // A breaker (or the releasing holder) is at work. Watch until it
426
+ // finishes — the lock changes or the claim goes — the holder renews, or
427
+ // the claim proves abandoned.
428
+ const since = performance.now();
429
+ for (;;) {
430
+ await sleep(50);
431
+ if ((readOptional(lockPath(vaultRoot)) ?? "") !== raw.trim())
432
+ return false;
433
+ if (readOptional(claim) !== claimant)
434
+ return false;
435
+ if (renewed())
436
+ return false;
437
+ if (performance.now() - since > CLAIM_STALE_MS)
438
+ break;
439
+ }
440
+ }
441
+ // Abandoned: escalate to the next level.
442
+ }
443
+ return false;
444
+ }
445
+ function claimantIsDead(raw) {
446
+ try {
447
+ const c = JSON.parse(raw);
448
+ return (c.host === hostId() &&
449
+ typeof c.pid === "number" &&
450
+ c.pid !== process.pid &&
451
+ !isProcessAlive(c.pid));
452
+ }
453
+ catch {
454
+ return false;
455
+ }
456
+ }
457
+ // Succession claims are only meaningful while the lock they name is current;
458
+ // a new holder clears them. (A late breaker re-creating one still finds the
459
+ // lock changed and moves nothing.)
460
+ function clearClaims(vaultRoot) {
461
+ try {
462
+ for (const f of readdirSync(join(vaultRoot, ".daftari"))) {
463
+ if (f.startsWith("process.lock.succ-"))
464
+ unlinkSync(join(vaultRoot, ".daftari", f));
465
+ }
466
+ }
467
+ catch {
468
+ // best effort
469
+ }
470
+ }
471
+ function clampHeartbeat(ms) {
472
+ return typeof ms === "number" && Number.isFinite(ms) && ms >= 10 && ms <= 60_000
473
+ ? ms
474
+ : HEARTBEAT_MS;
475
+ }
476
+ function clampLease(ms, heartbeatMs) {
477
+ return typeof ms === "number" && Number.isFinite(ms) && ms >= 2 * heartbeatMs && ms <= 600_000
478
+ ? ms
479
+ : Math.max(LEASE_MS, 10 * heartbeatMs);
480
+ }
481
+ const held = new Map();
482
+ // Renewal writes only the holder's own side file (tmp + atomic rename), never
483
+ // process.lock.
484
+ function writeHeartbeat(vaultRoot, nonce) {
485
+ const path = heartbeatPath(vaultRoot, nonce);
486
+ if (path === null)
168
487
  return;
488
+ const tmp = `${path}.tmp`;
489
+ try {
490
+ writeFileSync(tmp, JSON.stringify({ nonce, heartbeatAt: new Date().toISOString() }), "utf-8");
491
+ renameSync(tmp, path);
492
+ }
493
+ catch (e) {
494
+ try {
495
+ unlinkSync(tmp);
496
+ }
497
+ catch {
498
+ // nothing to clean up
499
+ }
500
+ throw e;
169
501
  }
502
+ }
503
+ function removeHeartbeat(vaultRoot, nonce) {
504
+ const path = heartbeatPath(vaultRoot, nonce);
505
+ if (path === null)
506
+ return;
170
507
  try {
171
- unlinkSync(lockPath(vaultRoot));
508
+ unlinkSync(path);
172
509
  }
173
510
  catch {
174
- // Already gone / concurrent removal — fine; the retry's exclusive create
175
- // resolves the outcome.
511
+ // never written, or already removed by a breaker
512
+ }
513
+ }
514
+ function stopHeartbeat(vaultRoot) {
515
+ const h = held.get(vaultRoot);
516
+ if (!h)
517
+ return;
518
+ clearInterval(h.timer);
519
+ held.delete(vaultRoot);
520
+ }
521
+ function startHeartbeat(vaultRoot, data, onLeaseLost) {
522
+ const nonce = data.nonce;
523
+ let warned = false;
524
+ // Each beat first checks that process.lock is still ours. Renewal touches
525
+ // only our own heartbeat file, so even a beat that stalls between the check
526
+ // and the write cannot disturb a successor: a stalled-and-resumed holder at
527
+ // worst refreshes a heartbeat file nobody reads, then sees the successor's
528
+ // nonce on the next beat and stops.
529
+ const beat = () => {
530
+ if (held.get(vaultRoot)?.nonce !== nonce)
531
+ return;
532
+ const raw = readRaw(lockPath(vaultRoot));
533
+ if (!raw.ok)
534
+ return; // transient read failure — try next beat
535
+ if (raw.value === null) {
536
+ // Removed out from under us (by hand, or by a breaker that judged the
537
+ // lease lapsed and has not claimed yet). Reclaim it with the same atomic
538
+ // create every acquirer uses: if a contender created first, the next
539
+ // beat sees its nonce and reports the loss.
540
+ tryCreateExclusive(lockPath(vaultRoot), JSON.stringify(data, null, 2));
541
+ return;
542
+ }
543
+ const current = parseLock(raw.value);
544
+ if (current === null)
545
+ return; // a contender mid-write; judge next beat
546
+ if (current.nonce !== nonce) {
547
+ stopHeartbeat(vaultRoot);
548
+ removeHeartbeat(vaultRoot, nonce);
549
+ removeHolderMarker(nonce);
550
+ process.stderr.write(`daftari: lost the vault lock for ${vaultRoot} — another process took it over ` +
551
+ `(holder now: pid=${current.pid}); stopping so two processes never write one vault\n`);
552
+ onLeaseLost?.();
553
+ return;
554
+ }
555
+ try {
556
+ writeHeartbeat(vaultRoot, nonce);
557
+ warned = false;
558
+ }
559
+ catch (e) {
560
+ if (!warned) {
561
+ warned = true;
562
+ process.stderr.write(`daftari: warning: could not renew the vault lease: ${e.message}\n`);
563
+ }
564
+ }
565
+ };
566
+ const timer = setInterval(beat, data.heartbeatMs);
567
+ timer.unref();
568
+ held.set(vaultRoot, { nonce, timer, data });
569
+ writeHolderMarker(nonce);
570
+ }
571
+ // Watch a lease until its heartbeat advances (holder alive), the lock is
572
+ // replaced/removed, a same-host holder's pid dies, or the deadline passes.
573
+ // One renewal window: long enough that any live holder, anywhere, renews at
574
+ // least once while we watch.
575
+ function renewalWindow(prior) {
576
+ return 2 * clampHeartbeat(prior.heartbeatMs) + 250;
577
+ }
578
+ // A dead local pid is never by itself proof that the holder is dead: a
579
+ // holder in another sandbox can share our host id, and its pid means nothing
580
+ // here. With `shortenOnDeadPid`, a pid seen dead only cuts the remaining wait
581
+ // down to one renewal window; the verdict still needs that window to pass
582
+ // with no renewal.
583
+ async function watchLease(vaultRoot, prior, deadline, shortenOnDeadPid = false) {
584
+ const pollMs = Math.max(10, Math.min(100, clampHeartbeat(prior.heartbeatMs) / 4));
585
+ const priorBeat = lastHeartbeat(vaultRoot, prior);
586
+ let until = deadline;
587
+ let shortened = false;
588
+ for (;;) {
589
+ const cur = readLockfile(vaultRoot);
590
+ if (cur.ok) {
591
+ if (cur.value === null || cur.value.nonce !== prior.nonce)
592
+ return { kind: "changed" };
593
+ if (lastHeartbeat(vaultRoot, cur.value) !== priorBeat) {
594
+ return { kind: "advanced", latest: cur.value };
595
+ }
596
+ }
597
+ if (shortenOnDeadPid && !shortened && !isProcessAlive(prior.pid)) {
598
+ shortened = true;
599
+ until = Math.min(until, Date.now() + renewalWindow(prior));
600
+ }
601
+ if (Date.now() >= until)
602
+ return { kind: "timeout" };
603
+ await sleep(pollMs);
604
+ }
605
+ }
606
+ function describeHolder(prior, foreign) {
607
+ const priorMode = prior.mode ?? "stdio";
608
+ return (`pid=${prior.pid}, mode=${priorMode}, started=${prior.startedAt}` +
609
+ (prior.bind ? `, bind=${prior.bind}` : "") +
610
+ (foreign && prior.host ? `, host=${prior.host.split("|")[0]}` : ""));
611
+ }
612
+ // The #5 refusal matrix for a LIVE holder. Null = the rule is to take over.
613
+ function modeRefusal(mode, prior, holder, takeover) {
614
+ const priorMode = prior.mode ?? "stdio";
615
+ if (mode === "cli") {
616
+ const what = priorMode === "serve" ? "daftari serve" : "daftari instance";
617
+ return new Error(`this vault is held by a live ${what} (${holder}). ` +
618
+ `A one-shot command never replaces a live holder: run it when no daftari ` +
619
+ `holds the vault, or do the same work through the running instance.`);
620
+ }
621
+ if (mode === "stdio" && priorMode === "cli") {
622
+ return new Error(`this vault is held by a one-shot daftari command (${holder}) that is ` +
623
+ `writing; retry once it finishes.`);
624
+ }
625
+ if (mode === "stdio" && priorMode === "serve") {
626
+ return new Error(`this vault is held by a live daftari serve (${holder}). ` +
627
+ `Connect to it over HTTP instead, or stop the server ` +
628
+ `deliberately (or replace it with 'daftari serve --takeover').`);
629
+ }
630
+ if (mode === "serve" && !takeover) {
631
+ return new Error(`this vault is held by a live daftari instance (${holder}). ` +
632
+ `A server start never silently replaces a live holder; ` +
633
+ `re-run with --takeover to replace it deliberately.`);
634
+ }
635
+ return null;
636
+ }
637
+ function foreignRefusal(holderLock, leaseMs) {
638
+ return new Error(`this vault is held by a live daftari on another machine (${describeHolder(holderLock, true)}). ` +
639
+ `A process on another machine cannot be signalled from here: stop it there, ` +
640
+ `or, if it has crashed, retry once its lease lapses (${Math.round(leaseMs / 1000)}s ` +
641
+ `after its last heartbeat).`);
642
+ }
643
+ async function judge(vaultRoot, prior, mode, takeover) {
644
+ // A pre-lease lockfile (no nonce/heartbeat): its holder never renews, so
645
+ // only a dead pid proves it stale. A live pid may be the old daftari or a
646
+ // recycled pid — without `ps` we cannot tell, so we refuse rather than
647
+ // signal a possibly unrelated process.
648
+ if (prior.nonce === undefined || prior.heartbeatAt === undefined) {
649
+ if (prior.pid === process.pid) {
650
+ return {
651
+ kind: "stale",
652
+ why: `names our own pid ${prior.pid} — ` +
653
+ `a leftover from a previous incarnation that had the same pid`,
654
+ };
655
+ }
656
+ if (!isProcessAlive(prior.pid)) {
657
+ return { kind: "stale", why: `pid=${prior.pid} not a live daftari instance` };
658
+ }
659
+ const holder = describeHolder(prior, false);
660
+ const refusal = modeRefusal(mode, prior, holder, takeover);
661
+ if (refusal)
662
+ return { kind: "refuse", error: refusal };
663
+ return {
664
+ kind: "refuse",
665
+ error: new Error(`this vault is held by an older daftari that does not renew a lease (${holder}). ` +
666
+ `It cannot be told apart from an unrelated process that reused its pid, so it is ` +
667
+ `not signalled: stop that daftari, or, if none is running, delete ${lockPath(vaultRoot)}.`),
668
+ };
669
+ }
670
+ let sameHost = isSameHost(prior);
671
+ const heartbeatMs = clampHeartbeat(prior.heartbeatMs);
672
+ const leaseMs = clampLease(prior.leaseMs, heartbeatMs);
673
+ const lastBeat = Date.parse(lastHeartbeat(vaultRoot, prior) ?? "");
674
+ let latest = prior;
675
+ let proven = false;
676
+ // Same-host fast paths — a lock naming our own pid (we are alive, so it is
677
+ // a previous incarnation's) or a pid that is dead here. Neither is lease
678
+ // evidence: a holder in another sandbox can share our host id, and then its
679
+ // pid says nothing about it. So both still need one renewal window with no
680
+ // renewal (~4s at the defaults) before the lock is called stale. A holder
681
+ // that renews in that window is alive somewhere else: our host identity
682
+ // collides with its, and it is treated as foreign from here on.
683
+ const ownPid = sameHost && prior.pid === process.pid;
684
+ const deadPid = sameHost && !ownPid && !isProcessAlive(prior.pid);
685
+ if (ownPid || deadPid) {
686
+ const w = await watchLease(vaultRoot, prior, Date.now() + renewalWindow(prior));
687
+ if (w.kind === "changed")
688
+ return { kind: "changed" };
689
+ if (w.kind === "timeout") {
690
+ return {
691
+ kind: "stale",
692
+ why: ownPid
693
+ ? `names our own pid ${prior.pid} — ` +
694
+ `a leftover from a previous incarnation that had the same pid`
695
+ : `pid=${prior.pid} not a live daftari instance`,
696
+ };
697
+ }
698
+ latest = w.latest;
699
+ proven = true;
700
+ sameHost = false;
701
+ }
702
+ const age = Date.now() - lastBeat;
703
+ const lapsedByClock = !(age <= leaseMs); // NaN (unparseable) counts as lapsed
704
+ // A heartbeat dated in our future: the holder's clock runs ahead, so our
705
+ // clock says nothing about when it last renewed. Judge it by local
706
+ // observation alone — a full lease with no renewal — or a crashed holder
707
+ // with a fast clock would block the vault for as long as its offset.
708
+ const futureDated = age < -heartbeatMs;
709
+ if (!proven && (lapsedByClock || futureDated)) {
710
+ // Lapsed by our clock: watch one more renewal window before believing it
711
+ // — a holder whose clock lags ours, or that just woke from sleep, renews.
712
+ const window = futureDated ? leaseMs : renewalWindow(prior);
713
+ const w = await watchLease(vaultRoot, prior, Date.now() + window);
714
+ if (w.kind === "changed")
715
+ return { kind: "changed" };
716
+ if (w.kind === "timeout") {
717
+ return {
718
+ kind: "stale",
719
+ why: `pid=${prior.pid}${sameHost ? "" : ` on ${prior.host?.split("|")[0]}`}: ` +
720
+ (futureDated ? `no renewal seen for ${window}ms (holder clock ahead)` : "lease lapsed"),
721
+ };
722
+ }
723
+ latest = w.latest;
724
+ proven = true;
725
+ }
726
+ const holder = describeHolder(latest, !sameHost);
727
+ const refusal = modeRefusal(mode, latest, holder, takeover);
728
+ if (refusal)
729
+ return { kind: "refuse", error: refusal };
730
+ if (!sameHost)
731
+ return { kind: "refuse", error: foreignRefusal(latest, leaseMs) };
732
+ if (!proven) {
733
+ // Signal only a holder whose heartbeat we SEE advance; a live pid alone
734
+ // may be recycled. Bounded by the lease: if it never renews, it is stale.
735
+ // A pid that dies meanwhile only shortens the wait to one renewal window.
736
+ const w = await watchLease(vaultRoot, latest, Date.parse(lastHeartbeat(vaultRoot, latest) ?? "") + leaseMs, true);
737
+ if (w.kind === "changed")
738
+ return { kind: "changed" };
739
+ if (w.kind === "timeout") {
740
+ return { kind: "stale", why: `pid=${prior.pid} lease lapsed without renewal` };
741
+ }
742
+ latest = w.latest;
743
+ // Renewing while its pid is dead here: it lives in another sandbox that
744
+ // shares our host id. It cannot be signalled from here.
745
+ if (!isProcessAlive(latest.pid))
746
+ return { kind: "refuse", error: foreignRefusal(latest, leaseMs) };
176
747
  }
748
+ return { kind: "signal", latest, holder };
177
749
  }
178
750
  // Acquire the per-vault process lock. Behavior (#52, amended by #5 spec
179
- // 2026-07-20 Decision 4):
751
+ // 2026-07-20 Decision 4, and by the lease lock, istf):
180
752
  // - No existing lock → atomic O_EXCL create, return ok.
181
- // - Existing lock with dead PID → stale, overwrite (every mode).
182
- // - Existing lock with live PID that does not look like a daftari for this
183
- // vault (PID recycled) → stale, overwrite (every mode).
184
- // - LIVE daftari holder — precedence favors the durable tenant:
753
+ // - Stale lock (lease lapsed, or same-host holder pid dead) → removed under
754
+ // the break mutex, then the O_EXCL create is retried (every mode).
755
+ // - LIVE holder — precedence favors the durable tenant:
185
756
  // stdio finding stdio → SIGTERM-and-wait takeover (the
186
757
  // single-user convenience, unchanged).
187
758
  // stdio finding serve → REFUSE, naming the server and the
@@ -192,10 +763,16 @@ export function removeLockIfUnchanged(vaultRoot, expected) {
192
763
  // double-start must not bounce every
193
764
  // session. With takeover, SIGTERM-and-
194
765
  // wait against either holder mode.
766
+ // A live holder on ANOTHER host cannot be signalled, so the takeover
767
+ // rows refuse for it too.
195
768
  //
196
769
  // Logs go to stderr (MCP convention; stdout is reserved for JSON-RPC).
197
770
  export async function acquireLock(vaultRoot, version, options = {}) {
198
771
  const mode = options.mode ?? "stdio";
772
+ const heartbeatMs = clampHeartbeat(options.heartbeatMs);
773
+ const leaseMs = clampLease(options.leaseMs, heartbeatMs);
774
+ // Re-acquiring a vault this process already holds replaces our own lock.
775
+ stopHeartbeat(vaultRoot);
199
776
  const our = {
200
777
  daftari: true,
201
778
  pid: process.pid,
@@ -204,100 +781,112 @@ export async function acquireLock(vaultRoot, version, options = {}) {
204
781
  version,
205
782
  mode,
206
783
  ...(options.bind ? { bind: options.bind } : {}),
784
+ host: hostId(),
785
+ macs: hostMacs(),
786
+ nonce: randomBytes(16).toString("hex"),
787
+ heartbeatAt: new Date().toISOString(),
788
+ heartbeatMs,
789
+ leaseMs,
207
790
  };
791
+ try {
792
+ mkdirSync(join(vaultRoot, ".daftari"), { recursive: true });
793
+ }
794
+ catch (e) {
795
+ return err(e);
796
+ }
208
797
  // The claim is ALWAYS the atomic O_EXCL create — never a plain overwrite.
209
798
  // On EEXIST we resolve the existing lock (refuse, or SIGTERM-and-wait a live
210
- // holder, or drop a defunct one) and loop so the create is retried. This
211
- // closes the stale-takeover TOCTOU: two processes that both saw a dead-PID
212
- // lock previously both fell through to an in-place writeLockfile and both
213
- // believed they held the vault; now only one can win the exclusive create.
799
+ // holder, or break a stale one) and loop so the create is retried.
214
800
  for (let attempt = 0; attempt < MAX_ACQUIRE_ATTEMPTS; attempt++) {
215
- const created = tryCreateExclusive(vaultRoot, our);
801
+ const mine = { ...our, heartbeatAt: new Date().toISOString() };
802
+ const created = tryCreateExclusive(lockPath(vaultRoot), JSON.stringify(mine, null, 2));
216
803
  if (!created.ok)
217
804
  return created;
218
- if (created.value)
805
+ if (created.value) {
806
+ startHeartbeat(vaultRoot, mine, options.onLeaseLost);
807
+ clearClaims(vaultRoot);
219
808
  return ok(undefined);
220
- const existing = readLockfile(vaultRoot);
221
- if (!existing.ok)
222
- return existing;
223
- if (existing.value === null) {
809
+ }
810
+ const raw = readRaw(lockPath(vaultRoot));
811
+ if (!raw.ok)
812
+ return raw;
813
+ if (raw.value === null) {
224
814
  // The lock vanished between our failed exclusive create and this read
225
815
  // (the holder released, or a competing acquirer removed a stale lock).
226
- // Retry the atomic create.
227
816
  continue;
228
817
  }
229
- const prior = existing.value;
230
- // A lock naming OUR OWN pid cannot be a live other holder — it is a
231
- // leftover from a previous incarnation that happened to get the same pid
232
- // (containers with a persistent vault volume make this common: pids are
233
- // near-deterministic there, so a crash-orphaned lock routinely names the
234
- // replacement process's own pid). Without this check the process would
235
- // mistake itself for a live holder — refusing to start, or SIGTERMing
236
- // itself under --takeover.
237
- if (prior.pid !== process.pid && isDaftariProcess(prior.pid, vaultRoot)) {
238
- const priorMode = prior.mode ?? "stdio";
239
- const holder = `pid=${prior.pid}, mode=${priorMode}, started=${prior.startedAt}` +
240
- (prior.bind ? `, bind=${prior.bind}` : "");
241
- if (mode === "stdio" && priorMode === "serve") {
242
- return err(new Error(`this vault is held by a live daftari serve (${holder}). ` +
243
- `Connect to it over HTTP instead, or stop the server ` +
244
- `deliberately (or replace it with 'daftari serve --takeover').`));
245
- }
246
- if (mode === "serve" && !options.takeover) {
247
- return err(new Error(`this vault is held by a live daftari instance (${holder}). ` +
248
- `A server start never silently replaces a live holder; ` +
249
- `re-run with --takeover to replace it deliberately.`));
250
- }
251
- process.stderr.write(`daftari: another instance is holding this vault (${holder}); ` +
252
- `sending SIGTERM and taking over\n`);
253
- try {
254
- process.kill(prior.pid, "SIGTERM");
255
- }
256
- catch {
257
- // Died between check and signal — fine.
258
- }
259
- const exited = await waitForExit(prior.pid, SIGTERM_GRACE_MS);
260
- if (!exited) {
261
- process.stderr.write(`daftari: warning: pid ${prior.pid} did not exit within ` +
262
- `${SIGTERM_GRACE_MS}ms; proceeding anyway\n`);
263
- }
818
+ const prior = parseLock(raw.value);
819
+ if (prior === null) {
820
+ // Unparseable: a creator mid-write (gone in microseconds) or garbage.
821
+ await sleep(UNREADABLE_GRACE_MS);
822
+ const again = readRaw(lockPath(vaultRoot));
823
+ if (!again.ok)
824
+ return again;
825
+ if (again.value !== raw.value)
826
+ continue;
827
+ process.stderr.write("daftari: removing unreadable lockfile\n");
828
+ await breakStale(vaultRoot, raw.value, undefined);
829
+ continue;
830
+ }
831
+ // Read the holder's heartbeat before judging: every stale verdict means
832
+ // "no renewal since this value", so the removal step compares against it.
833
+ const beatBeforeJudgment = lastHeartbeat(vaultRoot, prior);
834
+ const verdict = await judge(vaultRoot, prior, mode, options.takeover === true);
835
+ if (verdict.kind === "refuse")
836
+ return err(verdict.error);
837
+ if (verdict.kind === "changed")
838
+ continue;
839
+ if (verdict.kind === "stale") {
840
+ process.stderr.write(`daftari: removing stale lockfile (${verdict.why})\n`);
841
+ // Only if it is still byte-for-byte the lock we judged (a live holder
842
+ // never rewrites process.lock, so any change means a new claimant).
843
+ await breakStale(vaultRoot, raw.value, beatBeforeJudgment);
844
+ continue;
264
845
  }
265
- else if (prior.pid === process.pid) {
266
- // The own-pid case short-circuited above: the lock IS "a live daftari
267
- // instance" — this very process — so the generic message below would
268
- // be factually wrong and confusing in container logs.
269
- process.stderr.write(`daftari: removing stale lockfile (names our own pid ${prior.pid} — ` +
270
- `a leftover from a previous incarnation that had the same pid)\n`);
846
+ // signal: a live same-host holder whose heartbeat we saw advance.
847
+ process.stderr.write(`daftari: another instance is holding this vault (${verdict.holder}); ` +
848
+ `sending SIGTERM and taking over\n`);
849
+ try {
850
+ process.kill(verdict.latest.pid, "SIGTERM");
851
+ }
852
+ catch {
853
+ // Died between check and signal — fine.
271
854
  }
272
- else {
273
- process.stderr.write(`daftari: removing stale lockfile (pid=${prior.pid} not a live daftari instance)\n`);
855
+ const exited = await waitForExit(verdict.latest.pid, SIGTERM_GRACE_MS);
856
+ if (!exited) {
857
+ process.stderr.write(`daftari: warning: pid ${verdict.latest.pid} did not exit within ` +
858
+ `${SIGTERM_GRACE_MS}ms; it keeps the vault until it stops renewing\n`);
274
859
  }
275
- // Drop the defunct lock only if it is still the exact one we inspected,
276
- // then loop so the next tryCreateExclusive is the real atomic claim. If a
277
- // competing acquirer installed its own lock in the race window, its content
278
- // differs — leave it and re-evaluate as a live contender rather than
279
- // clobbering a valid lock.
280
- removeLockIfUnchanged(vaultRoot, prior);
860
+ // A clean exit released the lock itself. If it did not, the next pass
861
+ // sees a dead same-host pid (stale) — or, if it is still renewing, a live
862
+ // holder again — and never removes a lock that is still being renewed.
281
863
  }
282
864
  return err(new Error(`could not acquire the process lock for ${vaultRoot} after ` +
283
865
  `${MAX_ACQUIRE_ATTEMPTS} attempts — the vault is under heavy ` +
284
866
  `acquisition contention; retry`));
285
867
  }
286
- // Idempotent. Removes the lockfile only if it still belongs to us — protects
287
- // against a race where takeover happens during our shutdown and we'd
288
- // otherwise delete the new owner's lock. Stays sync because it runs from
868
+ // Idempotent. Removes the lockfile only if it still belongs to us (our nonce)
869
+ // — protects against a race where takeover happens during our shutdown and
870
+ // we'd otherwise delete the new owner's lock. Stays sync because it runs from
289
871
  // `process.on("exit")`, which forbids async work.
290
872
  export function releaseLock(vaultRoot) {
291
- const existing = readLockfile(vaultRoot);
292
- if (!existing.ok || existing.value === null)
293
- return;
294
- if (existing.value.pid !== process.pid)
873
+ const mine = held.get(vaultRoot);
874
+ stopHeartbeat(vaultRoot);
875
+ if (mine === undefined)
295
876
  return;
296
- try {
297
- unlinkSync(lockPath(vaultRoot));
298
- }
299
- catch {
300
- // Best-effort. If the file is already gone, fine.
877
+ // Release is a lock transition like any other, so it takes the same
878
+ // level-0 succession claim a breaker of our lock would. Only the claim
879
+ // holder may remove a given lock, so no breaker can sit between its check
880
+ // and its move while we release (and vice versa). If a breaker already
881
+ // holds the claim, it owns the removal: we leave the lock, which is stale
882
+ // the moment we exit.
883
+ const ourRaw = JSON.stringify(mine.data, null, 2);
884
+ const claimed = tryCreateExclusive(claimPath(vaultRoot, ourRaw, 0), claimBody());
885
+ if (claimed.ok && claimed.value) {
886
+ removeLockIfUnchanged(vaultRoot, mine.data);
887
+ dropClaims(vaultRoot, ourRaw, 0);
301
888
  }
889
+ removeHeartbeat(vaultRoot, mine.nonce);
890
+ removeHolderMarker(mine.nonce);
302
891
  }
303
892
  //# sourceMappingURL=lock.js.map