@animalabs/agent-framework 0.23.1 → 0.24.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 (338) hide show
  1. package/README.md +212 -42
  2. package/dist/src/agent.d.ts +60 -9
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +92 -12
  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 +14 -12
  8. package/dist/src/api/server.js.map +1 -1
  9. package/dist/src/code-execution/engine.d.ts +177 -0
  10. package/dist/src/code-execution/engine.d.ts.map +1 -0
  11. package/dist/src/code-execution/engine.js +494 -0
  12. package/dist/src/code-execution/engine.js.map +1 -0
  13. package/dist/src/code-execution/index.d.ts +5 -10
  14. package/dist/src/code-execution/index.d.ts.map +1 -1
  15. package/dist/src/code-execution/index.js +5 -9
  16. package/dist/src/code-execution/index.js.map +1 -1
  17. package/dist/src/code-execution/isolate/calls.d.ts +114 -0
  18. package/dist/src/code-execution/isolate/calls.d.ts.map +1 -0
  19. package/dist/src/code-execution/isolate/calls.js +145 -0
  20. package/dist/src/code-execution/isolate/calls.js.map +1 -0
  21. package/dist/src/code-execution/isolate/child-entry.d.ts +2 -0
  22. package/dist/src/code-execution/isolate/child-entry.d.ts.map +1 -0
  23. package/dist/src/code-execution/isolate/child-entry.js +5 -0
  24. package/dist/src/code-execution/isolate/child-entry.js.map +1 -0
  25. package/dist/src/code-execution/isolate/child-main.d.ts +26 -0
  26. package/dist/src/code-execution/isolate/child-main.d.ts.map +1 -0
  27. package/dist/src/code-execution/isolate/child-main.js +132 -0
  28. package/dist/src/code-execution/isolate/child-main.js.map +1 -0
  29. package/dist/src/code-execution/isolate/child.d.ts +44 -0
  30. package/dist/src/code-execution/isolate/child.d.ts.map +1 -0
  31. package/dist/src/code-execution/isolate/child.js +315 -0
  32. package/dist/src/code-execution/isolate/child.js.map +1 -0
  33. package/dist/src/code-execution/isolate/frames.d.ts +80 -0
  34. package/dist/src/code-execution/isolate/frames.d.ts.map +1 -0
  35. package/dist/src/code-execution/isolate/frames.js +210 -0
  36. package/dist/src/code-execution/isolate/frames.js.map +1 -0
  37. package/dist/src/code-execution/isolate/output.d.ts +68 -0
  38. package/dist/src/code-execution/isolate/output.d.ts.map +1 -0
  39. package/dist/src/code-execution/isolate/output.js +143 -0
  40. package/dist/src/code-execution/isolate/output.js.map +1 -0
  41. package/dist/src/code-execution/isolate/prelude.d.ts +109 -0
  42. package/dist/src/code-execution/isolate/prelude.d.ts.map +1 -0
  43. package/dist/src/code-execution/isolate/prelude.js +401 -0
  44. package/dist/src/code-execution/isolate/prelude.js.map +1 -0
  45. package/dist/src/code-execution/isolate/protocol.d.ts +151 -0
  46. package/dist/src/code-execution/isolate/protocol.d.ts.map +1 -0
  47. package/dist/src/code-execution/isolate/protocol.js +150 -0
  48. package/dist/src/code-execution/isolate/protocol.js.map +1 -0
  49. package/dist/src/code-execution/isolate/render.d.ts +57 -0
  50. package/dist/src/code-execution/isolate/render.d.ts.map +1 -0
  51. package/dist/src/code-execution/isolate/render.js +214 -0
  52. package/dist/src/code-execution/isolate/render.js.map +1 -0
  53. package/dist/src/code-execution/isolate/runner.d.ts +250 -0
  54. package/dist/src/code-execution/isolate/runner.d.ts.map +1 -0
  55. package/dist/src/code-execution/isolate/runner.js +854 -0
  56. package/dist/src/code-execution/isolate/runner.js.map +1 -0
  57. package/dist/src/code-execution/isolate/scripts.d.ts +175 -0
  58. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -0
  59. package/dist/src/code-execution/isolate/scripts.js +357 -0
  60. package/dist/src/code-execution/isolate/scripts.js.map +1 -0
  61. package/dist/src/code-execution/quickjs.wasm +0 -0
  62. package/dist/src/code-execution/tool-definition.d.ts +93 -43
  63. package/dist/src/code-execution/tool-definition.d.ts.map +1 -1
  64. package/dist/src/code-execution/tool-definition.js +176 -142
  65. package/dist/src/code-execution/tool-definition.js.map +1 -1
  66. package/dist/src/deadline-timer.d.ts +3 -0
  67. package/dist/src/deadline-timer.d.ts.map +1 -1
  68. package/dist/src/deadline-timer.js +1 -1
  69. package/dist/src/deadline-timer.js.map +1 -1
  70. package/dist/src/framework.d.ts +1036 -440
  71. package/dist/src/framework.d.ts.map +1 -1
  72. package/dist/src/framework.js +4131 -2228
  73. package/dist/src/framework.js.map +1 -1
  74. package/dist/src/gate/event-gate.d.ts +28 -1
  75. package/dist/src/gate/event-gate.d.ts.map +1 -1
  76. package/dist/src/gate/event-gate.js +88 -10
  77. package/dist/src/gate/event-gate.js.map +1 -1
  78. package/dist/src/held-writes.d.ts +16 -3
  79. package/dist/src/held-writes.d.ts.map +1 -1
  80. package/dist/src/held-writes.js +16 -3
  81. package/dist/src/held-writes.js.map +1 -1
  82. package/dist/src/index.d.ts +6 -6
  83. package/dist/src/index.d.ts.map +1 -1
  84. package/dist/src/index.js +9 -8
  85. package/dist/src/index.js.map +1 -1
  86. package/dist/src/mcpl/channel-registry.d.ts +471 -75
  87. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  88. package/dist/src/mcpl/channel-registry.js +1673 -337
  89. package/dist/src/mcpl/channel-registry.js.map +1 -1
  90. package/dist/src/mcpl/conversation-router.d.ts +12 -7
  91. package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
  92. package/dist/src/mcpl/conversation-router.js +12 -7
  93. package/dist/src/mcpl/conversation-router.js.map +1 -1
  94. package/dist/src/mcpl/convert-block.d.ts.map +1 -1
  95. package/dist/src/mcpl/convert-block.js +9 -5
  96. package/dist/src/mcpl/convert-block.js.map +1 -1
  97. package/dist/src/mcpl/inbound-source.d.ts +50 -0
  98. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  99. package/dist/src/mcpl/inbound-source.js +130 -0
  100. package/dist/src/mcpl/inbound-source.js.map +1 -1
  101. package/dist/src/mcpl/index.d.ts +2 -1
  102. package/dist/src/mcpl/index.d.ts.map +1 -1
  103. package/dist/src/mcpl/index.js +3 -2
  104. package/dist/src/mcpl/index.js.map +1 -1
  105. package/dist/src/mcpl/log-value.d.ts +6 -0
  106. package/dist/src/mcpl/log-value.d.ts.map +1 -1
  107. package/dist/src/mcpl/log-value.js +8 -0
  108. package/dist/src/mcpl/log-value.js.map +1 -1
  109. package/dist/src/mcpl/modern-connection.d.ts +15 -6
  110. package/dist/src/mcpl/modern-connection.d.ts.map +1 -1
  111. package/dist/src/mcpl/modern-connection.js +168 -53
  112. package/dist/src/mcpl/modern-connection.js.map +1 -1
  113. package/dist/src/mcpl/prose-grammar.d.ts +4 -5
  114. package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
  115. package/dist/src/mcpl/prose-grammar.js +4 -5
  116. package/dist/src/mcpl/prose-grammar.js.map +1 -1
  117. package/dist/src/mcpl/protocol-family.d.ts +97 -10
  118. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  119. package/dist/src/mcpl/protocol-family.js +173 -16
  120. package/dist/src/mcpl/protocol-family.js.map +1 -1
  121. package/dist/src/mcpl/push-coalescer.d.ts +132 -14
  122. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  123. package/dist/src/mcpl/push-coalescer.js +227 -50
  124. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  125. package/dist/src/mcpl/push-handler.d.ts +6 -1
  126. package/dist/src/mcpl/push-handler.d.ts.map +1 -1
  127. package/dist/src/mcpl/push-handler.js +4 -1
  128. package/dist/src/mcpl/push-handler.js.map +1 -1
  129. package/dist/src/mcpl/reference-fetcher.d.ts +2 -2
  130. package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
  131. package/dist/src/mcpl/reference-fetcher.js +4 -4
  132. package/dist/src/mcpl/reference-fetcher.js.map +1 -1
  133. package/dist/src/mcpl/server-connection.d.ts +50 -21
  134. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  135. package/dist/src/mcpl/server-connection.js +158 -74
  136. package/dist/src/mcpl/server-connection.js.map +1 -1
  137. package/dist/src/mcpl/tags.d.ts +24 -0
  138. package/dist/src/mcpl/tags.d.ts.map +1 -1
  139. package/dist/src/mcpl/tags.js +33 -0
  140. package/dist/src/mcpl/tags.js.map +1 -1
  141. package/dist/src/mcpl/tool-result-normalize.d.ts +2 -1
  142. package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
  143. package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
  144. package/dist/src/mcpl/transport.d.ts +55 -7
  145. package/dist/src/mcpl/transport.d.ts.map +1 -1
  146. package/dist/src/mcpl/transport.js +163 -34
  147. package/dist/src/mcpl/transport.js.map +1 -1
  148. package/dist/src/mcpl/types.d.ts +22 -6
  149. package/dist/src/mcpl/types.d.ts.map +1 -1
  150. package/dist/src/mcpl/types.js.map +1 -1
  151. package/dist/src/module-registry.d.ts +4 -2
  152. package/dist/src/module-registry.d.ts.map +1 -1
  153. package/dist/src/module-registry.js +100 -13
  154. package/dist/src/module-registry.js.map +1 -1
  155. package/dist/src/modules/discord/index.d.ts.map +1 -1
  156. package/dist/src/modules/discord/index.js +8 -13
  157. package/dist/src/modules/discord/index.js.map +1 -1
  158. package/dist/src/modules/history/index.d.ts.map +1 -1
  159. package/dist/src/modules/history/index.js +27 -4
  160. package/dist/src/modules/history/index.js.map +1 -1
  161. package/dist/src/modules/history/semantic.d.ts +15 -3
  162. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  163. package/dist/src/modules/history/semantic.js +27 -5
  164. package/dist/src/modules/history/semantic.js.map +1 -1
  165. package/dist/src/modules/index.d.ts +1 -1
  166. package/dist/src/modules/index.d.ts.map +1 -1
  167. package/dist/src/modules/index.js.map +1 -1
  168. package/dist/src/modules/unknown-tool.d.ts +4 -1
  169. package/dist/src/modules/unknown-tool.d.ts.map +1 -1
  170. package/dist/src/modules/unknown-tool.js +4 -1
  171. package/dist/src/modules/unknown-tool.js.map +1 -1
  172. package/dist/src/modules/workspace/branch-intent.d.ts +3 -1
  173. package/dist/src/modules/workspace/branch-intent.d.ts.map +1 -1
  174. package/dist/src/modules/workspace/branch-intent.js +3 -1
  175. package/dist/src/modules/workspace/branch-intent.js.map +1 -1
  176. package/dist/src/modules/workspace/edit-plan.d.ts +265 -0
  177. package/dist/src/modules/workspace/edit-plan.d.ts.map +1 -0
  178. package/dist/src/modules/workspace/edit-plan.js +794 -0
  179. package/dist/src/modules/workspace/edit-plan.js.map +1 -0
  180. package/dist/src/modules/workspace/edit-text.d.ts +117 -0
  181. package/dist/src/modules/workspace/edit-text.d.ts.map +1 -0
  182. package/dist/src/modules/workspace/edit-text.js +584 -0
  183. package/dist/src/modules/workspace/edit-text.js.map +1 -0
  184. package/dist/src/modules/workspace/effects.d.ts +5 -4
  185. package/dist/src/modules/workspace/effects.d.ts.map +1 -1
  186. package/dist/src/modules/workspace/effects.js +78 -25
  187. package/dist/src/modules/workspace/effects.js.map +1 -1
  188. package/dist/src/modules/workspace/index.d.ts +484 -61
  189. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  190. package/dist/src/modules/workspace/index.js +2173 -645
  191. package/dist/src/modules/workspace/index.js.map +1 -1
  192. package/dist/src/modules/workspace/observe.d.ts +213 -38
  193. package/dist/src/modules/workspace/observe.d.ts.map +1 -1
  194. package/dist/src/modules/workspace/observe.js +416 -36
  195. package/dist/src/modules/workspace/observe.js.map +1 -1
  196. package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
  197. package/dist/src/modules/workspace/reconcile.js +15 -8
  198. package/dist/src/modules/workspace/reconcile.js.map +1 -1
  199. package/dist/src/modules/workspace/text.d.ts +32 -0
  200. package/dist/src/modules/workspace/text.d.ts.map +1 -0
  201. package/dist/src/modules/workspace/text.js +67 -0
  202. package/dist/src/modules/workspace/text.js.map +1 -0
  203. package/dist/src/modules/workspace/types.d.ts +210 -6
  204. package/dist/src/modules/workspace/types.d.ts.map +1 -1
  205. package/dist/src/modules/workspace/types.js.map +1 -1
  206. package/dist/src/modules/workspace/watcher.d.ts +3 -2
  207. package/dist/src/modules/workspace/watcher.d.ts.map +1 -1
  208. package/dist/src/modules/workspace/watcher.js.map +1 -1
  209. package/dist/src/operator-log.d.ts +52 -24
  210. package/dist/src/operator-log.d.ts.map +1 -1
  211. package/dist/src/operator-log.js.map +1 -1
  212. package/dist/src/recovery/discord-awareness-outbox.d.ts +496 -72
  213. package/dist/src/recovery/discord-awareness-outbox.d.ts.map +1 -1
  214. package/dist/src/recovery/discord-awareness-outbox.js +1196 -289
  215. package/dist/src/recovery/discord-awareness-outbox.js.map +1 -1
  216. package/dist/src/recovery/offline-branch.d.ts +26 -1
  217. package/dist/src/recovery/offline-branch.d.ts.map +1 -1
  218. package/dist/src/recovery/offline-branch.js +164 -39
  219. package/dist/src/recovery/offline-branch.js.map +1 -1
  220. package/dist/src/recovery/recover-cli.js +23 -4
  221. package/dist/src/recovery/recover-cli.js.map +1 -1
  222. package/dist/src/send-tools.d.ts +11 -0
  223. package/dist/src/send-tools.d.ts.map +1 -0
  224. package/dist/src/send-tools.js +11 -0
  225. package/dist/src/send-tools.js.map +1 -0
  226. package/dist/src/tool-result-guard.d.ts +4 -3
  227. package/dist/src/tool-result-guard.d.ts.map +1 -1
  228. package/dist/src/tool-result-guard.js +5 -4
  229. package/dist/src/tool-result-guard.js.map +1 -1
  230. package/dist/src/tool-result-history.d.ts +1 -1
  231. package/dist/src/tool-result-history.js +1 -1
  232. package/dist/src/tune-out/coordinator.d.ts +21 -0
  233. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  234. package/dist/src/tune-out/coordinator.js +139 -37
  235. package/dist/src/tune-out/coordinator.js.map +1 -1
  236. package/dist/src/types/agent.d.ts +4 -0
  237. package/dist/src/types/agent.d.ts.map +1 -1
  238. package/dist/src/types/events.d.ts +62 -9
  239. package/dist/src/types/events.d.ts.map +1 -1
  240. package/dist/src/types/framework.d.ts +62 -58
  241. package/dist/src/types/framework.d.ts.map +1 -1
  242. package/dist/src/types/module.d.ts +40 -8
  243. package/dist/src/types/module.d.ts.map +1 -1
  244. package/dist/src/types/trace.d.ts +111 -10
  245. package/dist/src/types/trace.d.ts.map +1 -1
  246. package/dist/src/usage/types.d.ts +16 -0
  247. package/dist/src/usage/types.d.ts.map +1 -1
  248. package/dist/src/usage/usage-tracker.d.ts +14 -1
  249. package/dist/src/usage/usage-tracker.d.ts.map +1 -1
  250. package/dist/src/usage/usage-tracker.js +81 -41
  251. package/dist/src/usage/usage-tracker.js.map +1 -1
  252. package/package.json +6 -5
  253. package/src/agent.ts +93 -12
  254. package/src/api/server.ts +14 -12
  255. package/src/code-execution/engine.ts +595 -0
  256. package/src/code-execution/index.ts +5 -17
  257. package/src/code-execution/isolate/calls.ts +199 -0
  258. package/src/code-execution/isolate/child-entry.ts +5 -0
  259. package/src/code-execution/isolate/child-main.ts +132 -0
  260. package/src/code-execution/isolate/child.ts +327 -0
  261. package/src/code-execution/isolate/frames.ts +209 -0
  262. package/src/code-execution/isolate/output.ts +161 -0
  263. package/src/code-execution/isolate/prelude.ts +409 -0
  264. package/src/code-execution/isolate/protocol.ts +240 -0
  265. package/src/code-execution/isolate/render.ts +230 -0
  266. package/src/code-execution/isolate/runner.ts +911 -0
  267. package/src/code-execution/isolate/scripts.ts +479 -0
  268. package/src/code-execution/quickjs.wasm +0 -0
  269. package/src/code-execution/quickjs.wasm.LICENSES +149 -0
  270. package/src/code-execution/tool-definition.ts +236 -167
  271. package/src/deadline-timer.ts +1 -1
  272. package/src/framework.ts +4507 -2406
  273. package/src/gate/event-gate.ts +78 -11
  274. package/src/held-writes.ts +17 -3
  275. package/src/index.ts +30 -22
  276. package/src/mcpl/channel-registry.ts +1825 -368
  277. package/src/mcpl/conversation-router.ts +12 -7
  278. package/src/mcpl/convert-block.ts +9 -5
  279. package/src/mcpl/inbound-source.ts +131 -0
  280. package/src/mcpl/index.ts +4 -2
  281. package/src/mcpl/log-value.ts +9 -0
  282. package/src/mcpl/modern-connection.ts +162 -53
  283. package/src/mcpl/prose-grammar.ts +4 -5
  284. package/src/mcpl/protocol-family.ts +199 -21
  285. package/src/mcpl/push-coalescer.ts +306 -62
  286. package/src/mcpl/push-handler.ts +10 -2
  287. package/src/mcpl/reference-fetcher.ts +4 -4
  288. package/src/mcpl/server-connection.ts +180 -79
  289. package/src/mcpl/tags.ts +36 -0
  290. package/src/mcpl/tool-result-normalize.ts +2 -1
  291. package/src/mcpl/transport.ts +162 -33
  292. package/src/mcpl/types.ts +23 -6
  293. package/src/module-registry.ts +92 -13
  294. package/src/modules/discord/index.ts +8 -13
  295. package/src/modules/history/index.ts +25 -3
  296. package/src/modules/history/semantic.ts +29 -6
  297. package/src/modules/index.ts +1 -0
  298. package/src/modules/unknown-tool.ts +4 -1
  299. package/src/modules/workspace/branch-intent.ts +3 -1
  300. package/src/modules/workspace/edit-plan.ts +954 -0
  301. package/src/modules/workspace/edit-text.ts +618 -0
  302. package/src/modules/workspace/effects.ts +70 -19
  303. package/src/modules/workspace/index.ts +2247 -642
  304. package/src/modules/workspace/observe.ts +465 -56
  305. package/src/modules/workspace/reconcile.ts +14 -7
  306. package/src/modules/workspace/text.ts +68 -0
  307. package/src/modules/workspace/types.ts +211 -6
  308. package/src/modules/workspace/watcher.ts +3 -2
  309. package/src/operator-log.ts +47 -19
  310. package/src/recovery/discord-awareness-outbox.ts +1500 -356
  311. package/src/recovery/offline-branch.ts +189 -55
  312. package/src/recovery/recover-cli.ts +25 -4
  313. package/src/send-tools.ts +11 -0
  314. package/src/tool-result-guard.ts +6 -5
  315. package/src/tool-result-history.ts +1 -1
  316. package/src/tune-out/coordinator.ts +163 -42
  317. package/src/types/agent.ts +4 -0
  318. package/src/types/events.ts +62 -9
  319. package/src/types/framework.ts +62 -58
  320. package/src/types/module.ts +40 -8
  321. package/src/types/trace.ts +121 -15
  322. package/src/usage/types.ts +16 -0
  323. package/src/usage/usage-tracker.ts +86 -43
  324. package/dist/src/code-execution/py-runner.d.ts +0 -191
  325. package/dist/src/code-execution/py-runner.d.ts.map +0 -1
  326. package/dist/src/code-execution/py-runner.js +0 -655
  327. package/dist/src/code-execution/py-runner.js.map +0 -1
  328. package/dist/src/code-execution/runtime-py.d.ts +0 -50
  329. package/dist/src/code-execution/runtime-py.d.ts.map +0 -1
  330. package/dist/src/code-execution/runtime-py.js +0 -677
  331. package/dist/src/code-execution/runtime-py.js.map +0 -1
  332. package/dist/src/mcpl/prose-stream-router.d.ts +0 -88
  333. package/dist/src/mcpl/prose-stream-router.d.ts.map +0 -1
  334. package/dist/src/mcpl/prose-stream-router.js +0 -291
  335. package/dist/src/mcpl/prose-stream-router.js.map +0 -1
  336. package/src/code-execution/py-runner.ts +0 -791
  337. package/src/code-execution/runtime-py.ts +0 -677
  338. package/src/mcpl/prose-stream-router.ts +0 -268
@@ -4,7 +4,6 @@
4
4
  * Provides a unified workspace with mount-based filesystem access,
5
5
  * auto-sync between real filesystem and Chronicle, and manual materialization.
6
6
  */
7
- import { isUtf8 } from 'node:buffer';
8
7
  import { constants as fsConstants } from 'node:fs';
9
8
  import { open, readdir, readlink, stat, lstat, realpath } from 'node:fs/promises';
10
9
  import { basename, dirname, isAbsolute, join, parse, resolve, relative, sep } from 'node:path';
@@ -13,8 +12,11 @@ import { MountWatcher } from './watcher.js';
13
12
  import { hashContent, DEFAULT_MAX_FILE_SIZE } from './sync.js';
14
13
  import { DiskAgreement, sameRootIdentity } from './disk-agreement.js';
15
14
  import { BranchIntents } from './branch-intent.js';
16
- import { IGNORED, NONBLOCK, OTHER_MOUNT, ROOT_REPLACED, ROOT_UNAVAILABLE, checkDir, checkRoot, diskSpelling, filesystemTrustsCtime, foldsCase, inOtherMount, leadsInto, linkLeads, linkOnTheWay, linkRefusal, linkWords, locateRoot, nestedAtReal, nestedHolder, passedOverAt, readPrefix } from './observe.js';
15
+ import { IGNORED, NONBLOCK, OTHER_MOUNT, OUTSIDE_INCLUDE, ROOT_REPLACED, ROOT_UNAVAILABLE, beginsWithDir, checkDir, checkRoot, coversLanding, diskSpelling, filesystemTrustsCtime, foldsCase, includePatternReadable, inOtherMount, insideMount, leadsInto, linkOnTheWay, linkRefusal, linkWords, locateRoot, looksBinary, namesHolder, namesNestedPlace, nestedAtReal, nestedHolder, observePath, parsedSpelling, passedOverAt, pathSegments, readBytes, readPrefix, shownLeads, sniffImageMime, walkScope, withinIncludes } from './observe.js';
17
16
  import { TOOL_BATCH_HOOK_TIMEOUT_MS, ensureStateRegistered } from '../../module-registry.js';
17
+ import { DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS } from '../../tool-result-history.js';
18
+ import { countBudget, decodeForEdit, hintBudget, planFile } from './edit-plan.js';
19
+ import { cutLine, editList, editReceipt, fitted, refusalText } from './edit-text.js';
18
20
  import { NOT_PUSHED_IN_OTHER_MOUNT, WALK_CAP, entryMode, pushPaths, reconcilePass, settleAdoptionBeforeMutation, } from './reconcile.js';
19
21
  /** Default for how long the after-batch scan may hold the agent's next inference. */
20
22
  const AGENT_ACTION_SCAN_DEADLINE_MS = 20_000;
@@ -30,6 +32,18 @@ const CATCH_UP_BOUND_MS = 30_000;
30
32
  const NOT_RUNNING = 'The workspace has stopped: it takes no more work until it starts again';
31
33
  /** The workspace's own deadline must end before the framework's hook bound. */
32
34
  const AGENT_ACTION_SCAN_DEADLINE_MAX_MS = TOOL_BATCH_HOOK_TIMEOUT_MS - 1_000;
35
+ /** A direct mount's ignore list when its config names none (MountConfig.ignore). */
36
+ const DIRECT_MOUNT_IGNORE = ['node_modules', 'dist', '.git', 'build', 'coverage', 'target', '__pycache__', '.venv'];
37
+ /**
38
+ * How many files a direct mount's grep reads, and its listings look at, at
39
+ * once. Over a layout of seven checkouts, 5,929 files, a direct grep reading
40
+ * 16 at a time on Node's default threadpool had a median time below the
41
+ * store-backed grep's over the same files at every load tried, and one
42
+ * reading them in turn took 2 to 2.4 times as long.
43
+ */
44
+ const DIRECT_READS_AT_ONCE = 16;
45
+ /** Why sync passes over a direct mount, as its result's `skipped` says. */
46
+ const DIRECT_SYNC_SKIPPED = "a direct mount: its tools read disk as it is, so there's nothing to take in";
33
47
  class WorkspaceImageReadError extends Error {
34
48
  code;
35
49
  constructor(code, message) {
@@ -38,6 +52,13 @@ class WorkspaceImageReadError extends Error {
38
52
  this.name = 'WorkspaceImageReadError';
39
53
  }
40
54
  }
55
+ /** A path the mount's `include` doesn't cover: outside the mount. */
56
+ class OutsideIncludeError extends Error {
57
+ constructor(shownPath, mount) {
58
+ super(`"${shownPath}" is outside the mount's include: mount "${mount.name}" holds only ${(mount.include ?? []).join(', ')}. `
59
+ + 'The host\'s operator sets the include in the mount\'s configuration, so calling again with this path changes nothing.');
60
+ }
61
+ }
41
62
  /**
42
63
  * A file operation's path lies in another mount's directory nested in the
43
64
  * mount it names. The message names the mount that holds it and the path to
@@ -118,22 +139,30 @@ function matchesPartialPrefix(buffer, prefix) {
118
139
  * link's reason, as the observations give it, after the path; or, for a
119
140
  * directory the walk couldn't ask, a failure to read, coded `not_found` with
120
141
  * the readlink's errno, as every failed lookup is. A link's code follows
121
- * where it leads, so a caller choosing advice by code gets advice that fits:
142
+ * where its refusal says it leads (shownLeads), so a caller choosing advice
143
+ * by code gets advice that fits, and the code says no more than the message:
122
144
  * `escape` for a link leading outside the mount, the code a path resolving
123
- * outside it gets too; `other_mount` for one into a nested mount's directory,
124
- * the code that mount's own paths get; and `parent_symlink` for any other,
125
- * which `symlink`, a file that is itself a link, leaves apart.
145
+ * outside it gets too; `other_mount` for one into a nested mount's directory
146
+ * where the message names that mount (namesHolder), the code that mount's own
147
+ * paths get; and for any other, a link the mount's include doesn't cover
148
+ * among them, the code of a link the mount doesn't follow where it stands:
149
+ * `symlink` at the path itself, as any other link there gets, and
150
+ * `parent_symlink` among its directories, judged on the parsed path
151
+ * (`relativePath`), whatever spelling the caller gave. Where the link leads is
152
+ * read beneath `rootReal`, the root the check that found it resolved, so the
153
+ * link and its target are judged beneath one root, by that root's nesting
154
+ * (`nested`).
126
155
  */
127
- async function linkReadError(mount, found, mountPrefixedPath, nested) {
156
+ async function linkReadError(mount, found, mountPrefixedPath, relativePath, nested, rootReal) {
128
157
  if (!('link' in found)) {
129
158
  return new WorkspaceReadError('not_found', `Unable to read file: ${mountPrefixedPath}: ${linkWords(mount.config.name, found, null)}`, 'readlink', found.code);
130
159
  }
131
- const rootReal = await realpath(mount.config.path).catch(() => resolve(mount.config.path));
132
- const leads = await linkLeads(mount.config.path, rootReal, found.link);
133
- const reason = `${mountPrefixedPath}: ${linkWords(mount.config.name, found, leads, nested)}`;
134
- const code = leads.kind === 'outside' ? 'escape'
135
- : leads.kind === 'inside' && nestedHolder(leads.target, nested) ? 'other_mount'
136
- : 'parent_symlink';
160
+ const leads = await shownLeads(rootReal, rootReal, found, mount.config.include);
161
+ const reason = `${mountPrefixedPath}: ${linkWords(mount.config.name, found, leads, nested, mount.config.include)}`;
162
+ const holder = leads?.kind === 'inside' ? nestedHolder(leads.target, nested) : undefined;
163
+ const code = leads?.kind === 'outside' ? 'escape'
164
+ : leads?.kind === 'inside' && holder && namesHolder(leads, holder) ? 'other_mount'
165
+ : relativePath === found.link ? 'symlink' : 'parent_symlink';
137
166
  return new WorkspaceReadError(code, reason, 'readlink');
138
167
  }
139
168
  /**
@@ -149,6 +178,43 @@ function nestedDir(from, to) {
149
178
  return undefined;
150
179
  return rel.split(sep).join('/');
151
180
  }
181
+ /** Each directory above `path`, innermost first, to the filesystem's root. */
182
+ function ancestorsOf(path) {
183
+ const dirs = [];
184
+ for (let dir = dirname(path);; dir = dirname(dir)) {
185
+ dirs.push(dir);
186
+ if (dirname(dir) === dir)
187
+ return dirs;
188
+ }
189
+ }
190
+ /**
191
+ * Where a mount is nested in an outer mount, as a start places it: at its
192
+ * directory as configured beneath the outer mount's configured path
193
+ * (`outerPath`), beneath each directory above its configured path that is
194
+ * the outer root on disk (`above`, each with where it lies on disk), and
195
+ * where its real root (`real`) lies beneath the outer root (`outerReal`),
196
+ * each also as disk spells it beneath `spellAt`. Its real root is claimed
197
+ * where it doesn't hold the outer root, which it would otherwise claim
198
+ * whole. Undefined where it's nested nowhere.
199
+ */
200
+ async function placementOf(outerPath, outerReal, innerPath, real, above, spellAt) {
201
+ const configured = nestedDir(outerPath, innerPath);
202
+ const throughRoot = above.filter((a) => a.real === outerReal).map((a) => nestedDir(a.dir, innerPath));
203
+ const fromRoots = [];
204
+ for (const dir of [configured, ...throughRoot, nestedDir(outerReal, real)]) {
205
+ if (dir !== undefined && !fromRoots.some((s) => s.dir === dir))
206
+ fromRoots.push({ dir, root: join(outerPath, ...dir.split('/')) });
207
+ }
208
+ if (fromRoots.length === 0)
209
+ return undefined;
210
+ const spellings = [...fromRoots];
211
+ for (const found of fromRoots) {
212
+ const dir = await diskSpelling(spellAt, found.dir);
213
+ if (!spellings.some((s) => s.dir === dir))
214
+ spellings.push({ dir, root: join(outerPath, ...dir.split('/')) });
215
+ }
216
+ return { configured, fromRoots, spellings, claims: !isContainedPath(real, outerReal) };
217
+ }
152
218
  /** How many links realBeneath follows to a place not made yet before it stops, as the kernel's limit does. */
153
219
  const LINKS_FOLLOWED = 40;
154
220
  /**
@@ -156,13 +222,14 @@ const LINKS_FOLLOWED = 40;
156
222
  * it, with the links on its way and in it taken out, read without holding
157
223
  * the process. Where nothing is there yet, a link leads where its target
158
224
  * would be, and anything else lies beneath its nearest existing directory's
159
- * real path, with the rest as given. A link's target is read from the
160
- * link's directory as it is on disk, and nothing is resolved lexically on
161
- * the way, so a `..` is taken from where the links before it lead, as the
225
+ * real path, with the rest as given, a `..` after a name that isn't there
226
+ * taken lexically. A link's target is read from the link's directory as it
227
+ * is on disk, so a `..` is taken from where the links before it lead, as the
162
228
  * kernel takes it. Where realpath fails for any other reason, such as a
163
- * loop or a lack of permission, the whole path as path.resolve reads it.
229
+ * loop or a lack of permission, the whole path as path.resolve reads it, and
230
+ * `unresolved`, where given, takes the first such code.
164
231
  */
165
- async function realBeneath(given, links = 0) {
232
+ async function realBeneath(given, links = 0, unresolved) {
166
233
  // A trailing separator, as a link to a directory is often written, names
167
234
  // the same place, but readlink would then follow the link it names.
168
235
  const { root } = parse(given);
@@ -175,15 +242,36 @@ async function realBeneath(given, links = 0) {
175
242
  catch (err) {
176
243
  const code = errnoOf(err);
177
244
  const parent = dirname(absolute);
178
- if ((code !== 'ENOENT' && code !== 'ENOTDIR') || links >= LINKS_FOLLOWED || parent === absolute)
245
+ if ((code !== 'ENOENT' && code !== 'ENOTDIR') || links > LINKS_FOLLOWED || parent === absolute) {
246
+ if (unresolved)
247
+ unresolved.code ??= links > LINKS_FOLLOWED ? 'ELOOP' : code ?? 'EIO';
179
248
  return resolve(absolute);
180
- const place = await realBeneath(parent, links);
249
+ }
250
+ const place = await realBeneath(parent, links, unresolved);
181
251
  const target = await readlink(absolute).catch(() => null);
182
252
  if (target !== null)
183
- return realBeneath(isAbsolute(target) ? target : `${place}${sep}${target}`, links + 1);
253
+ return realBeneath(isAbsolute(target) ? target : `${place}${sep}${target}`, links + 1, unresolved);
184
254
  return join(place, basename(absolute));
185
255
  }
186
256
  }
257
+ /**
258
+ * A configured value as a refusal shows it: a number or a bigint as
259
+ * JavaScript writes it (JSON would say null for NaN, and throws for a
260
+ * bigint), anything else as JSON, or as String gives it where JSON can't,
261
+ * as for a list holding a bigint.
262
+ */
263
+ function shownValue(value) {
264
+ if (typeof value === 'number')
265
+ return String(value);
266
+ if (typeof value === 'bigint')
267
+ return `${value}n`;
268
+ try {
269
+ return JSON.stringify(value) ?? String(value);
270
+ }
271
+ catch {
272
+ return String(value);
273
+ }
274
+ }
187
275
  function isContainedPath(root, candidate) {
188
276
  if (candidate === root)
189
277
  return true;
@@ -589,6 +677,10 @@ export class WorkspaceModule {
589
677
  otherMounts = new Map();
590
678
  /** Whether each mount's root folds case (foldsCase), where disk has it, as the last start read it. */
591
679
  rootFoldsCase = new Map();
680
+ /** Where the last start placed each mount's root (readNesting's `reals`). */
681
+ placedRoots = new Map();
682
+ /** Each directory above each mount's configured path, with where the last start found it on disk (readNesting's `above`). */
683
+ placedAbove = new Map();
592
684
  /**
593
685
  * Whether a file's mode is observed, taken in and applied (MountRuntime's
594
686
  * `modesObserved`): not on Windows, which reports no POSIX modes. A test
@@ -600,13 +692,41 @@ export class WorkspaceModule {
600
692
  * mounts, so restoration must be second-callback-safe like watcher
601
693
  * startup already is (issue #72). Cleared after application. */
602
694
  savedState = null;
695
+ /**
696
+ * The mounts configured direct that run as 'chronicle' this session, with
697
+ * the changes the store held there that disk lacked (chooseKinds), for
698
+ * ensureRunning to say once both halves of the lifecycle have run.
699
+ */
700
+ notDirect = new Map();
603
701
  constructor(config) {
604
702
  for (const mount of config.mounts) {
605
703
  const cap = mount.walkCap;
606
704
  if (cap !== undefined && !(Number.isSafeInteger(cap) && cap > 0)) {
607
- // Numbers as JavaScript writes them (JSON would say null for NaN), anything else as JSON.
608
- const shown = typeof cap === 'number' ? String(cap) : typeof cap === 'bigint' ? `${cap}n` : JSON.stringify(cap) ?? String(cap);
609
- throw new Error(`[workspace] Mount "${mount.name}": walkCap must be a positive integer no larger than ${Number.MAX_SAFE_INTEGER}, not ${shown}`);
705
+ throw new Error(`[workspace] Mount "${mount.name}": walkCap must be a positive integer no larger than ${Number.MAX_SAFE_INTEGER}, not ${shownValue(cap)}`);
706
+ }
707
+ const backend = mount.backend;
708
+ if (backend !== undefined && backend !== 'chronicle' && backend !== 'direct') {
709
+ throw new Error(`[workspace] Mount "${mount.name}": backend must be 'chronicle' or 'direct', not ${shownValue(backend)}`);
710
+ }
711
+ const refused = backend === 'direct' ? directRefusals(mount) : [];
712
+ if (refused.length > 0) {
713
+ throw new Error(`[workspace] Mount "${mount.name}" is direct, which reads disk as it is with no store, watcher or push: ${refused.join('; ')}`);
714
+ }
715
+ const include = mount.include;
716
+ if (include !== undefined) {
717
+ // A pattern the matcher can't read would match nothing, and take every
718
+ // file out of the mount unsaid (includePatternReadable).
719
+ if (!Array.isArray(include) || include.length === 0) {
720
+ throw new Error(`[workspace] Mount "${mount.name}": include must be a non-empty list of names, "*.ext" globs or "dir/**" globs, not ${shownValue(include)}`);
721
+ }
722
+ // By index: an entry that is itself undefined, or a hole, is unreadable too.
723
+ const at = include.findIndex((p) => !includePatternReadable(p));
724
+ if (at >= 0) {
725
+ const unreadable = include[at];
726
+ throw new Error(`[workspace] Mount "${mount.name}": include must be a non-empty list of names, "*.ext" globs or "dir/**" globs, `
727
+ + `with no "." or ".." segment${sep === '\\' ? ' and no "\\", which this platform reads as a separator' : ''}; `
728
+ + `${shownValue(unreadable)} is none of these`);
729
+ }
610
730
  }
611
731
  }
612
732
  // Detect overlapping mount paths: a mount nested inside another is that
@@ -649,21 +769,32 @@ export class WorkspaceModule {
649
769
  // before the call, knowing no mount, and a later initStore starts clean.
650
770
  const mounts = new Map();
651
771
  const intents = new Map();
772
+ // A direct mount's files never go into the store, so its states aren't
773
+ // made. One that ran as 'chronicle' before has them, and they're read
774
+ // below for what the store holds there that disk lacks.
775
+ const made = this.config.mounts.some((m) => m.backend === 'direct') ? new Set(store.listStates().map((s) => s.id)) : null;
652
776
  // Register tree states for each mount: the workspace tree, and the
653
777
  // branch-local intent that qualifies it.
654
778
  for (const mount of this.config.mounts) {
655
779
  const treeStateId = `workspace/${mount.name}/tree`;
656
780
  const intentTreeStateId = `workspace/${mount.name}/intent`;
657
- for (const id of [treeStateId, intentTreeStateId]) {
658
- ensureStateRegistered(store, {
659
- id,
660
- strategy: 'tree',
661
- deltaSnapshotEvery: this.config.deltaSnapshotEvery ?? 50,
662
- fullSnapshotEvery: this.config.fullSnapshotEvery ?? 10,
663
- });
781
+ const direct = mount.backend === 'direct';
782
+ // A mount configured direct that ran as 'chronicle' runs direct only
783
+ // once chooseKinds finds nothing held there.
784
+ const ranStoreBacked = direct && made.has(treeStateId) && made.has(intentTreeStateId);
785
+ if (!direct) {
786
+ for (const id of [treeStateId, intentTreeStateId]) {
787
+ ensureStateRegistered(store, {
788
+ id,
789
+ strategy: 'tree',
790
+ deltaSnapshotEvery: this.config.deltaSnapshotEvery ?? 50,
791
+ fullSnapshotEvery: this.config.fullSnapshotEvery ?? 10,
792
+ });
793
+ }
664
794
  }
665
795
  mounts.set(mount.name, {
666
796
  config: mount,
797
+ direct: direct && !ranStoreBacked,
667
798
  treeStateId,
668
799
  intentTreeStateId,
669
800
  lastMaterializedSeq: 0,
@@ -673,7 +804,9 @@ export class WorkspaceModule {
673
804
  watcherReadyAt: null,
674
805
  watcherError: null,
675
806
  });
676
- intents.set(mount.name, new BranchIntents(store, intentTreeStateId));
807
+ if (!direct || ranStoreBacked) {
808
+ intents.set(mount.name, new BranchIntents(store, intentTreeStateId));
809
+ }
677
810
  }
678
811
  this.store = store;
679
812
  for (const [name, state] of mounts)
@@ -681,12 +814,56 @@ export class WorkspaceModule {
681
814
  for (const [name, intent] of intents)
682
815
  this.intents.set(name, intent);
683
816
  // What disk last agreed with, per mount and path: global records, so a
684
- // branch switch never rewinds it.
817
+ // branch switch never rewinds it. A mount configured direct has its
818
+ // evidence read only where a 'chronicle' run left its states, for what
819
+ // the store holds there that disk lacks (chooseKinds); one that never ran
820
+ // so has none to read, and none is begun for it.
685
821
  this.agreement = new DiskAgreement(store, { modesObserved: () => this.modesObserved });
686
- this.agreement.open(this.config.mounts.map((m) => ({ name: m.name, root: resolve(m.path) })));
822
+ this.agreement.open(this.config.mounts.filter((m) => intents.has(m.name)).map((m) => ({ name: m.name, root: resolve(m.path) })));
823
+ this.chooseKinds();
687
824
  this.applySavedState();
688
825
  this.ensureRunning();
689
826
  }
827
+ /**
828
+ * Whether each mount configured direct runs direct: not while the store
829
+ * holds changes there that disk lacks, on the branch selected then, so
830
+ * they stay in view (MountConfig.backend); it runs as 'chronicle' instead,
831
+ * and ensureRunning says so. Decided when initStore gives the store, and
832
+ * again at each start, which knows how the mounts nest, so a start that
833
+ * finds none held starts the mount direct. A path held more than one way
834
+ * is named for the last way set here.
835
+ */
836
+ chooseKinds() {
837
+ // Every mount is decided before any is set, so a read of the store that
838
+ // throws leaves the decisions as they were.
839
+ const decided = new Map();
840
+ for (const [name, state] of this.mounts) {
841
+ if (state.config.backend !== 'direct')
842
+ continue;
843
+ // One with no states from a 'chronicle' run holds nothing.
844
+ if (!this.intents.has(name)) {
845
+ decided.set(name, []);
846
+ continue;
847
+ }
848
+ const held = this.heldChanges(state);
849
+ const what = new Map();
850
+ for (const path of held.owed)
851
+ what.set(path, 'changed in the workspace');
852
+ for (const path of held.unreadable)
853
+ what.set(path, UNREADABLE_INTENT);
854
+ for (const path of held.deletions)
855
+ what.set(path, 'deleted in the workspace');
856
+ for (const path of held.conflicts)
857
+ what.set(path, 'in conflict');
858
+ decided.set(name, [...what].sort(([a], [b]) => a.localeCompare(b)).map(([path, label]) => ({ path, what: label })));
859
+ }
860
+ this.notDirect = new Map();
861
+ for (const [name, held] of decided) {
862
+ this.mounts.get(name).direct = held.length === 0;
863
+ if (held.length > 0)
864
+ this.notDirect.set(name, held);
865
+ }
866
+ }
690
867
  // ==========================================================================
691
868
  // Reconciliation plumbing
692
869
  // ==========================================================================
@@ -713,7 +890,7 @@ export class WorkspaceModule {
713
890
  * A mount as observation reads it, with the root identity the workspace
714
891
  * recorded for it, if any: what a pass reads beneath (runtime), with
715
892
  * rootIdentity's, and what a disk read checks its root against (readRoot),
716
- * with rootIdentityForRead's.
893
+ * with rootIdentityForRead's. A direct mount's has none (diskView).
717
894
  */
718
895
  viewOf(mount, rootIdentity) {
719
896
  return {
@@ -722,11 +899,39 @@ export class WorkspaceModule {
722
899
  rootIdentity,
723
900
  followSymlinks: mount.config.followSymlinks === true,
724
901
  maxFileSize: mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
725
- ignore: mount.config.ignore ?? [],
902
+ ignore: this.ignoreOf(mount),
903
+ ...(mount.config.include ? { include: mount.config.include } : {}),
726
904
  others: this.othersOf(mount.config.name),
727
905
  nested: this.nestedOf(mount.config.name),
728
906
  };
729
907
  }
908
+ /**
909
+ * A mount's ignore list: its config's, or, for a mount configured direct
910
+ * that names none, the direct kind's default (MountConfig.ignore), whichever
911
+ * kind it runs as this session, as its watch mode goes by its config
912
+ * (watchOf).
913
+ */
914
+ ignoreOf(mount) {
915
+ return mount.config.ignore ?? (mount.config.backend === 'direct' ? [...DIRECT_MOUNT_IGNORE] : []);
916
+ }
917
+ /**
918
+ * A direct mount as its tools read it: its view, with no root identity,
919
+ * since it promises what's at its root now and keeps no evidence to check
920
+ * that against (MountConfig.backend), and its root as realpath resolves it,
921
+ * or as given where that fails, as a pass's runtime takes it. The view
922
+ * reads beneath that root, so a walk, a listing and grep's reads judge
923
+ * and open their files beneath one root, however its configured path is
924
+ * repointed meanwhile. A read of one file goes through openContainedFile
925
+ * instead, which refuses it once its root is no longer the directory it
926
+ * checked.
927
+ */
928
+ async diskView(mount) {
929
+ const root = resolve(mount.config.path);
930
+ const rootReal = await realpath(root).catch(() => root);
931
+ const view = { ...this.viewOf(mount, undefined), root: rootReal };
932
+ const moved = await this.movedNesting(mount, rootReal);
933
+ return { view: moved === null ? view : { ...view, nested: moved, others: moved.map((n) => n.dir) }, rootReal, moved };
934
+ }
730
935
  /** The view reconciliation needs of a mount, refreshed per pass. */
731
936
  async runtime(mount) {
732
937
  const root = resolve(mount.config.path);
@@ -746,7 +951,7 @@ export class WorkspaceModule {
746
951
  intents: this.intents.get(mount.config.name),
747
952
  readOnly: mount.config.mode === 'read-only',
748
953
  walkCap: mount.config.walkCap ?? WALK_CAP,
749
- catchUpScan: (mount.config.watch ?? 'always') === 'always',
954
+ catchUpScan: watchOf(mount.config) === 'always',
750
955
  modesObserved: this.modesObserved,
751
956
  };
752
957
  }
@@ -759,16 +964,19 @@ export class WorkspaceModule {
759
964
  * under that spelling beside their own. So the start stops before a segment
760
965
  * spelled any other way, not there, or not a directory, and before a link,
761
966
  * which a walk of the whole mount doesn't go through either. It lists only
762
- * directories it has checked lie inside the mount, and none the mount
763
- * passes over by design, which the walk then answers for.
967
+ * directories it has checked lie inside the mount, and, on a 'chronicle'
968
+ * mount, none it passes over by design, which the walk then answers for.
969
+ * A direct mount walks a path its tools name whatever its ignore list or
970
+ * an editor's file name covers there (MountConfig.ignore), so there it
971
+ * lists such directories too, and only another mount's it doesn't.
764
972
  */
765
973
  async walkStart(mount, base, beneath) {
766
974
  if (beneath === '')
767
975
  return base;
768
- const { view, rootReal } = await this.runtime(mount);
976
+ const { view, rootReal } = mount.direct ? await this.diskView(mount) : await this.runtime(mount);
769
977
  let start = base;
770
978
  for (const segment of beneath.split('/')) {
771
- if (start !== '' && passedOverAt(start, view.ignore, view.others) !== undefined)
979
+ if (start !== '' && (mount.direct ? inOtherMount(start, view.others) : passedOverAt(start, view.ignore, view.others) !== undefined))
772
980
  break;
773
981
  const here = await checkDir(view, rootReal, start);
774
982
  if (here.kind !== 'checked')
@@ -804,10 +1012,25 @@ export class WorkspaceModule {
804
1012
  /** One store→disk push; the caller holds the mount's turn. */
805
1013
  async pushUnlocked(mount, paths, opts = {}) {
806
1014
  const watcher = this.watchers.get(mount.config.name);
807
- return pushPaths(this.getStore(), this.agreementOrThrow(), await this.runtime(mount), paths, {
1015
+ // A path outside the mount's include never reaches disk, even when the
1016
+ // workspace's history holds it from before the include. It's skipped,
1017
+ // and a materialize counts it, with the reason.
1018
+ const inside = [];
1019
+ const outside = [];
1020
+ for (const p of paths) {
1021
+ // A key no spelling names, such as an earlier version's `a//b.txt`,
1022
+ // isn't the mount's either, and isn't the include's to report.
1023
+ if (!parsedSpelling(p))
1024
+ continue;
1025
+ (insideMount(p, mount.config.include) ? inside : outside).push(p);
1026
+ }
1027
+ const pushed = await pushPaths(this.getStore(), this.agreementOrThrow(), await this.runtime(mount), inside, {
808
1028
  ...opts,
809
1029
  beforeEffect: (p) => watcher?.suppress(p),
810
1030
  });
1031
+ for (const path of outside)
1032
+ pushed.skipped.push({ path, reason: OUTSIDE_INCLUDE });
1033
+ return pushed;
811
1034
  }
812
1035
  async start(ctx) {
813
1036
  // Which mounts are nested where, with the roots placed where disk has
@@ -817,7 +1040,7 @@ export class WorkspaceModule {
817
1040
  // before they're known. A stop begun meanwhile stands, and this start then
818
1041
  // sets nothing.
819
1042
  const stops = this.stopsBegun;
820
- const { nesting, reals } = await this.readNesting();
1043
+ const { nesting, reals, above } = await this.readNesting();
821
1044
  const rootFoldsCase = new Map();
822
1045
  for (const mount of this.config.mounts)
823
1046
  rootFoldsCase.set(mount.name, await foldsCase(reals.get(mount.name)));
@@ -825,6 +1048,8 @@ export class WorkspaceModule {
825
1048
  return;
826
1049
  this.otherMounts = nesting;
827
1050
  this.rootFoldsCase = rootFoldsCase;
1051
+ this.placedRoots = reals;
1052
+ this.placedAbove = above;
828
1053
  this.ctx = ctx;
829
1054
  this.stopped = false;
830
1055
  // Decode persisted state if restarting; application waits until mounts
@@ -953,16 +1178,20 @@ export class WorkspaceModule {
953
1178
  /**
954
1179
  * Start chokidar watchers and emit workspace:mounted events.
955
1180
  * Idempotent: safe to call from both start() and initStore(), fires once
956
- * per mount regardless of which runs second.
1181
+ * per mount regardless of which runs second. Once both have run, it
1182
+ * decides again which mounts configured direct run direct, now that the
1183
+ * mounts' nesting is known, and says which don't, once for this start.
957
1184
  */
958
1185
  ensureRunning() {
959
1186
  if (!this.ctx || this.mounts.size === 0)
960
1187
  return;
1188
+ this.chooseKinds();
1189
+ if (this.notDirect.size > 0)
1190
+ this.sayNotDirect();
961
1191
  for (const [name, mount] of this.mounts) {
962
1192
  if (this.watchers.has(name))
963
1193
  continue;
964
- const watchMode = mount.config.watch ?? 'always';
965
- if (watchMode === 'always') {
1194
+ if (watchOf(mount.config) === 'always') {
966
1195
  // Chokidar is started with ignoreInitial:true, so changes made while
967
1196
  // the session was down would be invisible. A catch-up pass takes them
968
1197
  // in under the three-way rule: only real differences produce tree
@@ -1042,6 +1271,50 @@ export class WorkspaceModule {
1042
1271
  });
1043
1272
  }
1044
1273
  }
1274
+ /**
1275
+ * Say, for whoever runs the host, which mounts configured direct run as
1276
+ * 'chronicle' this session (chooseKinds), what the workspace holds there
1277
+ * that keeps them so, and the two ways to start one direct: on stderr,
1278
+ * and as one ops alert for them all (the framework's failures log, its
1279
+ * `ops:alert` trace and, where one is set, its webhook, which posts one
1280
+ * alert of a kind per cooldown and keeps only the start and end of a long
1281
+ * one). So the words of fixed length, what's happening and the ways out,
1282
+ * come first, and the mounts and what they hold after them.
1283
+ */
1284
+ sayNotDirect() {
1285
+ const mounts = [...this.notDirect];
1286
+ const one = mounts.length === 1;
1287
+ // An intent the workspace can't read may hold a change or may not, so
1288
+ // it's counted as what it is.
1289
+ const counted = (paths) => {
1290
+ const u = paths.filter((h) => h.what === UNREADABLE_INTENT).length;
1291
+ const c = paths.length - u;
1292
+ return [
1293
+ c > 0 ? `${c} change${c === 1 ? '' : 's'} that disk lacks` : '',
1294
+ u > 0 ? `${u} intent${u === 1 ? '' : 's'} it can't read` : '',
1295
+ ].filter((part) => part !== '').join(' and ');
1296
+ };
1297
+ const each = mounts.map(([name, paths]) => `"${name}" (${counted(paths)})`);
1298
+ const which = one
1299
+ ? `Mount "${mounts[0][0]}" holds ${counted(mounts[0][1])}`
1300
+ : `Mounts ${each.slice(0, -1).join(', ')} and ${each[each.length - 1]} hold`;
1301
+ const held = mounts.flatMap(([name, paths]) => paths.map((h) => `"${name}/${h.path}" (${h.what})`));
1302
+ // Materialize settles an intent the workspace can't read only where the
1303
+ // workspace holds a copy there, and says nothing of one it doesn't, so
1304
+ // the ways out say what does wherever one is held, past the ten paths
1305
+ // named too.
1306
+ const intents = mounts.some(([, paths]) => paths.some((h) => h.what === UNREADABLE_INTENT))
1307
+ ? "Sync the path of an intent it can't read. "
1308
+ : '';
1309
+ const message = (one
1310
+ ? "A mount configured direct runs as 'chronicle' this session. To start it direct, settle each held change, then start it again: "
1311
+ : "Mounts configured direct run as 'chronicle' this session. To start a mount direct, settle each change held at it, then start it again: ") +
1312
+ "sync its path to take disk's copy, or configure the mount 'chronicle' and read-write, materialize it, " +
1313
+ `follow the answer, and restore its direct config. ${intents}${which}: ${held.slice(0, 10).join(', ')}` +
1314
+ `${held.length > 10 ? `, and ${held.length - 10} more` : ''}.`;
1315
+ console.warn(`[workspace] ${message}`);
1316
+ this.ctx?.notifyOps?.('workspace-mount-not-direct', 'framework', message, { held: Object.fromEntries(mounts.map(([name, paths]) => [name, paths.length])) });
1317
+ }
1045
1318
  async initialScan(mountName) {
1046
1319
  const store = this.store;
1047
1320
  const mount = this.mounts.get(mountName);
@@ -1108,18 +1381,34 @@ export class WorkspaceModule {
1108
1381
  }
1109
1382
  this.ctx = null;
1110
1383
  }
1111
- /** Mount names + modes, for peer callers (framework spill/journal paths)
1112
- * that need a writable mount without reaching into private state. */
1384
+ /** Mount names + modes, and each mount's include where it sets one, for
1385
+ * peer callers (framework spill/journal paths) that need a mount for files
1386
+ * of their own, the first writable one without an include
1387
+ * (firstWritableMountName), without reaching into private state. */
1113
1388
  getMounts() {
1114
1389
  return [...this.mounts.values()].map((m) => ({
1115
1390
  name: m.config.name,
1116
1391
  mode: m.config.mode === 'read-only' ? 'read-only' : 'read-write',
1392
+ ...(m.config.include ? { include: [...m.config.include] } : {}),
1117
1393
  }));
1118
1394
  }
1119
1395
  // ==========================================================================
1120
1396
  // Tool Definitions
1121
1397
  // ==========================================================================
1122
1398
  getTools() {
1399
+ // Where a mount runs direct, four descriptions say what that changes.
1400
+ // A host with none keeps them as they were, and its residents' caches.
1401
+ const direct = [...this.mounts.values()].some((m) => m.direct);
1402
+ const lsDirect = direct
1403
+ ? ' A direct mount (ls without a path says which, with its ignore list) lists disk\'s files as they are now: each with '
1404
+ + 'its size and no state, or a note where the mount doesn\'t take it. A path its ignore list covers is listed when you name it.'
1405
+ : '';
1406
+ const grepDirect = direct
1407
+ ? ' On a direct mount, grep searches disk\'s files as they are now (version disk), and lists as skipped, with why, '
1408
+ + 'those it doesn\'t: binary, over the size limit, or not read, such as a link the mount doesn\'t follow.'
1409
+ : '';
1410
+ const globDirect = direct ? ' On a direct mount, a match carries its size, or a note where the mount doesn\'t take it, and no state.' : '';
1411
+ const syncDirect = direct ? ' A direct mount is listed under `skipped`: its tools read disk as it is, so there\'s nothing to take in.' : '';
1123
1412
  return [
1124
1413
  {
1125
1414
  name: 'read',
@@ -1165,18 +1454,62 @@ export class WorkspaceModule {
1165
1454
  },
1166
1455
  {
1167
1456
  name: 'edit',
1168
- description: 'Edit a file by replacing a substring. The oldString must be unique unless replaceAll is true.',
1457
+ description: 'Edit a file by replacing exact text. oldString must occur exactly once, or with replaceAll at least once, '
1458
+ + "and every occurrence is replaced; occurrences that overlap count, but can't each be replaced. "
1459
+ + 'A miss shows the closest region it finds, numbered, and a count that differs shows the lines that matched. '
1460
+ + 'CRLF line ends are matched with LF text and kept, as is a BOM. As second chances, straight and curly quotes match as equal, '
1461
+ + "and an oldString carrying the file's BOM at its start or a line's CR at its end, as a character page shows them, matches without them, "
1462
+ + 'its newString read the same way. '
1463
+ + "Only the replaced text changes, and the new text's line ends take those of the text it replaces. "
1464
+ + 'A change disk made to the file is taken in first, and the answer says so. '
1465
+ + 'The answer shows the changed region, numbered, a long line from shortly before the change on it, as its length allows. '
1466
+ + 'For several edits at once, in one file or across files, applied all or none, use edit_many.',
1169
1467
  inputSchema: {
1170
1468
  type: 'object',
1171
1469
  properties: {
1172
1470
  path: { type: 'string', description: 'File path (mount-prefixed)' },
1173
- oldString: { type: 'string', description: 'String to find' },
1174
- newString: { type: 'string', description: 'Replacement string' },
1175
- replaceAll: { type: 'boolean', description: 'Replace all occurrences (default: false)' },
1471
+ oldString: { type: 'string', description: 'Exact text to replace, including whitespace and indentation' },
1472
+ newString: { type: 'string', description: 'Replacement text' },
1473
+ replaceAll: { type: 'boolean', description: 'Replace every occurrence (default: false)' },
1176
1474
  },
1177
1475
  required: ['path', 'oldString', 'newString'],
1178
1476
  },
1179
1477
  },
1478
+ {
1479
+ name: 'edit_many',
1480
+ description: 'Apply several exact edits at once, in one file or across files of one mount, all or none: no edit is stored unless every edit applies. '
1481
+ + "Each edit's oldString must occur in its file exactly `occurrences` times (1 when left out), and every one is replaced; "
1482
+ + "occurrences that overlap count, but can't each be replaced. "
1483
+ + "Each edit is matched in its file as this call reads it, never in another edit's result, so the list's order doesn't matter, "
1484
+ + "and two edits' matches may touch but not overlap. Matching is edit's. "
1485
+ + "A refusal names the problems it finds, each by its edit's number in the list (from 1). "
1486
+ + 'All or none holds in the workspace: on a mount that writes to disk, disk can still refuse a file, '
1487
+ + "and the answer then says every edit is stored and names each file disk refused, with its push's reason. "
1488
+ + "The answer shows each edit's first changed region, numbered, a long line from shortly before each change on it, as its length allows.",
1489
+ inputSchema: {
1490
+ type: 'object',
1491
+ properties: {
1492
+ edits: {
1493
+ type: 'array',
1494
+ description: "The edits, each matched in its file as this call reads it, never in another edit's result",
1495
+ items: {
1496
+ type: 'object',
1497
+ properties: {
1498
+ path: { type: 'string', description: 'File path (mount-prefixed); every edit names a file of the same mount' },
1499
+ oldString: { type: 'string', description: 'Exact text to replace, as the file holds it before this call' },
1500
+ newString: { type: 'string', description: 'Replacement text' },
1501
+ occurrences: {
1502
+ type: 'integer',
1503
+ description: 'How many times oldString occurs in the file (default: 1); every one is replaced, and any other count is refused',
1504
+ },
1505
+ },
1506
+ required: ['path', 'oldString', 'newString'],
1507
+ },
1508
+ },
1509
+ },
1510
+ required: ['edits'],
1511
+ },
1512
+ },
1180
1513
  {
1181
1514
  name: 'delete',
1182
1515
  description: 'Delete a file from the workspace. On a mount without autoMaterialize the disk copy stays, '
@@ -1200,18 +1533,18 @@ export class WorkspaceModule {
1200
1533
  + 'interrupted) — sync the path to take disk, or materialize that path with force to take the workspace, '
1201
1534
  + 'with applyDeletions too where the workspace deleted it; '
1202
1535
  + 'disk-missing-provenance-unknown; unverified (disk could not be checked). `incomplete` names regions '
1203
- + 'the listing could not see.',
1536
+ + 'the listing could not see.' + lsDirect,
1204
1537
  inputSchema: {
1205
1538
  type: 'object',
1206
1539
  properties: {
1207
- path: { type: 'string', description: 'Directory path (mount-prefixed, optional)' },
1540
+ path: { type: 'string', description: 'Directory path (mount-prefixed, optional; without it, the mounts are listed, each with its include where it has one)' },
1208
1541
  recursive: { type: 'boolean', description: 'List recursively (default: false)' },
1209
1542
  },
1210
1543
  },
1211
1544
  },
1212
1545
  {
1213
1546
  name: 'glob',
1214
- description: 'Find files matching a glob pattern, checked against disk first; each match carries its state, as ls describes.',
1547
+ description: 'Find files matching a glob pattern, checked against disk first; each match carries its state, as ls describes.' + globDirect,
1215
1548
  inputSchema: {
1216
1549
  type: 'object',
1217
1550
  properties: {
@@ -1227,7 +1560,7 @@ export class WorkspaceModule {
1227
1560
  + 'which version matched: the workspace\'s (with its state); the disk version kept with a conflict '
1228
1561
  + '(conflicting-disk); or, once disk has changed since the conflict was recorded, that recorded version '
1229
1562
  + '(recorded-disk). Disk versions it could not search are listed as skipped: disk-only files (binary or '
1230
- + 'over the size limit), and a conflict\'s disk version that is binary, oversize, or newer than the one recorded.',
1563
+ + 'over the size limit), and a conflict\'s disk version that is binary, oversize, or newer than the one recorded.' + grepDirect,
1231
1564
  inputSchema: {
1232
1565
  type: 'object',
1233
1566
  properties: {
@@ -1253,7 +1586,9 @@ export class WorkspaceModule {
1253
1586
  {
1254
1587
  name: 'materialize',
1255
1588
  description: 'Write workspace files to the real filesystem. Use after writing/editing to push changes to disk. '
1256
- + 'Never deletes disk files unless applyDeletions is given; lists workspace deletions it left on disk.',
1589
+ + 'Never deletes disk files unless applyDeletions is given; lists workspace deletions it left on disk. '
1590
+ + 'On a mount with an include, what the include doesn\'t cover is never written, and one naming a '
1591
+ + 'directory counts what it left beneath it under `passedOver`, by mount and reason, without naming it.',
1257
1592
  inputSchema: {
1258
1593
  type: 'object',
1259
1594
  properties: {
@@ -1285,15 +1620,17 @@ export class WorkspaceModule {
1285
1620
  + 'reported nowhere else is counted under `passedOver`, by mount and reason: another mount\'s '
1286
1621
  + 'directory nested in this one, entries the mount\'s ignore list covers, and entries with an '
1287
1622
  + 'editor\'s swap or backup file name (`.name.swp` and `.name.swx` as the whole name, names ending '
1288
- + 'in `~` or in `.subl…tmp`), that hold nothing the workspace tracks (such a directory counts once, '
1289
- + 'with what lies beneath it). So a '
1623
+ + 'in `~` or in `.subl…tmp`), each holding nothing the workspace tracks (such a directory counts '
1624
+ + 'once, with what lies beneath it); and files and links outside the mount\'s include, a link '
1625
+ + 'counted as "a symlink, not walked" instead where it leads to a directory on a mount that follows '
1626
+ + 'symlinks, and wherever it leads on one that doesn\'t. So a '
1290
1627
  + 'total of 0, with no conflicts and nothing under `passedOver`, `incomplete` or `skipped`, means the '
1291
1628
  + 'sync looked everywhere and nothing had changed. A path the mount ignores, or an editor\'s file, is '
1292
1629
  + 'synced when you name it, and listed under `ignored`: a sync without a path passes over it. A path '
1293
1630
  + 'in another mount\'s directory isn\'t synced even when you name it: use the mount that holds it. Naming '
1294
1631
  + 'an ignored directory sets aside the patterns that cover it or a directory above it; one that '
1295
1632
  + 'covers only something inside it still applies, and what it covers is passed over, as are editors\' '
1296
- + 'files inside it.',
1633
+ + 'files inside it.' + syncDirect,
1297
1634
  inputSchema: {
1298
1635
  type: 'object',
1299
1636
  properties: {
@@ -1324,7 +1661,7 @@ export class WorkspaceModule {
1324
1661
  const mount = this.config.mounts.find(m => m.name === mountName);
1325
1662
  if (!mount)
1326
1663
  throw new Error(`Unknown mount: "${mountName}"`);
1327
- // Against the resolved root, as parsePath judges it.
1664
+ // Against the resolved root, as parsePathAsGiven's traversal guard judges it.
1328
1665
  const root = resolve(mount.path);
1329
1666
  const resolved = resolve(root, slash < 0 ? '' : path.slice(slash + 1));
1330
1667
  if (!isContainedPath(root, resolved))
@@ -1381,17 +1718,17 @@ export class WorkspaceModule {
1381
1718
  const input = call.input;
1382
1719
  const generated = typeof input?.path === 'string' ? this.findGeneratedTextFile(input.path) : undefined;
1383
1720
  if (generated) {
1384
- if (call.callerAgentName !== generated.agentName)
1385
- return { success: false, isError: true, error: 'Generated file belongs to another agent' };
1386
- if (call.name !== 'read')
1387
- return { success: false, isError: true, error: 'Generated file is read-only; edit the presentation configuration instead' };
1388
- return await this.handleRead(input, generated.read());
1721
+ if (call.name === 'read' && call.callerAgentName === generated.agentName) {
1722
+ return await this.handleRead(input, generated.read());
1723
+ }
1724
+ return { success: false, isError: true, error: this.generatedFileRefusal(generated, call.callerAgentName) };
1389
1725
  }
1390
1726
  switch (call.name) {
1391
1727
  case 'read': return await this.handleRead(input);
1392
1728
  case 'read_image': return await this.handleReadImage(input);
1393
1729
  case 'write': return await this.handleWrite(input);
1394
- case 'edit': return await this.handleEdit(input);
1730
+ case 'edit': return await this.handleEdit(input, call.resultMaxChars);
1731
+ case 'edit_many': return await this.handleEditMany(input, call.resultMaxChars, call.callerAgentName);
1395
1732
  case 'delete': return await this.handleDelete(input);
1396
1733
  case 'ls': return await this.handleLs(input);
1397
1734
  case 'glob': return await this.handleGlob(input);
@@ -1400,7 +1737,7 @@ export class WorkspaceModule {
1400
1737
  case 'materialize': return await this.handleMaterialize(input);
1401
1738
  case 'sync': return await this.handleSync(input);
1402
1739
  default:
1403
- return { success: false, error: `Unknown tool: ${call.name}`, isError: true };
1740
+ return { success: false, error: `Unknown tool: ${call.name}, so nothing was done`, isError: true };
1404
1741
  }
1405
1742
  }
1406
1743
  catch (err) {
@@ -1478,8 +1815,11 @@ export class WorkspaceModule {
1478
1815
  // ==========================================================================
1479
1816
  /**
1480
1817
  * Resolve a mount-prefixed path (e.g. "tickets/2026-04-22-foo.md") to its
1481
- * absolute filesystem path. Returns null if the mount is unknown or the
1482
- * resolved path escapes the mount root.
1818
+ * absolute filesystem path. Returns null if the mount is unknown or
1819
+ * doesn't hold the path: one that leaves the mount's directory, lies in
1820
+ * another mount's directory nested in it, or falls outside its include, or
1821
+ * one that can't name a file of it, with a separator right after the
1822
+ * mount's name or a lone UTF-16 surrogate.
1483
1823
  *
1484
1824
  * **Lexical containment only.** The guard reasons about `..` segments in the
1485
1825
  * path string; it knows nothing about what is on disk. A symlink inside the
@@ -1488,15 +1828,26 @@ export class WorkspaceModule {
1488
1828
  * path for resolution-only purposes (write targets, nonexistent paths,
1489
1829
  * display); for reading file content, use {@link readFileFromDisk}, which
1490
1830
  * enforces the mount's `followSymlinks` policy and canonical containment.
1831
+ * It judges other mounts' directories by where the last start placed them,
1832
+ * so for a direct mount whose root has moved since, it can differ from
1833
+ * `readFileFromDisk`, which takes the nesting where the root lies now
1834
+ * (movedNesting), about which paths lie in another mount's directory.
1491
1835
  *
1492
1836
  * @deprecated for direct filesystem reads — call `readFileFromDisk()`.
1493
1837
  */
1494
1838
  resolveAbsolutePath(mountPrefixedPath) {
1495
1839
  try {
1496
- // Synchronous, so the path as given: it reaches the same file, and
1497
- // the nested-mount check matches it as configured or as disk spells
1498
- // the nested mount's directory (readNesting).
1499
- const { mount, relativePath } = this.refuseNested({ ...this.parsePathAsGiven(mountPrefixedPath), path: mountPrefixedPath });
1840
+ // Synchronous, so the path as given. The nested-mount check takes it
1841
+ // in each spelling readNesting knows for the nested mount's directory,
1842
+ // or in any spelling a disk that folds names may fold to one of them,
1843
+ // erring toward that mount (holderOf's asGiven, beginsWithDir). The
1844
+ // include judges it as given, so on a disk that
1845
+ // folds names a covered name whose file disk spells otherwise returns
1846
+ // that file's path, which the tools refuse, and a covered file named in
1847
+ // another case is null, which the tools read. A path the mount doesn't
1848
+ // hold, outside its include or in another mount's directory nested in
1849
+ // it, is null, as for a path that leaves the mount's directory.
1850
+ const { mount, relativePath } = this.refuseNotHeld({ ...this.parsePathAsGiven(mountPrefixedPath), path: mountPrefixedPath }, mountPrefixedPath, true);
1500
1851
  return resolve(mount.config.path, relativePath);
1501
1852
  }
1502
1853
  catch {
@@ -1519,10 +1870,13 @@ export class WorkspaceModule {
1519
1870
  * (agent-framework #277).
1520
1871
  *
1521
1872
  * A write whose tree entry is set but that then fails returns success
1522
- * false with `data: { inChronicle: true }`: its copy on disk was refused, or
1523
- * something after the entry (recording its intent, the event, the push)
1524
- * threw. The workspace's tools read the file from the tree, so it is there
1525
- * for them, on the branch that was current when the entry was set.
1873
+ * false with `data: { inChronicle: true }`: its copy on disk was refused,
1874
+ * the store failed after recording the entry, which skips the push where
1875
+ * the mount pushes, or something after the entry (recording its intent,
1876
+ * the event, the push) threw. The workspace's tools read the file from the
1877
+ * tree, so it is there for them, on the branch that was current when the
1878
+ * entry was set. A set that threw and couldn't be read back throws, saying
1879
+ * that whether the entry is set isn't known.
1526
1880
  */
1527
1881
  async writeBinary(mountPrefixedPath, data, mimeType, options = {}) {
1528
1882
  if (!this.running())
@@ -1572,7 +1926,12 @@ export class WorkspaceModule {
1572
1926
  catch (error) {
1573
1927
  if (!committed)
1574
1928
  throw error;
1575
- failure = `Stored "${mountPrefixedPath}" in Chronicle, but the rest of the write failed: ${error instanceof Error ? error.message : String(error)}.`;
1929
+ // As write words it: a store that failed after recording the file
1930
+ // skipped its push, so on a mount that pushes, disk lacks it.
1931
+ failure = error instanceof StoredThenFailed
1932
+ ? `Stored "${mountPrefixedPath}" in Chronicle, but the store failed after recording it: ${error.message}.`
1933
+ + (error.pushes ? " Its push to disk didn't run, so disk lacks the change until a materialize of the path writes it." : '')
1934
+ : `Stored "${mountPrefixedPath}" in Chronicle, but the rest of the write failed: ${error instanceof Error ? error.message : String(error)}.`;
1576
1935
  }
1577
1936
  if (failure !== null) {
1578
1937
  // The file is in the Chronicle tree, where the workspace's tools read
@@ -1588,8 +1947,10 @@ export class WorkspaceModule {
1588
1947
  }
1589
1948
  /**
1590
1949
  * Read a file's raw bytes from a mount (through the Chronicle tree, synced
1591
- * first like the `read` tool). Public API for the framework's synthesized
1592
- * `read_image` tool and other peer callers that need binary content.
1950
+ * first like the `read` tool; on a direct mount, from disk as
1951
+ * readBinaryFromDisk reads it, at most the mount's `maxFileSize`). Public
1952
+ * API for the framework's synthesized `read_image` tool and other peer
1953
+ * callers that need binary content.
1593
1954
  */
1594
1955
  async readBinary(mountPrefixedPath) {
1595
1956
  if (!this.running())
@@ -1605,6 +1966,9 @@ export class WorkspaceModule {
1605
1966
  catch (error) {
1606
1967
  return { error: error instanceof Error ? error.message : String(error) };
1607
1968
  }
1969
+ // A direct mount's bytes are disk's, as read takes them, at most its size limit.
1970
+ if (mount.direct)
1971
+ return this.bytesFromDisk(mount, relativePath, mountPrefixedPath, mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE);
1608
1972
  const store = this.getStore();
1609
1973
  return this.withMount(mount, async () => {
1610
1974
  await this.ensureSynced(mount, relativePath);
@@ -1649,8 +2013,11 @@ export class WorkspaceModule {
1649
2013
  catch (error) {
1650
2014
  return { error: error instanceof Error ? error.message : String(error) };
1651
2015
  }
1652
- const absolutePath = resolve(mount.config.path, relativePath);
1653
- const maxBytes = opts.maxBytes;
2016
+ const read = await this.bytesFromDisk(mount, relativePath, mountPrefixedPath, opts.maxBytes);
2017
+ return 'error' in read ? read : { data: read.data, absolutePath: resolve(mount.config.path, relativePath) };
2018
+ }
2019
+ /** A file's bytes as readBinaryFromDisk reads them, once its path is parsed. */
2020
+ async bytesFromDisk(mount, relativePath, mountPrefixedPath, maxBytes) {
1654
2021
  let tooLarge;
1655
2022
  try {
1656
2023
  const { handle, fileStat } = await this.openContainedFile(mount, relativePath, mountPrefixedPath, (fileStat) => {
@@ -1661,7 +2028,7 @@ export class WorkspaceModule {
1661
2028
  });
1662
2029
  try {
1663
2030
  if (maxBytes === undefined)
1664
- return { data: await handle.readFile(), absolutePath };
2031
+ return { data: await handle.readFile() };
1665
2032
  // No more than maxBytes is loaded: a file grown past it since the
1666
2033
  // fstat above is refused here, as one already over it was there. Its
1667
2034
  // size is an fstat's after the read, and at least one more than the
@@ -1669,7 +2036,7 @@ export class WorkspaceModule {
1669
2036
  const { bytes, more } = await readPrefix(handle, maxBytes, fileStat.size);
1670
2037
  if (more)
1671
2038
  return { error: `File too large: ${Math.max((await handle.stat()).size, bytes.length + 1)} > ${maxBytes} bytes` };
1672
- return { data: bytes, absolutePath };
2039
+ return { data: bytes };
1673
2040
  }
1674
2041
  finally {
1675
2042
  await handle.close();
@@ -1713,7 +2080,9 @@ export class WorkspaceModule {
1713
2080
  * as configured still names it as configured (resolveAbsolutePath). A
1714
2081
  * directory not on disk keeps the spellings the roots give alone. Each
1715
2082
  * mount's real root comes back beside the nesting (`reals`), for what
1716
- * start reads there.
2083
+ * start reads there, and each directory above each configured path with
2084
+ * where it lies on disk (`above`), for a direct mount whose root moves
2085
+ * (movedNesting).
1717
2086
  */
1718
2087
  async readNesting() {
1719
2088
  const reals = new Map();
@@ -1725,11 +2094,8 @@ export class WorkspaceModule {
1725
2094
  const given = resolve(mount.path);
1726
2095
  reals.set(mount.name, await realBeneath(given));
1727
2096
  const dirs = [];
1728
- for (let dir = dirname(given);; dir = dirname(dir)) {
2097
+ for (const dir of ancestorsOf(given))
1729
2098
  dirs.push({ dir, real: await realBeneath(dir) });
1730
- if (dirname(dir) === dir)
1731
- break;
1732
- }
1733
2099
  above.set(mount.name, dirs);
1734
2100
  }
1735
2101
  const nesting = new Map();
@@ -1740,26 +2106,10 @@ export class WorkspaceModule {
1740
2106
  if (outer === inner)
1741
2107
  continue;
1742
2108
  const real = reals.get(inner.name);
1743
- const innerPath = resolve(inner.path);
1744
- const configured = nestedDir(outerPath, innerPath);
1745
- const fromRoots = [];
1746
- // Its directory as configured, read against this mount's root as
1747
- // configured and from each directory above it that is this mount's
1748
- // root on disk, and its real root against this mount's.
1749
- const throughRoot = above.get(inner.name).filter((a) => a.real === outerReal).map((a) => nestedDir(a.dir, innerPath));
1750
- for (const dir of [configured, ...throughRoot, nestedDir(outerReal, real)]) {
1751
- if (dir !== undefined && !fromRoots.some((s) => s.dir === dir))
1752
- fromRoots.push({ dir, root: join(outerPath, ...dir.split('/')) });
1753
- }
1754
- if (fromRoots.length === 0)
2109
+ const at = await placementOf(outerPath, outerReal, resolve(inner.path), real, above.get(inner.name), outerPath);
2110
+ if (at === undefined)
1755
2111
  continue;
1756
- const spellings = [...fromRoots];
1757
- for (const found of fromRoots) {
1758
- const dir = await diskSpelling(outerPath, found.dir);
1759
- if (!spellings.some((s) => s.dir === dir))
1760
- spellings.push({ dir, root: join(outerPath, ...dir.split('/')) });
1761
- }
1762
- const claims = !isContainedPath(real, outerReal);
2112
+ const { configured, fromRoots, spellings, claims } = at;
1763
2113
  nesting.set(outer.name, [...(nesting.get(outer.name) ?? []), { name: inner.name, ...(claims ? { real } : {}), fromRoots, spellings }]);
1764
2114
  const placed = fromRoots.filter((s) => s.dir !== configured);
1765
2115
  if (placed.length > 0) {
@@ -1768,30 +2118,156 @@ export class WorkspaceModule {
1768
2118
  }
1769
2119
  }
1770
2120
  }
1771
- return { nesting, reals };
2121
+ return { nesting, reals, above };
1772
2122
  }
1773
- /** The mounts nested in `mountName`, by directory, name and real root where it has one (MountView's `nested`), in each spelling known. */
2123
+ /**
2124
+ * The mounts nested in `mountName`, by directory, name, real root where it
2125
+ * has one, and include (MountView's `nested`), in each spelling known.
2126
+ */
1774
2127
  nestedOf(mountName) {
1775
- return (this.otherMounts.get(mountName) ?? []).flatMap((o) => o.spellings.map((s) => ({ dir: s.dir, name: o.name, real: o.real })));
2128
+ return (this.otherMounts.get(mountName) ?? []).flatMap((o) => o.spellings.map((s) => ({ dir: s.dir, name: o.name, real: o.real, include: this.mounts.get(o.name)?.config.include })));
2129
+ }
2130
+ /**
2131
+ * The mounts nested in `mount` as a call of it that resolved its root to
2132
+ * `rootReal` sees them: movedNesting where that differs from where the
2133
+ * last start placed it, the start's placement (nestedOf) otherwise.
2134
+ */
2135
+ async nestedFor(mount, rootReal) {
2136
+ return (await this.movedNesting(mount, rootReal)) ?? this.nestedOf(mount.config.name);
2137
+ }
2138
+ /**
2139
+ * The mounts nested in a direct mount whose root a check resolved to
2140
+ * `rootReal`, where that's elsewhere than the last start placed it, as when
2141
+ * a link it's configured through is repointed; null where the start's
2142
+ * placement holds, or where nothing is at `rootReal`: there the parse's
2143
+ * checks keep the start's placement, and a read says the root is gone. A
2144
+ * direct mount reads beneath whatever directory is at its root, so a check
2145
+ * judges which mount a path is by the root it resolved. A tool's parse
2146
+ * resolves it once, and its respelling and its checks of the path it's
2147
+ * given (parseFilePath's, refusesAsOutside, grep's) read disk beneath that
2148
+ * root and judge by the nesting there. A read and a walk each resolve it
2149
+ * for themselves, and judge the include and the nesting again beneath it.
2150
+ * So a root repointed during a call can change which answer or refusal a
2151
+ * path gets, but nothing a read or a walk serves is a file the include
2152
+ * leaves out, nothing a walk serves lies in another mount's directory as
2153
+ * its own nesting places it, and nothing a read serves lies in the
2154
+ * directory of a mount its own nesting claims by real root. Whoever writes
2155
+ * the disk can race a read in two ways, as a rename during a call can on
2156
+ * any mount. On a disk that folds names, a read judges the include by the
2157
+ * path as its parse spelled it, so a root repointed between the two can
2158
+ * have it serve a file the new root spells otherwise (sameLevels). And a
2159
+ * mount nested by its directories alone, since its real root holds this
2160
+ * one, is judged by the parse's nesting, so a root repointed between a
2161
+ * read's parse and its open can have it serve a path in that mount's
2162
+ * directory. Each mount is placed as a start places it (placementOf), from
2163
+ * where its real root and the directories above its configured path lie on
2164
+ * disk. For a mount configured at this mount's own path or beneath it,
2165
+ * that's where they lie now: beneath `rootReal` where they lie beneath this
2166
+ * mount's path, and the directories above this mount's path as resolving
2167
+ * that path finds them. For any other mount, it's where the last start
2168
+ * found them. Each carries its own include, as nestedOf gives it. It
2169
+ * resolves nothing but the directories on this mount's own configured path
2170
+ * and those beneath its root, so a share elsewhere that doesn't answer
2171
+ * holds only its own calls, unless such a directory is a link into it,
2172
+ * where that mount's files lie. What it leaves to the next start: a mount
2173
+ * configured elsewhere whose own root has moved since, as when a link on
2174
+ * its configured path is repointed, this mount's own reached through
2175
+ * another link among them, that mount's spellings through other links, and
2176
+ * the other mounts' own placements, so a direct root moved into another
2177
+ * mount's directory is that mount's too, as a nested mount's root moved
2178
+ * while running stays placed.
2179
+ */
2180
+ async movedNesting(mount, rootReal) {
2181
+ // One start's placements, whatever a start in the meantime sets.
2182
+ const { placedRoots, placedAbove } = this;
2183
+ const placed = placedRoots.get(mount.config.name);
2184
+ if (!mount.direct || placed === undefined || placed === rootReal)
2185
+ return null;
2186
+ const there = await stat(rootReal).then(() => true, (err) => {
2187
+ const code = errnoOf(err);
2188
+ return code !== 'ENOENT' && code !== 'ENOTDIR';
2189
+ });
2190
+ if (!there)
2191
+ return null;
2192
+ const outerPath = resolve(mount.config.path);
2193
+ const nested = [];
2194
+ // The directories above this mount's own path, as they lie on disk now,
2195
+ // resolved as resolving the path itself does.
2196
+ let ownAbove;
2197
+ const aboveOwn = async () => ownAbove ??= await Promise.all(ancestorsOf(outerPath).map(async (dir) => ({ dir, real: await realBeneath(dir) })));
2198
+ for (const inner of this.config.mounts) {
2199
+ if (inner.name === mount.config.name)
2200
+ continue;
2201
+ const innerPath = resolve(inner.path);
2202
+ const configured = nestedDir(outerPath, innerPath);
2203
+ let real;
2204
+ let above;
2205
+ if (configured !== undefined || innerPath === outerPath) {
2206
+ // A mount configured on this mount's own path, or beneath it, lies
2207
+ // where that path now leads: its real root, and each directory above
2208
+ // it, resolved now, beneath this root where they lie beneath it.
2209
+ const segments = configured?.split('/') ?? [];
2210
+ real = await realBeneath(join(rootReal, ...segments));
2211
+ const beneath = [];
2212
+ for (let i = segments.length - 1; i >= 1; i--) {
2213
+ beneath.push({ dir: join(outerPath, ...segments.slice(0, i)), real: await realBeneath(join(rootReal, ...segments.slice(0, i))) });
2214
+ }
2215
+ // This mount's own path, which is the root, would add only the
2216
+ // configured directory, which placementOf adds anyway.
2217
+ above = [...beneath, ...await aboveOwn()];
2218
+ }
2219
+ else {
2220
+ // Any other mount lies where the last start found it and the
2221
+ // directories above its path. One leading here only since, as
2222
+ // through this mount's own link, waits for the next start.
2223
+ real = placedRoots.get(inner.name);
2224
+ if (real === undefined)
2225
+ continue;
2226
+ above = placedAbove.get(inner.name) ?? [];
2227
+ }
2228
+ const at = await placementOf(outerPath, rootReal, innerPath, real, above, rootReal);
2229
+ if (at === undefined)
2230
+ continue;
2231
+ const include = this.mounts.get(inner.name)?.config.include;
2232
+ for (const s of at.spellings)
2233
+ nested.push({ dir: s.dir, name: inner.name, ...(at.claims ? { real } : {}), include });
2234
+ }
2235
+ return nested;
1776
2236
  }
1777
2237
  /**
1778
2238
  * The innermost mount nested in `mountName` whose directory holds a path
1779
2239
  * of that mount, judged lexically where the path lands (`.`, `..` and
1780
2240
  * repeated separators resolved, as for the traversal guard; a link of the
1781
2241
  * outer mount isn't followed), with the path to use there; undefined when
1782
- * no nested mount's directory holds it.
2242
+ * no nested mount's directory holds it. A path parsePath has respelled is
2243
+ * compared with the directory's spellings exactly. One judged as given
2244
+ * (`asGiven`, resolveAbsolutePath's) is compared loosely, as a disk that
2245
+ * folds names may compare it (beginsWithDir), so it can't reach that
2246
+ * mount's directory by spelling a segment otherwise. On a disk that tells
2247
+ * names apart, that takes a directory of this mount's own spelled like the
2248
+ * nested one in another way as that mount's too.
1783
2249
  */
1784
- holderOf(mountName, relativePath) {
2250
+ holderOf(mountName, relativePath, asGiven = false, moved = null) {
1785
2251
  const mount = this.mounts.get(mountName);
1786
2252
  if (!mount)
1787
2253
  return undefined;
1788
- const resolved = resolve(mount.config.path, relativePath);
1789
- const holder = (this.otherMounts.get(mountName) ?? [])
1790
- .flatMap((o) => o.spellings.filter((s) => isContainedPath(s.root, resolved)).map((s) => ({ name: o.name, root: s.root })))
1791
- .sort((a, b) => b.root.length - a.root.length)[0];
2254
+ const root = resolve(mount.config.path);
2255
+ const resolved = resolve(root, relativePath);
2256
+ if (!isContainedPath(root, resolved))
2257
+ return undefined;
2258
+ const segments = resolved === root ? [] : relative(root, resolved).split(sep);
2259
+ // A direct mount whose root a call found moved is judged by that call's
2260
+ // nesting (movedNesting), each directory beneath its configured path.
2261
+ const dirs = moved !== null
2262
+ ? moved.map((n) => ({ name: n.name, dir: n.dir }))
2263
+ : (this.otherMounts.get(mountName) ?? []).flatMap((o) => o.spellings.map((s) => ({ name: o.name, dir: s.dir })));
2264
+ const holder = dirs
2265
+ .filter((s) => beginsWithDir(segments, s.dir.split('/'), asGiven))
2266
+ .map((s) => ({ name: s.name, depth: s.dir.split('/').length }))
2267
+ .sort((a, b) => b.depth - a.depth)[0];
1792
2268
  if (!holder)
1793
2269
  return undefined;
1794
- const rest = relative(holder.root, resolved).split(sep).join('/');
2270
+ const rest = segments.slice(holder.depth).join('/');
1795
2271
  return { name: holder.name, use: rest ? `${holder.name}/${rest}` : holder.name };
1796
2272
  }
1797
2273
  /**
@@ -1799,8 +2275,8 @@ export class WorkspaceModule {
1799
2275
  * mount and the path to use: for a sync or a push, which of them leaves
1800
2276
  * it; for a listing, whose the path is.
1801
2277
  */
1802
- otherMountNote(mountName, relativePath, by) {
1803
- const holder = this.holderOf(mountName, relativePath);
2278
+ otherMountNote(mountName, relativePath, by, moved = null) {
2279
+ const holder = this.holderOf(mountName, relativePath, false, moved);
1804
2280
  const what = by === 'sync' ? ', which no sync of this mount takes in' : by === 'push' ? ', which no push of this mount writes' : '';
1805
2281
  return holder
1806
2282
  ? `it lies in mount "${holder.name}", nested in this one${what}: use "${holder.use}"`
@@ -1808,77 +2284,236 @@ export class WorkspaceModule {
1808
2284
  }
1809
2285
  /**
1810
2286
  * parsePath for the file operations (read, write, edit, delete, and the
1811
- * module's binary and disk reads and writes). A path in another mount's
1812
- * directory nested in this one is that mount's: this mount's passes don't
1813
- * observe it and its pushes don't write it, so its file operations refuse
1814
- * it, naming the innermost mount that holds it and the path to use there.
2287
+ * module's binary and disk reads and writes), refused where the mount
2288
+ * doesn't hold the path. A path in another mount's directory nested in
2289
+ * this one is that mount's: this mount's passes don't observe it and its
2290
+ * pushes don't write it, so the refusal names the innermost mount that
2291
+ * holds it and the path to use there. A path the mount's include doesn't
2292
+ * cover is outside the mount, whatever disk or the workspace's history has
2293
+ * there. A directory is checked the same way, since a path can be a
2294
+ * directory on one side and a file on the other.
1815
2295
  */
1816
2296
  async parseFilePath(path) {
1817
- const parsed = this.refuseNested(await this.parsePath(path));
1818
- // A path can also reach a nested mount's directory through a symlink on
1819
- // its way. No push of this mount writes it there and no read reads it,
1820
- // so it's refused here, before anything is stored, and the checks where
1821
- // disk is acted on refuse it again.
1822
- const refusal = await this.leadsIntoNested(parsed.mount, parsed.relativePath, parsed.path);
2297
+ const spelled = await this.parsePath(path);
2298
+ // Both checks judge by the nesting the parse found, and the second reads
2299
+ // disk beneath the root the parse resolved.
2300
+ const { mount, root, moved } = spelled;
2301
+ const parsed = this.refuseNotHeld(spelled, path, false, moved);
2302
+ // A path can also reach a nested mount's directory, or a file this
2303
+ // mount's own include leaves out, through a symlink on its way. No push
2304
+ // of this mount writes it there and no read reads it, so it's refused
2305
+ // here, before anything is stored, and the checks where disk is acted on
2306
+ // refuse it again.
2307
+ const refusal = await this.landingRefusal(mount, parsed.relativePath, parsed.path, moved ?? this.nestedOf(mount.config.name), root);
1823
2308
  if (refusal)
1824
2309
  throw refusal;
1825
2310
  return parsed;
1826
2311
  }
1827
2312
  /**
1828
2313
  * The refusal for a path of `mount` that reaches a nested mount's directory
1829
- * through a symlink on its way (nestedAtReal), or null where it doesn't. On
1830
- * a mount that doesn't follow the link, the refusal is the link's own
1831
- * (linkWords), as the readers and pushes give it. A mount with nothing
1832
- * nested has nothing to find, so it pays nothing.
1833
- */
1834
- async leadsIntoNested(mount, relativePath, path) {
1835
- const nested = this.nestedOf(mount.config.name);
1836
- if (nested.length === 0)
1837
- return null;
1838
- const holder = nestedAtReal(await realBeneath(resolve(mount.config.path, relativePath)), nested);
1839
- if (!holder)
2314
+ * through a symlink on its way (nestedAtReal), or a file this mount's own
2315
+ * include leaves out (coversLanding), or, on a mount that follows links
2316
+ * with an include, one realpath can't resolve, or null where it doesn't.
2317
+ * On a mount that doesn't follow the link, the refusal is the link's own
2318
+ * (linkWords), as the readers and pushes give it. On one that does, it
2319
+ * names the nested mount only where the place is that mount's
2320
+ * (namesNestedPlace); anywhere else the place is no mount's, so the path
2321
+ * leaves this one, in the disk readers' words, as it does where it lands
2322
+ * on a file this mount's include leaves out. A mount with nothing nested,
2323
+ * and without both an include and links followed, has nothing to find, so
2324
+ * it pays nothing. The caller gives the nesting and the root to judge by
2325
+ * (`nested`, `root`). A direct mount's file operation gives those its
2326
+ * parse found, so where the path lands, and any link on its way, is judged
2327
+ * beneath the root that parse resolved; any other caller gives the start's
2328
+ * nesting and the configured path.
2329
+ */
2330
+ async landingRefusal(mount, relativePath, path, nested, root) {
2331
+ const judged = mount.config.followSymlinks === true && mount.config.include !== undefined;
2332
+ if (nested.length === 0 && !judged)
1840
2333
  return null;
2334
+ const unresolved = {};
2335
+ const real = await realBeneath(resolve(root, relativePath), 0, unresolved);
2336
+ // Where realpath can't resolve the path, as for a loop or a directory
2337
+ // this process can't search, where it lands can't be judged, and a
2338
+ // promise about content fails closed: the path is refused, by every file
2339
+ // operation, in the words a disk read gives a path it can't resolve,
2340
+ // whatever the place realpath stopped short of would say.
2341
+ if (judged && unresolved.code !== undefined)
2342
+ return new WorkspaceReadError('not_found', `Unable to resolve file: ${path}`, 'realpath', unresolved.code);
2343
+ const holder = nestedAtReal(real, nested);
2344
+ if (!holder) {
2345
+ if (!judged)
2346
+ return null;
2347
+ const rootReal = await realBeneath(root);
2348
+ if (!isContainedPath(rootReal, real) || await stat(real).then((info) => info.isDirectory(), () => false))
2349
+ return null;
2350
+ return await coversLanding({ include: mount.config.include }, rootReal, real, relativePath) ? null : new WorkspaceReadError('escape', `Symlink escape detected: ${path}`, 'realpath');
2351
+ }
1841
2352
  if (mount.config.followSymlinks !== true) {
1842
- const found = await linkOnTheWay({ root: mount.config.path, followSymlinks: false }, relativePath);
2353
+ const rootReal = await realBeneath(root);
2354
+ const found = await linkOnTheWay({ root: rootReal, followSymlinks: false }, relativePath);
1843
2355
  if (found !== null)
1844
- return await linkReadError(mount, found, path, nested);
1845
- }
2356
+ return await linkReadError(mount, found, path, relativePath, nested, rootReal);
2357
+ }
2358
+ // On a mount with an include, the path to use there names each directory
2359
+ // on the place's way as that mount's, so a place beneath anything else
2360
+ // there, such as a file the include leaves out, isn't named; one beneath
2361
+ // a directory not there yet is.
2362
+ const onItsWay = holder.include === undefined
2363
+ || await stat(dirname(real)).then((info) => info.isDirectory(), (err) => errnoOf(err) === 'ENOENT');
2364
+ const directory = holder.include !== undefined && await stat(real).then((info) => info.isDirectory(), () => false);
2365
+ if (!onItsWay || !namesNestedPlace(holder.rest, holder.include, directory))
2366
+ return new WorkspaceReadError('escape', `Symlink escape detected: ${path}`, 'realpath');
1846
2367
  return new NestedMountError(path, mount.config.name, holder.name, holder.use, 'leads into');
1847
2368
  }
1848
- /** A parsed path, refused if it lies in a nested mount's directory (parseFilePath). */
1849
- refuseNested(parsed) {
1850
- const holder = this.holderOf(parsed.mount.config.name, parsed.relativePath);
2369
+ /**
2370
+ * A parsed path, refused where the mount doesn't hold it: in a nested
2371
+ * mount's directory first, naming the mount that holds it, then outside
2372
+ * the mount's include. Each is judged on the path as the caller parsed it:
2373
+ * as disk spells it for parseFilePath, as given for resolveAbsolutePath,
2374
+ * which is synchronous and says so (`asGiven`, so the nested-mount check
2375
+ * folds where disk does). The include's refusal shows the path as given
2376
+ * (`given`), since it answers the path the caller asked about.
2377
+ */
2378
+ refuseNotHeld(parsed, given, asGiven = false, moved = null) {
2379
+ const holder = this.holderOf(parsed.mount.config.name, parsed.relativePath, asGiven, moved);
1851
2380
  if (holder)
1852
2381
  throw new NestedMountError(parsed.path, parsed.mount.config.name, holder.name, holder.use);
2382
+ if (!insideMount(parsed.relativePath, parsed.mount.config.include)) {
2383
+ throw new OutsideIncludeError(given, parsed.mount.config);
2384
+ }
1853
2385
  return parsed;
1854
2386
  }
2387
+ /**
2388
+ * Whether a mount-relative path names a file, as grep decides what a path
2389
+ * it's given names: for a path the include covers, a file in the
2390
+ * workspace's history, or anything but a directory on disk. Grep takes it
2391
+ * as a directory only when neither side has a file there, and filters what
2392
+ * it finds beneath it by the mount's include. A path the include doesn't
2393
+ * cover names no file of the mount's, whatever disk or history holds
2394
+ * there, so one refusesAsOutside lets through is a directory. A direct
2395
+ * mount has no history: what a run of it as 'chronicle' left in the store
2396
+ * isn't its own, so disk alone decides. Disk is read beneath `root`: a
2397
+ * direct mount's is the root its parse resolved, a store-backed mount's
2398
+ * its configured path.
2399
+ */
2400
+ async namesFile(mount, relativePath, root) {
2401
+ return relativePath !== '' && insideMount(relativePath, mount.config.include) && ((!mount.direct && this.getStore().treeGet(mount.treeStateId, relativePath) !== null) ||
2402
+ await lstat(join(root, relativePath)).then((s) => !s.isDirectory(), () => false));
2403
+ }
2404
+ /**
2405
+ * Whether sync, materialize, grep, glob or ls refuses a path it's given as
2406
+ * outside the mount's include. A path the include doesn't cover is a scope
2407
+ * exactly where a listing names a directory: where disk has a directory
2408
+ * reached from the mount's root through directories, with no link among
2409
+ * them, or the workspace's history holds an entry beneath it that's the
2410
+ * mount's own to list (withinIncludes). The one exception is a directory
2411
+ * the ignore list covers, which a listing passes over and which is still a
2412
+ * scope when it's named, since a sync that names it takes in what's there
2413
+ * (#276). Anything else is refused, a file at the path included, which no
2414
+ * scope tool takes up. The walk descends no link it meets. Where covered
2415
+ * history makes a name a scope and disk has since put a link there, a
2416
+ * mount that doesn't follow symlinks refuses the link, as it refuses any
2417
+ * link on a path's way, and on a mount that does, a pass of the scope
2418
+ * follows the link, and its answer shows whether the link leads out of the
2419
+ * mount. A
2420
+ * path in another mount's directory nested in this one is that mount's,
2421
+ * whatever this mount's include says, so it isn't refused here: each tool
2422
+ * names the mount that holds it, as the file operations do. A direct mount
2423
+ * has no history, as namesFile says, and is judged beneath the root its
2424
+ * parse resolved (`root`), by the nesting there (`moved`, movedNesting).
2425
+ */
2426
+ async refusesAsOutside(mount, relativePath, moved, root) {
2427
+ if (this.holderOf(mount.config.name, relativePath, false, moved))
2428
+ return false;
2429
+ if (insideMount(relativePath, mount.config.include))
2430
+ return false;
2431
+ const own = { include: mount.config.include, nested: this.nestedOf(mount.config.name) };
2432
+ if (!mount.direct && this.getStore().treeList(mount.treeStateId, relativePath + '/')
2433
+ .some((entry) => withinIncludes(own, entry.path)))
2434
+ return false;
2435
+ // A directory, and each directory above it to the mount's root, as the
2436
+ // walk reaches it: through no link, since the walk descends none.
2437
+ const segments = relativePath.split('/');
2438
+ for (let i = 1; i <= segments.length; i++) {
2439
+ const entry = await lstat(join(root, ...segments.slice(0, i))).catch(() => null);
2440
+ if (!entry?.isDirectory())
2441
+ return true;
2442
+ }
2443
+ return false;
2444
+ }
1855
2445
  /**
1856
2446
  * Parse a mount-prefixed path into its mount and mount-relative path, as
1857
- * disk spells it (diskSpelling), with `path` the mount-prefixed path so
1858
- * spelled. On a disk that folds names, a path spelled otherwise reaches
1859
- * disk's file, so every tool takes it by disk's name: one name per file,
1860
- * and the names its answers give are disk's, except that a path that names
1861
- * a workspace entry exactly, or does once its directories take disk's
1862
- * spelling, keeps the entry's spelling. A path the workspace records an
1863
- * intent at, such as a deletion disk hasn't been given yet, counts as an
1864
- * entry here, so the calls that settle it reach it. The workspace's
1865
- * entries (entriesOf) stand in for disk where it has nothing yet, so a
1866
- * draft has one name too. Neither applies to a path that disk's spelling
1867
- * puts in a nested mount's directory.
2447
+ * disk spells it (diskSpelling). `path` is the mount-prefixed path in that
2448
+ * spelling where it differs from the one spelling, and otherwise the path
2449
+ * as the caller gave it. The path is read in its one spelling first
2450
+ * (parsePathAsGiven), so the respelling only ever sees a path with no
2451
+ * empty, `.` or `..` segment and no separator before its first. On a disk
2452
+ * that folds names, a path spelled otherwise reaches disk's file, so every
2453
+ * tool takes it by disk's name: one name per file, and the names its
2454
+ * answers give are disk's, except that a path that names a workspace entry
2455
+ * exactly, or does once its directories take disk's spelling, keeps the
2456
+ * entry's spelling, and what lies past a link on the way keeps the
2457
+ * caller's, since the step reads nothing past a link. A path the workspace
2458
+ * records an intent at, such as a deletion disk hasn't been given yet,
2459
+ * counts as an entry here, so the calls that settle it reach it. The
2460
+ * workspace's entries (entriesOf) stand in for disk where it has nothing
2461
+ * yet, so a draft has one name too. Neither applies to a path that disk's
2462
+ * spelling puts in a nested mount's directory. A direct mount holds no
2463
+ * entries, so its paths take disk's spelling alone. Past a nested mount's
2464
+ * directory the path stays as given, since what lies there is that mount's
2465
+ * to name. Every answer shows `path`, a name the include leaves out
2466
+ * included, since how disk spells a name the caller gave is no content of
2467
+ * that file, except the include's own refusal, which shows the path
2468
+ * exactly as given (refuseNotHeld), since it answers the path asked about.
1868
2469
  * A handler that must read something at the moment it's asked, as
1869
2470
  * handleSync reads the branch a path sync adopts on, reads it before
1870
- * calling this, since this awaits disk. The entries are read when the
1871
- * step needs them, some after those awaits, from the branch current then.
2471
+ * calling this, since this awaits disk. The entries are read when the step
2472
+ * needs them, some after those awaits, from the branch current then.
1872
2473
  */
1873
2474
  async parsePath(path) {
1874
2475
  const given = this.parsePathAsGiven(path);
1875
- const relativePath = await diskSpelling(resolve(given.mount.config.path), given.relativePath, this.entriesOf(given.mount));
2476
+ // A direct mount's root is resolved once here, so the respelling and the
2477
+ // checks of the path that follow read disk beneath one root and judge by
2478
+ // the nesting there (movedNesting).
2479
+ const configured = resolve(given.mount.config.path);
2480
+ const root = given.mount.direct ? await realpath(configured).catch(() => configured) : configured;
2481
+ const moved = given.mount.direct ? await this.movedNesting(given.mount, root) : null;
2482
+ const spelled = await diskSpelling(root, given.relativePath, given.mount.direct ? undefined : this.entriesOf(given.mount));
2483
+ // Past a nested mount's directory the path stays as given: what lies
2484
+ // there is that mount's, whose own include decides what a tool may name,
2485
+ // so this mount doesn't respell it.
2486
+ // The directory itself takes disk's spelling, as a listing names it.
2487
+ // The respelling keeps each segment's place, so the given path's rest
2488
+ // follows the directory's segments.
2489
+ const depth = this.nestedDepth(given.mount.config.name, spelled, moved);
2490
+ const relativePath = depth === undefined ? spelled
2491
+ : [...spelled.split('/').slice(0, depth), ...given.relativePath.split('/').slice(depth)].join('/');
1876
2492
  return {
1877
2493
  mount: given.mount,
1878
2494
  relativePath,
1879
2495
  path: relativePath === given.relativePath ? path : `${given.mount.config.name}/${relativePath}`,
2496
+ root,
2497
+ moved,
1880
2498
  };
1881
2499
  }
2500
+ /**
2501
+ * How many segments the innermost nested mount's directory that holds
2502
+ * `relativePath` has, in a spelling it's known by (othersOf), or, for a
2503
+ * direct mount whose root has moved, in the nesting there (`moved`);
2504
+ * undefined when no nested mount's directory holds it.
2505
+ */
2506
+ nestedDepth(mountName, relativePath, moved = null) {
2507
+ let depth;
2508
+ for (const dir of moved?.map((n) => n.dir) ?? this.othersOf(mountName)) {
2509
+ if (relativePath !== dir && !relativePath.startsWith(`${dir}/`))
2510
+ continue;
2511
+ const segments = dir.split('/').length;
2512
+ if (depth === undefined || segments > depth)
2513
+ depth = segments;
2514
+ }
2515
+ return depth;
2516
+ }
1882
2517
  /**
1883
2518
  * A mount's entries on the current branch, and the paths it records an
1884
2519
  * intent at there, as diskSpelling reads them when it does, whether its
@@ -1896,13 +2531,33 @@ export class WorkspaceModule {
1896
2531
  // given yet or a conflict, is the workspace's own name for the file
1897
2532
  // there, as an entry is, so the calls that settle it reach it.
1898
2533
  has: (path) => store.treeGet(mount.treeStateId, path) !== null || store.treeGet(intents.treeStateId, path) !== null,
1899
- under: (prefix) => store.treeList(mount.treeStateId, prefix).map((entry) => entry.path),
2534
+ // Only an entry this mount's include covers spells a draft's path
2535
+ // (insideMount): not a key no spelling names, such as `c/` or `a//b.txt`
2536
+ // from an earlier version, nor one the include leaves out, which would
2537
+ // respell a covered draft into a name the include leaves out. An entry
2538
+ // in a nested mount's directory that this mount's include covers
2539
+ // spells one whatever that mount's include says, so on a disk that
2540
+ // folds names, a draft naming the directory in another spelling takes
2541
+ // the entry's spelling and is judged as in it.
2542
+ under: (prefix) => store.treeList(mount.treeStateId, prefix).map((entry) => entry.path).filter((path) => insideMount(path, mount.config.include)),
1900
2543
  holder: (path) => this.holderOf(mount.config.name, path)?.name,
1901
2544
  rootFoldsCase: this.rootFoldsCase.get(mount.config.name) ?? false,
1902
2545
  };
1903
2546
  }
1904
2547
  /**
1905
- * Parse a mount-prefixed path into (mountName, relativePath), as spelled.
2548
+ * Parse a mount-prefixed path into its mount and the one mount-relative
2549
+ * path every later step reads, as given, before disk's spelling
2550
+ * (parsePath): `/` between segments (`\` read as `/` where it's the
2551
+ * platform's separator), with no empty or `.` segment and no trailing `/`,
2552
+ * and '' for the mount's root. So the traversal guard here and every later
2553
+ * step judge one spelling of the path, which parsePath then respells name
2554
+ * by name as disk lists them. A `..` segment takes back the segment before
2555
+ * it, before anything looks the path up, so a mount's include judges the
2556
+ * path every tool acts on, and one with nothing left to take back climbs
2557
+ * above the mount's root and is refused, whatever it reaches afterwards. A
2558
+ * separator straight after the mount's name would make the rest an
2559
+ * absolute path, so that is refused too, and every reader that takes a
2560
+ * path refuses it here, a disk reader included.
1906
2561
  */
1907
2562
  parsePathAsGiven(path) {
1908
2563
  // A file's name on disk is UTF-8, which can't hold a lone surrogate: the
@@ -1912,17 +2567,31 @@ export class WorkspaceModule {
1912
2567
  }
1913
2568
  const slashIdx = path.indexOf('/');
1914
2569
  const mountName = slashIdx >= 0 ? path.slice(0, slashIdx) : path;
1915
- const relativePath = slashIdx >= 0 ? path.slice(slashIdx + 1) : '';
2570
+ const given = slashIdx >= 0 ? path.slice(slashIdx + 1) : '';
1916
2571
  const mount = this.mounts.get(mountName);
1917
2572
  if (!mount) {
1918
2573
  throw new Error(`Unknown mount: "${mountName}". Available: ${[...this.mounts.keys()].join(', ')}`);
1919
2574
  }
1920
- // Path traversal guard (CWE-22): ensure resolved path stays within mount.
1921
- // Containment must compare with the PLATFORM separator (isContainedPath):
1922
- // resolve() emits backslashes on Windows, so a '/'-suffixed root never
1923
- // prefix-matches there and every in-mount path was rejected as traversal.
1924
- // Against the resolved root, so a root configured with a trailing
1925
- // separator, or relative, contains its own paths, the root included.
2575
+ const segments = pathSegments(given);
2576
+ if (given.startsWith('/') || (sep === '\\' && given.startsWith('\\'))) {
2577
+ throw new Error(`Path traversal detected: "${path}" has a separator right after mount "${mountName}", which makes it an absolute path: give it from the mount's root.`);
2578
+ }
2579
+ const kept = [];
2580
+ for (const segment of segments) {
2581
+ if (segment !== '..')
2582
+ kept.push(segment);
2583
+ else if (kept.pop() === undefined) {
2584
+ throw new Error(`Path traversal detected: "${path}" climbs above the root of mount "${mountName}".`);
2585
+ }
2586
+ }
2587
+ const relativePath = kept.join('/');
2588
+ // Path traversal guard (CWE-22), on the path every later step reads: on
2589
+ // Windows a first segment such as `C:` names another drive. Containment
2590
+ // must compare with the PLATFORM separator (isContainedPath): resolve()
2591
+ // emits backslashes on Windows, so a '/'-suffixed root never prefix-matches
2592
+ // there and every in-mount path was rejected as traversal. Against the
2593
+ // resolved root, so a root configured with a trailing separator, or
2594
+ // relative, contains its own paths, the root included.
1926
2595
  const root = resolve(mount.config.path);
1927
2596
  const resolved = resolve(root, relativePath);
1928
2597
  if (!isContainedPath(root, resolved)) {
@@ -1983,6 +2652,8 @@ export class WorkspaceModule {
1983
2652
  * which answers while the evidence awaits reopening; where even it can't
1984
2653
  * be read, as when the evidence was never read back whole, the read is
1985
2654
  * refused too, with an errno only where no directory is at the root's path.
2655
+ * A direct mount's root is checked against no identity, and its read reads
2656
+ * no evidence: it promises what's at its root now (diskView).
1986
2657
  */
1987
2658
  async readRoot(mount) {
1988
2659
  const name = mount.config.name;
@@ -1995,13 +2666,15 @@ export class WorkspaceModule {
1995
2666
  throw new WorkspaceReadError('mount_unavailable', `Mount unavailable: ${name}`, 'realpath_root', errnoOf(err));
1996
2667
  }
1997
2668
  let rootIdentity;
1998
- try {
1999
- rootIdentity = this.agreementOrThrow().rootIdentityForRead(name);
2000
- }
2001
- catch (err) {
2002
- // The evidence can't be read back, so neither can the check be made.
2003
- // Where no directory is at the root's path, its errno still says so.
2004
- throw new WorkspaceReadError('mount_unavailable', `Mount unavailable: ${name}: ${err instanceof Error ? err.message : String(err)}`, 'root', await rootAbsence(root));
2669
+ if (!mount.direct) {
2670
+ try {
2671
+ rootIdentity = this.agreementOrThrow().rootIdentityForRead(name);
2672
+ }
2673
+ catch (err) {
2674
+ // The evidence can't be read back, so neither can the check be made.
2675
+ // Where no directory is at the root's path, its errno still says so.
2676
+ throw new WorkspaceReadError('mount_unavailable', `Mount unavailable: ${name}: ${err instanceof Error ? err.message : String(err)}`, 'root', await rootAbsence(root));
2677
+ }
2005
2678
  }
2006
2679
  const checked = await checkRoot(this.viewOf(mount, rootIdentity), real);
2007
2680
  if ('dir' in checked)
@@ -2017,11 +2690,13 @@ export class WorkspaceModule {
2017
2690
  * with the code and errno readRoot gives what is at its path now (its stage
2018
2691
  * and words are this check's): gone, or not a directory, with ENOENT or
2019
2692
  * ENOTDIR, so a caller reads a root gone mid-read as one gone before it; or
2020
- * another directory, with none.
2693
+ * another directory, with none. A direct mount reads whatever directory is
2694
+ * at its root (MountConfig.backend), so for it, another directory there is
2695
+ * one the next read reads.
2021
2696
  */
2022
2697
  async rootMoved(mount) {
2023
2698
  const errno = await rootAbsence(resolve(mount.config.path));
2024
- const reason = errno === undefined ? ROOT_REPLACED : ROOT_UNAVAILABLE;
2699
+ const reason = errno !== undefined ? ROOT_UNAVAILABLE : mount.direct ? DIRECT_ROOT_REPLACED : ROOT_REPLACED;
2025
2700
  return new WorkspaceReadError('mount_unavailable', `Mount unavailable: ${mount.config.name}: ${reason}`, 'root', errno);
2026
2701
  }
2027
2702
  /**
@@ -2035,7 +2710,8 @@ export class WorkspaceModule {
2035
2710
  * among the directories on its way beneath the mount's root, wherever it
2036
2711
  * leads (linkOnTheWay), before anything resolves it: as `escape` for a
2037
2712
  * link leading outside the mount, as `other_mount` for one into a nested
2038
- * mount's directory, and as `parent_symlink` for any other.
2713
+ * mount's directory where its refusal names that mount, and as
2714
+ * `parent_symlink` for any other.
2039
2715
  * 2. `lstat` the lexical path — refuse directories; refuse a final-component
2040
2716
  * symlink when the mount does not `followSymlinks`; refuse anything else
2041
2717
  * that isn't a regular file, such as a FIFO, without opening it.
@@ -2083,10 +2759,15 @@ export class WorkspaceModule {
2083
2759
  // mount that doesn't follow symlinks goes through none among the
2084
2760
  // directories on the way, wherever it leads. Asked again of the path's
2085
2761
  // resolution after the open, below.
2086
- const linkView = { root: mount.config.path, followSymlinks: follow };
2762
+ // The checks below judge by the root step 0 checked, and read the links
2763
+ // on the path's way beneath it. The lstat and the open go through the
2764
+ // configured path, and step 5 refuses a read whose root is no longer the
2765
+ // directory step 0 checked, so what's served is judged beneath one root.
2766
+ const linkView = { root: realMountRoot, followSymlinks: follow };
2767
+ const nested = await this.nestedFor(mount, realMountRoot);
2087
2768
  const onTheWay = await linkOnTheWay(linkView, relativePath, 'parents');
2088
2769
  if (onTheWay !== null)
2089
- throw await linkReadError(mount, onTheWay, mountPrefixedPath, this.nestedOf(mount.config.name));
2770
+ throw await linkReadError(mount, onTheWay, mountPrefixedPath, relativePath, nested, realMountRoot);
2090
2771
  let fileInfo;
2091
2772
  try {
2092
2773
  fileInfo = await lstat(lexicalPath);
@@ -2167,14 +2848,23 @@ export class WorkspaceModule {
2167
2848
  throw new WorkspaceReadError('not_found', `Unable to resolve file: ${mountPrefixedPath}`, 'realpath', code);
2168
2849
  }
2169
2850
  // A directory swapped for a link since the walk above is caught here, by
2170
- // what the path resolved to after the open.
2851
+ // what the path resolved to after the open, and the check below holds
2852
+ // the opened file to that path. A link put back after this realpath,
2853
+ // leading to the opened file itself, passes both: a race this doesn't
2854
+ // close.
2171
2855
  const resolvedThrough = await linkRefusal(linkView, realMountRoot, relativePath, realFilePath);
2172
2856
  if (resolvedThrough !== null)
2173
- throw await linkReadError(mount, resolvedThrough, mountPrefixedPath, this.nestedOf(mount.config.name));
2174
- if (!isContainedPath(realMountRoot, realFilePath)) {
2857
+ throw await linkReadError(mount, resolvedThrough, mountPrefixedPath, relativePath, nested, realMountRoot);
2858
+ const inside = isContainedPath(realMountRoot, realFilePath);
2859
+ const holder = inside ? nestedAtReal(realFilePath, nested) : undefined;
2860
+ // A place in a nested mount's directory that its include leaves out is
2861
+ // no mount's, so the path leaves this one (namesNestedPlace), and so
2862
+ // does one reaching a file this mount's own include leaves out
2863
+ // (coversLanding).
2864
+ const own = holder === undefined && inside && !(await coversLanding({ include: mount.config.include }, realMountRoot, realFilePath, relativePath));
2865
+ if (!inside || own || (holder !== undefined && !namesNestedPlace(holder.rest, holder.include, false))) {
2175
2866
  throw new WorkspaceReadError('escape', `Symlink escape detected: ${mountPrefixedPath}`, 'realpath');
2176
2867
  }
2177
- const holder = nestedAtReal(realFilePath, this.nestedOf(mount.config.name));
2178
2868
  if (holder)
2179
2869
  throw new WorkspaceReadError('other_mount', leadsInto(mount.config.name, relativePath, holder), 'realpath');
2180
2870
  let pathStat;
@@ -2227,7 +2917,9 @@ export class WorkspaceModule {
2227
2917
  * - Once the workspace has recorded the mount root's identity, with the
2228
2918
  * first evidence it gathers there, a root that is another directory is
2229
2919
  * an unavailable mount: a replaced directory, a link swapped in for it,
2230
- * or an unmounted drive's mountpoint. In any mount, recorded or not, a
2920
+ * or an unmounted drive's mountpoint. A direct mount's reads check no
2921
+ * recorded identity: they read beneath whatever directory is at its
2922
+ * root (MountConfig.backend). In any mount, recorded or not, a
2231
2923
  * root that stops being the directory the read checked until the file
2232
2924
  * has been opened and checked is unavailable too: with ENOENT or
2233
2925
  * ENOTDIR where no directory is there, as before the read, and with no
@@ -2235,9 +2927,10 @@ export class WorkspaceModule {
2235
2927
  * the descriptor that was checked.
2236
2928
  *
2237
2929
  * Throws {@link WorkspaceReadError} with a `code` distinguishing unknown
2238
- * mount, lexical traversal, a path in another mount's directory nested in
2239
- * the one named (`other_mount`), unavailable mount, missing or non-regular
2240
- * file, directory, policy-denied symlink, outside-mount target, and
2930
+ * mount, lexical traversal, a path the mount's include doesn't cover
2931
+ * (`outside_include`), a path in another mount's directory nested in the one named
2932
+ * (`other_mount`), unavailable mount, missing or non-regular file,
2933
+ * directory, policy-denied symlink, outside-mount target, and
2241
2934
  * file-changed-during-read.
2242
2935
  */
2243
2936
  async readFileFromDisk(mountPrefixedPath, options = {}) {
@@ -2254,8 +2947,9 @@ export class WorkspaceModule {
2254
2947
  if (err instanceof WorkspaceReadError)
2255
2948
  throw err;
2256
2949
  const message = err instanceof Error ? err.message : String(err);
2257
- const code = err instanceof NestedMountError ? 'other_mount'
2258
- : message.startsWith('Unknown mount') ? 'unknown_mount' : 'traversal';
2950
+ const code = err instanceof OutsideIncludeError ? 'outside_include'
2951
+ : err instanceof NestedMountError ? 'other_mount'
2952
+ : message.startsWith('Unknown mount') ? 'unknown_mount' : 'traversal';
2259
2953
  throw new WorkspaceReadError(code, message, 'parse');
2260
2954
  }
2261
2955
  if (!relativePath) {
@@ -2388,9 +3082,11 @@ export class WorkspaceModule {
2388
3082
  /**
2389
3083
  * Commit a tool's write or delete to the workspace tree, with the branch
2390
3084
  * intent it implies: store origin for a path disk never agreed with; for a
2391
- * deletion, a tombstone, unless the evidence holds no agreed disk copy (P
3085
+ * deletion, a tombstone, written before the entry is removed, unless the
3086
+ * agreement's evidence for the path, P, holds no agreed disk copy (P
2392
3087
  * absent, or no P and store origin), when it clears the path's intent and
2393
- * pushes nothing. It pushes the change to disk when the mount opts in via
3088
+ * pushes nothing. It pushes the change to
3089
+ * disk when the mount opts in via
2394
3090
  * `autoMaterialize` — required for cross-agent pipelines, since another
2395
3091
  * agent's watcher on the same directory only sees real filesystem events.
2396
3092
  * The push follows materialize's rule: a disk copy that changed since it
@@ -2407,86 +3103,215 @@ export class WorkspaceModule {
2407
3103
  * the path, as an edit makes).
2408
3104
  */
2409
3105
  async commitToolChange(mount, relativePath, change, onCommitted) {
3106
+ const { refused, modeKept, notes } = await this.commitToolChanges(mount, [{ path: relativePath, change }], onCommitted && (() => onCommitted()));
3107
+ return { refused: refused.get(relativePath) ?? null, modeKept: modeKept.get(relativePath) ?? null, note: notes.get(relativePath) ?? null };
3108
+ }
3109
+ /**
3110
+ * commitToolChange for several paths of one mount at once, as edit_many
3111
+ * commits its files: every path's precondition is enforced before any entry
3112
+ * is set, then a deletion's tombstone is written, then every entry is set
3113
+ * in one record of the store, which takes all of them or none, then each
3114
+ * other path's intent, by the rule commitToolChange's doc gives, which the
3115
+ * code below applies, with no await between, and one push takes the paths
3116
+ * to disk, but for a deletion that clears its path's intent. `onCommitted`
3117
+ * is told of each path once the entries are set, also when the store throws
3118
+ * after setting them, whose error then goes on in place of the push
3119
+ * (changesLanded).
3120
+ * Answers, by path, the reason for each that reached the workspace but not
3121
+ * disk (`refused`), and, apart from it, why one whose bytes reached disk
3122
+ * left the file's mode as disk had it (`modeKept`), and that a deletion
3123
+ * clearing a conflict that named a disk file unlinked nothing (`notes`), as
3124
+ * commitToolChange answers them for one path.
3125
+ */
3126
+ async commitToolChanges(mount, changes, onCommitted) {
2410
3127
  const store = this.getStore();
3128
+ const agreement = this.agreementOrThrow();
2411
3129
  const intents = this.intents.get(mount.config.name);
2412
3130
  // The mutation's precondition, enforced here, synchronously with the
2413
3131
  // commit: whatever settleBeforeMutation's pass could or couldn't settle.
2414
- settleAdoptionBeforeMutation(store, this.agreementOrThrow(), { name: mount.config.name, treeStateId: mount.treeStateId }, relativePath);
2415
- const evidence = this.agreementOrThrow().get(mount.config.name, relativePath);
2416
- const known = evidence !== undefined;
2417
- if (change.kind === 'set') {
2418
- store.treeSet(mount.treeStateId, relativePath, { blobHash: change.blobHash, size: change.size, mode: change.mode ?? 0o644 });
2419
- // A later intent update or disk push can throw; the tree entry is
2420
- // already set, on the branch current now. If the active branch changes
2421
- // during the push, that branch's tree has the file and the new one may
2422
- // not.
2423
- onCommitted?.();
2424
- intents.update(relativePath, (cur) => {
2425
- const next = { ...cur };
2426
- delete next.tombstone;
2427
- // Disk has never agreed with this path: a missing disk copy is a draft
2428
- // not yet materialized, not a deletion.
2429
- if (!known)
2430
- next.origin = 'store';
2431
- return next;
2432
- });
2433
- }
2434
- else {
2435
- store.treeRemove(mount.treeStateId, relativePath);
2436
- onCommitted?.();
2437
- // A deletion whose evidence holds no agreed disk copy (disk last agreed
2438
- // it had nothing here, or has never agreed with this entry, which the
2439
- // workspace created) puts the store back at the agreement. Nothing on
2440
- // disk is the workspace's to unlink, so it pushes nothing, and it
2441
- // clears the path's whole intent: no tombstone, so it needs no proof of
2442
- // absence, which a path disk can't show, such as one beneath a symlink
2443
- // the mount doesn't follow, would never give; and no conflict, which
2444
- // has nothing left to be about once the workspace has given up its
2445
- // side. Whatever disk holds there is a sync's to observe, a file the
2446
- // workspace never saw included. Any other deletion keeps its
2447
- // tombstone, which guards it: a copy disk agreed with, a push of ours
2448
- // that may have landed (pending or interrupted), or an entry from
2449
- // before the evidence.
2450
- let agreed = true;
2451
- let note = null;
2452
- intents.update(relativePath, (cur) => {
2453
- agreed = !(evidence?.kind === 'absent' || (evidence === undefined && cur.origin === 'store'));
2454
- if (agreed) {
2455
- const next = { ...cur, tombstone: { hash: change.previousHash } };
2456
- delete next.origin;
2457
- return next;
3132
+ // Every path's comes first, so nothing that can refuse follows a set.
3133
+ for (const { path } of changes) {
3134
+ settleAdoptionBeforeMutation(store, agreement, { name: mount.config.name, treeStateId: mount.treeStateId }, path);
3135
+ }
3136
+ const entry = (change) => ({ blobHash: change.blobHash, size: change.size, mode: change.mode ?? 0o644 });
3137
+ // The changes the tree doesn't hold yet, which the read-back below checks,
3138
+ // read before any intent is written, so no read comes between a
3139
+ // tombstone's write and the put-back's guard.
3140
+ const changing = changes.filter(({ path, change }) => !holds(store.treeGet(mount.treeStateId, path), change));
3141
+ // Each path's intent, by the rule commitToolChange's doc gives. A
3142
+ // deletion's tombstone is written before its entry is removed. Removed
3143
+ // without it, the entry would read as a file this branch doesn't have,
3144
+ // which no materialize deletes and no second delete can reach
3145
+ // (anima-research/agent-framework#553). Every other intent is written
3146
+ // after the tree change: what it gives up, the tombstone a write replaces
3147
+ // or the origin and conflict a deletion clears, guards the path until the
3148
+ // change lands.
3149
+ const notes = new Map();
3150
+ const unpushed = new Set();
3151
+ const intentChanges = changes.map(({ path, change }) => {
3152
+ const evidence = agreement.get(mount.config.name, path);
3153
+ const cur = intents.get(path) ?? {};
3154
+ if (change.kind === 'remove') {
3155
+ // A deletion whose evidence holds no agreed disk copy (disk last
3156
+ // agreed it had nothing here, or has never agreed with this entry,
3157
+ // which the workspace created) puts the store back at the
3158
+ // agreement. Nothing on disk is the workspace's to unlink, so it
3159
+ // pushes nothing, and it clears the path's whole intent: no
3160
+ // tombstone, so it needs no proof of absence, which a path disk
3161
+ // can't show, such as one beneath a symlink the mount doesn't
3162
+ // follow, would never give; and no conflict, which has nothing left
3163
+ // to be about once the workspace has given up its side. Whatever
3164
+ // disk holds there is a sync's to observe, a file the workspace
3165
+ // never saw included. Any other deletion keeps its tombstone, which
3166
+ // guards it: a copy disk agreed with, a push of ours that may have
3167
+ // landed (pending or interrupted), or an entry from before the
3168
+ // evidence.
3169
+ if (!(evidence?.kind === 'absent' || (evidence === undefined && cur.origin === 'store'))) {
3170
+ return {
3171
+ path,
3172
+ first: true,
3173
+ next: (current) => {
3174
+ const next = { ...current, tombstone: { hash: change.previousHash } };
3175
+ delete next.origin;
3176
+ return next;
3177
+ },
3178
+ };
2458
3179
  }
3180
+ unpushed.add(path);
2459
3181
  // A conflict it clears may name a file disk held there, which the
2460
- // workspace never took in: the answer says that file wasn't unlinked,
2461
- // where the deletion alone would read as having removed it. The
2462
- // deletion doesn't look at disk, so a file nothing recorded gets no
2463
- // note.
3182
+ // workspace never took in: the answer says that file wasn't
3183
+ // unlinked, where the deletion alone would read as having removed
3184
+ // it. The deletion doesn't look at disk, so a file nothing recorded
3185
+ // gets no note.
2464
3186
  if (cur.conflict?.disk) {
2465
- note = `nothing was unlinked: when last observed, disk held a file at ${mount.config.name}/${relativePath} ` +
2466
- `that the workspace never took in (conflict: ${cur.conflict.kind}), and a sync observes whatever disk holds there`;
3187
+ notes.set(path, `nothing was unlinked: when last observed, disk held a file at ${mount.config.name}/${path} `
3188
+ + `that the workspace never took in (conflict: ${cur.conflict.kind}), and a sync observes whatever disk holds there`);
2467
3189
  }
2468
- return {};
2469
- });
2470
- if (!agreed)
2471
- return { refused: null, modeKept: null, note };
3190
+ return { path, first: false, next: () => ({}) };
3191
+ }
3192
+ return {
3193
+ path,
3194
+ first: false,
3195
+ next: (current) => {
3196
+ const next = { ...current };
3197
+ delete next.tombstone;
3198
+ // Disk has never agreed with this path: a missing disk copy is a
3199
+ // draft not yet materialized, not a deletion.
3200
+ if (evidence === undefined)
3201
+ next.origin = 'store';
3202
+ return next;
3203
+ },
3204
+ };
3205
+ });
3206
+ // A tombstone written for a change that then doesn't land is put back:
3207
+ // the path's intent record as it was, a damaged one's bytes included, so
3208
+ // a refused deletion changes nothing. The put-back is best effort, since
3209
+ // the error that stopped the call is its answer. A tombstone it leaves
3210
+ // beside the entry guards nothing: decide gives no verdict from one while
3211
+ // the entry is there, status and materialize take it as no deletion, and
3212
+ // the path's next agreement clears it.
3213
+ const written = [];
3214
+ const putBack = () => {
3215
+ for (const { path, record } of written) {
3216
+ try {
3217
+ if (record)
3218
+ store.treeSet(intents.treeStateId, path, record);
3219
+ else if (store.treeGet(intents.treeStateId, path))
3220
+ store.treeRemove(intents.treeStateId, path);
3221
+ }
3222
+ catch (error) {
3223
+ // Left beside the entry, where it guards nothing (above).
3224
+ console.warn(`[workspace] Mount "${mount.config.name}": a change to ${path} failed, and putting its branch intent back threw too `
3225
+ + `(${error instanceof Error ? error.message : String(error)}), so a tombstone may be left beside the entry. One there `
3226
+ + `deletes nothing, and the path's next agreement with disk clears it`);
3227
+ }
3228
+ }
3229
+ };
3230
+ try {
3231
+ for (const { path, first, next } of intentChanges) {
3232
+ if (!first)
3233
+ continue;
3234
+ written.push({ path, record: store.treeGet(intents.treeStateId, path) });
3235
+ intents.update(path, next);
3236
+ }
3237
+ }
3238
+ catch (error) {
3239
+ putBack();
3240
+ throw error;
3241
+ }
3242
+ // A store can fail after its record lands: Chronicle 0.4 writes a state's
3243
+ // auto-snapshot after appending its update, and that failure reaches the
3244
+ // caller with the update recorded (anima-research/chronicle#39). So a set
3245
+ // that threw is read back, and where every path it changes holds what its
3246
+ // change leaves, the record is in: the paths' intents follow, as for any
3247
+ // set, and then the error goes on in place of the push. A change the tree
3248
+ // already holds can't show whether the record is in, so a call whose every
3249
+ // change the tree holds already goes on as the store's own failure.
3250
+ let landedThenThrew = null;
3251
+ try {
3252
+ if (changes.length === 1) {
3253
+ const [{ path, change }] = changes;
3254
+ if (change.kind === 'set')
3255
+ store.treeSet(mount.treeStateId, path, entry(change));
3256
+ else
3257
+ store.treeRemove(mount.treeStateId, path);
3258
+ }
3259
+ else {
3260
+ // One record for every path, so a store that fails partway sets none.
3261
+ store.treeBatch(mount.treeStateId, changes.map(({ path, change }) => (change.kind === 'set'
3262
+ ? { op: 'set', path, entry: entry(change) }
3263
+ : { op: 'remove', path })));
3264
+ }
2472
3265
  }
2473
- if (!this.pushesOnCommit(mount))
2474
- return { refused: null, modeKept: null, note: null };
2475
- const pushed = await this.pushUnlocked(mount, [relativePath], {
2476
- applyDeletions: change.kind === 'remove',
3266
+ catch (error) {
3267
+ // A read-back that fails can't tell whether the change landed, so its
3268
+ // error goes on and a tombstone stays: put back where the removal did
3269
+ // land, it would leave #553's state, and beside an entry it guards
3270
+ // nothing.
3271
+ if (changing.length === 0 || !changesLanded(store, mount.treeStateId, changing, error)) {
3272
+ putBack();
3273
+ throw error;
3274
+ }
3275
+ landedThenThrew = { error };
3276
+ }
3277
+ // A later intent update or disk push can throw; the tree entries are
3278
+ // already set, on the branch current now. If the active branch changes
3279
+ // during the push, that branch's tree has the files and the new one may
3280
+ // not.
3281
+ for (const { path } of changes)
3282
+ onCommitted?.(path);
3283
+ for (const { path, first, next } of intentChanges)
3284
+ if (!first)
3285
+ intents.update(path, next);
3286
+ const pushing = changes.filter(({ path }) => !unpushed.has(path));
3287
+ if (landedThenThrew)
3288
+ throw new StoredThenFailed(landedThenThrew.error, this.pushesOnCommit(mount) && pushing.length > 0, notes);
3289
+ const refused = new Map();
3290
+ const modeKept = new Map();
3291
+ if (!this.pushesOnCommit(mount) || pushing.length === 0)
3292
+ return { refused, modeKept, notes };
3293
+ const pushed = await this.pushUnlocked(mount, pushing.map(({ path }) => path), {
3294
+ applyDeletions: pushing.some(({ change }) => change.kind === 'remove'),
2477
3295
  branchId: store.currentBranch().id,
2478
3296
  });
2479
- const refused = pushed.skipped.find((s) => s.path === relativePath);
2480
- if (!refused)
2481
- return { refused: null, modeKept: pushed.modesKept.find((k) => k.path === relativePath)?.reason ?? null, note: null };
2482
- this.ctx?.pushEvent({
2483
- type: 'workspace:materialize-failed',
2484
- mount: mount.config.name,
2485
- path: relativePath,
2486
- op: change.kind === 'set' ? 'write' : 'delete',
2487
- error: refused.reason,
2488
- });
2489
- return { refused: refused.reason, modeKept: null, note: null };
3297
+ for (const { path, change } of pushing) {
3298
+ const skipped = pushed.skipped.find((s) => s.path === path);
3299
+ if (!skipped) {
3300
+ const kept = pushed.modesKept.find((k) => k.path === path)?.reason;
3301
+ if (kept)
3302
+ modeKept.set(path, kept);
3303
+ continue;
3304
+ }
3305
+ refused.set(path, skipped.reason);
3306
+ this.ctx?.pushEvent({
3307
+ type: 'workspace:materialize-failed',
3308
+ mount: mount.config.name,
3309
+ path,
3310
+ op: change.kind === 'set' ? 'write' : 'delete',
3311
+ error: skipped.reason,
3312
+ });
3313
+ }
3314
+ return { refused, modeKept, notes };
2490
3315
  }
2491
3316
  // ==========================================================================
2492
3317
  // Lazy Sync
@@ -2542,6 +3367,69 @@ export class WorkspaceModule {
2542
3367
  return `File not found: ${path}`;
2543
3368
  }
2544
3369
  }
3370
+ /**
3371
+ * A file's bytes for read, from where the mount keeps what it reads: the
3372
+ * workspace's copy, taken in from disk first where it holds none
3373
+ * (ensureSynced); or, on a direct mount, disk's file as it is now
3374
+ * (bytesOnDisk). An error says why there are none to read.
3375
+ */
3376
+ async bytesOf(mount, relativePath, path) {
3377
+ if (mount.direct)
3378
+ return this.bytesOnDisk(mount, relativePath, path);
3379
+ const store = this.getStore();
3380
+ return this.withMount(mount, async () => {
3381
+ const report = await this.ensureSynced(mount, relativePath);
3382
+ const entry = store.treeGet(mount.treeStateId, relativePath);
3383
+ if (!entry)
3384
+ return { error: this.notInWorkspace(path, report) };
3385
+ const blob = store.getBlob(entry.blobHash);
3386
+ if (!blob)
3387
+ return { error: `Blob not found for: ${path}` };
3388
+ return { bytes: blob };
3389
+ });
3390
+ }
3391
+ /**
3392
+ * A direct mount's file for read: its bytes on disk as they are now,
3393
+ * through the mount's boundary as readFileFromDisk reaches them
3394
+ * (openContainedFile), whose refusals are the answer. What a 'chronicle'
3395
+ * mount never stores, it doesn't show either: a file over the mount's
3396
+ * size limit, and a binary one, with a NUL in its first 8 KB, which
3397
+ * read_image reads where it's an image.
3398
+ */
3399
+ async bytesOnDisk(mount, relativePath, path) {
3400
+ const maxSize = mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
3401
+ const over = `${path} is over the size limit (${maxSize} bytes), so read doesn't show it.`;
3402
+ let opened;
3403
+ try {
3404
+ opened = await this.openContainedFile(mount, relativePath, path, (fileStat) => {
3405
+ if (fileStat.size > maxSize)
3406
+ throw new Error(over);
3407
+ });
3408
+ }
3409
+ catch (err) {
3410
+ // A refusal that names only the path says why with its errno, as a
3411
+ // failed read below does.
3412
+ const bare = err instanceof WorkspaceReadError && err.errno !== undefined && err.message === `Unable to read file: ${path}`;
3413
+ return { error: bare ? `${err.message} (${err.errno})` : err instanceof Error ? err.message : String(err) };
3414
+ }
3415
+ try {
3416
+ // No more than the limit is loaded, as for a file over it at its fstat.
3417
+ const { bytes, more } = await readPrefix(opened.handle, maxSize, opened.fileStat.size);
3418
+ if (more)
3419
+ return { error: over };
3420
+ if (looksBinary(bytes)) {
3421
+ return { error: `${path} is binary, so read doesn't show it as text${sniffImageMime(bytes) ? '; read it with read_image.' : '.'}` };
3422
+ }
3423
+ return { bytes };
3424
+ }
3425
+ catch (err) {
3426
+ const errno = errnoOf(err);
3427
+ return { error: `Unable to read file: ${path}${errno ? ` (${errno})` : ''}` };
3428
+ }
3429
+ finally {
3430
+ await opened.handle.close();
3431
+ }
3432
+ }
2545
3433
  // ==========================================================================
2546
3434
  // Tool Handlers
2547
3435
  // ==========================================================================
@@ -2558,20 +3446,10 @@ export class WorkspaceModule {
2558
3446
  if (content === undefined) {
2559
3447
  const { mount, relativePath, path } = await this.parseFilePath(input.path);
2560
3448
  input = { ...input, path };
2561
- const store = this.getStore();
2562
- const found = await this.withMount(mount, async () => {
2563
- const report = await this.ensureSynced(mount, relativePath);
2564
- const entry = store.treeGet(mount.treeStateId, relativePath);
2565
- if (!entry)
2566
- return { error: this.notInWorkspace(input.path, report) };
2567
- const blob = store.getBlob(entry.blobHash);
2568
- if (!blob)
2569
- return { error: `Blob not found for: ${input.path}` };
2570
- return { text: blob.toString('utf-8') };
2571
- });
3449
+ const found = await this.bytesOf(mount, relativePath, path);
2572
3450
  if ('error' in found)
2573
3451
  return { success: false, error: found.error, isError: true };
2574
- content = found.text;
3452
+ content = found.bytes.toString('utf-8');
2575
3453
  }
2576
3454
  if (characterPaging) {
2577
3455
  const start = Math.min(offsetChars, content.length);
@@ -2660,49 +3538,25 @@ export class WorkspaceModule {
2660
3538
  }
2661
3539
  const maxSize = mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
2662
3540
  let treeError = null;
2663
- try {
2664
- const image = this.tryReadImageFromTree(mount, relativePath, input.path, maxSize);
2665
- if (image) {
2666
- return {
2667
- success: true,
2668
- data: [
2669
- {
2670
- type: 'text',
2671
- text: `Path: ${input.path}\nMIME: ${image.mimeType}\nBytes: ${image.bytes.byteLength}`,
2672
- },
2673
- {
2674
- type: 'image',
2675
- data: image.bytes.toString('base64'),
2676
- mimeType: image.mimeType,
2677
- },
2678
- ],
2679
- };
2680
- }
2681
- }
2682
- catch (err) {
2683
- if (err instanceof WorkspaceImageReadError) {
2684
- treeError = err;
3541
+ // The workspace's copy first, where it holds one, then disk's. A direct
3542
+ // mount holds none, so its image is disk's.
3543
+ if (!mount.direct) {
3544
+ try {
3545
+ const image = this.tryReadImageFromTree(mount, relativePath, input.path, maxSize);
3546
+ if (image)
3547
+ return imageResult(input.path, image);
2685
3548
  }
2686
- else {
2687
- throw err;
3549
+ catch (err) {
3550
+ if (err instanceof WorkspaceImageReadError) {
3551
+ treeError = err;
3552
+ }
3553
+ else {
3554
+ throw err;
3555
+ }
2688
3556
  }
2689
3557
  }
2690
3558
  try {
2691
- const image = await this.readImageFromFilesystem(mount, relativePath, input.path, maxSize);
2692
- return {
2693
- success: true,
2694
- data: [
2695
- {
2696
- type: 'text',
2697
- text: `Path: ${input.path}\nMIME: ${image.mimeType}\nBytes: ${image.bytes.byteLength}`,
2698
- },
2699
- {
2700
- type: 'image',
2701
- data: image.bytes.toString('base64'),
2702
- mimeType: image.mimeType,
2703
- },
2704
- ],
2705
- };
3559
+ return imageResult(input.path, await this.readImageFromFilesystem(mount, relativePath, input.path, maxSize));
2706
3560
  }
2707
3561
  catch (err) {
2708
3562
  if (err instanceof WorkspaceImageReadError) {
@@ -2745,160 +3599,429 @@ export class WorkspaceModule {
2745
3599
  catch (error) {
2746
3600
  if (!committed)
2747
3601
  throw error;
2748
- return storedButUnfinished('write', input.path, { threw: error instanceof Error ? error.message : String(error) });
3602
+ return storedButUnfinished('write', input.path, error instanceof StoredThenFailed
3603
+ ? { storeFailed: error.message, pushes: error.pushes }
3604
+ : { threw: error instanceof Error ? error.message : String(error) });
2749
3605
  }
2750
3606
  if (refused !== null)
2751
3607
  return storedButUnfinished('write', input.path, { refused });
2752
3608
  return { success: true, data: { ...receipt, ...(modeKept ? { modeKept } : {}) } };
2753
3609
  }
2754
- async handleEdit(input) {
2755
- // Refused before anything is read: an empty oldString matches between
2756
- // every character, and UTF-8 can't store a lone surrogate.
2757
- if (input.oldString === '') {
2758
- return { success: false, isError: true, error: 'The edit did nothing: "oldString" is empty, and an empty string matches between every character. Give the text to replace.' };
2759
- }
2760
- for (const field of ['oldString', 'newString']) {
2761
- if (LONE_SURROGATE.test(input[field])) {
2762
- return { success: false, isError: true, error: `The edit did nothing: "${field}" holds a lone UTF-16 surrogate, which UTF-8 can't store.` };
3610
+ async handleEdit(input, maxChars = DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS) {
3611
+ return this.applyEdits('edit', [{
3612
+ path: input.path,
3613
+ oldString: input.oldString,
3614
+ newString: input.newString,
3615
+ expected: input.replaceAll ? 'all' : 1,
3616
+ }], maxChars);
3617
+ }
3618
+ async handleEditMany(input, maxChars = DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS, callerAgentName) {
3619
+ if (input.edits.length === 0) {
3620
+ return { success: false, isError: true, error: 'The edit_many call did nothing: "edits" is empty. Give at least one edit.' };
3621
+ }
3622
+ return this.applyEdits('edit_many', input.edits.map((edit) => ({
3623
+ path: edit.path,
3624
+ oldString: edit.oldString,
3625
+ newString: edit.newString,
3626
+ expected: edit.occurrences ?? 1,
3627
+ })), maxChars, callerAgentName);
3628
+ }
3629
+ /**
3630
+ * A call's edits, all or none, applied to the stored copies of their files:
3631
+ * edit's one, or edit_many's in the files of one mount. Each edit is matched
3632
+ * in its file's text as this call reads it, never in another edit's result
3633
+ * (edit-plan.ts), and any problem refuses the call with none of its edits
3634
+ * stored: edit names its first problem, and edit_many every problem found.
3635
+ *
3636
+ * Each edit's own input is checked first, and each path's mount. A problem
3637
+ * there refuses edit at once, before any file's text is read, and edit_many
3638
+ * when its edits name more than one mount, which no one pass settles.
3639
+ * Otherwise edit_many goes on to settle and plan the rest, so its one
3640
+ * refusal names the problems it finds; the settling is what a read or a
3641
+ * listing of its files would take in from disk, and the refusal says what
3642
+ * it took in. A failure before the commit sets the entries stores none of
3643
+ * them, and edit_many's answer to it says so. A store that throws as it
3644
+ * sets them is read back (commitToolChanges), so the answer says they're
3645
+ * stored where its record landed, and that it can't tell where they
3646
+ * couldn't be read back.
3647
+ * Under the mount's turn, one pass settles every path with disk, by the
3648
+ * rule a listing uses, so the edits apply to what disk now holds. That pass
3649
+ * is the only step that awaits before the commit: every file is then read,
3650
+ * every edit planned, and every entry set (commitToolChanges) with no turn
3651
+ * of the event loop between, so no pass, branch change or other call moves
3652
+ * the tree between a file's read and its set. Disk then takes what it can
3653
+ * of the stored change.
3654
+ *
3655
+ * The answer is held to `maxChars`, the length the call's result may have
3656
+ * (ToolCall.resultMaxChars), as edit-text.ts describes.
3657
+ */
3658
+ async applyEdits(tool, given, maxChars, callerAgentName) {
3659
+ const refuse = (problems, notes = []) => ({ success: false, isError: true, error: refusalText(tool, problems, notes, maxChars) });
3660
+ // Each edit's own input, before anything is read: an empty old text
3661
+ // matches between every character, and UTF-8 can't store a lone surrogate.
3662
+ const problems = [];
3663
+ const specs = new Map();
3664
+ for (const [index, edit] of given.entries()) {
3665
+ const spec = {
3666
+ index,
3667
+ oldText: edit.oldString.replaceAll('\r\n', '\n'),
3668
+ newText: edit.newString.replaceAll('\r\n', '\n'),
3669
+ expected: edit.expected,
3670
+ };
3671
+ const found = problems.length;
3672
+ if (spec.oldText === '') {
3673
+ problems.push({ kind: 'input', edit: index, text: '"oldString" is empty, and an empty string matches between every character. Give the text to replace.' });
2763
3674
  }
2764
- }
2765
- const { mount, relativePath, path } = await this.parseFilePath(input.path);
2766
- input = { ...input, path };
2767
- if (mount.config.mode === 'read-only') {
2768
- return { success: false, error: `Mount "${mount.config.name}" is read-only`, isError: true };
2769
- }
3675
+ else if (spec.oldText === spec.newText) {
3676
+ // An edit's new text takes the line ends of the text it replaces, so
3677
+ // one whose only change is its line ends changes nothing.
3678
+ problems.push({
3679
+ kind: 'input',
3680
+ edit: index,
3681
+ text: edit.oldString !== edit.newString
3682
+ ? "oldString and newString are the same once their CRLF line ends are read as LF, so there's nothing to change: an edit keeps the file's line ends, and write replaces the whole file, line ends included."
3683
+ : "oldString and newString are the same, so there's nothing to change.",
3684
+ });
3685
+ }
3686
+ for (const field of ['oldString', 'newString']) {
3687
+ if (LONE_SURROGATE.test(edit[field])) {
3688
+ problems.push({ kind: 'input', edit: index, text: `"${field}" holds a lone UTF-16 surrogate, which UTF-8 can't store.` });
3689
+ }
3690
+ }
3691
+ if (problems.length === found)
3692
+ specs.set(index, spec);
3693
+ }
3694
+ // edit names its first problem, so one in its input refuses it before
3695
+ // its path is looked up on disk.
3696
+ if (tool === 'edit' && problems.length)
3697
+ return refuse(problems);
3698
+ // Each path in its mount, as disk spells it, before any file's text is
3699
+ // read. Edits of one stored path are one file, planned once from one
3700
+ // text, whatever path named it, and named as disk spells it.
3701
+ const parsed = new Map();
3702
+ const targets = new Map();
3703
+ const mounts = new Map();
3704
+ for (const [index, { path }] of given.entries()) {
3705
+ if (!parsed.has(path))
3706
+ parsed.set(path, await this.editablePath(tool, path, callerAgentName));
3707
+ const where = parsed.get(path);
3708
+ if ('kind' in where) {
3709
+ where.edits.push(index);
3710
+ continue;
3711
+ }
3712
+ mounts.set(where.mount.config.name, where.mount);
3713
+ const key = `${where.mount.config.name}/${where.relativePath}`;
3714
+ let target = targets.get(key);
3715
+ if (!target)
3716
+ targets.set(key, (target = { relativePath: where.relativePath, path: where.path, edits: [], specs: [] }));
3717
+ target.edits.push(index);
3718
+ const spec = specs.get(index);
3719
+ if (spec)
3720
+ target.specs.push(spec);
3721
+ }
3722
+ for (const where of parsed.values())
3723
+ if ('kind' in where)
3724
+ problems.push(where);
3725
+ if (mounts.size > 1) {
3726
+ problems.push({ kind: 'mounts', edits: [...targets.values()].flatMap((target) => target.edits), mounts: [...mounts.keys()] });
3727
+ }
3728
+ const [mount] = mounts.values();
3729
+ if (tool === 'edit' && problems.length)
3730
+ return refuse(problems);
3731
+ if (!mount || mounts.size > 1)
3732
+ return refuse(problems);
2770
3733
  const store = this.getStore();
3734
+ // Whether the commit set the call's entries, all of them at once.
2771
3735
  let committed = false;
2772
- let appliedNote = null;
3736
+ // What each file's settling took in, for a receipt.
3737
+ const applied = new Map();
3738
+ // The conflict each file's settling found, on a mount that doesn't push:
3739
+ // the success answer names it, and so does the answer to a store that
3740
+ // failed after recording the edits, which stand as on a success.
3741
+ const conflicts = new Map();
2773
3742
  try {
2774
3743
  return await this.withMount(mount, async () => {
2775
- // The edit applies to the path as disk holds it now: a change on disk
2776
- // to a file the workspace holds is taken in first, by the rule a
2777
- // listing uses. The pass settles a pending intent on the path too, as
2778
- // settleBeforeMutation's would, and the commit enforces the rest
2779
- // (commitToolChange). A write passes over its path only to settle a
2780
- // pending intent, since it replaces the whole file. As every file
2781
- // tool's pass does, it names the path it acts on, so a file the
2782
- // mount passes over by design is observed (see PassOptions.named).
2783
- const pass = await this.passUnlocked(mount, { kind: 'paths', paths: [relativePath] }, { named: true });
2784
- const report = pass.reports.get(relativePath);
2785
- // A mode taken in alone isn't a change to the text: it brings nothing
2786
- // new to read, as it makes no event (emitFsEvents), and the edit then
2787
- // writes at the mode disk has, so it leaves nothing to say.
2788
- const took = (op) => pass.ops.some((o) => o.path === relativePath && o.op === op && !o.modeOnly);
2789
- // Which copy the edit used, when it isn't the one the workspace last
2790
- // agreed on with disk: disk's newer text, or the workspace's copy
2791
- // because disk's couldn't be read or disk has none. A file the
2792
- // workspace didn't hold has no older copy, so taking it in needs no
2793
- // word.
2794
- const whichCopy = (verb) => took('modified')
2795
- ? `Disk's copy had changed since the workspace last agreed with it, so it was taken in first, and the edit ${verb} that text.`
2796
- : report?.state === 'unverified'
2797
- ? `The path couldn't be checked against disk (${report.note ?? 'not observed'}), so the edit ${verb} the workspace's copy.`
2798
- : report?.state === 'disk-missing-provenance-unknown'
2799
- ? `Disk has no copy of this file, and nothing records whether it was deleted there, so the edit ${verb} the workspace's copy.`
2800
- : null;
2801
- // A conflict the pass found is named when the edit is refused for the
2802
- // text it found, on either kind of mount, and on a success where the
2803
- // mount doesn't push, since such a mount keeps the conflict until
2804
- // materialize or sync settles it. A pushing mount's success met none
2805
- // (below). A stored edit that couldn't finish leaves it to the push's
2806
- // reason, which names the conflict, or to ls, which its answer points to.
2807
- const conflict = report?.state === 'conflict' ? report.conflict?.kind ?? 'both-changed' : null;
2808
- // Where disk has no copy now, whatever the conflict's kind, a sync of
2809
- // the path takes disk's deletion and a forced materialize writes the
2810
- // workspace's copy back. Where it has one, a sync keeps it and gives
2811
- // up the workspace's, whether or not the workspace can hold disk's
2812
- // copy: one it can't hold stays on disk alone.
2813
- const conflictNote = (where) => conflict === null ? null
2814
- : `The path is in conflict with disk (${conflict}): the edit ${where} the workspace's copy. ` + (report?.diskNow === 'absent'
2815
- ? "Sync the path to take disk's deletion, which removes the workspace's copy, or materialize it with force to write the workspace's copy back to disk."
2816
- : "Sync the path to keep disk's copy and give up the workspace's, or materialize it with force to write the workspace's over disk's.");
2817
- const suffix = [whichCopy('looked in'), conflictNote('looked in')].filter((n) => n !== null).map((n) => ` ${n}`).join('');
2818
- appliedNote = whichCopy('applied to');
2819
- const entry = store.treeGet(mount.treeStateId, relativePath);
2820
- if (!entry) {
2821
- // A pass also drops a copy disk made binary or too large, which
2822
- // the disk-only answer describes; any other drop is disk's deletion.
2823
- const error = took('deleted') && report?.state !== 'disk-only'
2824
- ? `File not found: ${input.path}. Disk's copy was deleted since the workspace last agreed with it, and that was taken in first.`
2825
- : this.notInWorkspace(input.path, report);
2826
- return { success: false, error, isError: true };
2827
- }
2828
- const blob = store.getBlob(entry.blobHash);
2829
- if (!blob) {
2830
- return { success: false, error: `Blob not found for: ${input.path}`, isError: true };
2831
- }
2832
- // Decoding would turn each invalid sequence into U+FFFD, and writing
2833
- // the text back would change bytes the edit never named.
2834
- if (!isUtf8(blob)) {
2835
- return {
2836
- success: false,
2837
- isError: true,
2838
- error: `The edit did nothing: ${input.path} isn't valid UTF-8, so editing it would change bytes outside the text it replaces. `
2839
- + `Read shows each invalid byte sequence as U+FFFD, and a write replaces the whole file as UTF-8, so writing back what read shows puts U+FFFD in their place.${suffix}`,
2840
- };
2841
- }
2842
- let content = blob.toString('utf-8');
2843
- // An edit that would replace nothing is refused, replaceAll or not;
2844
- // without replaceAll, the text must occur once, and the refusal says
2845
- // how often it does. With replaceAll, whether it occurs is enough.
2846
- const count = input.replaceAll
2847
- ? Number(content.includes(input.oldString))
2848
- : content.split(input.oldString).length - 1;
2849
- if (count === 0) {
2850
- return { success: false, error: `String not found in ${input.path}.${suffix}`, isError: true };
2851
- }
2852
- if (count > 1 && !input.replaceAll) {
2853
- return {
2854
- success: false,
2855
- error: `String found ${count} times in ${input.path}. Use replaceAll: true or provide more context.${suffix}`,
2856
- isError: true,
2857
- };
2858
- }
2859
- // A replacer function, so that the new text goes in as given: in a
2860
- // replacement string, $&, $$, $' and $` are patterns.
2861
- content = input.replaceAll
2862
- ? content.replaceAll(input.oldString, () => input.newString)
2863
- : content.replace(input.oldString, () => input.newString);
2864
- const newBuffer = Buffer.from(content, 'utf-8');
2865
- const newBlobHash = store.storeBlob(newBuffer, 'text/plain');
2866
- const { refused, modeKept } = await this.commitToolChange(mount, relativePath, {
2867
- kind: 'set',
2868
- blobHash: newBlobHash,
2869
- size: newBuffer.byteLength,
2870
- mode: entry.mode,
2871
- }, () => { committed = true; });
2872
- if (refused !== null)
2873
- return storedButUnfinished('edit', input.path, { refused }, appliedNote);
2874
- // The edit makes the path the workspace's own change (commitToolChange),
2875
- // so a file disk lacked goes back with this edit's push, or with the
2876
- // next materialize where the mount doesn't push. A push that didn't
2877
- // complete answers above, with its reason. One that completed met no
2878
- // conflict, since this push, unforced, stops at one: the edit made the
2879
- // two copies agree, which settles it, or there was none. So only a
2880
- // mount that doesn't push still holds the conflict the pass found.
3744
+ // As every file tool's pass does, it names the paths it acts on, so a
3745
+ // file the mount passes over by design is observed (see PassOptions.named).
3746
+ const pass = await this.passUnlocked(mount, { kind: 'paths', paths: [...targets.values()].map((target) => target.relativePath) }, { named: true });
3747
+ // Nothing below awaits until the commit's push.
3748
+ const maxSize = mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
3749
+ const hints = hintBudget();
3750
+ // As much as the largest file the call names holds, at least, so the
3751
+ // budget is the same whatever order its files are planned in.
3752
+ let largest = maxSize;
3753
+ for (const target of targets.values())
3754
+ largest = Math.max(largest, store.treeGet(mount.treeStateId, target.relativePath)?.size ?? 0);
3755
+ const counts = countBudget(largest);
3756
+ const notes = [];
2881
3757
  const pushes = this.pushesOnCommit(mount);
2882
- const backOnDisk = report?.state === 'disk-missing-provenance-unknown'
2883
- ? `${pushes ? 'Its push put the file back on disk' : 'A materialize of the path puts it back on disk'}; if it was deleted there on purpose, delete it here too.`
2884
- : null;
2885
- const notes = [appliedNote, backOnDisk, pushes ? null : conflictNote('is in')].filter((n) => n !== null);
3758
+ const plans = [];
3759
+ for (const target of targets.values()) {
3760
+ const report = pass.reports.get(target.relativePath);
3761
+ // A mode taken in alone isn't a change to the text: it brings nothing
3762
+ // new to read, as it makes no event (emitFsEvents), and the edits
3763
+ // then write at the mode disk has, so it leaves nothing to say.
3764
+ const took = (op) => pass.ops.some((o) => o.path === target.relativePath && o.op === op && !o.modeOnly);
3765
+ // Which copy the edits used, when it isn't the one the workspace
3766
+ // last agreed on with disk: disk's newer text, or the workspace's
3767
+ // copy because disk's couldn't be read or disk has none. A file the
3768
+ // workspace didn't hold has no older copy, so taking it in needs no
3769
+ // word.
3770
+ const subject = tool === 'edit' ? 'the edit' : editList(target.edits);
3771
+ const whichCopy = (verb) => took('modified')
3772
+ ? `Disk's copy${tool === 'edit' ? '' : ` of ${target.path}`} had changed since the workspace last agreed with it, so it was taken in first, and ${subject} ${verb} that text.`
3773
+ : report?.state === 'unverified'
3774
+ ? `${tool === 'edit' ? 'The path' : target.path} couldn't be checked against disk (${report.note ?? 'not observed'}), so ${subject} ${verb} the workspace's copy.`
3775
+ : report?.state === 'disk-missing-provenance-unknown'
3776
+ ? `Disk has no copy of ${tool === 'edit' ? 'this file' : target.path}, and nothing records whether it was deleted there, so ${subject} ${verb} the workspace's copy.`
3777
+ : null;
3778
+ // A conflict the pass found is named when the edits are refused for
3779
+ // the text they found, on either kind of mount, and on a success
3780
+ // where the mount doesn't push, since such a mount keeps the conflict
3781
+ // until materialize or sync settles it. A pushing mount's push that
3782
+ // completed met none: unforced, it stops at a conflict, so the edits
3783
+ // made the two copies agree, which settles it, or there was none.
3784
+ // Edits stored that couldn't finish leave it to the push's reason,
3785
+ // which names the conflict, or to ls, which that answer points to
3786
+ // when the rest of the call failed; where the store failed after
3787
+ // recording them, the answer names it as the success does.
3788
+ // What a sync does follows what disk holds now, whatever kind the
3789
+ // conflict was recorded as: where disk has no copy, it takes the
3790
+ // deletion; where disk has one, it keeps disk's copy and gives up
3791
+ // the workspace's, though a copy the workspace can't hold, binary
3792
+ // or past maxFileSize, isn't taken in.
3793
+ const conflict = report?.state === 'conflict' ? report.conflict?.kind ?? 'both-changed' : null;
3794
+ const conflictNote = (where) => conflict === null ? null
3795
+ : `${tool === 'edit' ? 'The path' : target.path} is in conflict with disk (${conflict}): ${subject} ${where} the workspace's copy. `
3796
+ + (report?.diskNow === 'absent'
3797
+ ? "Sync the path to take disk's deletion, which removes the workspace's copy, or materialize it with force to write the workspace's copy back to disk."
3798
+ : "Sync the path to keep disk's copy and give up the workspace's, or materialize it with force to write the workspace's over disk's.");
3799
+ applied.set(target, whichCopy('applied to'));
3800
+ // The edits make the path the workspace's own change, so a file disk
3801
+ // lacked goes back with this call's push, or with the next
3802
+ // materialize where the mount doesn't push. A push that didn't
3803
+ // complete answers with its reason instead.
3804
+ const backOnDisk = report?.state !== 'disk-missing-provenance-unknown' ? null
3805
+ : tool === 'edit'
3806
+ ? `${pushes ? 'Its push put the file back on disk' : 'A materialize of the path puts it back on disk'}; if it was deleted there on purpose, delete it here too.`
3807
+ : `${pushes ? `This call's push put ${target.path} back on disk` : `A materialize of ${target.path} puts it back on disk`}; if it was deleted there on purpose, delete it here too.`;
3808
+ const lookedIn = [whichCopy('looked in'), conflictNote('looked in')].filter((note) => note !== null);
3809
+ const entry = store.treeGet(mount.treeStateId, target.relativePath);
3810
+ if (!entry) {
3811
+ // A pass also drops a copy disk made binary or too large, which
3812
+ // the disk-only answer describes; any other drop is disk's deletion.
3813
+ const text = took('deleted') && report?.state !== 'disk-only'
3814
+ ? `File not found: ${target.path}. Disk's copy was deleted since the workspace last agreed with it, and that was taken in first.`
3815
+ : this.notInWorkspace(target.path, report);
3816
+ problems.push({ kind: 'file', edits: target.edits, path: target.path, text, whole: true });
3817
+ continue;
3818
+ }
3819
+ notes.push(...lookedIn);
3820
+ const blob = store.getBlob(entry.blobHash);
3821
+ if (!blob) {
3822
+ problems.push({ kind: 'file', edits: target.edits, path: target.path, text: `Blob not found for: ${target.path}`, whole: true });
3823
+ continue;
3824
+ }
3825
+ // Decoding would turn each invalid sequence into U+FFFD, and writing
3826
+ // the text back would change bytes the edits never named.
3827
+ const file = decodeForEdit(blob);
3828
+ if (!file) {
3829
+ problems.push({
3830
+ kind: 'file',
3831
+ edits: target.edits,
3832
+ path: target.path,
3833
+ text: `${target.path} isn't valid UTF-8, so editing it would change bytes outside the text it replaces. `
3834
+ + 'Read shows each invalid byte sequence as U+FFFD, and a write replaces the whole file as UTF-8, so writing back what read shows puts U+FFFD in their place.',
3835
+ whole: false,
3836
+ });
3837
+ continue;
3838
+ }
3839
+ if (!target.specs.length)
3840
+ continue;
3841
+ const planned = planFile(file, blob, target.specs, hints, maxSize, counts);
3842
+ if ('problems' in planned) {
3843
+ // One at a time: a call of many edits can have more problems
3844
+ // than a spread passes as arguments.
3845
+ for (const problem of planned.problems)
3846
+ problems.push({ ...problem, path: target.path });
3847
+ continue;
3848
+ }
3849
+ // The planner refuses a file its counts take past the limit before
3850
+ // building it, from the least its bytes can be; one it built past
3851
+ // the limit, as its CRs or multi-byte characters can take it, is
3852
+ // refused here.
3853
+ if ('tooLarge' in planned || planned.plan.bytes.length > maxSize) {
3854
+ const size = 'tooLarge' in planned ? `at least ${planned.tooLarge.toLocaleString('en-US')}` : planned.plan.bytes.length.toLocaleString('en-US');
3855
+ problems.push({
3856
+ kind: 'file',
3857
+ edits: target.edits,
3858
+ path: target.path,
3859
+ text: `${target.path} would be ${size} bytes with ${tool === 'edit' ? 'this edit' : editList(target.edits)}, `
3860
+ + `past the ${maxSize.toLocaleString('en-US')}-byte limit this mount sets on a file, so the workspace couldn't keep it. `
3861
+ + "An edit that leaves the file within the limit applies. The limit is the mount's maxFileSize setting, which only whoever runs the host can change.",
3862
+ whole: false,
3863
+ });
3864
+ continue;
3865
+ }
3866
+ plans.push({
3867
+ target,
3868
+ plan: planned.plan,
3869
+ mode: entry.mode,
3870
+ backOnDisk,
3871
+ conflictNote: pushes ? null : conflictNote(tool === 'edit' || target.edits.length === 1 ? 'is in' : 'are in'),
3872
+ });
3873
+ const conflicted = plans.at(-1).conflictNote;
3874
+ if (conflicted !== null)
3875
+ conflicts.set(target, conflicted);
3876
+ }
3877
+ if (problems.length)
3878
+ return refuse(problems, notes);
3879
+ const { refused, modeKept } = await this.commitToolChanges(mount, plans.map(({ target, plan, mode }) => ({
3880
+ path: target.relativePath,
3881
+ change: { kind: 'set', blobHash: store.storeBlob(plan.bytes, 'text/plain'), size: plan.bytes.length, mode },
3882
+ })), () => { committed = true; });
3883
+ if (refused.size > 0)
3884
+ return this.editsStoredButUnfinished(tool, [...targets.values()], applied, conflicts, { refused, modeKept }, maxChars);
2886
3885
  return {
2887
3886
  success: true,
2888
- data: {
2889
- path: input.path,
2890
- size: newBuffer.byteLength,
2891
- ...(notes.length > 0 ? { note: notes.join(' ') } : {}),
2892
- ...(modeKept ? { modeKept } : {}),
2893
- },
3887
+ data: editReceipt(tool, plans.map(({ target, plan, backOnDisk, conflictNote }) => ({
3888
+ path: target.path,
3889
+ plan,
3890
+ notes: [applied.get(target) ?? null, backOnDisk, conflictNote].filter((note) => note !== null),
3891
+ modeKept: modeKept.get(target.relativePath) ?? null,
3892
+ })), given.length, maxChars),
2894
3893
  };
2895
3894
  });
2896
3895
  }
2897
3896
  catch (error) {
2898
- if (!committed)
2899
- throw error;
2900
- return storedButUnfinished('edit', input.path, { threw: error instanceof Error ? error.message : String(error) }, appliedNote);
3897
+ const message = error instanceof Error ? error.message : String(error);
3898
+ if (committed) {
3899
+ return this.editsStoredButUnfinished(tool, [...targets.values()], applied, conflicts, error instanceof StoredThenFailed
3900
+ ? { storeFailed: message, pushes: error.pushes }
3901
+ : { threw: message }, maxChars);
3902
+ }
3903
+ // A set that threw and couldn't be read back may have stored the edits,
3904
+ // and a second call could then apply them twice.
3905
+ if (error instanceof CommitUnknownError) {
3906
+ const [set, read] = [cutLine(error.setError), cutLine(error.readError)];
3907
+ return {
3908
+ success: false,
3909
+ isError: true,
3910
+ error: tool === 'edit_many'
3911
+ ? `The edit_many call can't tell whether it stored its edits: the store failed as it set them (${set}), and reading them back failed too (${read}). `
3912
+ + 'Read its files before sending it again: a second call can apply its edits twice.'
3913
+ : `Whether the edit of "${[...targets.values()][0].path}" is stored isn't known: the store failed as it set it (${set}), and reading it back failed too (${read}). `
3914
+ + 'Read the file before sending the edit again: a second edit can apply the change twice.',
3915
+ };
3916
+ }
3917
+ // The commit sets every entry in one record or none, and a set that
3918
+ // threw was read back, so nothing is stored; or every change was one
3919
+ // the tree already held, which leaves the tree as it was either way.
3920
+ if (tool === 'edit_many')
3921
+ return { success: false, isError: true, error: `The edit_many call stored none of its edits: ${cutLine(message)}` };
3922
+ throw error;
3923
+ }
3924
+ }
3925
+ /**
3926
+ * Where an edit's path is in its mount, or why the call can't edit it: a
3927
+ * path no mount holds, one outside its mount or holding a lone surrogate
3928
+ * (parsePath), one a nested mount holds or that leads into one through a
3929
+ * link (parseFilePath), a path that names its mount's root, a read-only
3930
+ * mount, or for edit_many a generated file. edit's
3931
+ * generated file is refused before it gets here, by the same rule
3932
+ * (handleToolCall checks a call's `path`, which edit_many's input lacks).
3933
+ */
3934
+ async editablePath(tool, path, callerAgentName) {
3935
+ const unusable = (text) => ({ kind: 'file', edits: [], path, text, whole: true });
3936
+ try {
3937
+ // In the one spelling every file tool reads, as disk spells it, so two
3938
+ // spellings of a file are one entry and, in one call, one plan
3939
+ // (parsePathAsGiven); and a path in a mount nested inside this one is
3940
+ // that mount's, which every file tool refuses here (parseFilePath).
3941
+ const where = await this.parseFilePath(path);
3942
+ // One that names the mount's root, its bare name included, names no
3943
+ // file.
3944
+ if (where.relativePath === '')
3945
+ return unusable(`${path} names the root of mount "${where.mount.config.name}", which isn't a file; ls ${where.mount.config.name} lists the files in it.`);
3946
+ if (where.mount.config.mode === 'read-only')
3947
+ return unusable(`Mount "${where.mount.config.name}" is read-only`);
3948
+ const generated = tool === 'edit_many' ? this.findGeneratedTextFile(path) : undefined;
3949
+ if (generated)
3950
+ return unusable(`${path}: ${this.generatedFileRefusal(generated, callerAgentName)}.`);
3951
+ return where;
3952
+ }
3953
+ catch (error) {
3954
+ return unusable(error instanceof Error ? error.message : String(error));
3955
+ }
3956
+ }
3957
+ /**
3958
+ * Why a call can't change a generated file: another agent's is that agent's,
3959
+ * and the agent's own is read-only, since it shows the agent's tool
3960
+ * presentation, which set_tool_visibility and set_tool_description change.
3961
+ */
3962
+ generatedFileRefusal(generated, callerAgentName) {
3963
+ return callerAgentName !== generated.agentName
3964
+ ? 'Generated file belongs to another agent'
3965
+ : 'Generated file is read-only; change the tool presentation it shows with set_tool_visibility or set_tool_description instead';
3966
+ }
3967
+ /**
3968
+ * The answer to edits stored but not finished: the commit set every file's
3969
+ * entry, and then disk refused some of their pushes, or the store failed
3970
+ * after recording them, so their push didn't run, or the rest of the call
3971
+ * failed. It stays an error, since part of the call failed, and leads with
3972
+ * what is stored, which must not be sent again: a second call can apply
3973
+ * those edits twice. edit's is the answer write and delete give, one path's;
3974
+ * edit_many's lists the files disk refused, each with its push's reason,
3975
+ * notes each file disk took with its mode left as disk had it, as the
3976
+ * success answer's `modeKept` does, within `maxChars`, and never says to
3977
+ * send the call again. Where the store failed after recording the edits,
3978
+ * which stand as on a success, it names each conflict the success answer
3979
+ * would (`conflicts`, found only where the mount doesn't push).
3980
+ */
3981
+ editsStoredButUnfinished(tool, targets, applied, conflicts, outcome, maxChars) {
3982
+ const conflictOf = (target) => ('storeFailed' in outcome ? conflicts.get(target) ?? null : null);
3983
+ if (tool === 'edit') {
3984
+ const [target] = targets;
3985
+ const note = [applied.get(target) ?? null, conflictOf(target)].filter((text) => text !== null).join(' ');
3986
+ return storedButUnfinished('edit', target.path, 'refused' in outcome ? { refused: outcome.refused.get(target.relativePath) } : outcome, note || null);
3987
+ }
3988
+ const stored = "Every edit of this call is stored in the workspace, so don't send the call again: a second call can apply its edits twice.";
3989
+ // The head is never cut, so what stands for the whole call goes in it,
3990
+ // and the parts are the files disk refused, each with its push's reason.
3991
+ let head;
3992
+ const parts = [];
3993
+ if ('refused' in outcome) {
3994
+ const files = targets.length;
3995
+ const refused = outcome.refused.size;
3996
+ head = `${stored}\n\n${files === 1
3997
+ ? "Disk didn't take the call's one file. Its push didn't complete:"
3998
+ : `Disk took ${files - refused} of the call's ${files} files. ${refused === 1
3999
+ ? "This file's push didn't complete:"
4000
+ : "These files' pushes didn't complete, each with its reason:"}`}`;
4001
+ for (const target of targets) {
4002
+ const reason = outcome.refused.get(target.relativePath);
4003
+ if (reason !== undefined)
4004
+ parts.push(`${target.path}: ${reason}`);
4005
+ }
2901
4006
  }
4007
+ else if ('storeFailed' in outcome) {
4008
+ head = `${stored}\n\nThe store failed after recording them: ${cutLine(outcome.storeFailed)}.`
4009
+ + (outcome.pushes ? " Their push to disk didn't run, so disk lacks them until a materialize of their files writes them." : '');
4010
+ }
4011
+ else {
4012
+ head = `${stored}\n\nThe rest of the call failed: ${cutLine(outcome.threw)}. ls shows each path's state.`;
4013
+ }
4014
+ const kept = 'modeKept' in outcome
4015
+ ? targets.flatMap((target) => {
4016
+ const reason = outcome.modeKept.get(target.relativePath);
4017
+ return reason === undefined ? [] : [`Disk took ${target.path}: ${reason}.`];
4018
+ })
4019
+ : [];
4020
+ const notes = [
4021
+ ...kept,
4022
+ ...targets.flatMap((target) => [applied.get(target) ?? null, conflictOf(target)]).filter((note) => !!note),
4023
+ ];
4024
+ return { success: false, isError: true, error: fitted(head, parts, notes, maxChars, 'stored') };
2902
4025
  }
2903
4026
  async handleDelete(input) {
2904
4027
  const { mount, relativePath, path } = await this.parseFilePath(input.path);
@@ -2931,64 +4054,157 @@ export class WorkspaceModule {
2931
4054
  catch (error) {
2932
4055
  if (!committed)
2933
4056
  throw error;
4057
+ if (error instanceof StoredThenFailed) {
4058
+ // Its note, as the success answer's: a deletion that cleared a
4059
+ // conflict naming a disk file unlinked nothing.
4060
+ const note = error.notes.get(relativePath);
4061
+ return storedButUnfinished('delete', input.path, { storeFailed: error.message, pushes: error.pushes }, note === undefined ? null : `${note.charAt(0).toUpperCase()}${note.slice(1)}.`);
4062
+ }
2934
4063
  return storedButUnfinished('delete', input.path, { threw: error instanceof Error ? error.message : String(error) });
2935
4064
  }
2936
4065
  }
2937
4066
  async handleLs(input) {
2938
- const store = this.getStore();
2939
4067
  if (!input.path) {
2940
- // List all mounts
4068
+ // List all mounts, with the kind a mount configured direct runs as
4069
+ // this session and the ignore list it walks by, whose default no
4070
+ // config shows, and each with its include where it has one, so the
4071
+ // files a mount holds show before a path outside them is refused.
2941
4072
  const mounts = [...this.mounts.entries()].map(([name, m]) => ({
2942
4073
  name,
2943
4074
  path: m.config.path,
2944
4075
  mode: m.config.mode,
4076
+ ...(m.config.backend === 'direct' ? { backend: m.direct ? 'direct' : 'chronicle', ignore: this.ignoreOf(m) } : {}),
4077
+ ...(m.config.include ? { include: [...m.config.include] } : {}),
2945
4078
  }));
2946
4079
  return { success: true, data: { mounts } };
2947
4080
  }
2948
- const { mount, relativePath, path } = await this.parsePath(input.path);
4081
+ const { mount, relativePath, path, moved, root } = await this.parsePath(input.path);
4082
+ // A path outside the mount's include that's no scope (refusesAsOutside)
4083
+ // is refused, as glob refuses it, and shown as given.
4084
+ if (await this.refusesAsOutside(mount, relativePath, moved, root)) {
4085
+ return { success: false, error: new OutsideIncludeError(input.path, mount.config).message, isError: true };
4086
+ }
2949
4087
  input = { ...input, path };
2950
4088
  const recursive = input.recursive === true;
2951
4089
  // Every listing checks the paths it shows against disk first, under the
2952
- // three-way rule, whatever the mount's watch mode.
2953
- return this.withMount(mount, async () => {
2954
- const pass = await this.passUnlocked(mount, { kind: 'dir', dir: relativePath, recursive });
2955
- const reports = [...pass.reports.values()].sort((a, b) => a.path.localeCompare(b.path));
2956
- const incomplete = pass.incomplete.length > 0 ? { incomplete: pass.incomplete } : {};
2957
- if (recursive) {
2958
- return {
2959
- success: true,
2960
- data: {
2961
- path: input.path,
2962
- entries: reports.map((r) => ({ path: r.path, ...stateView(r) })),
2963
- count: reports.length,
2964
- ...incomplete,
2965
- },
2966
- };
2967
- }
2968
- // Non-recursive: the scope's files, and the directories beneath it that
2969
- // disk or the workspace has.
2970
- const prefix = relativePath ? relativePath + '/' : '';
2971
- const dirNames = new Set(pass.dirs.map((d) => d.slice(prefix.length)));
2972
- for (const entry of store.treeList(mount.treeStateId, prefix || undefined)) {
2973
- const slash = entry.path.indexOf('/', prefix.length);
2974
- if (slash >= 0)
2975
- dirNames.add(entry.path.slice(prefix.length, slash));
2976
- }
2977
- const children = [
2978
- ...[...dirNames].sort().map((name) => ({ name, type: 'directory' })),
2979
- ...reports.map((r) => ({ name: r.path.slice(prefix.length), type: 'file', ...stateView(r) })),
2980
- ];
4090
+ // three-way rule, whatever the mount's watch mode; a direct mount's
4091
+ // shows disk's.
4092
+ const listing = await this.listingOf(mount, relativePath, recursive);
4093
+ const incomplete = listing.incomplete.length > 0 ? { incomplete: listing.incomplete } : {};
4094
+ if (recursive) {
2981
4095
  return {
2982
4096
  success: true,
2983
4097
  data: {
2984
4098
  path: input.path,
2985
- entries: children,
2986
- count: children.length,
4099
+ entries: listing.files,
4100
+ count: listing.files.length,
2987
4101
  ...incomplete,
2988
4102
  },
2989
4103
  };
4104
+ }
4105
+ // Non-recursive: the scope's files, and the directories beneath it.
4106
+ const prefix = relativePath ? relativePath + '/' : '';
4107
+ const children = [
4108
+ ...listing.dirs.map((d) => d.slice(prefix.length)).sort().map((name) => ({ name, type: 'directory' })),
4109
+ ...listing.files.map(({ path: file, ...view }) => ({ name: file.slice(prefix.length), type: 'file', ...view })),
4110
+ ];
4111
+ return {
4112
+ success: true,
4113
+ data: {
4114
+ path: input.path,
4115
+ entries: children,
4116
+ count: children.length,
4117
+ ...incomplete,
4118
+ },
4119
+ };
4120
+ }
4121
+ /**
4122
+ * What a listing shows of a directory scope, from where the mount keeps
4123
+ * what it reads: the store-backed kind's pass (listingFromStore), or, on a
4124
+ * direct mount, disk (listingFromDisk). `keep` chooses the files shown.
4125
+ */
4126
+ listingOf(mount, dir, recursive, keep) {
4127
+ return mount.direct ? this.listingFromDisk(mount, dir, recursive, keep) : this.listingFromStore(mount, dir, recursive, keep);
4128
+ }
4129
+ /**
4130
+ * A 'chronicle' mount's listing: a pass over the scope under the three-way
4131
+ * rule, each path it decided with its state, and the directories beneath
4132
+ * the scope that disk or the workspace has.
4133
+ */
4134
+ listingFromStore(mount, dir, recursive, keep) {
4135
+ const store = this.getStore();
4136
+ return this.withMount(mount, async () => {
4137
+ const pass = await this.passUnlocked(mount, { kind: 'dir', dir, recursive });
4138
+ const files = [...pass.reports.values()]
4139
+ .sort((a, b) => a.path.localeCompare(b.path))
4140
+ .filter((report) => keep === undefined || keep(report.path))
4141
+ .map((report) => ({ path: report.path, ...stateView(report) }));
4142
+ if (recursive)
4143
+ return { files, dirs: [], incomplete: pass.incomplete };
4144
+ // Read with the pass's reports, on the branch it decided on, before
4145
+ // anything else takes the mount's turn.
4146
+ const dirs = new Set(pass.dirs);
4147
+ const prefix = dir ? dir + '/' : '';
4148
+ // History implies a directory only where it's the mount's own to name
4149
+ // (withinIncludes): not history in a nested mount's directory that
4150
+ // that mount's include leaves out.
4151
+ const own = { include: mount.config.include, nested: this.nestedOf(mount.config.name) };
4152
+ for (const entry of store.treeList(mount.treeStateId, prefix || undefined)) {
4153
+ if (!withinIncludes(own, entry.path))
4154
+ continue;
4155
+ const slash = entry.path.indexOf('/', prefix.length);
4156
+ if (slash >= 0)
4157
+ dirs.add(entry.path.slice(0, slash));
4158
+ }
4159
+ return { files, dirs: [...dirs], incomplete: pass.incomplete };
2990
4160
  });
2991
4161
  }
4162
+ /**
4163
+ * A direct mount's listing: its walk of the scope (diskWalk), with each
4164
+ * entry it took as disk has it now, observed as a pass observes it: a
4165
+ * file's size, or why the mount doesn't take it (a link it doesn't follow,
4166
+ * one that leaves the mount, what isn't a regular file). A file gone since
4167
+ * the walk listed it is no longer there to show.
4168
+ */
4169
+ async listingFromDisk(mount, dir, recursive, keep) {
4170
+ const { view, rootReal, taken, dirs, incomplete } = await this.diskWalk(mount, dir, recursive);
4171
+ const files = [];
4172
+ await inOrder(taken.filter((path) => keep === undefined || keep(path)), DIRECT_READS_AT_ONCE, (path) => observePath(view, rootReal, path), (seen, path) => {
4173
+ if (seen.kind === 'file')
4174
+ files.push({ path, size: seen.size });
4175
+ else if (seen.kind === 'unobserved')
4176
+ files.push({ path, note: seen.reason });
4177
+ });
4178
+ return { files, dirs, incomplete };
4179
+ }
4180
+ /**
4181
+ * A direct mount's walk of a scope, from its view (diskView): the entries
4182
+ * it took that aren't directories (files, links and the like), in path
4183
+ * order; the directories directly beneath a scope it doesn't descend; and
4184
+ * the regions it couldn't see that a pass reports beside no tracked file:
4185
+ * what it couldn't list, what the cap left, and a scope in another mount's
4186
+ * directory, said as a listing says it. A path the walk names is walked
4187
+ * whatever the mount's ignore list or an editor's file name covers there
4188
+ * (MountConfig.ignore), as a path sync's walk is.
4189
+ */
4190
+ async diskWalk(mount, dir, recursive) {
4191
+ const { view, rootReal, moved } = await this.diskView(mount);
4192
+ const walk = await walkScope(view, rootReal, dir, recursive, mount.config.walkCap ?? WALK_CAP, { named: true });
4193
+ const incomplete = walk.incomplete
4194
+ .filter((region) => region.kind === 'error' || region.kind === 'cap' || (region.kind === 'ignored' && region.path === dir && dir !== ''))
4195
+ .map((region) => ({
4196
+ path: region.path,
4197
+ reason: region.reason === OTHER_MOUNT ? this.otherMountNote(mount.config.name, region.path, 'list', moved) : region.reason,
4198
+ }));
4199
+ return {
4200
+ view,
4201
+ rootReal,
4202
+ taken: [...walk.files, ...walk.othersTaken].sort((a, b) => a.localeCompare(b)),
4203
+ // A walk that doesn't descend sees the scope's own subdirectories alone.
4204
+ dirs: recursive ? [] : [...walk.dirs],
4205
+ incomplete,
4206
+ };
4207
+ }
2992
4208
  async handleGlob(input) {
2993
4209
  const regex = globToRegex(input.pattern);
2994
4210
  const matches = [];
@@ -2996,21 +4212,27 @@ export class WorkspaceModule {
2996
4212
  // Search across mounts
2997
4213
  const mountsToSearch = input.path
2998
4214
  ? [await this.parsePath(input.path)]
2999
- : [...this.mounts.values()].map(m => ({ mount: m, relativePath: '' }));
4215
+ : [...this.mounts.values()].map(m => ({ mount: m, relativePath: '', moved: null, root: resolve(m.config.path) }));
4216
+ // The path is a directory to search in. One outside the mount's include
4217
+ // that's no scope (refusesAsOutside) is refused, as grep refuses it,
4218
+ // rather than searched and reported as matching nothing.
4219
+ if (input.path) {
4220
+ const { mount, relativePath, moved, root } = mountsToSearch[0];
4221
+ if (await this.refusesAsOutside(mount, relativePath, moved, root)) {
4222
+ return { success: false, error: new OutsideIncludeError(input.path, mount.config).message, isError: true };
4223
+ }
4224
+ }
3000
4225
  // Every match lies beneath the pattern's literal directory, so the walk
3001
4226
  // starts there: past the walk's cap, a walk of the whole scope can stop
3002
4227
  // before it gets there.
3003
4228
  const patternDir = literalDirOf(input.pattern);
3004
4229
  for (const { mount, relativePath } of mountsToSearch) {
3005
4230
  const start = await this.walkStart(mount, relativePath, patternDir);
3006
- const pass = await this.withMount(mount, () => this.passUnlocked(mount, { kind: 'dir', dir: start, recursive: true }));
3007
- for (const report of [...pass.reports.values()].sort((a, b) => a.path.localeCompare(b.path))) {
3008
- const testPath = relativePath ? report.path.slice(relativePath.length + 1) : report.path;
3009
- if (regex.test(testPath)) {
3010
- matches.push({ path: `${mount.config.name}/${report.path}`, ...stateView(report) });
3011
- }
3012
- }
3013
- for (const region of pass.incomplete) {
4231
+ const matched = (path) => regex.test(relativePath ? path.slice(relativePath.length + 1) : path);
4232
+ const listing = await this.listingOf(mount, start, true, matched);
4233
+ for (const { path, ...view } of listing.files)
4234
+ matches.push({ path: `${mount.config.name}/${path}`, ...view });
4235
+ for (const region of listing.incomplete) {
3014
4236
  incomplete.push({ path: `${mount.config.name}/${region.path}`, reason: region.reason });
3015
4237
  }
3016
4238
  }
@@ -3025,7 +4247,6 @@ export class WorkspaceModule {
3025
4247
  };
3026
4248
  }
3027
4249
  async handleGrep(input) {
3028
- const store = this.getStore();
3029
4250
  let regex;
3030
4251
  try {
3031
4252
  regex = new RegExp(input.pattern);
@@ -3043,7 +4264,15 @@ export class WorkspaceModule {
3043
4264
  const contextAfter = input.contextAfter ?? 0;
3044
4265
  const mountsToSearch = input.path
3045
4266
  ? [await this.parsePath(input.path)]
3046
- : [...this.mounts.values()].map(m => ({ mount: m, relativePath: '' }));
4267
+ : [...this.mounts.values()].map(m => ({ mount: m, relativePath: '', moved: null, root: resolve(m.config.path) }));
4268
+ // A path outside the mount's include that's no scope is refused, as read
4269
+ // refuses it, rather than searched and reported as holding no match.
4270
+ if (input.path) {
4271
+ const { mount, relativePath, moved, root } = mountsToSearch[0];
4272
+ if (await this.refusesAsOutside(mount, relativePath, moved, root)) {
4273
+ return { success: false, error: new OutsideIncludeError(input.path, mount.config).message, isError: true };
4274
+ }
4275
+ }
3047
4276
  const results = [];
3048
4277
  const skipped = [];
3049
4278
  const incomplete = [];
@@ -3063,12 +4292,13 @@ export class WorkspaceModule {
3063
4292
  }
3064
4293
  return found;
3065
4294
  };
3066
- for (const { mount, relativePath } of mountsToSearch) {
4295
+ for (const { mount, relativePath, moved, root } of mountsToSearch) {
3067
4296
  // A path named in another mount's directory, as holderOf resolves it,
3068
4297
  // is that mount's: grep searches nothing of this mount's there, and
3069
- // says whose it is.
3070
- if (this.holderOf(mount.config.name, relativePath)) {
3071
- incomplete.push({ path: `${mount.config.name}/${relativePath}`, reason: this.otherMountNote(mount.config.name, relativePath, 'list') });
4298
+ // says whose it is. A direct mount's is judged by the nesting its parse
4299
+ // found where its root lies now (movedNesting).
4300
+ if (this.holderOf(mount.config.name, relativePath, false, moved)) {
4301
+ incomplete.push({ path: `${mount.config.name}/${relativePath}`, reason: this.otherMountNote(mount.config.name, relativePath, 'list', moved) });
3072
4302
  continue;
3073
4303
  }
3074
4304
  // A `path` and a filter whose directories don't overlap leave no file
@@ -3077,116 +4307,17 @@ export class WorkspaceModule {
3077
4307
  if (deeper === null)
3078
4308
  continue;
3079
4309
  const start = await this.walkStart(mount, relativePath, deeper === relativePath ? '' : deeper.slice(relativePath ? relativePath.length + 1 : 0));
3080
- await this.withMount(mount, async () => {
3081
- // A `path` naming a single file greps just that file; otherwise it is a
3082
- // directory prefix. (A file path once produced the prefix "notes.md/"
3083
- // and silently matched nothing.)
3084
- const fileScope = relativePath !== '' && (store.treeGet(mount.treeStateId, relativePath) !== null ||
3085
- await lstat(join(mount.config.path, relativePath)).then((s) => !s.isDirectory(), () => false));
3086
- // What follows reads the tree and branch intent to go with the pass's
3087
- // reports, synchronously. They must be the branch the pass decided
3088
- // on: one selected in between would label its content with the other
3089
- // branch's states. So a pass whose branch is no longer selected runs
3090
- // again, and a branch that keeps changing leaves the scope unsearched.
3091
- //
3092
- // A copy held at a path that now leads into a nested mount's directory
3093
- // through a link is that mount's file too: read refuses it
3094
- // (parseFilePath), so grep searches none of it and says why. The pass
3095
- // can't check such a path's disk, so only an unverified one can be
3096
- // one. Asking awaits disk, so it's done before the branch is
3097
- // compared, and a branch selected meanwhile runs the pass again.
3098
- let pass = null;
3099
- let refused = new Map();
3100
- for (let attempt = 0; attempt < 3 && pass === null; attempt++) {
3101
- const next = await this.passUnlocked(mount, fileScope
3102
- ? { kind: 'paths', paths: [relativePath] }
3103
- : { kind: 'dir', dir: start, recursive: true });
3104
- const asked = new Map();
3105
- for (const report of next.reports.values()) {
3106
- if (report.state !== 'unverified')
3107
- continue;
3108
- const refusal = await this.leadsIntoNested(mount, report.path, `${mount.config.name}/${report.path}`);
3109
- if (refusal)
3110
- asked.set(report.path, refusal.message);
3111
- }
3112
- if (next.branchId === undefined || next.branchId === store.currentBranch().id) {
3113
- pass = next;
3114
- refused = asked;
3115
- }
3116
- }
3117
- if (pass === null) {
3118
- incomplete.push({
3119
- path: `${mount.config.name}/${relativePath}`,
3120
- reason: 'the selected branch kept changing while grep ran; nothing here was searched — grep again',
3121
- });
3122
- return;
3123
- }
3124
- for (const region of pass.incomplete) {
3125
- incomplete.push({ path: `${mount.config.name}/${region.path}`, reason: region.reason });
3126
- }
3127
- const intents = this.intents.get(mount.config.name);
3128
- for (const report of [...pass.reports.values()].sort((a, b) => a.path.localeCompare(b.path))) {
3129
- if (fileGlob && !fileGlob.test(report.path))
3130
- continue;
3131
- const file = `${mount.config.name}/${report.path}`;
3132
- if (report.state === 'disk-only') {
3133
- skipped.push({
3134
- file,
3135
- reason: 'disk-only: binary or over the size limit, never stored',
3136
- ...(report.size !== undefined ? { size: report.size } : {}),
3137
- ...(report.mimeType ? { mimeType: report.mimeType } : {}),
3138
- });
3139
- continue;
3140
- }
3141
- // A path in another mount's directory is that mount's: grep gives
3142
- // none of this mount's copy of it, as read refuses it. Beneath a
3143
- // scope it's passed over by design, like the directory.
3144
- if (inOtherMount(report.path, this.othersOf(mount.config.name)))
3145
- continue;
3146
- const refusal = refused.get(report.path);
3147
- if (refusal !== undefined) {
3148
- skipped.push({ file, reason: refusal });
3149
- continue;
3150
- }
3151
- // The workspace's version, labelled with the path's state.
3152
- const entry = store.treeGet(mount.treeStateId, report.path);
3153
- const blob = entry ? store.getBlob(entry.blobHash) : null;
3154
- if (blob) {
3155
- const found = search(blob.toString('utf-8'));
3156
- if (found.length > 0)
3157
- results.push({ file, state: report.state, version: 'workspace', matches: found });
3158
- }
3159
- else if (entry) {
3160
- skipped.push({ file, reason: 'the workspace copy is missing from the store, so it was not searched' });
3161
- }
3162
- if (report.state !== 'conflict')
3163
- continue;
3164
- // A conflict's disk side. The version recorded with the conflict is
3165
- // disk's only while disk still holds it; once disk has changed
3166
- // since, it is labelled as recorded, and a file disk holds now
3167
- // (never stored) is listed as not searched. A binary or oversize
3168
- // disk version was never stored either.
3169
- const disk = intents.get(report.path)?.conflict?.disk;
3170
- const changed = report.conflict?.diskChangedSinceRecorded === true;
3171
- const diskBlob = disk?.stored ? store.getBlob(disk.stored) : null;
3172
- if (diskBlob) {
3173
- const found = search(diskBlob.toString('utf-8'));
3174
- if (found.length > 0)
3175
- results.push({ file, state: report.state, version: changed ? 'recorded-disk' : 'conflicting-disk', matches: found });
3176
- }
3177
- if (disk?.stored && !diskBlob) {
3178
- skipped.push({ file, reason: 'conflict: the disk version recorded with the conflict is missing from the store, so it was not searched' });
3179
- }
3180
- if (changed) {
3181
- if (report.diskNow === 'file') {
3182
- skipped.push({ file, reason: 'conflict: disk changed since the conflict was recorded; grep searches stored text, so the file disk holds now was not searched' });
3183
- }
3184
- }
3185
- else if (disk && !disk.stored) {
3186
- skipped.push({ file, reason: 'conflict: the disk version is binary or over the size limit, never stored', size: disk.size });
3187
- }
3188
- }
3189
- });
4310
+ const searched = (text) => {
4311
+ const matches = search(text.text);
4312
+ if (matches.length > 0)
4313
+ results.push({ file: text.file, ...(text.state !== undefined ? { state: text.state } : {}), version: text.version, matches });
4314
+ };
4315
+ const kept = (path) => fileGlob === null || fileGlob.test(path);
4316
+ const found = mount.direct
4317
+ ? await this.textsFromDisk(mount, relativePath, root, start, kept, searched)
4318
+ : await this.textsFromStore(mount, relativePath, start, kept, searched);
4319
+ skipped.push(...found.skipped);
4320
+ incomplete.push(...found.incomplete);
3190
4321
  }
3191
4322
  return {
3192
4323
  success: true,
@@ -3199,6 +4330,164 @@ export class WorkspaceModule {
3199
4330
  },
3200
4331
  };
3201
4332
  }
4333
+ /**
4334
+ * The texts a 'chronicle' mount's grep searches beneath `start`, or in the
4335
+ * single file `relativePath` names, those `keep` lets through, each handed
4336
+ * to `each` in path order: a pass over the scope, then each path's
4337
+ * workspace copy, labelled with its state, and a conflict's disk side.
4338
+ * What it doesn't search is in `skipped`, and what it couldn't see in
4339
+ * `incomplete`, each mount-prefixed.
4340
+ */
4341
+ async textsFromStore(mount, relativePath, start, keep, each) {
4342
+ const store = this.getStore();
4343
+ const skipped = [];
4344
+ const incomplete = [];
4345
+ await this.withMount(mount, async () => {
4346
+ // A `path` naming a single file greps just that file; otherwise it is a
4347
+ // directory prefix. (A file path once produced the prefix "notes.md/"
4348
+ // and silently matched nothing.)
4349
+ const fileScope = await this.namesFile(mount, relativePath, resolve(mount.config.path));
4350
+ // What follows reads the tree and branch intent to go with the pass's
4351
+ // reports, synchronously. They must be the branch the pass decided
4352
+ // on: one selected in between would label its content with the other
4353
+ // branch's states. So a pass whose branch is no longer selected runs
4354
+ // again, and a branch that keeps changing leaves the scope unsearched.
4355
+ //
4356
+ // A copy held at a path that now leads into a nested mount's directory
4357
+ // through a link is that mount's file too, and one that now lands on a
4358
+ // file this mount's include leaves out is no file of this mount's:
4359
+ // read refuses either (parseFilePath), so grep searches none of it and
4360
+ // says why. The pass
4361
+ // can't check such a path's disk, so only an unverified one can be
4362
+ // one. Asking awaits disk, so it's done before the branch is
4363
+ // compared, and a branch selected meanwhile runs the pass again.
4364
+ let pass = null;
4365
+ let refused = new Map();
4366
+ for (let attempt = 0; attempt < 3 && pass === null; attempt++) {
4367
+ const next = await this.passUnlocked(mount, fileScope
4368
+ ? { kind: 'paths', paths: [relativePath] }
4369
+ : { kind: 'dir', dir: start, recursive: true });
4370
+ const asked = new Map();
4371
+ for (const report of next.reports.values()) {
4372
+ if (report.state !== 'unverified')
4373
+ continue;
4374
+ const refusal = await this.landingRefusal(mount, report.path, `${mount.config.name}/${report.path}`, this.nestedOf(mount.config.name), resolve(mount.config.path));
4375
+ if (refusal)
4376
+ asked.set(report.path, refusal.message);
4377
+ }
4378
+ if (next.branchId === undefined || next.branchId === store.currentBranch().id) {
4379
+ pass = next;
4380
+ refused = asked;
4381
+ }
4382
+ }
4383
+ if (pass === null) {
4384
+ incomplete.push({
4385
+ path: `${mount.config.name}/${relativePath}`,
4386
+ reason: 'the selected branch kept changing while grep ran; nothing here was searched — grep again',
4387
+ });
4388
+ return;
4389
+ }
4390
+ for (const region of pass.incomplete) {
4391
+ incomplete.push({ path: `${mount.config.name}/${region.path}`, reason: region.reason });
4392
+ }
4393
+ const intents = this.intents.get(mount.config.name);
4394
+ for (const report of [...pass.reports.values()].sort((a, b) => a.path.localeCompare(b.path))) {
4395
+ if (!keep(report.path))
4396
+ continue;
4397
+ const file = `${mount.config.name}/${report.path}`;
4398
+ if (report.state === 'disk-only') {
4399
+ skipped.push({
4400
+ file,
4401
+ reason: 'disk-only: binary or over the size limit, never stored',
4402
+ ...(report.size !== undefined ? { size: report.size } : {}),
4403
+ ...(report.mimeType ? { mimeType: report.mimeType } : {}),
4404
+ });
4405
+ continue;
4406
+ }
4407
+ // A path in another mount's directory is that mount's: grep gives
4408
+ // none of this mount's copy of it, as read refuses it. Beneath a
4409
+ // scope it's passed over by design, like the directory.
4410
+ if (inOtherMount(report.path, this.othersOf(mount.config.name)))
4411
+ continue;
4412
+ const refusal = refused.get(report.path);
4413
+ if (refusal !== undefined) {
4414
+ skipped.push({ file, reason: refusal });
4415
+ continue;
4416
+ }
4417
+ // The workspace's version, labelled with the path's state.
4418
+ const entry = store.treeGet(mount.treeStateId, report.path);
4419
+ const blob = entry ? store.getBlob(entry.blobHash) : null;
4420
+ if (blob) {
4421
+ each({ file, state: report.state, version: 'workspace', text: blob.toString('utf-8') });
4422
+ }
4423
+ else if (entry) {
4424
+ skipped.push({ file, reason: 'the workspace copy is missing from the store, so it was not searched' });
4425
+ }
4426
+ if (report.state !== 'conflict')
4427
+ continue;
4428
+ // A conflict's disk side. The version recorded with the conflict is
4429
+ // disk's only while disk still holds it; once disk has changed
4430
+ // since, it is labelled as recorded, and a file disk holds now
4431
+ // (never stored) is listed as not searched. A binary or oversize
4432
+ // disk version was never stored either.
4433
+ const disk = intents.get(report.path)?.conflict?.disk;
4434
+ const changed = report.conflict?.diskChangedSinceRecorded === true;
4435
+ const diskBlob = disk?.stored ? store.getBlob(disk.stored) : null;
4436
+ if (diskBlob) {
4437
+ each({ file, state: report.state, version: changed ? 'recorded-disk' : 'conflicting-disk', text: diskBlob.toString('utf-8') });
4438
+ }
4439
+ if (disk?.stored && !diskBlob) {
4440
+ skipped.push({ file, reason: 'conflict: the disk version recorded with the conflict is missing from the store, so it was not searched' });
4441
+ }
4442
+ if (changed) {
4443
+ if (report.diskNow === 'file') {
4444
+ skipped.push({ file, reason: 'conflict: disk changed since the conflict was recorded; grep searches stored text, so the file disk holds now was not searched' });
4445
+ }
4446
+ }
4447
+ else if (disk && !disk.stored) {
4448
+ skipped.push({ file, reason: 'conflict: the disk version is binary or over the size limit, never stored', size: disk.size });
4449
+ }
4450
+ }
4451
+ });
4452
+ return { skipped, incomplete };
4453
+ }
4454
+ /**
4455
+ * The texts a direct mount's grep searches beneath `start`, or in the
4456
+ * single file `relativePath` names, as namesFile judges it beneath `root`,
4457
+ * the root grep's parse resolved, those `keep` lets through, each handed
4458
+ * to `each` in path order: each file its walk took (diskWalk), read from
4459
+ * disk as it is now, DIRECT_READS_AT_ONCE at a time. A file over the size
4460
+ * limit, a binary one and one the mount doesn't take are in `skipped`,
4461
+ * each with why, as a 'chronicle' mount's grep lists what it never stored;
4462
+ * one gone since the walk listed it isn't there to search.
4463
+ */
4464
+ async textsFromDisk(mount, relativePath, root, start, keep, each) {
4465
+ const name = mount.config.name;
4466
+ const fileScope = await this.namesFile(mount, relativePath, root);
4467
+ const { view, rootReal, taken, incomplete } = fileScope
4468
+ ? { ...(await this.diskView(mount)), taken: [relativePath], incomplete: [] }
4469
+ : await this.diskWalk(mount, start, true);
4470
+ const maxSize = mount.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
4471
+ const skipped = [];
4472
+ await inOrder(taken.filter(keep), DIRECT_READS_AT_ONCE, (path) => readBytes(view, rootReal, path, maxSize), (read, path) => {
4473
+ const file = `${name}/${path}`;
4474
+ if (read.kind === 'absent')
4475
+ return;
4476
+ if (read.kind === 'unobserved') {
4477
+ skipped.push({ file, reason: read.reason });
4478
+ return;
4479
+ }
4480
+ const mimeType = sniffImageMime(read.head);
4481
+ const what = { size: read.size, ...(mimeType ? { mimeType } : {}) };
4482
+ if (read.bytes === null)
4483
+ skipped.push({ file, reason: `over the size limit (${maxSize} bytes)`, ...what });
4484
+ else if (looksBinary(read.head))
4485
+ skipped.push({ file, reason: 'binary: a NUL in its first 8 KB', ...what });
4486
+ else
4487
+ each({ file, version: 'disk', text: read.bytes.toString('utf-8') });
4488
+ });
4489
+ return { skipped, incomplete: incomplete.map((region) => ({ path: `${name}/${region.path}`, reason: region.reason })) };
4490
+ }
3202
4491
  async handleStatus(input) {
3203
4492
  const store = this.getStore();
3204
4493
  const status = {};
@@ -3208,24 +4497,29 @@ export class WorkspaceModule {
3208
4497
  for (const [name, mount] of this.mounts) {
3209
4498
  if (input.mount !== undefined && name !== input.mount)
3210
4499
  continue;
3211
- const entries = store.treeList(mount.treeStateId);
4500
+ if (mount.direct) {
4501
+ // A direct mount keeps nothing to count: its kind, and the ignore
4502
+ // list its walks go by, whose default no config shows.
4503
+ status[name] = { path: mount.config.path, mode: mount.config.mode, backend: 'direct', ignore: this.ignoreOf(mount) };
4504
+ continue;
4505
+ }
4506
+ // What the workspace's history holds outside the mount's include isn't the mount's,
4507
+ // and nor is what it holds in a nested mount's directory that mount's include leaves
4508
+ // out (withinIncludes), which no listing names either.
4509
+ const listable = { include: mount.config.include, nested: this.nestedOf(name) };
4510
+ const entries = store.treeList(mount.treeStateId).filter((e) => withinIncludes(listable, e.path));
3212
4511
  const currentSeq = store.currentSequence();
3213
- const own = this.ownPaths(mount);
3214
- const intents = this.intents.get(name).list().filter(([p]) => own(p));
3215
- const conflictPaths = intents.filter(([, bi]) => bi.conflict).map(([p]) => p);
3216
- // A workspace deletion is pending until a push confirms it on disk:
3217
- // left there without applyDeletions, or unlinked but unconfirmed.
3218
- const deletionPaths = intents.filter(([, bi]) => bi.tombstone).map(([p]) => p);
3219
- // Pending is what disk owes by the evidence: every entry it doesn't
3220
- // show on disk (a refused or failed push stays owed), conflicts and
3221
- // deletions. An entry from before the evidence isn't counted until a
3222
- // listing or a materialize checks it: unchecked isn't unpushed.
3223
- const pending = new Set([...conflictPaths, ...deletionPaths, ...this.entriesByEvidence(mount).owed]);
4512
+ const { conflicts: conflictPaths, deletions: deletionPaths, owed } = this.heldChanges(mount);
4513
+ const pending = new Set([...conflictPaths, ...deletionPaths, ...owed]);
3224
4514
  const currentBranch = store.currentBranch();
3225
4515
  status[name] = {
3226
4516
  path: mount.config.path,
3227
4517
  mode: mount.config.mode,
3228
- watch: mount.config.watch ?? 'always',
4518
+ // A mount configured direct runs as 'chronicle' this session
4519
+ // (chooseKinds), by the direct kind's ignore list where its config
4520
+ // names none.
4521
+ ...(mount.config.backend === 'direct' ? { backend: 'chronicle', ignore: this.ignoreOf(mount) } : {}),
4522
+ watch: watchOf(mount.config),
3229
4523
  fileCount: entries.length,
3230
4524
  lastMaterializedSeq: mount.lastMaterializedSeq,
3231
4525
  currentSeq,
@@ -3241,6 +4535,36 @@ export class WorkspaceModule {
3241
4535
  }
3242
4536
  return { success: true, data: status };
3243
4537
  }
4538
+ /**
4539
+ * What the store holds of a mount that disk lacks, on the selected branch,
4540
+ * among the mount's own paths. Status counts the first three as pending:
4541
+ * recorded conflicts; workspace deletions, pending until a push confirms
4542
+ * them on disk (left there without applyDeletions, or unlinked but
4543
+ * unconfirmed); and what disk owes by the evidence (entriesByEvidence's
4544
+ * `owed`: every entry it doesn't show on disk, a refused or failed push's
4545
+ * included). An entry from before the evidence isn't among them until a
4546
+ * listing or a materialize checks it: unchecked isn't unpushed. A
4547
+ * tombstone beside an entry that's still there, left by a deletion or a
4548
+ * write that stopped partway (commitToolChanges), is no deletion: it holds
4549
+ * no change disk lacks, and its entry is judged by the evidence as any
4550
+ * other is. The fourth, intents that can't be read, may hold a deletion
4551
+ * or a conflict, so a mount configured direct counts them too (initStore).
4552
+ * Each lies where the mount's include covers, as status counts them: what
4553
+ * the workspace's history holds outside it is no change of the mount's,
4554
+ * and no push writes it to disk (pushUnlocked).
4555
+ */
4556
+ heldChanges(mount) {
4557
+ const store = this.getStore();
4558
+ const own = this.ownPaths(mount);
4559
+ // What the workspace's history holds outside the mount's include isn't the mount's.
4560
+ const intents = this.intents.get(mount.config.name).list().filter(([p]) => insideMount(p, mount.config.include) && own(p));
4561
+ return {
4562
+ conflicts: intents.filter(([, bi]) => bi.conflict).map(([p]) => p),
4563
+ deletions: intents.filter(([p, bi]) => bi.tombstone && !store.treeGet(mount.treeStateId, p)).map(([p]) => p),
4564
+ owed: this.entriesByEvidence(mount).owed,
4565
+ unreadable: intents.filter(([, bi]) => bi.unreadable !== undefined).map(([p]) => p),
4566
+ };
4567
+ }
3244
4568
  /**
3245
4569
  * What a materialize of `mount` should consider: a named file, or every
3246
4570
  * tracked path beneath a named directory; otherwise what the evidence says
@@ -3271,18 +4595,26 @@ export class WorkspaceModule {
3271
4595
  const { owed, unchecked, agreed } = this.entriesByEvidence(mount);
3272
4596
  for (const path of [...owed, ...unchecked])
3273
4597
  selected.add(path);
3274
- for (const [p, bi] of intents)
3275
- if (bi.conflict || bi.tombstone)
4598
+ // A tombstone is a deletion only where its entry is gone: one beside an
4599
+ // entry that's still there, left by a change that stopped partway
4600
+ // (commitToolChanges), would select an agreed entry, and a forced push
4601
+ // would write it over a newer disk copy. A deletion or conflict held
4602
+ // outside the mount's include isn't the mount's, as status counts it:
4603
+ // not taken up, so not reported skipped.
4604
+ for (const [p, bi] of intents) {
4605
+ if ((bi.conflict || (bi.tombstone && !store.treeGet(mount.treeStateId, p))) && insideMount(p, mount.config.include))
3276
4606
  selected.add(p);
4607
+ }
3277
4608
  return { paths: [...selected], inPlace: agreed > 0 };
3278
4609
  }
3279
4610
  /**
3280
4611
  * Whether a path of the mount is its own to push and to count as owed:
3281
4612
  * not in another mount's directory nested in it. Copies the mount's tree
3282
- * holds there (stored before the nesting) stay in its history and its
3283
- * listings (and in status's fileCount, which counts the tree), passed over
3284
- * by its syncs, and left out of what it pushes and of status's pending
3285
- * changes, conflicts and workspace deletions.
4613
+ * holds there (stored before the nesting) stay in its history, and in its
4614
+ * listings and status's fileCount where that mount's include covers them
4615
+ * (withinIncludes). Its syncs pass over them, and
4616
+ * they're left out of what it pushes and of status's pending changes,
4617
+ * conflicts and workspace deletions.
3286
4618
  */
3287
4619
  ownPaths(mount) {
3288
4620
  const others = this.othersOf(mount.config.name);
@@ -3310,7 +4642,9 @@ export class WorkspaceModule {
3310
4642
  let agreed = 0;
3311
4643
  const own = this.ownPaths(mount);
3312
4644
  for (const e of store.treeList(mount.treeStateId)) {
3313
- if (!own(e.path))
4645
+ // Outside the mount's include, or in another mount's directory nested
4646
+ // in it: neither owed to disk nor counted as on it.
4647
+ if (!insideMount(e.path, mount.config.include) || !own(e.path))
3314
4648
  continue;
3315
4649
  const p = agreement.get(name, e.path);
3316
4650
  if (p === undefined)
@@ -3333,8 +4667,16 @@ export class WorkspaceModule {
3333
4667
  const pendingDeletions = [];
3334
4668
  const modesKept = [];
3335
4669
  let explicit = null;
3336
- if (input.path)
3337
- explicit = await this.parsePath(input.path);
4670
+ if (input.path) {
4671
+ const parsed = await this.parsePath(input.path);
4672
+ explicit = parsed;
4673
+ // A path outside the mount's include that's no scope (refusesAsOutside)
4674
+ // is refused; beneath a directory, the push leaves out what the include
4675
+ // doesn't cover.
4676
+ if (await this.refusesAsOutside(parsed.mount, parsed.relativePath, parsed.moved, parsed.root)) {
4677
+ return { success: false, error: new OutsideIncludeError(input.path, explicit.mount.config).message, isError: true };
4678
+ }
4679
+ }
3338
4680
  let mountsToMaterialize;
3339
4681
  if (explicit) {
3340
4682
  mountsToMaterialize = [{ name: explicit.mount.config.name, mount: explicit.mount }];
@@ -3360,6 +4702,10 @@ export class WorkspaceModule {
3360
4702
  // whatever branch is current when its turn comes, unguarded. The push
3361
4703
  // then writes nothing if the branch changes after that.
3362
4704
  const blocked = [];
4705
+ // What the push left because the mount's include doesn't cover it is
4706
+ // counted, as a sync's passedOver counts it, and not named: no tool names
4707
+ // a file outside the include.
4708
+ const passedOver = [];
3363
4709
  const guarded = [];
3364
4710
  let proceeded = 0;
3365
4711
  for (const { name, mount } of mountsToMaterialize) {
@@ -3407,10 +4753,17 @@ export class WorkspaceModule {
3407
4753
  pendingDeletions.push({ mount: name, path: p });
3408
4754
  // Refusals ride the same skipped list as branch blocks: divergence must
3409
4755
  // be visible, not resolved silently either way.
4756
+ let outside = 0;
3410
4757
  for (const s of pushed.skipped) {
4758
+ if (s.reason === OUTSIDE_INCLUDE) {
4759
+ outside++;
4760
+ continue;
4761
+ }
3411
4762
  const reason = s.reason === NOT_PUSHED_IN_OTHER_MOUNT ? this.otherMountNote(name, s.path, 'push') : s.reason;
3412
4763
  blocked.push({ mount: name, reason: `${s.path}: ${reason}` });
3413
4764
  }
4765
+ if (outside > 0)
4766
+ passedOver.push({ mount: name, reason: OUTSIDE_INCLUDE, count: outside });
3414
4767
  // Written paths whose mode stayed as disk had it: no refusal, so not
3415
4768
  // among what was skipped.
3416
4769
  for (const k of pushed.modesKept)
@@ -3455,6 +4808,7 @@ export class WorkspaceModule {
3455
4808
  }
3456
4809
  : {}),
3457
4810
  ...(blocked.length > 0 ? { skipped: blocked } : {}),
4811
+ ...(passedOver.length > 0 ? { passedOver } : {}),
3458
4812
  ...(modesKept.length > 0 ? { modesKept } : {}),
3459
4813
  },
3460
4814
  // What disk lost, then what it was written: kept in the stub if the
@@ -3511,7 +4865,13 @@ export class WorkspaceModule {
3511
4865
  // A path names its own mount; otherwise the given mount, or every mount.
3512
4866
  let targets;
3513
4867
  if (input.path) {
3514
- const { mount, relativePath } = await this.parsePath(input.path);
4868
+ const { mount, relativePath, moved, root } = await this.parsePath(input.path);
4869
+ // A path outside the mount's include that's no scope (refusesAsOutside)
4870
+ // is refused; beneath a directory, the walk passes over what the include
4871
+ // doesn't cover.
4872
+ if (await this.refusesAsOutside(mount, relativePath, moved, root)) {
4873
+ return { success: false, error: new OutsideIncludeError(input.path, mount.config).message, isError: true };
4874
+ }
3515
4875
  targets = [{ name: mount.config.name, mount, relativePath }];
3516
4876
  }
3517
4877
  else if (input.mount) {
@@ -3525,6 +4885,12 @@ export class WorkspaceModule {
3525
4885
  targets = [...this.mounts.entries()].map(([name, mount]) => ({ name, mount, relativePath: '' }));
3526
4886
  }
3527
4887
  for (const { name, mount, relativePath } of targets) {
4888
+ // A direct mount's tools read disk as it is, so a sync has nothing to
4889
+ // take in there, and says it didn't look rather than that nothing changed.
4890
+ if (mount.direct) {
4891
+ allSkipped.push({ mount: name, path: relativePath, reason: DIRECT_SYNC_SKIPPED });
4892
+ continue;
4893
+ }
3528
4894
  const pass = await this.withMount(mount, async () => {
3529
4895
  if (input.acceptRoot && await this.acceptRootUnlocked(mount))
3530
4896
  rootsAccepted.push(name);
@@ -3602,7 +4968,7 @@ export class WorkspaceModule {
3602
4968
  // without a path passes over it, so nothing else keeps it current
3603
4969
  // (agent-framework #276). A path in another mount's directory isn't
3604
4970
  // synced at all, and the note says so.
3605
- const passedOver = passedOverAt(relativePath, mount.config.ignore ?? [], this.othersOf(name));
4971
+ const passedOver = passedOverAt(relativePath, this.ignoreOf(mount), this.othersOf(name));
3606
4972
  if (passedOver !== undefined) {
3607
4973
  allIgnored.push({
3608
4974
  mount: name,
@@ -3666,12 +5032,15 @@ export class WorkspaceModule {
3666
5032
  * The watcher's ops only choose which paths to look at: each path is
3667
5033
  * observed again and decided under the three-way rule, so an event that
3668
5034
  * arrives late or out of order can't delete or revert anything by itself.
5035
+ * A path outside the mount (insideMount), such as one its include doesn't
5036
+ * cover, is no pass's to decide (gather), so a batch of nothing else takes
5037
+ * no turn of the mount.
3669
5038
  */
3670
5039
  async handleFsChanges(mountName, changes) {
3671
5040
  const mount = this.mounts.get(mountName);
3672
5041
  if (!this.store || !this.running() || !mount)
3673
5042
  return;
3674
- const paths = [...new Set(changes.map((c) => c.path))];
5043
+ const paths = [...new Set(changes.map((c) => c.path))].filter((p) => insideMount(p, mount.config.include));
3675
5044
  if (paths.length === 0)
3676
5045
  return;
3677
5046
  await this.withMount(mount, () => this.passUnlocked(mount, { kind: 'paths', paths }));
@@ -3692,7 +5061,7 @@ export class WorkspaceModule {
3692
5061
  async onToolBatchComplete(_agentName) {
3693
5062
  // Every agent's workspace is the store's current branch, so the agent
3694
5063
  // that ran the batch doesn't choose what is scanned.
3695
- const mounts = [...this.mounts.values()].filter((m) => m.config.watch === 'on-agent-action');
5064
+ const mounts = [...this.mounts.values()].filter((m) => watchOf(m.config) === 'on-agent-action');
3696
5065
  if (mounts.length === 0 || !this.store || !this.running())
3697
5066
  return;
3698
5067
  const deadlineMs = this.agentActionScanDeadlineMs();
@@ -3837,6 +5206,46 @@ export class WorkspaceModule {
3837
5206
  }
3838
5207
  }
3839
5208
  }
5209
+ /**
5210
+ * Run `work` on each item, at most `width` at once, and hand each result to
5211
+ * `each` in the items' order, as soon as it and those before it are done.
5212
+ * A result handed on is let go, so what's held at once is at most `width`
5213
+ * results, as a direct grep's file contents are. A `work` that rejects
5214
+ * rejects this when its turn comes; any started after it finish unheard.
5215
+ * Exported for its tests.
5216
+ */
5217
+ export async function inOrder(items, width, work, each) {
5218
+ const waiting = [];
5219
+ let started = 0;
5220
+ for (let i = 0; i < items.length; i++) {
5221
+ while (started < items.length && started < i + width) {
5222
+ const running = work(items[started]);
5223
+ // Handled from the start, so a rejection that comes before its turn
5224
+ // isn't an unhandled one; awaiting it below still throws it.
5225
+ running.catch(() => { });
5226
+ waiting.push(running);
5227
+ started++;
5228
+ }
5229
+ each(await waiting.shift(), items[i]);
5230
+ }
5231
+ }
5232
+ /** read_image's answer for an image, wherever it was read from. */
5233
+ function imageResult(path, image) {
5234
+ return {
5235
+ success: true,
5236
+ data: [
5237
+ {
5238
+ type: 'text',
5239
+ text: `Path: ${path}\nMIME: ${image.mimeType}\nBytes: ${image.bytes.byteLength}`,
5240
+ },
5241
+ {
5242
+ type: 'image',
5243
+ data: image.bytes.toString('base64'),
5244
+ mimeType: image.mimeType,
5245
+ },
5246
+ ],
5247
+ };
5248
+ }
3840
5249
  /** What a listing shows of a path beyond its name. */
3841
5250
  function stateView(report) {
3842
5251
  return {
@@ -3852,6 +5261,104 @@ function stateView(report) {
3852
5261
  // ==========================================================================
3853
5262
  /** A lone UTF-16 surrogate, which UTF-8 can't store: in `u` mode, a pair is one code point. */
3854
5263
  const LONE_SURROGATE = /\p{Cs}/u;
5264
+ /** Why a direct mount's read stopped when it found another directory put at its root as it opened the file. */
5265
+ const DIRECT_ROOT_REPLACED = 'the mount root was replaced as the file was opened: reading it again reads the directory there now';
5266
+ /**
5267
+ * How the alert that a mount configured direct runs as 'chronicle' names an
5268
+ * intent the workspace can't read. A sync of its path settles it, with
5269
+ * disk's copy, or with none where disk has none, and where disk's file
5270
+ * can't be read it skips the path and says why. Materialize settles one
5271
+ * only where the workspace holds a copy there: a plain one skips it and says
5272
+ * to sync, a forced one writes the copy, and where the workspace holds none
5273
+ * it neither selects nor names it.
5274
+ */
5275
+ const UNREADABLE_INTENT = "its workspace intent can't be read; a sync of the path settles it or says why not";
5276
+ /**
5277
+ * A mount's watch mode as it runs. A mount configured direct watches
5278
+ * nothing, whichever kind it runs as this session: its config takes no
5279
+ * other mode (directRefusals), and leaving it out means 'never' there.
5280
+ */
5281
+ function watchOf(config) {
5282
+ return config.watch ?? (config.backend === 'direct' ? 'never' : 'always');
5283
+ }
5284
+ /**
5285
+ * What a direct mount's config sets that would never act there, each with
5286
+ * the way out (MountConfig.backend): a direct mount is read-only, and has no
5287
+ * watcher to tune, no change event to wake on and no push to make.
5288
+ */
5289
+ function directRefusals(mount) {
5290
+ const refused = [];
5291
+ if (mount.mode !== 'read-only') {
5292
+ refused.push(mount.mode === undefined ? "mode must be 'read-only' (left out, it's 'read-write')" : `mode must be 'read-only', not ${shownValue(mount.mode)}`);
5293
+ }
5294
+ if (mount.watch !== undefined && mount.watch !== 'never')
5295
+ refused.push(`watch ${shownValue(mount.watch)} would watch nothing (leave it out, or set 'never')`);
5296
+ for (const key of ['watchDebounceMs', 'watchRootPollMs']) {
5297
+ if (mount[key] !== undefined)
5298
+ refused.push(`${key} would tune no watcher (leave it out)`);
5299
+ }
5300
+ const wake = mount.wakeOnChange;
5301
+ if (wake === true || (Array.isArray(wake) && wake.length > 0))
5302
+ refused.push('wakeOnChange would never wake (leave it out)');
5303
+ if (mount.autoMaterialize === true)
5304
+ refused.push('autoMaterialize would never push (leave it out)');
5305
+ return refused;
5306
+ }
5307
+ /**
5308
+ * Whether a tree entry is what a change leaves: for a set, an entry with its
5309
+ * blob, size and mode; for a removal, none.
5310
+ */
5311
+ function holds(entry, change) {
5312
+ return change.kind === 'set'
5313
+ ? entry !== null && entry.blobHash === change.blobHash && entry.size === change.size && entry.mode === (change.mode ?? 0o644)
5314
+ : entry === null;
5315
+ }
5316
+ /**
5317
+ * Whether a store's set that threw recorded the changes anyway: every path
5318
+ * holds what its change leaves. The changes given are those the tree didn't
5319
+ * hold before the set, and one record takes all of them or none, so their
5320
+ * holding shows the record is in. Reading them back can fail too, and then
5321
+ * whether they're stored isn't known (CommitUnknownError).
5322
+ */
5323
+ function changesLanded(store, treeStateId, changes, setError) {
5324
+ try {
5325
+ return changes.every(({ path, change }) => holds(store.treeGet(treeStateId, path), change));
5326
+ }
5327
+ catch (readError) {
5328
+ throw new CommitUnknownError(setError, readError);
5329
+ }
5330
+ }
5331
+ /**
5332
+ * A store's set threw, and reading its entries back threw too, so whether the
5333
+ * change is stored isn't known. Its message says so after both errors.
5334
+ */
5335
+ class CommitUnknownError extends Error {
5336
+ setError;
5337
+ readError;
5338
+ constructor(setError, readError) {
5339
+ const text = (error) => (error instanceof Error ? error.message : String(error));
5340
+ super(`${text(setError)}; reading its entries back failed too (${text(readError)}), so whether the change is stored isn't known`);
5341
+ this.name = 'CommitUnknownError';
5342
+ this.setError = text(setError);
5343
+ this.readError = text(readError);
5344
+ }
5345
+ }
5346
+ /**
5347
+ * A store's set that threw after recording the change (changesLanded): the
5348
+ * entries are set and their intents follow, and the store's error goes on in
5349
+ * place of the push. `pushes` says whether the mount would have pushed the
5350
+ * change to disk, and `notes` are commitToolChanges' own, by path.
5351
+ */
5352
+ class StoredThenFailed extends Error {
5353
+ pushes;
5354
+ notes;
5355
+ constructor(storeError, pushes, notes) {
5356
+ super(storeError instanceof Error ? storeError.message : String(storeError));
5357
+ this.pushes = pushes;
5358
+ this.notes = notes;
5359
+ this.name = 'StoredThenFailed';
5360
+ }
5361
+ }
3855
5362
  /**
3856
5363
  * The answer to a write, edit or delete that the workspace stored but
3857
5364
  * couldn't finish: its push to disk didn't complete, or what follows the tree
@@ -3860,7 +5367,8 @@ const LONE_SURROGATE = /\p{Cs}/u;
3860
5367
  * and sending it again could apply it twice. The push's reason says what disk
3861
5368
  * holds and the way out, as materialize takes it. The text carries all of it,
3862
5369
  * since an error's data reaches neither the model nor a code_execution
3863
- * script. An edit's note on which copy it applied to comes last.
5370
+ * script. A note comes last: an edit's on which copy it applied to, or a
5371
+ * deletion's that it unlinked nothing.
3864
5372
  */
3865
5373
  function storedButUnfinished(tool, path, outcome, note = null) {
3866
5374
  const change = tool === 'delete' ? 'deletion' : tool;
@@ -3868,7 +5376,12 @@ function storedButUnfinished(tool, path, outcome, note = null) {
3868
5376
  + (tool === 'edit' ? ': a second edit can apply the change twice.' : '.');
3869
5377
  const rest = 'refused' in outcome
3870
5378
  ? ` Its push to disk didn't complete: ${outcome.refused}.`
3871
- : ` The rest of the call failed: ${outcome.threw}. ls shows the path's state.`;
5379
+ : 'storeFailed' in outcome
5380
+ ? ` The store failed after recording it: ${outcome.storeFailed}.` + (!outcome.pushes ? ''
5381
+ : tool === 'delete'
5382
+ ? ' Its push to disk didn\'t run, so disk keeps the file until a materialize of the path with applyDeletions deletes it.'
5383
+ : ' Its push to disk didn\'t run, so disk lacks the change until a materialize of the path writes it.')
5384
+ : ` The rest of the call failed: ${outcome.threw}. ls shows the path's state.`;
3872
5385
  return { success: false, isError: true, error: stored + rest + (note !== null ? ` ${note}` : '') };
3873
5386
  }
3874
5387
  /**
@@ -3889,15 +5402,18 @@ function linesOf(content) {
3889
5402
  const INPUT_MINIMUMS = {
3890
5403
  read: { offset: 1, limit: 1, offsetChars: 0, limitChars: 1 },
3891
5404
  grep: { contextBefore: 0, contextAfter: 0 },
5405
+ edit_many: { occurrences: 1 },
3892
5406
  };
3893
5407
  /**
3894
5408
  * Why a tool call's input doesn't fit its tool's schema, or null when it does:
3895
5409
  * an object, each required field present, and each field its schema calls a
3896
5410
  * string, a boolean or an integer of that type, an integer at least its
3897
- * minimum. The workspace's schemas use no other types. Without it, an edit
3898
- * missing `newString` wrote the word "undefined", and an offset of 1.5
3899
- * numbered lines 1.5, 2.5 and on. A field the schema doesn't describe is left
3900
- * to its handler.
5411
+ * minimum. A field it calls an array of objects is an array, and each of its
5412
+ * items is checked the same way against the items' schema, with the same
5413
+ * minimums (edit_many's edits). The workspace's schemas use no other types.
5414
+ * Without it, an edit missing `newString` wrote the word "undefined", and an
5415
+ * offset of 1.5 numbered lines 1.5, 2.5 and on. A field the schema doesn't
5416
+ * describe is left to its handler.
3901
5417
  */
3902
5418
  function inputProblem(schema, input, minimums = {}) {
3903
5419
  if (input === null || typeof input !== 'object' || Array.isArray(input)) {
@@ -3909,7 +5425,8 @@ function inputProblem(schema, input, minimums = {}) {
3909
5425
  return `"${name}" is required`;
3910
5426
  }
3911
5427
  for (const [name, value] of Object.entries(fields)) {
3912
- const type = schema.properties?.[name]?.type;
5428
+ const property = schema.properties?.[name];
5429
+ const type = property?.type;
3913
5430
  if (value === undefined || type === undefined)
3914
5431
  continue;
3915
5432
  const minimum = minimums[name];
@@ -3917,11 +5434,22 @@ function inputProblem(schema, input, minimums = {}) {
3917
5434
  : type === 'boolean' ? typeof value === 'boolean'
3918
5435
  : type === 'integer'
3919
5436
  ? Number.isSafeInteger(value) && (minimum === undefined || value >= minimum)
3920
- : true;
5437
+ : type === 'array' ? Array.isArray(value)
5438
+ : true;
5439
+ if (fits && type === 'array' && property?.items?.type === 'object') {
5440
+ for (const [i, item] of value.entries()) {
5441
+ const problem = item !== null && typeof item === 'object' && !Array.isArray(item)
5442
+ ? inputProblem(property.items, item, minimums)
5443
+ : 'it must be an object of the fields its schema lists';
5444
+ if (problem !== null)
5445
+ return `"${name}" item ${i + 1}: ${problem}`;
5446
+ }
5447
+ }
3921
5448
  if (!fits) {
3922
5449
  const wanted = type === 'string' ? 'a string'
3923
5450
  : type === 'boolean' ? 'true or false'
3924
- : minimum === undefined ? 'a whole number' : `a whole number of at least ${minimum}`;
5451
+ : type === 'array' ? 'an array'
5452
+ : minimum === undefined ? 'a whole number' : `a whole number of at least ${minimum}`;
3925
5453
  const got = value === null ? 'null'
3926
5454
  : typeof value === 'number' ? String(value)
3927
5455
  : Array.isArray(value) ? 'an array'