@animalabs/agent-framework 0.26.2 → 0.28.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 (371) hide show
  1. package/README.md +99 -8
  2. package/dist/src/agent.d.ts +291 -23
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +596 -61
  5. package/dist/src/agent.js.map +1 -1
  6. package/dist/src/api/server.d.ts.map +1 -1
  7. package/dist/src/api/server.js +5 -4
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/auto-continue.d.ts +34 -0
  10. package/dist/src/auto-continue.d.ts.map +1 -0
  11. package/dist/src/auto-continue.js +36 -0
  12. package/dist/src/auto-continue.js.map +1 -0
  13. package/dist/src/code-execution/isolate/scripts.d.ts +11 -0
  14. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  15. package/dist/src/code-execution/isolate/scripts.js +5 -1
  16. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  17. package/dist/src/cut-off-round.d.ts +24 -0
  18. package/dist/src/cut-off-round.d.ts.map +1 -0
  19. package/dist/src/cut-off-round.js +87 -0
  20. package/dist/src/cut-off-round.js.map +1 -0
  21. package/dist/src/framework.d.ts +1038 -193
  22. package/dist/src/framework.d.ts.map +1 -1
  23. package/dist/src/framework.js +5967 -1514
  24. package/dist/src/framework.js.map +1 -1
  25. package/dist/src/gate/event-gate.d.ts +405 -46
  26. package/dist/src/gate/event-gate.d.ts.map +1 -1
  27. package/dist/src/gate/event-gate.js +2646 -399
  28. package/dist/src/gate/event-gate.js.map +1 -1
  29. package/dist/src/gate/index.d.ts +3 -2
  30. package/dist/src/gate/index.d.ts.map +1 -1
  31. package/dist/src/gate/index.js +2 -1
  32. package/dist/src/gate/index.js.map +1 -1
  33. package/dist/src/gate/recipe-reconcile.d.ts +103 -0
  34. package/dist/src/gate/recipe-reconcile.d.ts.map +1 -0
  35. package/dist/src/gate/recipe-reconcile.js +325 -0
  36. package/dist/src/gate/recipe-reconcile.js.map +1 -0
  37. package/dist/src/gate/reply-judge.d.ts +116 -0
  38. package/dist/src/gate/reply-judge.d.ts.map +1 -0
  39. package/dist/src/gate/reply-judge.js +467 -0
  40. package/dist/src/gate/reply-judge.js.map +1 -0
  41. package/dist/src/gate/types.d.ts +229 -8
  42. package/dist/src/gate/types.d.ts.map +1 -1
  43. package/dist/src/heartbeat/heartbeat.d.ts +184 -0
  44. package/dist/src/heartbeat/heartbeat.d.ts.map +1 -0
  45. package/dist/src/heartbeat/heartbeat.js +752 -0
  46. package/dist/src/heartbeat/heartbeat.js.map +1 -0
  47. package/dist/src/heartbeat/reminder-time.d.ts +5 -0
  48. package/dist/src/heartbeat/reminder-time.d.ts.map +1 -0
  49. package/dist/src/heartbeat/reminder-time.js +107 -0
  50. package/dist/src/heartbeat/reminder-time.js.map +1 -0
  51. package/dist/src/index.d.ts +10 -4
  52. package/dist/src/index.d.ts.map +1 -1
  53. package/dist/src/index.js +7 -2
  54. package/dist/src/index.js.map +1 -1
  55. package/dist/src/mcpl/capability-mask.d.ts.map +1 -1
  56. package/dist/src/mcpl/capability-mask.js +3 -2
  57. package/dist/src/mcpl/capability-mask.js.map +1 -1
  58. package/dist/src/mcpl/channel-registry.d.ts +433 -113
  59. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  60. package/dist/src/mcpl/channel-registry.js +1154 -435
  61. package/dist/src/mcpl/channel-registry.js.map +1 -1
  62. package/dist/src/mcpl/conversation-router.d.ts +16 -8
  63. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  64. package/dist/src/mcpl/conversation-router.js +29 -15
  65. package/dist/src/mcpl/conversation-router.js.map +1 -1
  66. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  67. package/dist/src/mcpl/convert-block.js +14 -2
  68. package/dist/src/mcpl/convert-block.js.map +1 -1
  69. package/dist/src/mcpl/hook-orchestrator.d.ts +7 -1
  70. package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
  71. package/dist/src/mcpl/hook-orchestrator.js +32 -7
  72. package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
  73. package/dist/src/mcpl/inbound-source.d.ts +26 -10
  74. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  75. package/dist/src/mcpl/inbound-source.js +40 -69
  76. package/dist/src/mcpl/inbound-source.js.map +1 -1
  77. package/dist/src/mcpl/index.d.ts +5 -1
  78. package/dist/src/mcpl/index.d.ts.map +1 -1
  79. package/dist/src/mcpl/index.js +4 -0
  80. package/dist/src/mcpl/index.js.map +1 -1
  81. package/dist/src/mcpl/inference-router.d.ts +14 -2
  82. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  83. package/dist/src/mcpl/inference-router.js +73 -28
  84. package/dist/src/mcpl/inference-router.js.map +1 -1
  85. package/dist/src/mcpl/prose-grammar.d.ts +4 -0
  86. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  87. package/dist/src/mcpl/prose-grammar.js +6 -0
  88. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  89. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  90. package/dist/src/mcpl/protocol-family.js +3 -0
  91. package/dist/src/mcpl/protocol-family.js.map +1 -1
  92. package/dist/src/mcpl/push-coalescer.d.ts +20 -2
  93. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  94. package/dist/src/mcpl/push-coalescer.js +33 -11
  95. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  96. package/dist/src/mcpl/reference-fetcher.d.ts +63 -42
  97. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  98. package/dist/src/mcpl/reference-fetcher.js +177 -145
  99. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  100. package/dist/src/mcpl/references.d.ts +380 -46
  101. package/dist/src/mcpl/references.d.ts.map +1 -1
  102. package/dist/src/mcpl/references.js +736 -77
  103. package/dist/src/mcpl/references.js.map +1 -1
  104. package/dist/src/mcpl/server-connection.d.ts +93 -4
  105. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  106. package/dist/src/mcpl/server-connection.js +176 -11
  107. package/dist/src/mcpl/server-connection.js.map +1 -1
  108. package/dist/src/mcpl/tags.d.ts +9 -2
  109. package/dist/src/mcpl/tags.d.ts.map +1 -1
  110. package/dist/src/mcpl/tags.js +12 -2
  111. package/dist/src/mcpl/tags.js.map +1 -1
  112. package/dist/src/mcpl/tool-lifecycle.d.ts +11 -0
  113. package/dist/src/mcpl/tool-lifecycle.d.ts.map +1 -1
  114. package/dist/src/mcpl/tool-lifecycle.js +21 -0
  115. package/dist/src/mcpl/tool-lifecycle.js.map +1 -1
  116. package/dist/src/mcpl/tool-presence.d.ts +311 -0
  117. package/dist/src/mcpl/tool-presence.d.ts.map +1 -0
  118. package/dist/src/mcpl/tool-presence.js +697 -0
  119. package/dist/src/mcpl/tool-presence.js.map +1 -0
  120. package/dist/src/mcpl/tool-result-normalize.d.ts +9 -3
  121. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  122. package/dist/src/mcpl/tool-result-normalize.js +14 -6
  123. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  124. package/dist/src/mcpl/tool-signature.d.ts +46 -0
  125. package/dist/src/mcpl/tool-signature.d.ts.map +1 -0
  126. package/dist/src/mcpl/tool-signature.js +321 -0
  127. package/dist/src/mcpl/tool-signature.js.map +1 -0
  128. package/dist/src/mcpl/toolset-host.d.ts +251 -0
  129. package/dist/src/mcpl/toolset-host.d.ts.map +1 -0
  130. package/dist/src/mcpl/toolset-host.js +720 -0
  131. package/dist/src/mcpl/toolset-host.js.map +1 -0
  132. package/dist/src/mcpl/toolsets-module.d.ts +83 -0
  133. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -0
  134. package/dist/src/mcpl/toolsets-module.js +523 -0
  135. package/dist/src/mcpl/toolsets-module.js.map +1 -0
  136. package/dist/src/mcpl/transport.d.ts +2 -2
  137. package/dist/src/mcpl/transport.d.ts.map +1 -1
  138. package/dist/src/mcpl/transport.js +3 -2
  139. package/dist/src/mcpl/transport.js.map +1 -1
  140. package/dist/src/mcpl/types.d.ts +24 -2
  141. package/dist/src/mcpl/types.d.ts.map +1 -1
  142. package/dist/src/mcpl/types.js.map +1 -1
  143. package/dist/src/mcpl/visible-content.d.ts +7 -9
  144. package/dist/src/mcpl/visible-content.d.ts.map +1 -1
  145. package/dist/src/mcpl/visible-content.js +21 -9
  146. package/dist/src/mcpl/visible-content.js.map +1 -1
  147. package/dist/src/module-registry.d.ts +27 -9
  148. package/dist/src/module-registry.d.ts.map +1 -1
  149. package/dist/src/module-registry.js +77 -17
  150. package/dist/src/module-registry.js.map +1 -1
  151. package/dist/src/modules/discord/index.js +1 -1
  152. package/dist/src/modules/discord/index.js.map +1 -1
  153. package/dist/src/modules/history/index.d.ts +2 -1
  154. package/dist/src/modules/history/index.d.ts.map +1 -1
  155. package/dist/src/modules/history/index.js +73 -28
  156. package/dist/src/modules/history/index.js.map +1 -1
  157. package/dist/src/modules/history/semantic.d.ts +108 -6
  158. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  159. package/dist/src/modules/history/semantic.js +273 -57
  160. package/dist/src/modules/history/semantic.js.map +1 -1
  161. package/dist/src/modules/workspace/answers.d.ts +22 -0
  162. package/dist/src/modules/workspace/answers.d.ts.map +1 -0
  163. package/dist/src/modules/workspace/answers.js +123 -0
  164. package/dist/src/modules/workspace/answers.js.map +1 -0
  165. package/dist/src/modules/workspace/branch-intent.d.ts +5 -3
  166. package/dist/src/modules/workspace/branch-intent.d.ts.map +1 -1
  167. package/dist/src/modules/workspace/branch-intent.js +6 -2
  168. package/dist/src/modules/workspace/branch-intent.js.map +1 -1
  169. package/dist/src/modules/workspace/direct-write.d.ts +184 -0
  170. package/dist/src/modules/workspace/direct-write.d.ts.map +1 -0
  171. package/dist/src/modules/workspace/direct-write.js +417 -0
  172. package/dist/src/modules/workspace/direct-write.js.map +1 -0
  173. package/dist/src/modules/workspace/disk-agreement.d.ts +33 -11
  174. package/dist/src/modules/workspace/disk-agreement.d.ts.map +1 -1
  175. package/dist/src/modules/workspace/disk-agreement.js +48 -17
  176. package/dist/src/modules/workspace/disk-agreement.js.map +1 -1
  177. package/dist/src/modules/workspace/edit-text.d.ts +27 -12
  178. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -1
  179. package/dist/src/modules/workspace/edit-text.js +61 -29
  180. package/dist/src/modules/workspace/edit-text.js.map +1 -1
  181. package/dist/src/modules/workspace/effects.d.ts +10 -0
  182. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  183. package/dist/src/modules/workspace/effects.js +21 -14
  184. package/dist/src/modules/workspace/effects.js.map +1 -1
  185. package/dist/src/modules/workspace/index.d.ts +308 -78
  186. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  187. package/dist/src/modules/workspace/index.js +2103 -720
  188. package/dist/src/modules/workspace/index.js.map +1 -1
  189. package/dist/src/modules/workspace/observe.d.ts +75 -63
  190. package/dist/src/modules/workspace/observe.d.ts.map +1 -1
  191. package/dist/src/modules/workspace/observe.js +366 -180
  192. package/dist/src/modules/workspace/observe.js.map +1 -1
  193. package/dist/src/modules/workspace/read-page.d.ts +41 -0
  194. package/dist/src/modules/workspace/read-page.d.ts.map +1 -0
  195. package/dist/src/modules/workspace/read-page.js +219 -0
  196. package/dist/src/modules/workspace/read-page.js.map +1 -0
  197. package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
  198. package/dist/src/modules/workspace/reconcile.js +26 -16
  199. package/dist/src/modules/workspace/reconcile.js.map +1 -1
  200. package/dist/src/modules/workspace/result-text.d.ts +68 -0
  201. package/dist/src/modules/workspace/result-text.d.ts.map +1 -0
  202. package/dist/src/modules/workspace/result-text.js +94 -0
  203. package/dist/src/modules/workspace/result-text.js.map +1 -0
  204. package/dist/src/modules/workspace/sync.d.ts +9 -0
  205. package/dist/src/modules/workspace/sync.d.ts.map +1 -1
  206. package/dist/src/modules/workspace/sync.js +14 -0
  207. package/dist/src/modules/workspace/sync.js.map +1 -1
  208. package/dist/src/modules/workspace/text.d.ts +29 -12
  209. package/dist/src/modules/workspace/text.d.ts.map +1 -1
  210. package/dist/src/modules/workspace/text.js +35 -33
  211. package/dist/src/modules/workspace/text.js.map +1 -1
  212. package/dist/src/modules/workspace/types.d.ts +137 -60
  213. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  214. package/dist/src/modules/workspace/types.js.map +1 -1
  215. package/dist/src/modules/workspace/watcher.d.ts.map +1 -1
  216. package/dist/src/modules/workspace/watcher.js +8 -3
  217. package/dist/src/modules/workspace/watcher.js.map +1 -1
  218. package/dist/src/prose-drafts.d.ts +4 -3
  219. package/dist/src/prose-drafts.d.ts.map +1 -1
  220. package/dist/src/prose-drafts.js +3 -2
  221. package/dist/src/prose-drafts.js.map +1 -1
  222. package/dist/src/reasoning-loss-notice.d.ts +23 -0
  223. package/dist/src/reasoning-loss-notice.d.ts.map +1 -0
  224. package/dist/src/reasoning-loss-notice.js +50 -0
  225. package/dist/src/reasoning-loss-notice.js.map +1 -0
  226. package/dist/src/reasoning-loss.d.ts +24 -0
  227. package/dist/src/reasoning-loss.d.ts.map +1 -0
  228. package/dist/src/reasoning-loss.js +102 -0
  229. package/dist/src/reasoning-loss.js.map +1 -0
  230. package/dist/src/send-tools.d.ts +3 -2
  231. package/dist/src/send-tools.d.ts.map +1 -1
  232. package/dist/src/send-tools.js +3 -2
  233. package/dist/src/send-tools.js.map +1 -1
  234. package/dist/src/sent-rows.d.ts +59 -0
  235. package/dist/src/sent-rows.d.ts.map +1 -0
  236. package/dist/src/sent-rows.js +145 -0
  237. package/dist/src/sent-rows.js.map +1 -0
  238. package/dist/src/silent-heartbeat.d.ts +17 -10
  239. package/dist/src/silent-heartbeat.d.ts.map +1 -1
  240. package/dist/src/silent-heartbeat.js.map +1 -1
  241. package/dist/src/stable-hash.d.ts +3 -0
  242. package/dist/src/stable-hash.d.ts.map +1 -0
  243. package/dist/src/stable-hash.js +15 -0
  244. package/dist/src/stable-hash.js.map +1 -0
  245. package/dist/src/stored-injections.d.ts +99 -0
  246. package/dist/src/stored-injections.d.ts.map +1 -0
  247. package/dist/src/stored-injections.js +106 -0
  248. package/dist/src/stored-injections.js.map +1 -0
  249. package/dist/src/text-as-stored.d.ts +4 -3
  250. package/dist/src/text-as-stored.d.ts.map +1 -1
  251. package/dist/src/text-as-stored.js +4 -3
  252. package/dist/src/text-as-stored.js.map +1 -1
  253. package/dist/src/thinking-drops.d.ts +74 -0
  254. package/dist/src/thinking-drops.d.ts.map +1 -0
  255. package/dist/src/thinking-drops.js +96 -0
  256. package/dist/src/thinking-drops.js.map +1 -0
  257. package/dist/src/tool-args.d.ts +12 -0
  258. package/dist/src/tool-args.d.ts.map +1 -1
  259. package/dist/src/tool-args.js +35 -1
  260. package/dist/src/tool-args.js.map +1 -1
  261. package/dist/src/tool-image-ledger.d.ts +9 -8
  262. package/dist/src/tool-image-ledger.d.ts.map +1 -1
  263. package/dist/src/tool-image-ledger.js +9 -8
  264. package/dist/src/tool-image-ledger.js.map +1 -1
  265. package/dist/src/tool-presentation.d.ts.map +1 -1
  266. package/dist/src/tool-presentation.js +3 -1
  267. package/dist/src/tool-presentation.js.map +1 -1
  268. package/dist/src/tool-result-guard.d.ts +12 -6
  269. package/dist/src/tool-result-guard.d.ts.map +1 -1
  270. package/dist/src/tool-result-guard.js +44 -17
  271. package/dist/src/tool-result-guard.js.map +1 -1
  272. package/dist/src/tool-result-history.d.ts +176 -24
  273. package/dist/src/tool-result-history.d.ts.map +1 -1
  274. package/dist/src/tool-result-history.js +411 -91
  275. package/dist/src/tool-result-history.js.map +1 -1
  276. package/dist/src/tune-out/coordinator.d.ts +17 -9
  277. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  278. package/dist/src/tune-out/coordinator.js +84 -37
  279. package/dist/src/tune-out/coordinator.js.map +1 -1
  280. package/dist/src/tune-out/tools.d.ts +4 -1
  281. package/dist/src/tune-out/tools.d.ts.map +1 -1
  282. package/dist/src/types/agent.d.ts +217 -7
  283. package/dist/src/types/agent.d.ts.map +1 -1
  284. package/dist/src/types/events.d.ts +33 -9
  285. package/dist/src/types/events.d.ts.map +1 -1
  286. package/dist/src/types/framework.d.ts +39 -3
  287. package/dist/src/types/framework.d.ts.map +1 -1
  288. package/dist/src/types/module.d.ts +95 -9
  289. package/dist/src/types/module.d.ts.map +1 -1
  290. package/dist/src/types/trace.d.ts +91 -3
  291. package/dist/src/types/trace.d.ts.map +1 -1
  292. package/package.json +5 -4
  293. package/src/agent.ts +661 -67
  294. package/src/api/server.ts +5 -4
  295. package/src/auto-continue.ts +43 -0
  296. package/src/code-execution/isolate/scripts.ts +11 -3
  297. package/src/cut-off-round.ts +98 -0
  298. package/src/framework.ts +6168 -1540
  299. package/src/gate/event-gate.ts +2895 -405
  300. package/src/gate/index.ts +10 -1
  301. package/src/gate/recipe-reconcile.ts +355 -0
  302. package/src/gate/reply-judge.ts +512 -0
  303. package/src/gate/types.ts +234 -9
  304. package/src/heartbeat/heartbeat.ts +804 -0
  305. package/src/heartbeat/reminder-time.ts +107 -0
  306. package/src/index.ts +11 -4
  307. package/src/mcpl/capability-mask.ts +3 -2
  308. package/src/mcpl/channel-registry.ts +1222 -468
  309. package/src/mcpl/conversation-router.ts +34 -16
  310. package/src/mcpl/convert-block.ts +14 -1
  311. package/src/mcpl/hook-orchestrator.ts +33 -6
  312. package/src/mcpl/inbound-source.ts +42 -69
  313. package/src/mcpl/index.ts +6 -1
  314. package/src/mcpl/inference-router.ts +79 -34
  315. package/src/mcpl/prose-grammar.ts +7 -0
  316. package/src/mcpl/protocol-family.ts +2 -0
  317. package/src/mcpl/push-coalescer.ts +51 -13
  318. package/src/mcpl/reference-fetcher.ts +201 -162
  319. package/src/mcpl/references.ts +851 -77
  320. package/src/mcpl/server-connection.ts +189 -11
  321. package/src/mcpl/tags.ts +13 -2
  322. package/src/mcpl/tool-lifecycle.ts +21 -0
  323. package/src/mcpl/tool-presence.ts +716 -0
  324. package/src/mcpl/tool-result-normalize.ts +18 -6
  325. package/src/mcpl/tool-signature.ts +316 -0
  326. package/src/mcpl/toolset-host.ts +727 -0
  327. package/src/mcpl/toolsets-module.ts +545 -0
  328. package/src/mcpl/transport.ts +3 -2
  329. package/src/mcpl/types.ts +25 -2
  330. package/src/mcpl/visible-content.ts +22 -9
  331. package/src/module-registry.ts +85 -26
  332. package/src/modules/discord/index.ts +1 -1
  333. package/src/modules/history/index.ts +70 -30
  334. package/src/modules/history/semantic.ts +308 -54
  335. package/src/modules/workspace/answers.ts +133 -0
  336. package/src/modules/workspace/branch-intent.ts +10 -5
  337. package/src/modules/workspace/direct-write.ts +460 -0
  338. package/src/modules/workspace/disk-agreement.ts +52 -21
  339. package/src/modules/workspace/edit-text.ts +84 -35
  340. package/src/modules/workspace/effects.ts +22 -13
  341. package/src/modules/workspace/index.ts +2142 -723
  342. package/src/modules/workspace/observe.ts +381 -177
  343. package/src/modules/workspace/read-page.ts +228 -0
  344. package/src/modules/workspace/reconcile.ts +27 -15
  345. package/src/modules/workspace/result-text.ts +121 -0
  346. package/src/modules/workspace/sync.ts +16 -0
  347. package/src/modules/workspace/text.ts +58 -32
  348. package/src/modules/workspace/types.ts +137 -60
  349. package/src/modules/workspace/watcher.ts +8 -3
  350. package/src/prose-drafts.ts +4 -3
  351. package/src/reasoning-loss-notice.ts +62 -0
  352. package/src/reasoning-loss.ts +120 -0
  353. package/src/send-tools.ts +3 -2
  354. package/src/sent-rows.ts +162 -0
  355. package/src/silent-heartbeat.ts +17 -10
  356. package/src/stable-hash.ts +14 -0
  357. package/src/stored-injections.ts +131 -0
  358. package/src/text-as-stored.ts +4 -3
  359. package/src/thinking-drops.ts +135 -0
  360. package/src/tool-args.ts +34 -1
  361. package/src/tool-image-ledger.ts +9 -8
  362. package/src/tool-presentation.ts +3 -1
  363. package/src/tool-result-guard.ts +45 -17
  364. package/src/tool-result-history.ts +471 -90
  365. package/src/tune-out/coordinator.ts +80 -37
  366. package/src/tune-out/tools.ts +4 -1
  367. package/src/types/agent.ts +220 -7
  368. package/src/types/events.ts +33 -9
  369. package/src/types/framework.ts +36 -3
  370. package/src/types/module.ts +91 -9
  371. package/src/types/trace.ts +94 -3
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import type { JsStore } from '@animalabs/chronicle';
22
+ import { storedBytes } from './sync.js';
22
23
 
23
24
  export type ConflictKind =
24
25
  /** Disk, workspace and the last agreement all differ. */
@@ -56,9 +57,11 @@ export interface BranchIntent {
56
57
  origin?: 'store';
57
58
  conflict?: ConflictRecord;
58
59
  /**
59
- * Why a recorded intent can't be read (its blob missing from the store, or
60
- * not an intent): a tombstone or conflict it held is unknown, never absent.
61
- * Never written; a put replaces the damaged record.
60
+ * Why a recorded intent can't be read (its blob missing from the store,
61
+ * a blob chronicle can't read, or not an intent): a tombstone or conflict
62
+ * it held is unknown, never absent.
63
+ * Never written; a put replaces the damaged record, unless it puts the same
64
+ * contents over a blob file chronicle can't read, which chronicle keeps.
62
65
  */
63
66
  unreadable?: string;
64
67
  }
@@ -70,8 +73,10 @@ function isEmpty(intent: BranchIntent): boolean {
70
73
 
71
74
  /** A recorded intent's blob, read; a damaged one says why it can't be. */
72
75
  function readIntent(store: JsStore, blobHash: string): BranchIntent {
73
- const blob = store.getBlob(blobHash);
74
- if (!blob) return { unreadable: "its record's blob is missing from the store" };
76
+ const stored = storedBytes(store, blobHash);
77
+ if ('missing' in stored) return { unreadable: "its record's blob is missing from the store" };
78
+ if ('unreadable' in stored) return { unreadable: `its record's blob can't be read from the store (${stored.unreadable})` };
79
+ const blob = stored.bytes;
75
80
  try {
76
81
  const parsed = JSON.parse(blob.toString('utf-8')) as unknown;
77
82
  if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as BranchIntent;
@@ -0,0 +1,460 @@
1
+ /**
2
+ * A direct mount's writes (MountConfig.backend): disk is the only copy, so a
3
+ * write lands there whole when its call answers, or doesn't happen and leaves
4
+ * disk as it was. Ported from anima-research/hands-mcp's staged write
5
+ * (src/shared.ts), behind the mount's boundary as the workspace's other
6
+ * effects hold it (effects.ts):
7
+ *
8
+ * - The file's directory is located inside the mount (checkDir), and where
9
+ * the file lands is judged as a push's write judges it (refusedLanding):
10
+ * inside the mount, in no nested mount's directory, and covered by the
11
+ * mount's include. A link at the file is refused on a mount that doesn't
12
+ * follow links; on one that does, the write goes to the file it leads to
13
+ * when the call stages it, judged the same way, and the link stays.
14
+ * - The new bytes are staged beside the file, in `.workspace-staged-<id>`,
15
+ * at the file's mode, special bits included as far as the kernel lets this
16
+ * process set them (a setgid bit only for a member of the file's group),
17
+ * and renamed over it, so a reader beside the agent never sees half a file
18
+ * and a process killed mid-write leaves the old file whole. A file this
19
+ * process may not write is refused, as a push's write, which opens it for
20
+ * writing, is refused: the rename needs only the directory's permission.
21
+ * A process that dies between staging and its rename leaves the staged
22
+ * file, under that name, which `ls` and `git status` show; so does a
23
+ * refused write whose removal of its staged file fails or can't tell the
24
+ * file is its own, or whose directory another writer moved after the
25
+ * staging, since the removal goes by path (discard) and the path then
26
+ * leads elsewhere. Nothing sweeps it, and the answer doesn't name it.
27
+ * The removal checks the staged name holds that file and unlinks it with
28
+ * no turn of the event loop between, so only a file another writer puts
29
+ * there in that instant can be removed in its place, or one put there
30
+ * that a stat can't tell from it: on the freed inode number, with the
31
+ * same size, mode and owner, in the same tick of a coarse clock.
32
+ * - The rename gives a hard-linked path a file of its own, and the other
33
+ * links keep the old text: `otherLinks` counts them for the answer.
34
+ * - Just before the rename, an edit's file is checked unchanged since its
35
+ * read, by its bytes, read again, and its identity (checkUnchanged),
36
+ * synchronously, so the check and the renames after it run with no turn
37
+ * of the event loop between. Only a change landing in that instant isn't
38
+ * seen, which for edit_many runs from the check through its last rename:
39
+ * no rename can be made conditional.
40
+ * - No sync. The store-backed kind syncs its pushes for its agreement
41
+ * record (reconcile.ts), and a direct mount keeps none, so a power loss
42
+ * or a kernel crash can lose a direct write after its answer said it
43
+ * landed, as it can a hands-mcp write. A process dying can't: the rename is
44
+ * whole by then.
45
+ *
46
+ * Node has no openat or renameat, so the stage and the rename go through the
47
+ * checked directory's path: a directory replaced by another writer on disk
48
+ * between the directory's check and the staging, or after its last check
49
+ * (placedStill), can redirect them, as effects.ts says of a create. For
50
+ * edit_many that last check is each file's, before the other files' checks.
51
+ */
52
+
53
+ import { randomUUID } from 'node:crypto';
54
+ import { accessSync, closeSync, constants as fsConstants, lstatSync, openSync, readSync, renameSync, unlinkSync } from 'node:fs';
55
+ import type { BigIntStats } from 'node:fs';
56
+ import { lstat, open, realpath } from 'node:fs/promises';
57
+ import { relative, sep } from 'node:path';
58
+ import { refusedLanding } from './effects.js';
59
+ import { ROOT_RECHECK, errnoWayOn, errnoWords, onlyTheHost, systemWords } from './answers.js';
60
+ import {
61
+ type CheckedDir,
62
+ type MountView,
63
+ NONBLOCK,
64
+ LEAVES_MOUNT,
65
+ NOT_A_DIRECTORY,
66
+ NOT_FOLLOWED,
67
+ OUTSIDE_PARENT,
68
+ ROOT_UNAVAILABLE,
69
+ checkDir,
70
+ checkRoot,
71
+ errno,
72
+ rootAbsence,
73
+ nameOf,
74
+ parentOf,
75
+ } from './observe.js';
76
+
77
+ const DIRECTORY_THERE = 'A file can\'t be written over a directory; give another path.';
78
+ const NOT_REGULAR_THERE = onlyTheHost('put a regular file there');
79
+
80
+ /** An open that follows no link at the path, where the platform has one. */
81
+ const NOFOLLOW = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0;
82
+
83
+ /** The name a staged file starts with, beside the file it replaces. */
84
+ export const STAGED_PREFIX = '.workspace-staged-';
85
+
86
+ /**
87
+ * Why a direct write didn't happen when its mount's root was replaced under
88
+ * it: a direct mount keeps no root to sync to (MountConfig.backend), so its
89
+ * next call works beneath whatever is there then.
90
+ */
91
+ export const ROOT_MOVED = 'the mount root changed while this call was being applied: a new call works beneath whatever directory the mount\'s path leads to then';
92
+
93
+ /**
94
+ * A file's identity as a write must find it unchanged: device, inode, size,
95
+ * mode, owner, group, and modification and change times, to the nanosecond.
96
+ * The mode, owner and group are fields of their own, since a chmod or chown
97
+ * in the same tick of a coarse clock as the file's last change leaves its
98
+ * change time as it was (checkUnchanged).
99
+ */
100
+ export interface FileIdentity {
101
+ dev: bigint;
102
+ ino: bigint;
103
+ size: bigint;
104
+ mode: bigint;
105
+ uid: bigint;
106
+ gid: bigint;
107
+ mtimeNs: bigint;
108
+ ctimeNs: bigint;
109
+ }
110
+
111
+ export const identityOf = (info: BigIntStats): FileIdentity => ({
112
+ dev: info.dev,
113
+ ino: info.ino,
114
+ size: info.size,
115
+ mode: info.mode,
116
+ uid: info.uid,
117
+ gid: info.gid,
118
+ mtimeNs: info.mtimeNs,
119
+ ctimeNs: info.ctimeNs,
120
+ });
121
+
122
+ export const sameIdentity = (a: FileIdentity, b: FileIdentity): boolean =>
123
+ a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid
124
+ && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
125
+
126
+ /** Another writer replaced, changed or removed the file between its read and its rename; nothing was written. */
127
+ export class FileChanged extends Error {}
128
+
129
+ /** Why a direct write didn't happen, in words for its answer; disk is as it was. */
130
+ export class WriteRefused extends Error {
131
+ constructor(message: string, readonly wayOn: string | null = null, readonly errno?: string) {
132
+ super(message);
133
+ }
134
+ }
135
+
136
+ const AFRESH = 'Calling again checks it afresh.';
137
+
138
+ const NAME_ITS_OWN = "Calling again won't change that; if you know the file it leads to, name that file by its own path.";
139
+
140
+ function rootWayOn(code: string | undefined): string {
141
+ return code === 'ENOENT' || code === 'ENOTDIR' ? onlyTheHost("put the mount's directory back at its path") : errnoWayOn(code, ROOT_RECHECK, true);
142
+ }
143
+
144
+ function refusedWayOn(reason: string, code?: string, hostsName = false): string | null {
145
+ if (reason === ROOT_UNAVAILABLE) return rootWayOn(code);
146
+ if (code !== undefined) return errnoWayOn(code, undefined, hostsName);
147
+ if (reason === NOT_FOLLOWED) return NAME_ITS_OWN;
148
+ if (reason === OUTSIDE_PARENT || reason === LEAVES_MOUNT) return "Calling again won't change that; the workspace writes only inside its mounts.";
149
+ if (reason === NOT_A_DIRECTORY) return "Calling again won't change that while something other than a directory stands where the path needs one; another path, or removing what stands there, would.";
150
+ return null;
151
+ }
152
+
153
+ /** A file's new bytes staged beside it, ready to be renamed over it (stageContained). */
154
+ export interface Staged {
155
+ /** Where the rename lands: the file's entry in its checked directory, a followed link's file's included. */
156
+ path: string;
157
+ /** The staged file, beside it. */
158
+ temp: string;
159
+ /**
160
+ * Which file the staged file is, so the rename moves, and a refusal
161
+ * removes, that one and no other put at its name: its whole identity,
162
+ * since a file made where it was unlinked can take its inode number.
163
+ */
164
+ tempIdentity: FileIdentity;
165
+ /** The mount's root and the file's directory, as checked when it was staged. */
166
+ root: CheckedDir;
167
+ parent: CheckedDir;
168
+ /**
169
+ * The other hard links the replaced file had, counted just before the
170
+ * rename and kept once it succeeds: the rename gives this path a file of
171
+ * its own, and they keep the old text. 0 until then, and for a new file.
172
+ */
173
+ otherLinks: number;
174
+ }
175
+
176
+ /**
177
+ * Test seams. `afterStage` is called once a call's files are staged, before
178
+ * they're checked unchanged (another writer acting then); `beforeRename`
179
+ * just before each rename, inside its refusal, so throwing stands for the
180
+ * rename failing. Production sets neither.
181
+ */
182
+ export const directWriteTestSeam: {
183
+ afterStage?: (paths: string[]) => void | Promise<void>;
184
+ beforeRename?: (path: string) => void;
185
+ } = {};
186
+
187
+ /** The mount-relative path of a real path inside the mount's root, `/`-separated. */
188
+ function relativeTo(rootReal: string, real: string): string {
189
+ return relative(rootReal, real).split(sep).join('/');
190
+ }
191
+
192
+ /**
193
+ * The checked directory a mount-relative file lies in, beneath a checked
194
+ * root, or why not. With `makeDirectory`, missing directories are made, as
195
+ * a push's write makes them; without it, a missing one refuses the write,
196
+ * since an edit replaces a file that exists.
197
+ */
198
+ async function directoryOf(view: MountView, rootReal: string, rel: string, makeDirectory: boolean): Promise<CheckedDir> {
199
+ const checked = await checkDir(view, rootReal, parentOf(rel), { create: makeDirectory });
200
+ if (checked.kind === 'checked') return checked.dir;
201
+ if (checked.kind === 'absent') throw new FileChanged(rel);
202
+ const reason = checked.outside ? OUTSIDE_PARENT : checked.reason;
203
+ throw new WriteRefused(reason, refusedWayOn(reason, checked.errno));
204
+ }
205
+
206
+ /**
207
+ * Stage `bytes` beside the mount-relative file `rel`, to be renamed over it:
208
+ * the first half of a direct write. The file keeps its mode, special bits
209
+ * included, as far as the kernel lets this process set them; a new file
210
+ * takes `0666` less the umask, as a shell's would. Its owner and group are
211
+ * this process's and the ones its directory gives a new file, and an ACL or
212
+ * extended attribute on the file isn't carried over, as with any write that
213
+ * renames over a file. Anything there that isn't a regular file is refused,
214
+ * and a refusal removes the staged file it made, except where the header
215
+ * says one is left. The staged file is written and moded through its own
216
+ * handle, never through its name again.
217
+ */
218
+ export async function stageContained(
219
+ view: MountView,
220
+ rootReal: string,
221
+ rel: string,
222
+ bytes: Buffer,
223
+ { makeDirectory = false }: { makeDirectory?: boolean } = {},
224
+ ): Promise<Staged> {
225
+ const root = await checkRoot(view, rootReal);
226
+ if ('reason' in root) {
227
+ const code = root.errno ?? await rootAbsence(rootReal);
228
+ throw new WriteRefused(root.reason, rootWayOn(code), code);
229
+ }
230
+ let parent = await directoryOf(view, rootReal, rel, makeDirectory);
231
+ let path = parent.at(nameOf(rel));
232
+ let info = await lstat(path, { bigint: true }).catch((err: unknown) => {
233
+ if (errno(err) === 'ENOENT') return null;
234
+ throw new WriteRefused(`cannot stat the file (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
235
+ });
236
+ if (info?.isSymbolicLink()) {
237
+ if (!view.followSymlinks) throw new WriteRefused(NOT_FOLLOWED, NAME_ITS_OWN);
238
+ // A followed link stands for the file it leads to, as a read takes it:
239
+ // the write goes there, judged where it lands, and the link stays.
240
+ const real = await realpath(path).catch((err: unknown) => {
241
+ throw errno(err) === 'ENOENT'
242
+ ? new WriteRefused("a symlink whose target doesn't exist", onlyTheHost('remove the link or make it lead to a file'))
243
+ : new WriteRefused(`cannot resolve the symlink (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
244
+ });
245
+ const leaves = await refusedLanding(view, rootReal, rel, real);
246
+ if (leaves !== null) throw new WriteRefused(leaves, refusedWayOn(leaves));
247
+ const realRel = relativeTo(rootReal, real);
248
+ parent = await directoryOf(view, rootReal, realRel, false);
249
+ path = parent.at(nameOf(realRel));
250
+ info = await lstat(path, { bigint: true }).catch((err: unknown) => {
251
+ // Gone since realpath found it: another writer's change.
252
+ if (errno(err) === 'ENOENT') throw new FileChanged(rel);
253
+ throw new WriteRefused(`cannot stat the file the symlink leads to (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
254
+ });
255
+ if (info.isSymbolicLink()) throw new FileChanged(rel);
256
+ } else {
257
+ // A file, or none yet, reached through a link among its directories
258
+ // lands where the mount may not act: in a nested mount's directory, or
259
+ // on a file its own include leaves out (refusedLanding).
260
+ const leaves = await refusedLanding(view, rootReal, rel, path);
261
+ if (leaves !== null) throw new WriteRefused(leaves, refusedWayOn(leaves));
262
+ }
263
+ if (info?.isDirectory()) throw new WriteRefused('a directory', DIRECTORY_THERE);
264
+ if (info && !info.isFile()) throw new WriteRefused('not a regular file', NOT_REGULAR_THERE);
265
+ // A fixed-length name, so a file whose own name is near the 255-byte limit can still be replaced.
266
+ const temp = parent.at(`${STAGED_PREFIX}${randomUUID()}`);
267
+ let made = false;
268
+ try {
269
+ // A new file is made at 0666 and the kernel takes the umask off as it
270
+ // makes it. A file being replaced gives the staged file its own mode,
271
+ // which only a chmod can set past the umask, and only after the bytes
272
+ // are written, since a write clears a set-user or set-group bit; until
273
+ // then the staged file is the owner's alone, so no other user can read
274
+ // a private file's new text while it's staged.
275
+ const handle = await open(temp, 'wx', info ? 0o600 : 0o666);
276
+ made = true;
277
+ let staged: Staged;
278
+ try {
279
+ await handle.writeFile(bytes);
280
+ if (info) await handle.chmod(Number(info.mode & 0o7777n));
281
+ const own = await handle.stat({ bigint: true });
282
+ staged = { path, temp, tempIdentity: identityOf(own), root: root.dir, parent, otherLinks: 0 };
283
+ } catch (err) {
284
+ // Removed while its handle is still open, so its device and inode
285
+ // name it and no other file: one made at its name since can't have
286
+ // taken its inode number. One that can't be told is left.
287
+ const mine = await handle.stat({ bigint: true }).catch(() => null);
288
+ if (mine) removeIf(temp, (there) => there.dev === mine.dev && there.ino === mine.ino);
289
+ await handle.close().catch(() => undefined);
290
+ throw err;
291
+ }
292
+ try {
293
+ await handle.close();
294
+ } catch (err) {
295
+ // Closed, or not, with its bytes in doubt: removed by its whole identity, as a refusal's.
296
+ await discard(staged);
297
+ throw err;
298
+ }
299
+ return staged;
300
+ } catch (err) {
301
+ // A staged file that couldn't be made names the directory: a push's
302
+ // write in place needs only the file, and this one needs both.
303
+ throw new WriteRefused(made
304
+ ? `cannot write the staged file beside it (${systemWords(errno(err), err)})`
305
+ : `cannot make the staged file in its directory (${systemWords(errno(err), err)}): a direct write needs to write the file's directory as well as the file`, errnoWayOn(errno(err)), errno(err));
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Throw unless the root and the file's directory are still the ones the
311
+ * staging checked, with a push's words for the directory (effects.ts
312
+ * moved()).
313
+ */
314
+ export async function placedStill(staged: Staged): Promise<void> {
315
+ if (!(await staged.root.stillHere())) throw new WriteRefused(ROOT_MOVED);
316
+ if (!(await staged.parent.stillHere())) throw new WriteRefused('the directory changed since it was checked', AFRESH);
317
+ }
318
+
319
+ /**
320
+ * Throw unless the file is still what its read found: FileChanged when it
321
+ * changed or is gone, nothing written. `expected` is null for a write, which
322
+ * read nothing and replaces whatever is there. Either way a link swapped in
323
+ * at the file the rename replaces (on a mount that follows links, the file
324
+ * the link at the agent's path led to when the call staged it) is refused
325
+ * rather than replaced, and so is a file this process may not write. It reads the entry the
326
+ * rename replaces, and then the file's bytes, synchronously, as renameInto
327
+ * runs, so a check and the renames after it run with no turn of the event
328
+ * loop between.
329
+ *
330
+ * The identity, taken once the bytes are read, catches a file replaced or
331
+ * re-moded under the call, which equal bytes wouldn't show. The bytes are
332
+ * compared with the ones the edit read: a kernel that stamps files from a
333
+ * coarse clock, as Linux before 6.13 does, leaves a file's identity as it
334
+ * was after a second write of the same size within one tick of its last
335
+ * change (on Debian's Linux 6.12.113 with ext4, 1,632 to 1,752 of 2,000
336
+ * such rewrites kept every stamp, in three runs), and the bytes show that
337
+ * change on every clock. The bytes are read through an open that follows
338
+ * no link and doesn't wait on a pipe put at the path since its lstat, and
339
+ * at most one byte past what the edit read, so the check never blocks and
340
+ * reads no more than that.
341
+ */
342
+ export function checkUnchanged(staged: Staged, expected: { identity: FileIdentity; bytes: Buffer } | null): void {
343
+ let now: BigIntStats;
344
+ try {
345
+ now = lstatSync(staged.path, { bigint: true });
346
+ } catch (err) {
347
+ if (errno(err) !== 'ENOENT') throw new WriteRefused(`cannot check that it hadn't changed (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
348
+ if (expected !== null) throw new FileChanged(staged.path);
349
+ return;
350
+ }
351
+ if (now.isSymbolicLink()) throw new WriteRefused('it became a symlink while this call was being applied', AFRESH);
352
+ if (now.isDirectory()) throw new WriteRefused('a directory', DIRECTORY_THERE);
353
+ if (!now.isFile()) throw new WriteRefused('not a regular file', NOT_REGULAR_THERE);
354
+ // As a push's write, which opens the file for writing, would be refused:
355
+ // the rename needs only the directory's permission, and would replace a
356
+ // file its owner made read-only.
357
+ try {
358
+ accessSync(staged.path, fsConstants.W_OK);
359
+ } catch (err) {
360
+ const code = errno(err);
361
+ // Removed since the lstat: a write makes the file anew; an edit's read is gone.
362
+ if (code === 'ENOENT') {
363
+ if (expected === null) return;
364
+ throw new FileChanged(staged.path);
365
+ }
366
+ if (code === 'EACCES' || code === 'EPERM') {
367
+ throw new WriteRefused(`a file the host's process may not write (${errnoWords(code)}): its mode or owner keeps that process out, and calling again is refused until the file's owner, or whoever runs the host, changes that`);
368
+ }
369
+ throw new WriteRefused(`cannot check that the host's process may write it (${systemWords(code, err)})`, errnoWayOn(code), code);
370
+ }
371
+ if (expected === null) return;
372
+ let bytes: Buffer;
373
+ let after: BigIntStats;
374
+ try {
375
+ // No link followed, and no wait on a pipe, if either was put at the path since the lstat.
376
+ const fd = openSync(staged.path, fsConstants.O_RDONLY | NOFOLLOW | NONBLOCK);
377
+ try {
378
+ // One byte past what the edit read, enough to see the file differs:
379
+ // a file another writer made larger, or a pipe a writer keeps
380
+ // filling, put at the path since, costs no more than that.
381
+ bytes = readBounded(fd, expected.bytes.length + 1);
382
+ } finally {
383
+ closeSync(fd);
384
+ }
385
+ // And the entry is still the file the edit read, after its bytes were read.
386
+ after = lstatSync(staged.path, { bigint: true });
387
+ } catch (err) {
388
+ // ELOOP: a link put at the path since the lstat; EAGAIN: a pipe, with a
389
+ // writer and nothing in it yet. Either is another writer's change.
390
+ if (errno(err) === 'ENOENT' || errno(err) === 'ELOOP' || errno(err) === 'EAGAIN') throw new FileChanged(staged.path);
391
+ throw new WriteRefused(`cannot check that it hadn't changed (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
392
+ }
393
+ if (!sameIdentity(identityOf(after), expected.identity) || !bytes.equals(expected.bytes)) throw new FileChanged(staged.path);
394
+ }
395
+
396
+ /** Up to `limit` bytes from the start of `fd`, fewer at its end. */
397
+ function readBounded(fd: number, limit: number): Buffer {
398
+ const buffer = Buffer.alloc(limit);
399
+ let filled = 0;
400
+ while (filled < limit) {
401
+ // From where the last read ended (a pipe has no positions to read at).
402
+ const got = readSync(fd, buffer, filled, limit - filled, null);
403
+ if (got === 0) break;
404
+ filled += got;
405
+ }
406
+ return buffer.subarray(0, filled);
407
+ }
408
+
409
+ /**
410
+ * Rename the staged file over the file, synchronously (checkUnchanged says
411
+ * why), counting the other hard links it splits the path from just before.
412
+ * A failed rename leaves the file as it was; the caller removes the staged
413
+ * file (discard).
414
+ */
415
+ export function renameInto(staged: Staged): void {
416
+ let otherLinks: number;
417
+ try {
418
+ directWriteTestSeam.beforeRename?.(staged.path);
419
+ // The staged file is still the one this call wrote, not another put at its name.
420
+ const temp = lstatSync(staged.temp, { bigint: true });
421
+ if (!temp.isFile() || !sameIdentity(identityOf(temp), staged.tempIdentity)) {
422
+ throw new WriteRefused('another writer replaced the staged copy of the new text before it could be renamed over the file, which is as it was', 'Calling again writes it afresh.');
423
+ }
424
+ otherLinks = otherLinksAt(staged.path);
425
+ renameSync(staged.temp, staged.path);
426
+ } catch (err) {
427
+ if (err instanceof WriteRefused) throw err;
428
+ throw new WriteRefused(`cannot rename the staged file over it (${systemWords(errno(err), err)})`, errnoWayOn(errno(err)), errno(err));
429
+ }
430
+ // Set once the rename has happened, so a count never stands for a split that didn't.
431
+ staged.otherLinks = otherLinks;
432
+ }
433
+
434
+ /** The other hard links of what the entry at `path` holds: 0 for none there, and when lstat fails, since the count only informs the answer. */
435
+ function otherLinksAt(path: string): number {
436
+ try {
437
+ return lstatSync(path).nlink - 1;
438
+ } catch {
439
+ return 0;
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Remove a staged file that won't be renamed, best effort: only the file
445
+ * this call staged, by its whole identity, since whatever another writer
446
+ * put at its name since is theirs, as renameInto leaves it too. Checked and
447
+ * removed synchronously, as the rename is (checkUnchanged says why).
448
+ */
449
+ export async function discard(staged: Staged): Promise<void> {
450
+ removeIf(staged.temp, (there) => there.isFile() && sameIdentity(identityOf(there), staged.tempIdentity));
451
+ }
452
+
453
+ /** Unlink what's at `path` if `ours` says it's the file meant; best effort, with no turn of the event loop between the check and the unlink. */
454
+ function removeIf(path: string, ours: (there: BigIntStats) => boolean): void {
455
+ try {
456
+ if (ours(lstatSync(path, { bigint: true }))) unlinkSync(path);
457
+ } catch {
458
+ // Gone already, or not ours to know: left, as the header says.
459
+ }
460
+ }
@@ -10,14 +10,14 @@
10
10
  * intent — tombstones, store origin, conflicts — lives in BranchIntents and
11
11
  * rewinds with the tree.
12
12
  *
13
- * P is evidence about one directory, so each mount also records the identity
14
- * (device and inode) of the root that evidence was gathered under. A root
15
- * that isn't that directory any more (an unmounted drive whose mountpoint is
16
- * now empty, a replaced directory) is an unavailable mount, never a disk on
17
- * which every file was deleted; only an explicit acceptance takes it, and
18
- * that starts its evidence afresh. A place, where a walk stopped (`walks`),
19
- * binds no root: it only says where the next walk starts, in whatever
20
- * directory the root is by then.
13
+ * P is evidence about one directory, so each mount also records the identity of
14
+ * the root that evidence was gathered under (sameRootIdentity says when two
15
+ * name the same directory). A root that isn't that directory any more (an
16
+ * unmounted drive whose mountpoint is now empty, a replaced directory) is an
17
+ * unavailable mount, never a disk on which every file was deleted; only an
18
+ * explicit acceptance takes it, and that starts its evidence afresh. A place,
19
+ * where a walk stopped (`walks`), binds no root: it only says where the next
20
+ * walk starts, in whatever directory the root is by then.
21
21
  *
22
22
  * Every transition is write-ahead (see reconcile.ts): an `intent` entry
23
23
  * (`pending`, with the prior value and the expected one) is durable before the
@@ -33,9 +33,18 @@
33
33
  * succeed, since its completion releases a draft's protection.
34
34
  */
35
35
 
36
+ import { AsyncLocalStorage } from 'node:async_hooks';
36
37
  import { resolve } from 'node:path';
37
38
  import type { JsStore } from '@animalabs/chronicle';
38
39
  import { RecordJournal } from '../../record-journal.js';
40
+ import { Refusal, onlyTheHost } from './answers.js';
41
+
42
+ const UNTIL_REOPENED = "the workspace can't check its files against disk until its store is reopened";
43
+ const REOPEN = onlyTheHost('reopen it with a restart');
44
+
45
+ export class EvidenceUnavailable extends Refusal {}
46
+
47
+ export const callGate = new AsyncLocalStorage<{ passed: boolean }>();
39
48
 
40
49
  /** Everything `stat` says about a file that can vouch for unchanged bytes. */
41
50
  export interface Fingerprint {
@@ -94,10 +103,15 @@ export interface Interrupted {
94
103
 
95
104
  export type Physical = Agreed | Pending | Interrupted;
96
105
 
97
- /** Which directory a mount root is: its device and inode, as decimal strings. */
106
+ /**
107
+ * Which directory a mount root is: its device and inode, and its birth time
108
+ * in nanoseconds as the runtime reports it, where that is above zero, as decimal
109
+ * strings.
110
+ */
98
111
  export interface RootIdentity {
99
112
  dev: string;
100
113
  ino: string;
114
+ born?: string;
101
115
  }
102
116
 
103
117
  /** Whether two configured roots name the same path, whatever their spelling
@@ -106,8 +120,17 @@ function sameRootPath(a: string, b: string): boolean {
106
120
  return resolve(a) === resolve(b);
107
121
  }
108
122
 
123
+ /**
124
+ * Whether two identities name the same directory: the same device and inode,
125
+ * or the same inode and birth time on another device, since macOS can give a
126
+ * volume another device number after a reboot. A birth time in whole seconds
127
+ * doesn't count across devices: filesystems made in the same second can give
128
+ * their roots one inode (2 on ext4) and one birth time.
129
+ */
109
130
  export function sameRootIdentity(a: RootIdentity, b: RootIdentity): boolean {
110
- return a.dev === b.dev && a.ino === b.ino;
131
+ if (a.ino !== b.ino) return false;
132
+ if (a.dev === b.dev) return true;
133
+ return a.born !== undefined && a.born === b.born && !a.born.endsWith('000000000');
111
134
  }
112
135
 
113
136
  type JournalEntry =
@@ -219,18 +242,18 @@ export class DiskAgreement {
219
242
  */
220
243
  ensureReconciled(): void {
221
244
  if (this.journal.needsReopen) {
222
- throw new Error(
223
- 'Disk-agreement evidence is unavailable until the store is reopened, as at the next start: ' +
224
- 'an append to its journal failed inside the store, and the evidence may lack what it recorded',
225
- );
245
+ throw new EvidenceUnavailable(`${UNTIL_REOPENED}: an append to its record of what disk last agreed with failed inside the store, so that record may lack what the append held. ${REOPEN}`);
226
246
  }
227
247
  if (!this.whole) {
228
- throw new Error(
229
- 'Disk-agreement evidence is unavailable until the store is reopened, as at the next start: ' +
230
- 'reading it back from the store failed',
231
- );
248
+ throw new EvidenceUnavailable(`${UNTIL_REOPENED}: reading back its record of what disk last agreed with failed. ${REOPEN}`);
232
249
  }
233
250
  if (this.journal.needsReconcile) this.rebuild();
251
+ const gate = callGate.getStore();
252
+ if (gate) gate.passed = true;
253
+ }
254
+
255
+ get awaitsReopen(): boolean {
256
+ return this.journal.needsReopen || !this.whole;
234
257
  }
235
258
 
236
259
  /** Whether evidence recorded so far still awaits a barrier. */
@@ -314,11 +337,19 @@ export class DiskAgreement {
314
337
 
315
338
  /**
316
339
  * Record the root's identity just before the first evidence a mount gains:
317
- * the caller saw it as the root while gathering that evidence. A no-op once
318
- * one is recorded; changing it is acceptRoot's alone.
340
+ * the caller saw it as the root while gathering that evidence. Once one is
341
+ * recorded, the same directory seen on another device, or with a birth
342
+ * time the record lacks, replaces it and keeps the evidence; another
343
+ * directory is acceptRoot's alone.
319
344
  */
320
345
  recordRootIdentity(mount: string, identity: RootIdentity): void {
321
- if (this.rootIdentity(mount) !== undefined) return;
346
+ const recorded = this.rootIdentity(mount);
347
+ if (recorded !== undefined) {
348
+ if (!sameRootIdentity(recorded, identity)) return;
349
+ const renumbered = recorded.dev !== identity.dev;
350
+ const bornLearned = recorded.born === undefined && identity.born !== undefined;
351
+ if (!renumbered && !bornLearned) return;
352
+ }
322
353
  this.write({ t: 'root', mount, identity }, {});
323
354
  }
324
355