toolroll 0.9.134 → 0.9.135

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 (277) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/acp-check-repo-schema.js +52 -0
  3. package/dist/acp-check.js +1 -1
  4. package/dist/acp-client.js +3 -3
  5. package/dist/acp-inspect.js +2 -1
  6. package/dist/agent-detect.js +1 -1
  7. package/dist/agent-fence.js +4 -4
  8. package/dist/agent-thread/chat-turn.js +2 -2
  9. package/dist/agent-thread/direct-host.js +2 -2
  10. package/dist/agent-thread/fence.js +2 -2
  11. package/dist/agent-thread/git-workspace.js +2 -2
  12. package/dist/agent-thread/guards.js +1 -1
  13. package/dist/agent-thread/providers.js +1 -1
  14. package/dist/agent-thread/ship.js +2 -2
  15. package/dist/approval-decision.js +1 -0
  16. package/dist/approval-password.js +1 -1
  17. package/dist/approval-summary.js +1 -1
  18. package/dist/attest.js +1 -1
  19. package/dist/batch-checks.js +2 -2
  20. package/dist/boot-identity.js +1 -1
  21. package/dist/bounded-spawn.js +2 -2
  22. package/dist/browser/{chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +4 -4
  23. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.br +0 -0
  24. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.gz +0 -0
  25. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js +2 -0
  26. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.br +0 -0
  27. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.gz +0 -0
  28. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js +4 -0
  29. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.br +0 -0
  30. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.gz +0 -0
  31. package/dist/browser/{chunk-core.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js → chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js} +12 -12
  32. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.br +0 -0
  33. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.gz +0 -0
  34. package/dist/browser/{chunk-flow-view.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.js → chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js} +7 -7
  35. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.br +0 -0
  36. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.gz +0 -0
  37. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js +4 -0
  38. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.br +0 -0
  39. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.gz +0 -0
  40. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js +6 -0
  41. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.br +0 -0
  42. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.gz +0 -0
  43. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js +2 -0
  44. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.br +0 -0
  45. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.gz +0 -0
  46. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js +20 -0
  47. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.br +0 -0
  48. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.gz +0 -0
  49. package/dist/browser/{chunk-shared.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js → chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js} +2 -2
  50. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.br +0 -0
  51. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.gz +0 -0
  52. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js +2 -0
  53. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.br +0 -0
  54. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.gz +0 -0
  55. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js +2 -0
  56. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.br +0 -0
  57. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.gz +0 -0
  58. package/dist/browser/{chunk-shared.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js → chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js} +3 -3
  59. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.br +0 -0
  60. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.gz +0 -0
  61. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js +2 -0
  62. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.br +0 -0
  63. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.gz +0 -0
  64. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js +2 -0
  65. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.br +0 -0
  66. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.gz +0 -0
  67. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js +2 -0
  68. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.br +0 -0
  69. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.gz +0 -0
  70. package/dist/browser/{chunk-shared.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js → chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js} +3 -3
  71. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.br +0 -0
  72. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.gz +0 -0
  73. package/dist/browser/{chunk-sonner.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.js → chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js} +1 -1
  74. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.br +0 -0
  75. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.gz +0 -0
  76. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js +2 -0
  77. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.br +0 -0
  78. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.gz +0 -0
  79. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js +2 -0
  80. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.br +0 -0
  81. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.gz +0 -0
  82. package/dist/browser/manifest.json +194 -194
  83. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css +4 -0
  84. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.br +0 -0
  85. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.gz +0 -0
  86. package/dist/browser/{workspace.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.js → workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js} +4 -4
  87. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.br +0 -0
  88. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.gz +0 -0
  89. package/dist/browser-open.js +1 -1
  90. package/dist/build-review.js +2 -2
  91. package/dist/builder.js +21 -14
  92. package/dist/canvas-capture.js +2 -2
  93. package/dist/canvas-freshness.js +1 -1
  94. package/dist/central-recovery-stage.js +1 -1
  95. package/dist/chat-actions.js +3 -3
  96. package/dist/chat-decide.js +8 -4
  97. package/dist/cli-help.js +8 -7
  98. package/dist/cli.js +2 -2
  99. package/dist/companion/bonjour.js +1 -1
  100. package/dist/companion/daemon.js +1 -1
  101. package/dist/companion/passkey-gate.js +1 -1
  102. package/dist/companion/reads.js +1 -1
  103. package/dist/companion/store.js +1 -1
  104. package/dist/companion/webauthn.js +1 -1
  105. package/dist/companion/work.js +1 -1
  106. package/dist/container-state.js +2 -2
  107. package/dist/containment.js +2 -2
  108. package/dist/contracts/chat-actions.js +1 -1
  109. package/dist/contracts/console-api.js +1 -1
  110. package/dist/contracts/engine-api.js +1 -1
  111. package/dist/controller-supervisor.js +2 -2
  112. package/dist/credential-broker.js +1 -1
  113. package/dist/demo.js +2 -2
  114. package/dist/easy-start.js +1 -1
  115. package/dist/egress.js +1 -1
  116. package/dist/engine-handoff.js +1 -1
  117. package/dist/engine-reads.js +1 -1
  118. package/dist/evals.js +2 -2
  119. package/dist/exec.js +4 -4
  120. package/dist/fast-owner-schema.js +33 -0
  121. package/dist/fast-start.js +1 -1
  122. package/dist/flow-unattended.js +2 -2
  123. package/dist/github-import.js +1 -1
  124. package/dist/github-read.js +1 -1
  125. package/dist/install-mode.js +2 -3
  126. package/dist/invoke.js +9 -7
  127. package/dist/laptop-background.js +1 -1
  128. package/dist/lead-capabilities.js +1 -1
  129. package/dist/live-backup-change.js +2 -2
  130. package/dist/live-backup.js +2 -2
  131. package/dist/live-terminal.js +3 -3
  132. package/dist/local-checks.js +1 -1
  133. package/dist/local-landing.js +22 -3
  134. package/dist/local-owner.js +1 -1
  135. package/dist/machine-identity.js +1 -1
  136. package/dist/model-catalog.js +8 -5
  137. package/dist/model-choices.js +3 -3
  138. package/dist/model-routing.js +1 -1
  139. package/dist/models-cli.js +2 -2
  140. package/dist/names.js +1 -1
  141. package/dist/onboard.js +1 -1
  142. package/dist/operate-remote-arguments.js +1 -1
  143. package/dist/operate.js +33 -16
  144. package/dist/orphan-sweep.js +1 -1
  145. package/dist/owner-mode.js +4 -0
  146. package/dist/peek-cli.js +2 -2
  147. package/dist/phase-routing.js +1 -1
  148. package/dist/pi-build.js +1 -1
  149. package/dist/plane-review.js +1 -1
  150. package/dist/planner-source.js +2 -2
  151. package/dist/planner.js +1 -1
  152. package/dist/pre-run-phase.js +1 -1
  153. package/dist/presence-hold.js +1 -1
  154. package/dist/process-liveness.js +1 -1
  155. package/dist/process-tree.js +1 -1
  156. package/dist/project-tools.js +2 -2
  157. package/dist/prompt.js +1 -1
  158. package/dist/proposal.js +1 -1
  159. package/dist/protected-storage.js +2 -2
  160. package/dist/provider-home.js +1 -1
  161. package/dist/provider-limits.js +1 -1
  162. package/dist/provider.js +2 -2
  163. package/dist/public-access.js +1 -1
  164. package/dist/pull-request-flow.js +2 -2
  165. package/dist/read-executor.js +1 -1
  166. package/dist/release-adapters.js +2 -2
  167. package/dist/release-carry.js +3 -3
  168. package/dist/release-resume.js +2 -2
  169. package/dist/release-start.js +1 -0
  170. package/dist/result-follow-ups.js +2 -2
  171. package/dist/review-switch.js +1 -1
  172. package/dist/route-change.js +25 -3
  173. package/dist/run-closeout.js +2 -2
  174. package/dist/runner.js +1 -1
  175. package/dist/sandbox-launch.js +2 -2
  176. package/dist/sandbox-runtime.js +1 -1
  177. package/dist/scope.js +1 -1
  178. package/dist/scout-browser.js +1 -1
  179. package/dist/serve.js +3 -3
  180. package/dist/server/chat.js +1 -1
  181. package/dist/server/direct-chat.js +1 -1
  182. package/dist/server/engine-api.js +1 -1
  183. package/dist/server/http.js +1 -1
  184. package/dist/server/one-time-secret.js +1 -1
  185. package/dist/server/route-table.js +1 -1
  186. package/dist/server/runtime.js +1 -1
  187. package/dist/server/settings-phone.js +1 -1
  188. package/dist/server/settings-section-table.js +1 -1
  189. package/dist/server/settings-sections.js +1 -1
  190. package/dist/server/settings.js +2 -1
  191. package/dist/server/task-view-data.js +3 -3
  192. package/dist/server/task-views.js +1 -1
  193. package/dist/server/tasks.js +5 -5
  194. package/dist/server/terminals.js +1 -1
  195. package/dist/settings-data.js +1 -1
  196. package/dist/settings-proofs.js +1 -1
  197. package/dist/shared-deps.js +4 -4
  198. package/dist/sign-in-page.js +2 -2
  199. package/dist/ssr-workspace.js +88 -88
  200. package/dist/staged-runtimes.js +1 -1
  201. package/dist/status-probe.js +2 -2
  202. package/dist/stop-proof.js +2 -2
  203. package/dist/storage-sweep-child.js +2 -2
  204. package/dist/storage-sweep-process.js +1 -1
  205. package/dist/storage.js +2 -2
  206. package/dist/store-baseline.js +5 -33
  207. package/dist/store.js +19 -14
  208. package/dist/subscription-usage.js +3 -3
  209. package/dist/surface.js +1 -1
  210. package/dist/test-temp.js +1 -1
  211. package/dist/tool-broker.js +1 -1
  212. package/dist/toolroll-update.js +3 -3
  213. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  214. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  215. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  216. package/dist/tui/linux-x64/toolroll-tui +0 -0
  217. package/dist/tui-launch.js +1 -1
  218. package/dist/welcome-facts.js +1 -1
  219. package/package.json +1 -1
  220. package/dist/browser/chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js.br +0 -0
  221. package/dist/browser/chunk-agents-live-view.e97fbf607cb8075aad7a48664556d11ea41469785f82384b5171b76c524f71e2.js.gz +0 -0
  222. package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js +0 -2
  223. package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js.br +0 -0
  224. package/dist/browser/chunk-bundle.48f442a2868e9b77e9f54c5b77f1bba629ccd1615de8a2f62619b811783314f6.js.gz +0 -0
  225. package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js +0 -4
  226. package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js.br +0 -0
  227. package/dist/browser/chunk-chat-parts.1669e6985c5c0c11eea6792ea177ea4c9f7e7ebf27bd3b31742feb6a26d5b2a5.js.gz +0 -0
  228. package/dist/browser/chunk-core.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js.br +0 -0
  229. package/dist/browser/chunk-core.64343d638685133eb96578bfb35bf560f329d0743ac5deda720ae27f5699c9d9.js.gz +0 -0
  230. package/dist/browser/chunk-flow-view.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.js.br +0 -0
  231. package/dist/browser/chunk-flow-view.264e801af330461985aadcab42bc4ac4e036ba124394a7b5a100f2cd1edf89f0.js.gz +0 -0
  232. package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js +0 -4
  233. package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js.br +0 -0
  234. package/dist/browser/chunk-flows-extra-view.6761503a97e1f17b474703ff5687a8682c54f9db1715e0a9762a979030a1b036.js.gz +0 -0
  235. package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js +0 -6
  236. package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js.br +0 -0
  237. package/dist/browser/chunk-pages-bundle.365da73d009e3ced30b55bca7107f548dc832f7a9f52926d3dcd68aa5596da11.js.gz +0 -0
  238. package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js +0 -2
  239. package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js.br +0 -0
  240. package/dist/browser/chunk-result-view.d4dc562a1a6a52a1497e25300d5f80c220952ceb5bb719ca32ef8dc1e74a4124.js.gz +0 -0
  241. package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js +0 -20
  242. package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js.br +0 -0
  243. package/dist/browser/chunk-settings-view.ff302e1c5faf5486c96e5fc96fa32492da4153e6e19997ce7b718adab21bf3b7.js.gz +0 -0
  244. package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js +0 -2
  245. package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js.br +0 -0
  246. package/dist/browser/chunk-shared.152678a803cfb6dee935162fbbbdb38d031d80f1d32ce48610f37bc1c8621e49.js.gz +0 -0
  247. package/dist/browser/chunk-shared.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js.br +0 -0
  248. package/dist/browser/chunk-shared.26f6cbfdeb9bcd63231f23dbf96cacb39b78324aeed2503e86109efa89fa27db.js.gz +0 -0
  249. package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js +0 -2
  250. package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js.br +0 -0
  251. package/dist/browser/chunk-shared.4e21c6b33b9a525e63c360d20a1830f1a26c5021f5d218f2300f21ff840af27e.js.gz +0 -0
  252. package/dist/browser/chunk-shared.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js.br +0 -0
  253. package/dist/browser/chunk-shared.5b47ca221b8b77b26ce8006f0569c981df2b905005cebe9fc54444d4906d436e.js.gz +0 -0
  254. package/dist/browser/chunk-shared.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js.br +0 -0
  255. package/dist/browser/chunk-shared.85e1b9e0838ccc819e7b8368f80dd5240dda90f53ea2974a256a8fa4122ba2fb.js.gz +0 -0
  256. package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js +0 -2
  257. package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js.br +0 -0
  258. package/dist/browser/chunk-shared.a326d625dea5cda744678a73b38c0cb2688721c9228e26d262279ecd5c2d7d11.js.gz +0 -0
  259. package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js +0 -2
  260. package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js.br +0 -0
  261. package/dist/browser/chunk-shared.e906e9c8c0859e000616dbc382f88597447f30205c92b7cb9a8e2351f3ef2722.js.gz +0 -0
  262. package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js +0 -2
  263. package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js.br +0 -0
  264. package/dist/browser/chunk-shared.f6354151d62439f2d78f5d17cf9bc44f35b4da37685beb77467d98dd9cc6f1e4.js.gz +0 -0
  265. package/dist/browser/chunk-sonner.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.js.br +0 -0
  266. package/dist/browser/chunk-sonner.160372eb4f9455847ca83e8ff5d983c6b3010ef0dc2eaf541e2eaceaac3b994c.js.gz +0 -0
  267. package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js +0 -2
  268. package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js.br +0 -0
  269. package/dist/browser/chunk-task-view.325b506afc26b25147b2e90cec5ad1392d50e6150a7fb33c81a996daa99bb05a.js.gz +0 -0
  270. package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js +0 -2
  271. package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js.br +0 -0
  272. package/dist/browser/chunk-team-chat.d560bcc5d819e63133d377b8a6f10f901356e680771f19d4fe1af044adfffb22.js.gz +0 -0
  273. package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css +0 -4
  274. package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css.br +0 -0
  275. package/dist/browser/workspace.ac1270b58f672fa920535348cc582f5fc68247b341d6fc8ec733b25336f2b9cc.css.gz +0 -0
  276. package/dist/browser/workspace.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.js.br +0 -0
  277. package/dist/browser/workspace.efd01c3aaf8e07c4a64194e2bfbd7aee4f7fa515f2acebdfdd90af1badba8ce7.js.gz +0 -0
@@ -1,4 +1,4 @@
1
- import{randomBytes,randomUUID}from"node:crypto";import{lstatSync,mkdirSync,readdirSync,realpathSync,rmSync}from"node:fs";import{hostname}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{Worker}from"node:worker_threads";import{checkBackupFolder,databaseTag}from"./backup.js";import{holdLiveBackup,liveBackupState,recordLiveBackup,releaseLiveBackup}from"./store.js";import{LIVE_FULL_CHECK_EVERY_MS,liveCheckOf,MARKER_SOURCE,markerOffThread,newLiveCopyMemory,QUICK_SUFFIX}from"./live-backup-change.js";const LIVE_DAILY_DAYS=7,LEASE_MS=15*6e4;export function defaultLiveFolder(databaseFile){let database=resolve(databaseFile);try{database=realpathSync(database)}catch(error){if(error.code!=="ENOENT")throw error}let at=dirname(database);try{at=realpathSync(at)}catch{}return join(at,"backups","live")}export const liveFolderOf=(settings,databaseFile)=>settings.folder??defaultLiveFolder(databaseFile);export function liveFolderProblem(folder,forbidden,protectedRoot){const said=checkBackupFolder(folder,forbidden);if(said!==null)return said;if(protectedRoot!==void 0){const rel=relative(resolve(protectedRoot),resolve(folder));if(rel===".."||rel.startsWith("../")||rel.startsWith("..\\")||isAbsolute(rel))return`Choose a location inside the protected backup folder ${protectedRoot}.`}let stat;try{stat=lstatSync(folder)}catch{return null}if(stat.isSymbolicLink()||!stat.isDirectory())return`${folder} isn't a plain folder.`;if(typeof process.getuid=="function"&&stat.uid!==process.getuid())return`${folder} belongs to another user.`;if((stat.mode&18)!==0)return`Other users can write to ${folder}.`;let real;try{real=realpathSync(folder)}catch{return`${folder} can't be read.`}return real!==resolve(folder)?`${folder} goes through a link; choose its real path (${real}).`:null}const NAME=tag=>new RegExp(`^live-${tag}-(\\d{4}-\\d{2}-\\d{2})-(\\d{6})(?:-(\\d+))?(?:\\.quick)?\\.db$`),PARTIAL=tag=>new RegExp(`^\\.live-${tag}-.*\\.partial$`),stampOf=now=>now.toISOString().replace(/\.\d+Z$/,"").replace("T","-").replace(/:/g,"");export function liveCopies(folder,tag){let names;try{names=readdirSync(folder)}catch{return[]}const pattern=NAME(tag);return names.flatMap(name=>{const m=pattern.exec(name);if(m===null)return[];try{if(!lstatSync(join(folder,name)).isFile())return[]}catch{return[]}const time=m[2],madeAt=`${m[1]}T${time.slice(0,2)}:${time.slice(2,4)}:${time.slice(4,6)}.000Z`;return[{name,path:join(folder,name),day:m[1],check:liveCheckOf(name),madeAt,order:`${m[1]}-${m[2]}-${(m[3]??"1").padStart(6,"0")}`}]}).sort((a,b)=>a.order<b.order?1:a.order>b.order?-1:0).map(({name,path,day,check,madeAt})=>({name,path,day,check,madeAt}))}export function lastFullCheckAt(folder,tag){return liveCopies(folder,tag).find(one=>one.check==="integrity")?.madeAt??null}export function pruneLiveCopies(folder,tag,keep,now,protect){const copies=liveCopies(folder,tag),kept=new Set(copies.slice(0,Math.max(1,keep)).map(one=>one.path)),oldest=new Date(now.getTime()-(LIVE_DAILY_DAYS-1)*864e5).toISOString().slice(0,10),days=new Set;for(const one of copies)one.day>=oldest&&!days.has(one.day)&&(days.add(one.day),kept.add(one.path));for(const one of typeof protect=="string"||protect===null?[protect]:protect)one!==null&&kept.add(resolve(one));let removed=0;for(const one of copies)if(!kept.has(one.path))try{rmSync(one.path),removed++}catch{}try{for(const name of readdirSync(folder).filter(one=>PARTIAL(tag).test(one))){const path=join(folder,name),stat=lstatSync(path);stat.isFile()&&now.getTime()-stat.mtimeMs>60*6e4&&rmSync(path,{force:!0})}}catch{}return removed}const COPY_THREAD=`
1
+ import{randomBytes,randomUUID}from"node:crypto";import{lstatSync,mkdirSync,readdirSync,realpathSync,rmSync}from"node:fs";import{hostname}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{Worker}from"node:worker_threads";import{checkBackupFolder,databaseTag}from"./backup.js";import{holdLiveBackup,liveBackupState,recordLiveBackup,releaseLiveBackup}from"./store.js";import{LIVE_FULL_CHECK_EVERY_MS,liveCheckOf,MARKER_SOURCE,markerOffThread,newLiveCopyMemory,QUICK_SUFFIX}from"./live-backup-change.js";import{withoutLeadTokenEnv}from"./names.js";const LIVE_DAILY_DAYS=7,LEASE_MS=15*6e4;export function defaultLiveFolder(databaseFile){let database=resolve(databaseFile);try{database=realpathSync(database)}catch(error){if(error.code!=="ENOENT")throw error}let at=dirname(database);try{at=realpathSync(at)}catch{}return join(at,"backups","live")}export const liveFolderOf=(settings,databaseFile)=>settings.folder??defaultLiveFolder(databaseFile);export function liveFolderProblem(folder,forbidden,protectedRoot){const said=checkBackupFolder(folder,forbidden);if(said!==null)return said;if(protectedRoot!==void 0){const rel=relative(resolve(protectedRoot),resolve(folder));if(rel===".."||rel.startsWith("../")||rel.startsWith("..\\")||isAbsolute(rel))return`Choose a location inside the protected backup folder ${protectedRoot}.`}let stat;try{stat=lstatSync(folder)}catch{return null}if(stat.isSymbolicLink()||!stat.isDirectory())return`${folder} isn't a plain folder.`;if(typeof process.getuid=="function"&&stat.uid!==process.getuid())return`${folder} belongs to another user.`;if((stat.mode&18)!==0)return`Other users can write to ${folder}.`;let real;try{real=realpathSync(folder)}catch{return`${folder} can't be read.`}return real!==resolve(folder)?`${folder} goes through a link; choose its real path (${real}).`:null}const NAME=tag=>new RegExp(`^live-${tag}-(\\d{4}-\\d{2}-\\d{2})-(\\d{6})(?:-(\\d+))?(?:\\.quick)?\\.db$`),PARTIAL=tag=>new RegExp(`^\\.live-${tag}-.*\\.partial$`),stampOf=now=>now.toISOString().replace(/\.\d+Z$/,"").replace("T","-").replace(/:/g,"");export function liveCopies(folder,tag){let names;try{names=readdirSync(folder)}catch{return[]}const pattern=NAME(tag);return names.flatMap(name=>{const m=pattern.exec(name);if(m===null)return[];try{if(!lstatSync(join(folder,name)).isFile())return[]}catch{return[]}const time=m[2],madeAt=`${m[1]}T${time.slice(0,2)}:${time.slice(2,4)}:${time.slice(4,6)}.000Z`;return[{name,path:join(folder,name),day:m[1],check:liveCheckOf(name),madeAt,order:`${m[1]}-${m[2]}-${(m[3]??"1").padStart(6,"0")}`}]}).sort((a,b)=>a.order<b.order?1:a.order>b.order?-1:0).map(({name,path,day,check,madeAt})=>({name,path,day,check,madeAt}))}export function lastFullCheckAt(folder,tag){return liveCopies(folder,tag).find(one=>one.check==="integrity")?.madeAt??null}export function pruneLiveCopies(folder,tag,keep,now,protect){const copies=liveCopies(folder,tag),kept=new Set(copies.slice(0,Math.max(1,keep)).map(one=>one.path)),oldest=new Date(now.getTime()-(LIVE_DAILY_DAYS-1)*864e5).toISOString().slice(0,10),days=new Set;for(const one of copies)one.day>=oldest&&!days.has(one.day)&&(days.add(one.day),kept.add(one.path));for(const one of typeof protect=="string"||protect===null?[protect]:protect)one!==null&&kept.add(resolve(one));let removed=0;for(const one of copies)if(!kept.has(one.path))try{rmSync(one.path),removed++}catch{}try{for(const name of readdirSync(folder).filter(one=>PARTIAL(tag).test(one))){const path=join(folder,name),stat=lstatSync(path);stat.isFile()&&now.getTime()-stat.mtimeMs>60*6e4&&rmSync(path,{force:!0})}}catch{}return removed}const COPY_THREAD=`
2
2
  const { workerData, parentPort } = require("node:worker_threads");
3
3
  const { DatabaseSync, backup } = require("node:sqlite");
4
4
  const fs = require("node:fs"), crypto = require("node:crypto"), path = require("node:path");
@@ -35,4 +35,4 @@ ${MARKER_SOURCE}
35
35
  parentPort.postMessage({ ok: false, problem: String((error && error.message) || error).slice(0, 300) });
36
36
  }
37
37
  })();
38
- `;function copyOffThread(source,folder,tag,now,check="integrity"){const stamp=stampOf(now),end=check==="quick"?QUICK_SUFFIX:".db";let name=`live-${tag}-${stamp}${end}`;for(let n=2;(()=>{try{return lstatSync(join(folder,name)),!0}catch{return!1}})();n++)name=`live-${tag}-${stamp}-${n}${end}`;const target=join(folder,name),partial=join(folder,`.live-${tag}-${stamp}.${randomBytes(4).toString("hex")}.partial`);return new Promise(done=>{const thread=new Worker(COPY_THREAD,{eval:!0,workerData:{source,partial,target,check}});let settled=!1;const finish=answer=>{settled||(settled=!0,done(answer))};thread.once("message",message=>finish(message.ok?{ok:!0,check,marker:typeof message.marker=="string"?message.marker:null,copy:{file:target,sha256:String(message.sha256),bytes:Number(message.bytes),schemaVersion:Number(message.schemaVersion)}}:{ok:!1,problem:message.problem??"the copy failed"})),thread.once("error",error=>{rmSync(partial,{force:!0}),finish({ok:!1,problem:String(error.message).slice(0,300)})}),thread.once("exit",()=>finish({ok:!1,problem:"the copy stopped before it finished"}))})}function liveCopyDue(store,now,memory){const state=liveBackupState(store);if(!state.settings.enabled)return!1;const every=state.settings.everyMinutes*6e4,last=Math.max(state.latest===null?0:Date.parse(state.latest.madeAt),state.triedAt===null?0:Date.parse(state.triedAt),memory?.lookedAt??0);return!Number.isFinite(last)||now.getTime()-last>=every}function stillCovers(covered,folder,tag){if(covered===null||liveCopies(folder,tag)[0]?.path!==covered.file)return!1;try{const stat=lstatSync(covered.file);return stat.isFile()&&stat.size===covered.bytes}catch{return!1}}function noteQuickCopy(store,now){store.handle.prepare("UPDATE live_backup SET tried_at = ?, problem = NULL WHERE id = 1").run(now.toISOString())}export async function liveBackupPass(store,databaseFile,holder,forbidden,clock=()=>new Date,memory=newLiveCopyMemory()){const now=clock();if(!liveCopyDue(store,now,memory))return null;const tag=databaseTag(databaseFile),protectedRoot=dirname(defaultLiveFolder(databaseFile)),before=liveBackupState(store),folder=liveFolderOf(before.settings,databaseFile),usable=liveFolderProblem(folder,forbidden(),protectedRoot)===null,lastFull=usable?lastFullCheckAt(folder,tag):null,fullAge=lastFull===null?NaN:now.getTime()-Date.parse(lastFull),fullDue=!(fullAge>=0&&fullAge<LIVE_FULL_CHECK_EVERY_MS);if(usable&&!fullDue&&stillCovers(memory.covered,folder,tag)){const covered=memory.covered;memory.lookedAt=now.getTime();const seen=await markerOffThread(databaseFile);if(seen.ok&&seen.marker===covered.marker)return{ok:!0,unchanged:!0,file:covered.file}}if(!holdLiveBackup(store,holder,now,new Date(now.getTime()+LEASE_MS)))return null;try{const state=liveBackupState(store),at=liveFolderOf(state.settings,databaseFile),fail=problem2=>(recordLiveBackup(store,{ok:!1,problem:problem2},clock()),{ok:!1,problem:problem2});let problem=liveFolderProblem(at,forbidden(),protectedRoot);if(problem!==null)return fail(problem);try{mkdirSync(at,{recursive:!0,mode:448})}catch(error){return fail(`${at} couldn't be made (${error.message})`)}if(problem=liveFolderProblem(at,forbidden(),protectedRoot),problem!==null)return fail(problem);const full=at!==folder||fullDue||lastFullCheckAt(at,tag)===null,made=await copyOffThread(databaseFile,at,tag,now,full?"integrity":"quick");if(!made.ok)return fail(made.problem);const copy={...made.copy,madeAt:now.toISOString()};return made.check==="integrity"?recordLiveBackup(store,{ok:!0,copy},clock()):noteQuickCopy(store,clock()),memory.covered=made.marker===null?null:{file:copy.file,bytes:copy.bytes,marker:made.marker},memory.lookedAt=now.getTime(),pruneLiveCopies(at,tag,state.settings.keep,clock(),[copy.file,liveBackupState(store).latest?.file??null]),{ok:!0,copy,check:made.check}}finally{releaseLiveBackup(store,holder)}}export function startLiveBackups(store,databaseFile,forbidden,everyMs=6e4){const holder=`${hostname()}:${process.pid}:${randomUUID().slice(0,8)}`,memory=newLiveCopyMemory();let stopped=!1,timer=null,running=Promise.resolve();const pass=()=>{stopped||(running=liveBackupPass(store,databaseFile,holder,forbidden,()=>new Date,memory).catch(()=>null).finally(()=>{stopped||(timer=setTimeout(pass,everyMs),timer.unref?.())}))};return timer=setTimeout(pass,3e4),timer.unref?.(),async()=>{stopped=!0,timer!==null&&clearTimeout(timer),await Promise.race([running,new Promise(resolveWait=>setTimeout(resolveWait,1e4).unref?.())])}}
38
+ `;function copyOffThread(source,folder,tag,now,check="integrity"){const stamp=stampOf(now),end=check==="quick"?QUICK_SUFFIX:".db";let name=`live-${tag}-${stamp}${end}`;for(let n=2;(()=>{try{return lstatSync(join(folder,name)),!0}catch{return!1}})();n++)name=`live-${tag}-${stamp}-${n}${end}`;const target=join(folder,name),partial=join(folder,`.live-${tag}-${stamp}.${randomBytes(4).toString("hex")}.partial`);return new Promise(done=>{const thread=new Worker(COPY_THREAD,{eval:!0,workerData:{source,partial,target,check},env:withoutLeadTokenEnv(process.env)});let settled=!1;const finish=answer=>{settled||(settled=!0,done(answer))};thread.once("message",message=>finish(message.ok?{ok:!0,check,marker:typeof message.marker=="string"?message.marker:null,copy:{file:target,sha256:String(message.sha256),bytes:Number(message.bytes),schemaVersion:Number(message.schemaVersion)}}:{ok:!1,problem:message.problem??"the copy failed"})),thread.once("error",error=>{rmSync(partial,{force:!0}),finish({ok:!1,problem:String(error.message).slice(0,300)})}),thread.once("exit",()=>finish({ok:!1,problem:"the copy stopped before it finished"}))})}function liveCopyDue(store,now,memory){const state=liveBackupState(store);if(!state.settings.enabled)return!1;const every=state.settings.everyMinutes*6e4,last=Math.max(state.latest===null?0:Date.parse(state.latest.madeAt),state.triedAt===null?0:Date.parse(state.triedAt),memory?.lookedAt??0);return!Number.isFinite(last)||now.getTime()-last>=every}function stillCovers(covered,folder,tag){if(covered===null||liveCopies(folder,tag)[0]?.path!==covered.file)return!1;try{const stat=lstatSync(covered.file);return stat.isFile()&&stat.size===covered.bytes}catch{return!1}}function noteQuickCopy(store,now){store.handle.prepare("UPDATE live_backup SET tried_at = ?, problem = NULL WHERE id = 1").run(now.toISOString())}export async function liveBackupPass(store,databaseFile,holder,forbidden,clock=()=>new Date,memory=newLiveCopyMemory()){const now=clock();if(!liveCopyDue(store,now,memory))return null;const tag=databaseTag(databaseFile),protectedRoot=dirname(defaultLiveFolder(databaseFile)),before=liveBackupState(store),folder=liveFolderOf(before.settings,databaseFile),usable=liveFolderProblem(folder,forbidden(),protectedRoot)===null,lastFull=usable?lastFullCheckAt(folder,tag):null,fullAge=lastFull===null?NaN:now.getTime()-Date.parse(lastFull),fullDue=!(fullAge>=0&&fullAge<LIVE_FULL_CHECK_EVERY_MS);if(usable&&!fullDue&&stillCovers(memory.covered,folder,tag)){const covered=memory.covered;memory.lookedAt=now.getTime();const seen=await markerOffThread(databaseFile);if(seen.ok&&seen.marker===covered.marker)return{ok:!0,unchanged:!0,file:covered.file}}if(!holdLiveBackup(store,holder,now,new Date(now.getTime()+LEASE_MS)))return null;try{const state=liveBackupState(store),at=liveFolderOf(state.settings,databaseFile),fail=problem2=>(recordLiveBackup(store,{ok:!1,problem:problem2},clock()),{ok:!1,problem:problem2});let problem=liveFolderProblem(at,forbidden(),protectedRoot);if(problem!==null)return fail(problem);try{mkdirSync(at,{recursive:!0,mode:448})}catch(error){return fail(`${at} couldn't be made (${error.message})`)}if(problem=liveFolderProblem(at,forbidden(),protectedRoot),problem!==null)return fail(problem);const full=at!==folder||fullDue||lastFullCheckAt(at,tag)===null,made=await copyOffThread(databaseFile,at,tag,now,full?"integrity":"quick");if(!made.ok)return fail(made.problem);const copy={...made.copy,madeAt:now.toISOString()};return made.check==="integrity"?recordLiveBackup(store,{ok:!0,copy},clock()):noteQuickCopy(store,clock()),memory.covered=made.marker===null?null:{file:copy.file,bytes:copy.bytes,marker:made.marker},memory.lookedAt=now.getTime(),pruneLiveCopies(at,tag,state.settings.keep,clock(),[copy.file,liveBackupState(store).latest?.file??null]),{ok:!0,copy,check:made.check}}finally{releaseLiveBackup(store,holder)}}export function startLiveBackups(store,databaseFile,forbidden,everyMs=6e4){const holder=`${hostname()}:${process.pid}:${randomUUID().slice(0,8)}`,memory=newLiveCopyMemory();let stopped=!1,timer=null,running=Promise.resolve();const pass=()=>{stopped||(running=liveBackupPass(store,databaseFile,holder,forbidden,()=>new Date,memory).catch(()=>null).finally(()=>{stopped||(timer=setTimeout(pass,everyMs),timer.unref?.())}))};return timer=setTimeout(pass,3e4),timer.unref?.(),async()=>{stopped=!0,timer!==null&&clearTimeout(timer),await Promise.race([running,new Promise(resolveWait=>setTimeout(resolveWait,1e4).unref?.())])}}
@@ -1,4 +1,4 @@
1
- import{randomBytes}from"node:crypto";import{createRequire}from"node:module";import{execFileSync}from"node:child_process";import{existsSync,lstatSync,mkdirSync,readdirSync,readlinkSync,realpathSync,rmSync,statSync,writeFileSync}from"node:fs";import{delimiter,isAbsolute,join}from"node:path";import{codingEnvironment}from"./agent-thread/providers.js";import{materializeProjectSkills}from"./project-skills.js";import{teardownGit,refusal,recordedCommonDir,TEARDOWN_FLAGS}from"./teardown-git.js";import{run}from"./exec.js";import{ENV,ENV_ALLOWLIST}from"./remote-main.js";import{sleep}from"./sleep.js";export const TERMINAL_PROGRAMS=["claude","codex","antigravity","shell"],MAX_LIVE_TERMINALS=8;const MAX_KEPT_TERMINALS=16;export const MAX_VIEWERS=4,CLOSE_GRACE_MS=2e3,MAX_PENDING_INPUT=1024*1024;const CUSTODY_REFRESH_MS=5e3,COLS={min:2,max:500};export const ROWS={min:1,max:200};const ttyName=path=>typeof path=="string"&&/^\/dev\/(ttys\d+|pts\/\d+|tty[a-z]?\d+)$/.test(path)?path.slice(5):null;export function pendingInputOf(pty){const queue=pty?._writeStream?._writeQueue;if(!Array.isArray(queue))return 1/0;let bytes=0;for(const task of queue){if(!Buffer.isBuffer(task?.buffer)||typeof task.offset!="number")return 1/0;bytes+=task.buffer.byteLength-task.offset}return bytes}export function dropPendingInput(pty){const stream=pty?._writeStream;return stream===void 0||!Array.isArray(stream._writeQueue)?!1:(stream._writeQueue.length=0,stream._writeImmediate!==void 0&&(clearImmediate(stream._writeImmediate),stream._writeImmediate=void 0),!0)}export function loadPtySpawn(){try{const pty=createRequire(import.meta.url)("@lydell/node-pty");return(file,args,options)=>{const native=pty.spawn(file,args,{name:"xterm-256color",cwd:options.cwd,env:options.env,cols:options.cols,rows:options.rows});return{get pid(){return native.pid},tty:ttyName(native.ptsName),pendingInput:()=>pendingInputOf(native),onData:listener=>native.onData(listener),onExit:listener=>native.onExit(listener),write:data=>native.write(data),resize:(cols,rows)=>native.resize(cols,rows),kill:signal=>native.kill(signal),pause:()=>native.pause(),resume:()=>native.resume(),dropInput:()=>{dropPendingInput(native)}}}}catch{return null}}const SCREEN_SCROLLBACK_LINES=5e3,require=createRequire(import.meta.url);export class ScreenMirror{lines;terminal;serializer;constructor(cols,rows,lines=SCREEN_SCROLLBACK_LINES){this.lines=lines;const{Terminal}=require("@xterm/headless"),{SerializeAddon}=require("@xterm/addon-serialize");this.terminal=new Terminal({cols,rows,scrollback:lines,allowProposedApi:!0}),this.serializer=new SerializeAddon,this.terminal.loadAddon(this.serializer)}pending=0;write(data){const size=data.length;this.pending+=size;try{return this.terminal.write(data,()=>{this.pending-=size}),!0}catch{return this.pending-=size,!1}}resize(cols,rows){try{this.terminal.resize(cols,rows)}catch{}}snapshot(done){this.terminal.write("",()=>{let screen="";for(let lines=this.lines;;lines=Math.floor(lines/2)){try{screen=this.serializer.serialize({scrollback:lines})}catch{screen=""}if(screen.length<=SNAPSHOT_MAX_CHARS||lines===0)break}done(screen.length<=SNAPSHOT_MAX_CHARS?screen:"")})}dispose(){try{this.terminal.dispose()}catch{}}}export const VIEWER_PAUSE_BYTES=1024*1024;const VIEWER_RESUME_BYTES=256*1024;export const MIRROR_PAUSE_CHARS=4*1024*1024;const MIRROR_RESUME_CHARS=1024*1024,ATTACH_HOLD_BYTES=4*1024*1024,SNAPSHOT_MAX_CHARS=8*1024*1024,SENSITIVE_EARLY_BYTES=256*1024,SENSITIVE_ATTACH_MS=3e4,MAX_AGENT_PANES=1,DROPPED_WORDS=`\r
1
+ import{randomBytes}from"node:crypto";import{createRequire}from"node:module";import{execFileSync}from"node:child_process";import{existsSync,lstatSync,mkdirSync,readdirSync,readlinkSync,realpathSync,rmSync,statSync,writeFileSync}from"node:fs";import{delimiter,isAbsolute,join}from"node:path";import{codingEnvironment}from"./agent-thread/providers.js";import{materializeProjectSkills}from"./project-skills.js";import{teardownGit,refusal,recordedCommonDir,TEARDOWN_FLAGS}from"./teardown-git.js";import{run}from"./exec.js";import{ENV,ENV_ALLOWLIST}from"./remote-main.js";import{withoutLeadTokenEnv}from"./names.js";import{sleep}from"./sleep.js";export const TERMINAL_PROGRAMS=["claude","codex","antigravity","shell"],MAX_LIVE_TERMINALS=8;const MAX_KEPT_TERMINALS=16;export const MAX_VIEWERS=4,CLOSE_GRACE_MS=2e3,MAX_PENDING_INPUT=1024*1024;const CUSTODY_REFRESH_MS=5e3,COLS={min:2,max:500};export const ROWS={min:1,max:200};const ttyName=path=>typeof path=="string"&&/^\/dev\/(ttys\d+|pts\/\d+|tty[a-z]?\d+)$/.test(path)?path.slice(5):null;export function pendingInputOf(pty){const queue=pty?._writeStream?._writeQueue;if(!Array.isArray(queue))return 1/0;let bytes=0;for(const task of queue){if(!Buffer.isBuffer(task?.buffer)||typeof task.offset!="number")return 1/0;bytes+=task.buffer.byteLength-task.offset}return bytes}export function dropPendingInput(pty){const stream=pty?._writeStream;return stream===void 0||!Array.isArray(stream._writeQueue)?!1:(stream._writeQueue.length=0,stream._writeImmediate!==void 0&&(clearImmediate(stream._writeImmediate),stream._writeImmediate=void 0),!0)}export function loadPtySpawn(){try{const pty=createRequire(import.meta.url)("@lydell/node-pty");return(file,args,options)=>{const native=pty.spawn(file,args,{name:"xterm-256color",cwd:options.cwd,env:options.env,cols:options.cols,rows:options.rows});return{get pid(){return native.pid},tty:ttyName(native.ptsName),pendingInput:()=>pendingInputOf(native),onData:listener=>native.onData(listener),onExit:listener=>native.onExit(listener),write:data=>native.write(data),resize:(cols,rows)=>native.resize(cols,rows),kill:signal=>native.kill(signal),pause:()=>native.pause(),resume:()=>native.resume(),dropInput:()=>{dropPendingInput(native)}}}}catch{return null}}const SCREEN_SCROLLBACK_LINES=5e3,require=createRequire(import.meta.url);export class ScreenMirror{lines;terminal;serializer;constructor(cols,rows,lines=SCREEN_SCROLLBACK_LINES){this.lines=lines;const{Terminal}=require("@xterm/headless"),{SerializeAddon}=require("@xterm/addon-serialize");this.terminal=new Terminal({cols,rows,scrollback:lines,allowProposedApi:!0}),this.serializer=new SerializeAddon,this.terminal.loadAddon(this.serializer)}pending=0;write(data){const size=data.length;this.pending+=size;try{return this.terminal.write(data,()=>{this.pending-=size}),!0}catch{return this.pending-=size,!1}}resize(cols,rows){try{this.terminal.resize(cols,rows)}catch{}}snapshot(done){this.terminal.write("",()=>{let screen="";for(let lines=this.lines;;lines=Math.floor(lines/2)){try{screen=this.serializer.serialize({scrollback:lines})}catch{screen=""}if(screen.length<=SNAPSHOT_MAX_CHARS||lines===0)break}done(screen.length<=SNAPSHOT_MAX_CHARS?screen:"")})}dispose(){try{this.terminal.dispose()}catch{}}}export const VIEWER_PAUSE_BYTES=1024*1024;const VIEWER_RESUME_BYTES=256*1024;export const MIRROR_PAUSE_CHARS=4*1024*1024;const MIRROR_RESUME_CHARS=1024*1024,ATTACH_HOLD_BYTES=4*1024*1024,SNAPSHOT_MAX_CHARS=8*1024*1024,SENSITIVE_EARLY_BYTES=256*1024,SENSITIVE_ATTACH_MS=3e4,MAX_AGENT_PANES=1,DROPPED_WORDS=`\r
2
2
  [Toolroll: earlier output was dropped]\r
3
3
  `,NO_LEDGER={reserve(){},running(){},release(){},forget(){}};export class TerminalError extends Error{constructor(message){super(message),this.name="TerminalError"}}export const COPY_CONFIG=`[core]
4
4
  repositoryformatversion = 0
@@ -7,6 +7,6 @@ import{randomBytes}from"node:crypto";import{createRequire}from"node:module";impo
7
7
  logallrefupdates = true
8
8
  `;const TAKE_OVER_ENV=["HOME","USER","LOGNAME","SHELL","PATH","LANG","LC_ALL","LC_CTYPE","LC_MESSAGES","TMPDIR","TZ"];function takeOverEnvironment(from,buildWritable=[]){const env={};for(const key of TAKE_OVER_ENV)typeof from[key]=="string"&&(env[key]=from[key]);return env.PATH!==void 0&&(env.PATH=trustedPath(env.PATH,buildWritable)),env}export function takeOverAgentEnvironment(from,buildWritable=[]){const env={...from};return env.PATH!==void 0&&(env.PATH=trustedPath(env.PATH,buildWritable)),env}export function trustedPath(path,buildWritable){const real=p=>{try{return realpathSync(p)}catch{return null}},roots=buildWritable.flatMap(root=>[root,real(root)]).filter(one=>one!==null&&one!==""),inside=p=>roots.some(root=>p===root||p.startsWith(root.endsWith("/")?root:`${root}/`));return path.split(delimiter).filter(entry=>{if(entry===""||!isAbsolute(entry)||entry.split("/").includes(".."))return!1;const resolved=real(entry);return!inside(entry)&&(resolved===null||!inside(resolved))}).join(delimiter)}const clamp=(value,range)=>Math.min(range.max,Math.max(range.min,Math.trunc(value)));export function onPath(name,env=process.env){if(isAbsolute(name))return existsSync(name)?name:null;const extensions=process.platform==="win32"?(env.PATHEXT??".EXE;.CMD;.BAT").split(";"):[""];for(const dir of(env.PATH??"").split(delimiter))if(dir!=="")for(const extension of extensions){const path=join(dir,name+extension);try{if(statSync(path).isFile())return path}catch{}}return null}function sanitizePrompt(prompt){if(prompt===void 0)return null;const cleaned=prompt.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").trim().slice(0,1200);return cleaned===""?null:cleaned.startsWith("-")?`Task: ${cleaned}`:cleaned}function defaultProgram(program,env,prompt){if(program==="shell"){if(process.platform==="win32")return{file:onPath("pwsh",env)??onPath("powershell",env)??"cmd.exe",args:[]};const shell=env.SHELL;return{file:shell!==void 0&&isAbsolute(shell)&&existsSync(shell)?shell:onPath("bash",env)??"/bin/sh",args:["-l"]}}const file=onPath(program==="antigravity"?"agy":program,env);if(file===null)return null;const brief=sanitizePrompt(prompt);return brief===null?{file,args:[]}:program==="antigravity"?{file,args:["-i",brief]}:{file,args:program==="claude"?["--",brief]:[brief]}}export class TerminalHost{options;sessions=new Map;starting=0;stopped=!1;clock;env;ledger;processes;custodyTimer=null;constructor(options){this.options=options,this.clock=options.clock??(()=>new Date),this.env=options.env??codingEnvironment,this.ledger=options.ledger??NO_LEDGER,this.processes=options.processes??readProcessTable}summary(session){const{id,owner,generation,localGeneration,task,run:run2,agent,repo,program,branch,worktree,startedAt,endedAt,exit,endedBy,cleanup}=session;return{id,owner,generation,localGeneration,task,run:run2,agent:agent===null?null:{...agent},repo,program,branch,worktree,startedAt,endedAt,exit,endedBy,cleanup}}list(owner){return[...this.sessions.values()].filter(one=>one.owner===owner).map(one=>this.summary(one)).reverse()}listAll(){return[...this.sessions.values()].filter(one=>one.agent===null).map(one=>this.summary(one)).reverse()}get(id){const session=this.sessions.get(id);return session===void 0?null:this.summary(session)}running(){return[...this.sessions.values()].filter(one=>one.endedAt===null&&one.agent===null).length}kept(){return[...this.sessions.values()].filter(one=>one.agent===null).length}startingAgents=0;async start({name:owner,generation,localGeneration=null},repoPath,program,size={cols:100,rows:30},admit=()=>null,from=null){if(this.stopped)throw new TerminalError("The console is stopping.");if(!TERMINAL_PROGRAMS.includes(program))throw new TerminalError("Choose Claude, Codex, Gemini or a shell.");if(this.running()+this.starting>=(this.options.maxSessions??MAX_LIVE_TERMINALS))throw new TerminalError(`At most ${this.options.maxSessions??MAX_LIVE_TERMINALS} terminals can run at once. Close one first.`);if(this.kept()+this.starting>=MAX_KEPT_TERMINALS)throw new TerminalError(`${MAX_KEPT_TERMINALS} terminals are kept already. Remove an ended one first.`);const roots=[this.options.worktreeRoot,...this.options.buildWritable?.()??[],...this.moreBuildWritable.flatMap(more=>more())],env={...from===null?this.env():program==="shell"?takeOverEnvironment(this.env(),roots):takeOverAgentEnvironment(this.env(),roots),TERM:"xterm-256color",COLORTERM:"truecolor"},command=this.options.programs?.[program]??defaultProgram(program,env,from?.prompt);if(command===null){const label=program==="claude"?"Claude Code":program==="codex"?"Codex":"The Antigravity CLI, which runs Gemini,",binary=program==="antigravity"?"agy":program;throw new TerminalError(`${label} isn't installed on this computer (\`${binary}\` is not on PATH).`)}const id=randomBytes(16).toString("hex");this.starting+=1;let reserved=!1;try{try{this.ledger.reserve(id),reserved=!0}catch(error){throw error instanceof TerminalError?error:new TerminalError(error instanceof Error?error.message:"No terminal can start right now.")}let repo;try{repo=realpathSync(repoPath)}catch{throw new TerminalError("That project folder is gone.")}const hardened=this.options.git??teardownGit(),git=async args=>{const result=await hardened(repo,args);if(result.code!==0)throw new TerminalError(refusal(result)!==null?`Toolroll won't run git in this project: ${refusal(result)}.`:"Git couldn't make a worktree for this terminal. Check the project and try again.");return result.stdout.trim()};if(realpathSync(await git(["rev-parse","--show-toplevel"]))!==repo)throw new TerminalError("Choose the root of a Git project.");if(from!==null&&!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(from.revision))throw new TerminalError("This build has no saved commit to open a terminal on.");const base=from===null?await git(["rev-parse","--verify","HEAD^{commit}"]):await git(["--no-replace-objects","rev-parse","--verify","--end-of-options",`${from.revision}^{commit}`]).catch(()=>"");if(from!==null&&base!==from.revision)throw new TerminalError("This build's saved commit isn't in the project any more, so there is nothing to open a terminal on.");const branch=`toolroll/live-${id.slice(0,12)}`,worktree=join(this.options.worktreeRoot,id);mkdirSync(this.options.worktreeRoot,{recursive:!0,mode:448}),from===null?await git(["worktree","add","-b",branch,"--",worktree,base]):await this.copyAt(repo,worktree,branch,base);const cols=clamp(size.cols,COLS),rows=clamp(size.rows,ROWS);let skillsDir=null;const launchEnv={...env};try{const snapshot=this.options.skillsForRepo?.(repo);if(snapshot&&snapshot.packages.length>0){const materialized=materializeProjectSkills(snapshot,join(this.options.worktreeRoot,".skills"),id.slice(0,16));materialized.directory!==null&&(skillsDir=materialized.directory,launchEnv.TOOLROLL_SKILLS_DIR=skillsDir)}}catch{}let pty;try{if(this.stopped)throw new TerminalError("The console is stopping.");const refused=admit();if(refused!==null)throw new TerminalError(refused);pty=this.options.spawn(command.file,command.args,{cwd:worktree,env:launchEnv,cols,rows})}catch(error){throw skillsDir!==null&&rmSync(skillsDir,{recursive:!0,force:!0}),from!==null?rmSync(worktree,{recursive:!0,force:!0}):(await git(["worktree","remove","--force","--",worktree]).catch(()=>{}),await git(["branch","-D","--",branch]).catch(()=>{})),error instanceof TerminalError?error:new TerminalError(`The program couldn't start: ${error instanceof Error?error.message:String(error)}`)}let resolveExited;const session={id,owner,generation,localGeneration,task:from?.task??null,run:from?.run??null,agent:null,base:from===null?null:base,repo,program,branch,worktree,startedAt:this.clock().toISOString(),endedAt:null,exit:null,endedBy:null,cleanup:null,pty,leader:pty.pid,tty:pty.tty,known:new Map,exitedAt:null,worktreeReal:realpathSync(worktree),startedMs:Date.now(),residentsOnly:!1,residentsSeen:new Map,cols,rows,screen:new ScreenMirror(cols,rows,this.options.scrollbackLines),paused:!1,flowTimer:null,attaching:0,viewers:new Set,controller:null,leaseEpoch:0,viewerActors:new Map,viewerGates:new Map,closing:null,exited:new Promise(resolve=>{resolveExited=resolve}),sensitive:!1,attachedOnce:!1,early:[],earlyBytes:0,dropped:!1,attachTimer:null,skillsDir};return this.sessions.set(id,session),this.ledger.running(id),reserved=!1,this.noteCustody(),pty.onData(data=>{this.noteSoon();const chunk=Buffer.from(data,"utf8");if(!session.screen.write(data))for(const viewer of session.viewers)try{viewer.overflow?.()}catch{}for(const viewer of session.viewers)try{viewer.output(chunk)}catch{}this.flow(session)}),pty.onExit(({exitCode,signal})=>{try{pty.dropInput?.()}catch{}session.pty=null,session.flowTimer!==null&&(clearInterval(session.flowTimer),session.flowTimer=null),session.exitedAt=Date.now(),session.endedAt=this.clock().toISOString(),session.exit={code:exitCode??null,signal:signal||null};for(const viewer of session.viewers)try{viewer.control({t:"exit",code:session.exit.code,signal:session.exit.signal})}catch{}this.options.record?.("exit",this.summary(session)),resolveExited(),session.closing===null&&(session.closing=this.sweep(session))}),this.options.record?.("start",this.summary(session)),this.summary(session)}finally{this.starting-=1,reserved&&this.ledger.release(id,null)}}async startCommand({name:owner,generation,localGeneration=null},agent,command,env,size={cols:100,rows:30},admit=()=>null,exited=()=>{}){if(this.stopped)throw new TerminalError("The console is stopping.");if([...this.sessions.values()].filter(one=>one.agent!==null).length+this.startingAgents>=MAX_AGENT_PANES)throw new TerminalError("A sign-in or install is already open. Finish it (or close it) first.");const id=randomBytes(16).toString("hex");this.startingAgents+=1;let reserved=!1;try{try{this.ledger.reserve(id),reserved=!0}catch(error){throw error instanceof TerminalError?error:new TerminalError(error instanceof Error?error.message:"No terminal can start right now.")}mkdirSync(this.options.worktreeRoot,{recursive:!0,mode:448});const folder=join(this.options.worktreeRoot,`agent-${id}`);mkdirSync(folder,{recursive:!1,mode:448});const cols=clamp(size.cols,COLS),rows=clamp(size.rows,ROWS);let pty;try{if(this.stopped)throw new TerminalError("The console is stopping.");const refused=admit();if(refused!==null)throw new TerminalError(refused);pty=this.options.spawn(command.file,[...command.args],{cwd:folder,env:{...env,TERM:"xterm-256color",COLORTERM:"truecolor"},cols,rows})}catch(error){throw rmSync(folder,{recursive:!0,force:!0}),error instanceof TerminalError?error:new TerminalError(`The program couldn't start: ${error instanceof Error?error.message:String(error)}`)}let resolveExited;const session={id,owner,generation,localGeneration,task:null,run:null,agent:{...agent},base:null,repo:"",program:"shell",branch:"",worktree:folder,startedAt:this.clock().toISOString(),endedAt:null,exit:null,endedBy:null,cleanup:null,pty,leader:pty.pid,tty:pty.tty,known:new Map,exitedAt:null,worktreeReal:realpathSync(folder),startedMs:Date.now(),residentsOnly:!1,residentsSeen:new Map,cols,rows,screen:new ScreenMirror(cols,rows,0),paused:!1,flowTimer:null,attaching:0,viewers:new Set,controller:null,leaseEpoch:0,viewerActors:new Map,viewerGates:new Map,closing:null,exited:new Promise(resolve=>{resolveExited=resolve}),sensitive:!0,attachedOnce:!1,early:[],earlyBytes:0,dropped:!1,attachTimer:null,skillsDir:null};return this.wire(session,()=>{resolveExited();try{exited()}catch{}}),this.sessions.set(id,session),this.ledger.running(id),reserved=!1,this.noteCustody(),session.attachTimer=setTimeout(()=>{session.attachTimer=null,!session.attachedOnce&&(this.forgetScreen(session),this.close(session.id,"console").then(()=>this.drop(session)))},this.options.sensitiveAttachMs??SENSITIVE_ATTACH_MS),session.attachTimer.unref?.(),this.options.record?.("start",this.summary(session)),this.summary(session)}finally{this.startingAgents-=1,reserved&&this.ledger.release(id,null)}}drop(session){this.sessions.get(session.id)===session&&(session.attachTimer!==null&&(clearTimeout(session.attachTimer),session.attachTimer=null),this.sessions.delete(session.id),this.ledger.forget(session.id),session.viewers.clear(),this.forgetScreen(session),session.screen.dispose(),rmSync(session.worktree,{recursive:!0,force:!0}),this.options.record?.("remove",this.summary(session)))}heldBytes(id){return this.sessions.get(id)?.earlyBytes??0}wire(session,onExited){const pty=session.pty;pty.onData(data=>{this.noteSoon();const chunk=Buffer.from(data,"utf8");if(session.sensitive)session.attachedOnce||(session.earlyBytes+chunk.byteLength<=SENSITIVE_EARLY_BYTES&&!session.dropped?(session.early.push(chunk),session.earlyBytes+=chunk.byteLength):(session.early=[],session.earlyBytes=0,session.dropped=!0));else if(!session.screen.write(data))for(const viewer of session.viewers)try{viewer.overflow?.()}catch{}for(const viewer of session.viewers)try{viewer.output(chunk)}catch{}this.flow(session)}),pty.onExit(({exitCode,signal})=>{try{pty.dropInput?.()}catch{}session.pty=null,session.flowTimer!==null&&(clearInterval(session.flowTimer),session.flowTimer=null),session.exitedAt=Date.now(),session.endedAt=this.clock().toISOString(),session.exit={code:exitCode??null,signal:signal||null};for(const viewer of session.viewers)try{viewer.control({t:"exit",code:session.exit.code,signal:session.exit.signal})}catch{}this.options.record?.("exit",this.summary(session)),session.sensitive&&this.forgetScreen(session),onExited(),session.closing===null&&(session.closing=this.sweep(session)),session.agent!==null&&session.closing.then(()=>this.drop(session))})}async copyAt(repo,folder,branch,revision){let source;try{source=realpathSync(recordedCommonDir(repo))}catch{throw new TerminalError("Toolroll couldn't read this project's own git folder, so it won't open a copy of the build.")}for(const borrowed of["alternates","http-alternates"])if(existsSync(join(source,"objects","info",borrowed)))throw new TerminalError("This project's git reads objects from another folder (alternates), so Toolroll won't copy a build from it.");const template=join(this.options.worktreeRoot,".empty-template");if(mkdirSync(template,{recursive:!0,mode:448}),readdirSync(template).length>0||lstatSync(template).isSymbolicLink())throw new TerminalError("Toolroll's terminal folder isn't as it left it.");const git=async(cwd,args,refused="Git couldn't make a copy of this build for the terminal.")=>{const result=await(this.options.copyGit??run)("git",[...TEARDOWN_FLAGS,...args],{cwd,envAllowlist:ENV_ALLOWLIST,env:{...ENV},timeoutMs:3e5,maxBuffer:16777216});if(result.code!==0)throw new TerminalError(refused);return result};mkdirSync(folder,{recursive:!1,mode:448});try{if(await git(folder,["init","--quiet",`--template=${template}`,"-b",branch]),writeFileSync(join(folder,".git","config"),COPY_CONFIG,{mode:384}),await git(folder,["-c","protocol.file.allow=always","-c","fetch.fsckObjects=true","-c","transfer.fsckObjects=true","-c","uploadpack.allowAnySHA1InWant=true","fetch","--quiet","--no-tags","--no-recurse-submodules","--depth","1","--",source,revision],"This build's saved commit didn't copy whole (an object in the project's git isn't what its name says), so Toolroll won't open it."),await git(folder,["reset","--quiet","--hard",revision]),(await git(folder,["rev-parse","--verify","HEAD^{commit}"])).stdout.trim()!==revision)throw new TerminalError("The copy of this build isn't at its saved commit.")}catch(error){throw rmSync(folder,{recursive:!0,force:!0}),error instanceof TerminalError?error:new TerminalError("Git couldn't make a copy of this build for the terminal.")}}attach(id,viewer){const session=this.sessions.get(id);if(session===void 0)throw new TerminalError("No such terminal.");if(session.sensitive)return this.attachOnce(session,viewer);if(session.viewers.size>=MAX_VIEWERS)throw new TerminalError(`This terminal is open in ${MAX_VIEWERS} places already. Close one of them.`);const held=[];let live=!1,heldBytes=0,attaching=!0;const done=()=>{attaching&&(attaching=!1,session.attaching-=1,this.flow(session))},gate={output:data=>{if(live)return viewer.output(data);if(heldBytes+=data.byteLength,heldBytes>ATTACH_HOLD_BYTES){held.length=0,session.viewers.delete(gate),done(),viewer.overflow?.();return}held.push({output:data})},control:message=>{live?viewer.control(message):held.push({control:message})},backlog:()=>viewer.backlog?.()??0,overflow:()=>viewer.overflow?.()};return session.viewers.add(gate),session.viewerActors.set(gate,viewer.actor??session.owner),session.viewerGates.set(viewer,gate),session.controller===null&&(session.controller=gate,session.leaseEpoch+=1),session.attaching+=1,this.flow(session),session.screen.snapshot(screen=>{if(done(),!!session.viewers.has(gate)){try{screen!==""&&viewer.output(Buffer.from(screen,"utf8")),viewer.control({t:"hello",cols:session.cols,rows:session.rows,program:session.program,ended:session.endedAt!==null}),session.exit!==null&&!held.some(one=>"control"in one&&one.control.t==="exit")&&viewer.control({t:"exit",code:session.exit.code,signal:session.exit.signal});for(const one of held)"output"in one?viewer.output(one.output):viewer.control(one.control)}catch{}held.length=0,live=!0,this.broadcastControl(session)}}),()=>{session.viewers.delete(gate),session.viewerActors.delete(gate),session.viewerGates.delete(viewer),session.controller===gate&&(session.controller=null,session.leaseEpoch+=1),done(),this.flow(session),this.broadcastControl(session)}}broadcastControl(session){const controller=session.controller===null?null:session.viewerActors.get(session.controller)??session.owner,viewers=[...session.viewers].map(one=>session.viewerActors.get(one)??session.owner);for(const one of session.viewers)try{one.control({t:"control",role:session.controller===one?"controller":"observer",controller,viewers,epoch:session.leaseEpoch})}catch{}}isController(id,viewer){const session=this.sessions.get(id);if(session===void 0)return!1;if(session.sensitive)return session.viewers.has(viewer);const gate=session.viewerGates.get(viewer);return gate!==void 0&&session.controller===gate}takeControl(id,viewer){const session=this.sessions.get(id);if(session===void 0||session.sensitive)return!1;const gate=session.viewerGates.get(viewer);return gate===void 0||!session.viewers.has(gate)?!1:(session.controller!==gate&&(session.controller=gate,session.leaseEpoch+=1,this.broadcastControl(session)),!0)}releaseControl(id,viewer){const session=this.sessions.get(id);if(session===void 0||session.sensitive)return;const gate=session.viewerGates.get(viewer);gate!==void 0&&session.controller===gate&&(session.controller=null,session.leaseEpoch+=1,this.broadcastControl(session))}controlState(id){const session=this.sessions.get(id);if(session===void 0)return null;const controller=session.controller===null?null:session.viewerActors.get(session.controller)??session.owner,viewers=[...session.viewers].map(one=>session.viewerActors.get(one)??session.owner);return{controller,viewers,epoch:session.leaseEpoch}}activePresence(){const out=[];for(const session of this.sessions.values()){if(session.sensitive||session.endedAt!==null)continue;const controller=session.controller===null?null:session.viewerActors.get(session.controller)??session.owner,viewers=[...new Set([...session.viewers].map(one=>session.viewerActors.get(one)??session.owner))].sort((a,b)=>a.localeCompare(b));out.push({id:session.id,taskId:session.task,repo:session.repo,program:session.program,controller,viewers})}return out}attachOnce(session,viewer){if(session.attachedOnce)throw new TerminalError("This sign-in is open in one place only.");session.attachedOnce=!0,session.attachTimer!==null&&(clearTimeout(session.attachTimer),session.attachTimer=null),session.viewers.add(viewer);const early=session.early;session.early=[],session.earlyBytes=0;try{viewer.control({t:"hello",cols:session.cols,rows:session.rows,program:session.program,ended:session.endedAt!==null}),session.dropped&&viewer.output(Buffer.from(DROPPED_WORDS,"utf8"));for(const chunk of early)viewer.output(chunk);session.exit!==null&&viewer.control({t:"exit",code:session.exit.code,signal:session.exit.signal})}catch{}return early.length=0,this.flow(session),()=>{session.viewers.delete(viewer),this.close(session.id,"owner").then(()=>this.drop(session))}}forgetScreen(session){session.early=[],session.earlyBytes=0,session.screen.dispose(),session.screen=new ScreenMirror(session.cols,session.rows,0)}replay(id){const session=this.sessions.get(id);return session===void 0||session.sensitive?Promise.resolve(""):new Promise(done=>session.screen.snapshot(done))}flow(session){const pty=session.pty;if(pty===null)return;const backlogs=[...session.viewers].map(one=>{try{return one.backlog?.()??0}catch{return 0}}),over=session.attaching>0||session.screen.pending>MIRROR_PAUSE_CHARS||backlogs.some(n=>n>VIEWER_PAUSE_BYTES),under=session.attaching===0&&session.screen.pending<=MIRROR_RESUME_CHARS&&backlogs.every(n=>n<=VIEWER_RESUME_BYTES);if(over&&!session.paused){session.paused=!0;try{pty.pause?.()}catch{}session.flowTimer??=setInterval(()=>this.flow(session),25),session.flowTimer.unref?.()}else if(under&&session.paused){session.paused=!1;try{pty.resume?.()}catch{}session.flowTimer!==null&&(clearInterval(session.flowTimer),session.flowTimer=null)}}moreBuildWritable=[];alsoBuildWritable(roots){this.moreBuildWritable.push(roots)}paused(id){return this.sessions.get(id)?.paused??!1}mirrorPending(id){return this.sessions.get(id)?.screen.pending??0}viewerCount(id){return this.sessions.get(id)?.viewers.size??0}input(id,data){const pty=this.sessions.get(id)?.pty;return pty==null?!0:pty.pendingInput()+Buffer.byteLength(data)>MAX_PENDING_INPUT?!1:(pty.write(data),this.noteSoon(),!0)}resize(id,cols,rows){const session=this.sessions.get(id);if(session?.pty!=null){session.cols=clamp(cols,COLS),session.rows=clamp(rows,ROWS);try{session.pty.resize(session.cols,session.rows)}catch{}session.screen.resize(session.cols,session.rows)}}noteTimer=null;noteSoon(){this.noteTimer===null&&(this.noteTimer=setTimeout(()=>{this.noteTimer=null,this.noteCustody()},250),this.noteTimer.unref?.())}noteCustody(){const live=[...this.sessions.values()].filter(one=>one.endedAt===null);if(live.length>0){const table=this.processes();if(table!==null)for(const session of live)for(const[pid,started]of membersOf(table,session))session.known.set(pid,started)}live.length>0&&this.custodyTimer===null?(this.custodyTimer=setInterval(()=>this.noteCustody(),CUSTODY_REFRESH_MS),this.custodyTimer.unref?.()):live.length===0&&this.custodyTimer!==null&&(clearInterval(this.custodyTimer),this.custodyTimer=null)}close(id,by="owner"){const session=this.sessions.get(id);return session===void 0?Promise.resolve():(session.closing!==null||(session.endedBy=by,this.options.record?.("close",this.summary(session)),session.closing=this.sweep(session)),session.closing)}async sweep(session){const grace=this.options.closeGraceMs??CLOSE_GRACE_MS,pause=sleep,leaderGone=()=>session.pty===null;let readable=!0;const ambiguous=new Set,members=()=>{const table=this.processes();if(table===null)return readable=!1,new Map;const found=membersOf(table,session,ambiguous);for(const[pid,started]of found)session.known.set(pid,started);return found},signal=(found,name)=>{try{session.pty?.dropInput?.()}catch{}const table=this.processes();table===null&&(readable=!1);const leaderStarted=session.known.get(session.leader);if(!leaderGone()&&(table===null||leaderStarted!==void 0&&table.get(session.leader)?.started===leaderStarted)){try{process.kill(-session.leader,name)}catch{}try{session.pty?.kill(name)}catch{}}if(table!==null)for(const[pid,started]of found){const now=table.get(pid);if(now!==void 0){if(now.started!==started){ambiguous.add(pid);continue}try{process.kill(pid,name)}catch{}}}};let cleanup="uncertain";try{if(process.platform==="win32"){try{session.pty?.dropInput?.()}catch{}try{session.pty?.kill()}catch{}await Promise.race([session.exited,pause(grace)]),cleanup=leaderGone()?"clean":"uncertain";return}signal(members(),"SIGHUP");for(const deadline=Date.now()+grace;Date.now()<deadline;)if(await pause(100),leaderGone()&&members().size===0&&readable){cleanup="clean";return}for(let round=0;round<20;round+=1){let found=members();if(!readable)return;if(found.size===0&&leaderGone()){cleanup="clean";return}for(let settle=0;settle<5;settle+=1){signal(found,"SIGSTOP");const again=members();if(!readable)return;const grew=[...again.keys()].some(pid=>!found.has(pid));if(found=again,!grew)break}signal(found,"SIGKILL"),await pause(100)}}finally{if(await Promise.race([session.exited,pause(1e3)]),cleanup==="clean"){const table=this.processes(),residents=table===null?null:(this.options.residents??worktreeResidents)(table,session.worktreeReal,session.startedMs);if(residents===null||residents.size>0){cleanup="uncertain",session.residentsOnly=residents!==null;for(const pid of residents??[]){const row=table.get(pid);row!==void 0&&session.residentsSeen.set(pid,row.started)}}}session.cleanup=readable&&leaderGone()&&ambiguous.size===0?cleanup:"uncertain",session.endedAt===null&&(session.endedAt=this.clock().toISOString()),this.ledger.release(session.id,session.cleanup),this.noteCustody()}}async remove(id){const session=this.sessions.get(id);if(session===void 0)return;if(session.pty!==null)throw new TerminalError("Close the terminal before removing it.");session.closing!==null&&await session.closing;const busy=new TerminalError("Something may still be running in this terminal's worktree, so the worktree stays. Stop it (or leave the folder), then remove the worktree with `git worktree remove`.");if(session.cleanup!=="clean"&&!session.residentsOnly)throw busy;const table=this.processes(),residents=table===null?null:(this.options.residents??worktreeResidents)(table,session.worktreeReal,session.startedMs);if(residents===null||residents.size>0||[...session.residentsSeen].some(([pid,started])=>table.get(pid)?.started===started))throw busy;if(session.base!==null){const own=await this.copyHasWork(session.worktree,session.base);if(own!==null)throw new TerminalError(own)}this.sessions.delete(id),this.ledger.forget(id);for(const viewer of session.viewers)try{viewer.control({t:"exit",code:session.exit?.code??null,signal:session.exit?.signal??null})}catch{}if(session.viewers.clear(),session.screen.dispose(),session.skillsDir!==null&&(rmSync(session.skillsDir,{recursive:!0,force:!0}),session.skillsDir=null),session.base!==null||session.agent!==null){rmSync(session.worktree,{recursive:!0,force:!0}),this.options.record?.("remove",this.summary(session));return}const result=await(this.options.git??teardownGit())(session.repo,["worktree","remove","--force","--",session.worktree]);if(this.options.record?.("remove",this.summary(session)),result.code!==0&&existsSync(session.worktree)){const why=refusal(result);throw new TerminalError(`The terminal is gone, but its worktree stays${why===null?"":` (${why})`}. Remove it with \`git worktree remove\`.`)}}async copyHasWork(folder,base){const read=async args=>(this.options.copyGit??run)("git",[...TEARDOWN_FLAGS,...args],{cwd:folder,envAllowlist:ENV_ALLOWLIST,env:{...ENV},timeoutMs:6e4,maxBuffer:16777216}),stays=what=>`This copy holds ${what} that exist nowhere else, so it stays at ${folder}. Copy what you need out of it, then delete the folder.`;try{const own=await read(["rev-list","--all","--reflog","--not",base,"--"]),status=await read(["status","--porcelain","--untracked-files=all","--ignore-submodules=all"]);if(own.code!==0||status.code!==0)return stays("work (its git couldn't be read)");const commits=own.stdout.split(`
9
9
  `).filter(line=>/^[0-9a-f]{40,64}$/.test(line)),lost=[];if(commits.length>0){const named=await read(["log","--no-walk=unsorted","--format=%h %s",...commits.slice(0,5),"--"]),list=named.code===0?named.stdout.trim().split(`
10
- `).map(line=>line.slice(0,80)).join("; "):commits.slice(0,5).map(one=>one.slice(0,12)).join(", ");lost.push(`${commits.length} commit${commits.length===1?"":"s"} (${list}${commits.length>5?"; …":""})`)}return status.stdout.trim()!==""&&lost.push("changes not committed"),lost.length===0?null:stays(lost.join(" and "))}catch{return stays("work (its git couldn't be read)")}}get admitting(){return!this.stopped}async stop(){return this.stopped=!0,await Promise.all([...this.sessions.keys()].map(id=>this.close(id,"console"))),this.custodyTimer!==null&&(clearInterval(this.custodyTimer),this.custodyTimer=null),this.noteTimer!==null&&(clearTimeout(this.noteTimer),this.noteTimer=null),{clean:[...this.sessions.values()].every(one=>one.cleanup==="clean")}}}export function readProcessTable(){let text;try{text=execFileSync("ps",["-A","-o","pid=,ppid=,uid=,tty=,lstart="],{encoding:"utf8",timeout:2e3,maxBuffer:8*1024*1024})}catch{return null}const table=new Map;for(const line of text.split(`
11
- `)){if(line.trim()==="")continue;const match=/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);if(match===null)return null;table.set(Number(match[1]),{ppid:Number(match[2]),uid:Number(match[3]),tty:match[4],started:match[5]})}return table.size===0?null:table}export function membersOf(table,session,ambiguous){const found=new Map,live=session.exitedAt===null,onTerminal=tty=>session.tty!==null&&tty===session.tty;for(const[pid,row]of table){if(pid===process.pid||pid<=1)continue;(session.known.get(pid)===row.started||pid===session.leader&&live||live&&onTerminal(row.tty))&&found.set(pid,row.started)}for(let grew=!0;grew;){grew=!1;for(const[pid,row]of table)!found.has(pid)&&pid!==process.pid&&found.has(row.ppid)&&(found.set(pid,row.started),grew=!0)}if(ambiguous!==void 0&&!live)for(const[pid,row]of table)!found.has(pid)&&pid!==process.pid&&pid>1&&onTerminal(row.tty)&&ambiguous.add(pid);return found}function cwdsOf(pids){const cwds=new Map,unreadable=[];if(pids.length===0)return{cwds,unreadable};if(process.platform==="linux"){for(const pid2 of pids)try{cwds.set(pid2,readlinkSync(`/proc/${pid2}/cwd`))}catch(error){const code=error.code;if(code==="EACCES"||code==="EPERM")unreadable.push(pid2);else if(code!=="ENOENT")return null}return{cwds,unreadable}}let text;try{text=execFileSync("lsof",["-a","-d","cwd","-Fpn","-p",pids.join(",")],{encoding:"utf8",timeout:1e4,maxBuffer:16*1024*1024})}catch(error){const failure=error;if(failure.status!==1||failure.signal!=null||failure.code==="ETIMEDOUT"||typeof failure.stdout!="string")return null;text=failure.stdout}let pid=null;for(const line of text.split(`
10
+ `).map(line=>line.slice(0,80)).join("; "):commits.slice(0,5).map(one=>one.slice(0,12)).join(", ");lost.push(`${commits.length} commit${commits.length===1?"":"s"} (${list}${commits.length>5?"; …":""})`)}return status.stdout.trim()!==""&&lost.push("changes not committed"),lost.length===0?null:stays(lost.join(" and "))}catch{return stays("work (its git couldn't be read)")}}get admitting(){return!this.stopped}async stop(){return this.stopped=!0,await Promise.all([...this.sessions.keys()].map(id=>this.close(id,"console"))),this.custodyTimer!==null&&(clearInterval(this.custodyTimer),this.custodyTimer=null),this.noteTimer!==null&&(clearTimeout(this.noteTimer),this.noteTimer=null),{clean:[...this.sessions.values()].every(one=>one.cleanup==="clean")}}}export function readProcessTable(){let text;try{text=execFileSync("ps",["-A","-o","pid=,ppid=,uid=,tty=,lstart="],{encoding:"utf8",timeout:2e3,maxBuffer:8*1024*1024,env:withoutLeadTokenEnv(process.env)})}catch{return null}const table=new Map;for(const line of text.split(`
11
+ `)){if(line.trim()==="")continue;const match=/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);if(match===null)return null;table.set(Number(match[1]),{ppid:Number(match[2]),uid:Number(match[3]),tty:match[4],started:match[5]})}return table.size===0?null:table}export function membersOf(table,session,ambiguous){const found=new Map,live=session.exitedAt===null,onTerminal=tty=>session.tty!==null&&tty===session.tty;for(const[pid,row]of table){if(pid===process.pid||pid<=1)continue;(session.known.get(pid)===row.started||pid===session.leader&&live||live&&onTerminal(row.tty))&&found.set(pid,row.started)}for(let grew=!0;grew;){grew=!1;for(const[pid,row]of table)!found.has(pid)&&pid!==process.pid&&found.has(row.ppid)&&(found.set(pid,row.started),grew=!0)}if(ambiguous!==void 0&&!live)for(const[pid,row]of table)!found.has(pid)&&pid!==process.pid&&pid>1&&onTerminal(row.tty)&&ambiguous.add(pid);return found}function cwdsOf(pids){const cwds=new Map,unreadable=[];if(pids.length===0)return{cwds,unreadable};if(process.platform==="linux"){for(const pid2 of pids)try{cwds.set(pid2,readlinkSync(`/proc/${pid2}/cwd`))}catch(error){const code=error.code;if(code==="EACCES"||code==="EPERM")unreadable.push(pid2);else if(code!=="ENOENT")return null}return{cwds,unreadable}}let text;try{text=execFileSync("lsof",["-a","-d","cwd","-Fpn","-p",pids.join(",")],{encoding:"utf8",timeout:1e4,maxBuffer:16*1024*1024,env:withoutLeadTokenEnv(process.env)})}catch(error){const failure=error;if(failure.status!==1||failure.signal!=null||failure.code==="ETIMEDOUT"||typeof failure.stdout!="string")return null;text=failure.stdout}let pid=null;for(const line of text.split(`
12
12
  `))line.startsWith("p")?pid=Number(line.slice(1)):line.startsWith("n")&&pid!==null&&cwds.set(pid,line.slice(1));return{cwds,unreadable}}function worktreeResidents(table,worktreeReal,terminalStartedMs=0){const uid=process.getuid?.()??-1,candidates=[...table].filter(([pid,row])=>pid!==process.pid&&row.uid===uid).map(([pid])=>pid),read=cwdsOf(candidates);return read===null||read.unreadable.some(pid=>{const started=table.get(pid)?.started;return started===void 0||!(Date.parse(started)<terminalStartedMs-1e3)})?null:new Set([...read.cwds].filter(([,cwd])=>cwd===worktreeReal||cwd.startsWith(`${worktreeReal}/`)).map(([pid])=>pid))}export const MAX_FRAME_BYTES=64*1024;export function parseTerminalFrame(text){if(Buffer.byteLength(text)>MAX_FRAME_BYTES)return null;let value;try{value=JSON.parse(text)}catch{return null}if(value===null||typeof value!="object"||Array.isArray(value))return null;const frame=value,keys=Object.keys(frame).sort().join(",");if(frame.t==="in"&&keys==="d,t"&&typeof frame.d=="string")return{t:"in",d:frame.d};if(frame.t==="take-control"&&keys==="t")return{t:"take-control"};if(frame.t==="release-control"&&keys==="t")return{t:"release-control"};if(frame.t==="resize"&&keys==="cols,rows,t"){const cols=frame.cols,rows=frame.rows;if(Number.isSafeInteger(cols)&&Number.isSafeInteger(rows)&&cols>=COLS.min&&cols<=COLS.max&&rows>=ROWS.min&&rows<=ROWS.max)return{t:"resize",cols,rows}}return null}
@@ -1 +1 @@
1
- import{soloNow}from"./install-mode.js";import{localModeOn}from"./local-owner.js";import{localWorkEligible}from"./scope.js";const LOCAL_CHECKS_CEILING="sign-ins",WORDS={team:"Running checks without a password works only on a solo install. Sign in with your password to run them.","local-mode-off":"Local mode is off, so running checks needs your password.","not-owner":"Only this computer's owner runs checks here without a password.","no-scope":"This task has no approved plan, so running its checks needs your password.",release:"Running a release's checks needs your password.",protected:"This is protected work, so running its checks needs your password.",escalated:"Work with wider permissions needs your password to run its checks.",coordinator:"Work a coordinator filed needs your password to run its checks.",unsandboxed:"This project's checks run without a sandbox, so running them needs your password.",imported:"A task from outside needs your password to run its checks."};export function localChecksRefusal(store,by,taskId){if(!soloNow(store))return WORDS.team;const eligible=localWorkEligible(store,by,taskId,{act:"retry"});return eligible.ok?null:WORDS[eligible.reason]}export function localChecksStanding(store,input){if(!soloNow(store)||!localModeOn(store))return{ok:!1,problem:"Asked for without a password, and the install is no longer solo with local mode on, so they didn't run."};const refused=localChecksRefusal(store,input.by,input.taskId);return refused!==null?{ok:!1,problem:`Asked for without a password, and now: ${refused}`}:{ok:!0,access:LOCAL_CHECKS_CEILING}}export class LocalChecksLapsed extends Error{}
1
+ import{ownerMode}from"./owner-mode.js";import{localModeOn}from"./local-owner.js";import{localWorkEligible}from"./scope.js";const LOCAL_CHECKS_CEILING="sign-ins",WORDS={team:"Running checks without a password works only on a solo install. Sign in with your password to run them.","local-mode-off":"Local mode is off, so running checks needs your password.","not-owner":"Only this computer's owner runs checks here without a password.","no-scope":"This task has no approved plan, so running its checks needs your password.",release:"Running a release's checks needs your password.",protected:"This is protected work, so running its checks needs your password.",escalated:"Work with wider permissions needs your password to run its checks.",coordinator:"Work a coordinator filed needs your password to run its checks.",unsandboxed:"This project's checks run without a sandbox, so running them needs your password.",imported:"A task from outside needs your password to run its checks."};export function localChecksRefusal(store,by,taskId){if(ownerMode(store)!=="fast")return WORDS.team;const eligible=localWorkEligible(store,by,taskId,{act:"retry"});return eligible.ok?null:WORDS[eligible.reason]}export function localChecksStanding(store,input){if(ownerMode(store)!=="fast"||!localModeOn(store))return{ok:!1,problem:"Asked for without a password, and the install is no longer solo with local mode on, so they didn't run."};const refused=localChecksRefusal(store,input.by,input.taskId);return refused!==null?{ok:!1,problem:`Asked for without a password, and now: ${refused}`}:{ok:!0,access:LOCAL_CHECKS_CEILING}}export class LocalChecksLapsed extends Error{}
@@ -1,10 +1,11 @@
1
- import{createHash}from"node:crypto";import{lstatSync,mkdtempSync,realpathSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{assignmentOf}from"./assignment.js";import{projectCheckSet,quickVerifyKey}from"./check-levels.js";import{recordActionWhole}from"./action-ledger.js";import{reproveApprover,verifyApproverStanding}from"./principal.js";import{localActNow,LOCAL_OWNER_LAPSED}from"./local-owner.js";import{publishingOf}from"./pull-request-flow.js";import{readGit,wholeChangeBaseOf}from"./task-base.js";import{catchUpConflictOf}from"./revision-catch-up.js";import{checkPasskeyAction,consumePasskeyAction}from"./companion/passkey-gate.js";import{passkeyProofDetail}from"./companion/webauthn.js";import{deviceAccountStands,getPairedDevice}from"./companion/store.js";export const LAND_DESTINATION="land destination",LAND_INTENT="land intent",LAND_PROVED_ACTION="land proved",LAND_SETTLED="land settled",LAND_HANDOFF="land handoff",LAND_HANDOFF_SETTLED="land handoff settled";function checkBindingsOf(store,repo){return{full:store.liveVerifyCommand(repo)?.digest??null,quick:store.liveVerifyCommand(quickVerifyKey(repo))?.digest??null,setup:store.liveWorktreeSetup(repo)?.digest??null,access:String(store.projectCheckAccess(repo))}}const OID=/^[0-9a-f]{40}$/,refuse=(reason,message)=>({ok:!1,reason,message}),short=oid=>oid.slice(0,7),keyOf=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,16);export function landableBranch(name){return name===""||name==="HEAD"||name.startsWith("-")||name.length>100||!/^[A-Za-z0-9._/-]+$/.test(name)||name.startsWith("toolroll/")?!1:name.split("/").every(part=>part!==""&&!part.startsWith(".")&&!part.startsWith("-")&&!part.endsWith(".lock")&&!part.endsWith("."))&&!name.includes("..")}function commonDirOf(repo){try{const dotgit=join(realpathSync(repo),".git"),held=lstatSync(dotgit);return held.isDirectory()&&!held.isSymbolicLink()?realpathSync(dotgit):null}catch{return null}}function gitFor(repo,given){const git=hardenedGit(given??execRun,"build",{repo});return(args,cwd=repo,timeoutMs=6e4)=>git("git",args,{cwd,timeoutMs})}function rows(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail FROM action_ledger WHERE ${where} ORDER BY id DESC`).all(...args).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null"));return detail!==null&&typeof detail=="object"?[{id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail}]:[]}catch{return[]}})}function recordedDestination(store,repo){const row=rows(store,"repo = ? AND action = ? AND source = 'request'",[repo,LAND_DESTINATION])[0],ref=row?.detail.ref,common=row?.detail.common;return typeof ref=="string"&&typeof common=="string"?{ref,common}:null}function intentOf(row){const d=row.detail;if(d.v!==1||typeof d.ref!="string"||typeof d.old!="string"||typeof d.commit!="string"||!OID.test(d.old)||!OID.test(d.commit)||d.mode!=="files"&&d.mode!=="ref"||typeof d.key!="string"||d.kind!=="land"&&d.kind!=="undo")return null;const candidate=typeof d.candidate=="string"&&OID.test(d.candidate)?d.candidate:d.commit;return{id:row.id,at:row.at,repo:row.repo,task:row.task,run:row.run,kind:d.kind,ref:d.ref,old:d.old,commit:d.commit,candidate,mode:d.mode,key:d.key,reverts:typeof d.reverts=="number"||typeof d.reverts=="string"?d.reverts:null,fromHandoff:typeof d.fromHandoff=="number"?d.fromHandoff:null}}function intents(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail,repo,task_id,run_id FROM action_ledger WHERE ${where} AND action = ? ORDER BY id DESC`).all(...args,LAND_INTENT).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null")),one=intentOf({id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail,repo:String(row.repo),task:String(row.task_id),run:Number(row.run_id)});return one===null?[]:[one]}catch{return[]}})}function settledOf(store,intent){const row=rows(store,"action = ? AND outcome LIKE ?",[LAND_SETTLED,`${intent}:%`])[0];return row===void 0?null:{outcome:row.outcome.slice(String(intent).length+1),at:row.at,detail:row.detail}}export function landingOf(store,rootId){const all=intents(store,"task_id = ?",[rootId]),landed=all.find(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);if(landed===void 0)return null;const name=landed.fromHandoff!==null?`handoff:${landed.fromHandoff}`:`intent:${landed.id}`,undone=all.some(one=>one.kind==="undo"&&(one.reverts===name||one.reverts===landed.id)&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);return{intent:landed,at:settledOf(store,landed.id).at,undone}}async function treeProblem(git,commit){const listed=await git(["ls-tree","-r","-z","--full-tree",commit]);if(listed.code!==0)return"its files couldn't be read";for(const entry of listed.stdout.split("\0")){if(entry==="")continue;const match=/^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$/s.exec(entry);if(match===null)return"its files couldn't be read";const[,mode,,oid,path]=match;if(mode==="160000")return"it holds a submodule";if(path===".gitattributes"||path.endsWith("/.gitattributes")){const blob=await git(["cat-file","blob",oid]);if(blob.code!==0)return"its .gitattributes couldn't be read";if(/\b(filter|working-tree-encoding)\s*=/.test(blob.stdout)||/(^|\s)filter(\s|$)/m.test(blob.stdout))return"its files use a Git filter (like Git LFS) or an encoding"}if(path===".gitmodules")return"it holds a submodule"}return null}async function checkoutsOn(git,ref){const listed=await git(["worktree","list","--porcelain","-z"]);if(listed.code!==0)return null;const found=[];let path=null;for(const line of listed.stdout.split("\0"))if(line.startsWith("worktree "))path=line.slice(9);else if(line===`branch ${ref}`&&path!==null)try{found.push(realpathSync(path))}catch{found.push(path)}return found}async function placeOf(git,project,ref,old){const branch=ref.slice(11),symbolic=await git(["symbolic-ref","-q",ref]);if(symbolic.code===0)return{kind:"problem",reason:"destination",message:`${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//,"")}), so Toolroll won't move it. Land it with git yourself.`};if(symbolic.code!==1)return{kind:"problem",reason:"git",message:`Toolroll couldn't read ${branch}.`};if(old!==null){const read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]);if(read.code!==0||read.stdout.trim()!==old)return{kind:"problem",reason:"moved",message:`${branch} moved since you looked. Look again, then land it.`}}const on=await checkoutsOn(git,ref);if(on===null)return{kind:"problem",reason:"git",message:"Toolroll couldn't list this project's checkouts."};if(on.length===0)return{kind:"free"};let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}return on.length!==1||on[0]!==repoReal?{kind:"problem",reason:"occupied",message:`${branch} is checked out in another folder, so Toolroll won't move it or suggest a command to run there. Switch that folder to another branch, then land it.`}:{kind:"folder"}}function handoffRefOf(taskId,commit){return`refs/toolroll/land/${/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(taskId)&&!taskId.includes("..")&&!taskId.endsWith(".lock")&&!taskId.endsWith(".")?taskId:createHash("sha256").update(taskId).digest("hex").slice(0,16)}/${oidOrThrow(commit)}`}function projectOf(store,repo){if(repo===null||!store.knownRepos().includes(repo))return null;const common=commonDirOf(repo);return common===null?null:{repo,common}}export function publishesThroughPullRequests(store,repo){try{return publishingOf(store,repo).on||store.publicationGrantFor(repo)!==null}catch{return!0}}export const PULL_REQUESTS_INSTEAD="This project publishes through pull requests; open one from the task instead.";const ALREADY_MSG=(ref,commit)=>`Already on ${ref.replace(/^refs\/heads\//,"")} (${short(commit)}).`,MOVED_MSG=(branch,old)=>`${branch} moved on since this work started (it's at ${short(old)} now). Send it back: Toolroll builds it again on the current ${branch} with this work merged in, and its checks run on both together.`,CONFLICT_MSG=(branch,old,files,candidate)=>{const named=files.slice(0,3).map(one=>shownName(one)).join(", ");return`${branch} moved on since this work started (it's at ${short(old)} now), and its newer changes conflict with this work${named===""?"":` in ${named}${files.length>3?", …":""}`}. Toolroll can't merge them by itself. To land it, merge ${short(candidate)} into ${branch} yourself and resolve the conflicts, or file a new task on the current ${branch}.`};export function landingBranchOf(store,repo,fallback){const recorded=recordedDestination(store,repo);return recorded!==null&&recorded.common===commonDirOf(repo)?recorded.ref.slice(11):fallback}export async function readLanding(store,taskId,access,now,options){const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);if(assignment.repo!==null&&publishesThroughPullRequests(store,assignment.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,assignment.repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const git=gitFor(project.repo,options.git);if(options.undo===!0)return readUndo(store,assignment.rootId,project,git,options);const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const later=assignment.completion.digest!==receipt.digest;if(later&&assignment.completion.historical!==!0)return refuse("checks","This result changed since you accepted it. Look at it again, then land it.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");const landed=landingOf(store,assignment.rootId);if(landed!==null&&!landed.undone&&landed.intent.candidate===candidate){const reverted=landedStanding(store,assignment.rootId,readGit)?.reverted===!0;return{ok:!0,landed:{at:landed.at,ref:landed.intent.ref,commit:landed.intent.commit,mode:landed.intent.mode,...reverted?{reverted}:{}}}}const checks=receipt.checks.status==="passed"?"passed":!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"?"none":null;if(checks===null)return receipt.checks.status==="failed"?refuse("checks",later?`Its checks failed when they ran again after you accepted it (${receipt.checks.detail.replace(/\.$/,"")}). It stays Complete; it can't land until they pass on its exact commit.`:"Its checks failed. Only work whose checks passed on its exact commit lands."):refuse("checks",later?"Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it.":"Its checks haven't passed on its exact commit. Run checks, then land it.");const destination=await destinationOf(store,project,git,options.into);if(!destination.ok)return destination;const run=store.getRun(receipt.runId),base=run===null||run.branch===null?null:wholeChangeBaseOf(store,run.taskRef,run.branch)??run.baseRevision,read=await planFor(git,project,destination,{kind:"land",taskId:receipt.taskId,rootId:assignment.rootId,runId:receipt.runId,receipt:receipt.digest,completion:assignment.completion.digest,candidate,checks,bindings:checkBindingsOf(store,project.repo)},{base,message:squashMessage(store.getTask(receipt.taskId)?.title??null,receipt.taskId),time:Math.max(0,Math.floor(Date.parse(assignment.completion.at)/1e3)||0),handedOff:handoffsOf(store,project.repo,assignment.rootId).filter(one=>one.candidate===candidate).map(one=>one.commit)});if(!read.ok&&read.reason==="nothing"){const seen=recognisedOnBranch(store,project.repo,assignment.rootId,candidate,readGit);if(seen!==null&&seen.reverted)return refuse("nothing",`${seen.words}.`)}if(!read.ok&&read.reason==="moved"){const now2=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=now2.stdout.trim(),files=now2.code===0&&OID.test(old)?catchUpConflictOf(store,receipt.taskId,old):null;if(files!==null)return refuse("moved",CONFLICT_MSG(destination.ref.slice(11),old,files,candidate))}return read}export function landedLine(landed){return`Landed on ${landed.ref.replace(/^refs\/heads\//,"")} (${short(landed.commit)})${landed.reverted===!0?" · a later commit reverted it":""}.`}async function destinationOf(store,project,git,into){const recorded=recordedDestination(store,project.repo);if(into!==void 0){if(!landableBranch(into))return refuse("destination",`\`${into}\` isn't a branch Toolroll can land on.`);const ref2=`refs/heads/${into}`;return{ok:!0,ref:ref2,recorded:recorded?.ref===ref2&&recorded.common===project.common}}if(recorded!==null&&recorded.common===project.common)return{ok:!0,ref:recorded.ref,recorded:!0};const head=await git(["symbolic-ref","-q","HEAD"]),ref=head.stdout.trim();return head.code!==0||!ref.startsWith("refs/heads/")||!landableBranch(ref.slice(11))?refuse("destination","Your project folder isn't on a branch Toolroll can land on. Name one: --into <branch>."):{ok:!0,ref,recorded:!1}}const UNSAFE_MESSAGE=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]+/g;function squashMessage(title,taskId){const plain=text=>text.replace(UNSAFE_MESSAGE," ").replace(/\s+/g," ").trim(),line=plain(title??"").slice(0,200),id=plain(taskId).slice(0,100);return line===""?`Toolroll task ${id}`:`${line} (Toolroll task ${id})`}async function changesOf(git,old,candidate){const stat=await git(["diff","--numstat","-z","--no-renames","--no-ext-diff","--no-textconv",old,candidate]);if(stat.code!==0)return null;const files=[];let added=0,removed=0;for(const entry of stat.stdout.split("\0")){const match=/^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);match!==null&&(added+=match[1]==="-"?0:Number(match[1]),removed+=match[2]==="-"?0:Number(match[2]),files.push(match[3]))}return{files:files.slice(0,20),fileCount:files.length,added,removed}}async function planFor(git,project,destination,fixed,squashing=null){const{ref}=destination,branch=ref.slice(11),read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),old=read.stdout.trim();if(read.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);if(fixed.candidate!==null){if(old===fixed.candidate)return refuse("nothing",ALREADY_MSG(ref,old));const type=await git(["cat-file","-t",fixed.candidate]);if(type.code!==0||type.stdout.trim()!=="commit")return refuse("git",`This result's commit ${short(fixed.candidate)} is no longer in the project.`);for(const landed of[fixed.candidate,...squashing?.handedOff??[]])if((await git(["merge-base","--is-ancestor",landed,old])).code===0)return refuse("nothing",ALREADY_MSG(ref,landed));const ancestor=await git(["merge-base","--is-ancestor",old,fixed.candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const problem=await treeProblem(git,fixed.candidate)??await treeProblem(git,old);if(problem!==null)return refuse("unsupported",`This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`)}let squash=null;if(fixed.candidate!==null){const tree=await git(["rev-parse","--verify","-q",`${fixed.candidate}^{tree}`]),changes=await changesOf(git,old,fixed.candidate);if(tree.code!==0||!OID.test(tree.stdout.trim())||changes===null)return refuse("git",`Toolroll couldn't read what ${short(fixed.candidate)} changes.`);const message=squashing?.message??`Toolroll task ${fixed.taskId}`,time=squashing?.time??0,treeId=tree.stdout.trim();squash={policy:"squash",base:squashing?.base??null,commit:commitIdOf(squashBody(treeId,old,time,message)),tree:treeId,checkedTree:treeId,time,message,...changes}}const place=await placeOf(git,project,ref,old);if(place.kind==="problem")return refuse(place.reason,place.message);if(place.kind==="folder"&&fixed.kind==="undo"){const command=gitCommand(project.repo,["revert","--no-edit",`${oidOrThrow(fixed.reverts.old)}..${oidOrThrow(fixed.reverts.landed)}`]);return refuse("occupied",`${branch} is checked out in your project folder, so Toolroll won't touch its files. ${command===null?UNSAFE_FOLDER(`git revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`):`To do it yourself there: ${command}`}`)}const mode=place.kind==="free"?"ref":"handoff",plan={...fixed,squash,repo:project.repo,ref,branch,old,mode,...place.kind==="folder"?{handoff:{folder:project.repo}}:{},recorded:destination.recorded};return{ok:!0,plan:{...plan,key:keyOf({v:1,...plan,common:project.common})}}}async function readUndo(store,rootId,project,git,options){const landed=landingOf(store,rootId);if(landed!==null&&landed.undone)return refuse("nothing","This landing was already undone.");const brought=landed===null?await broughtIn(store,git,project.repo,rootId):null,source=landed!==null?{key:landed.intent.key,task:landed.intent.task,run:landed.intent.run,ref:landed.intent.ref,old:landed.intent.old,commit:landed.intent.commit,name:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`}:brought===null?null:{key:brought.key,task:brought.task,run:brought.run,ref:brought.ref,old:brought.old,commit:brought.commit,name:`handoff:${brought.id}`};return source===null?refuse("nothing","This task hasn't landed, so there's nothing to undo."):planFor(git,project,{ref:source.ref,recorded:!0},{kind:"undo",taskId:source.task,rootId,runId:source.run,receipt:source.key,completion:source.key,candidate:null,checks:"none",reverts:{source:source.name,old:source.old,landed:source.commit},bindings:checkBindingsOf(store,project.repo)})}function landedCommits(store,rootId){return new Set(intents(store,"task_id = ?",[rootId]).filter(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0).map(one=>one.commit))}async function broughtIn(store,git,repo,rootId){const landed=landedCommits(store,rootId);for(const one of handoffsOf(store,repo,rootId))if(!landed.has(one.commit)&&(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code===0)return one;return null}function squashBody(tree,parent,time,message){const who=`Toolroll <land@toolroll.invalid> ${time} +0000`;return`tree ${tree}
1
+ import{createHash}from"node:crypto";import{existsSync,lstatSync,mkdtempSync,readFileSync,realpathSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{isAbsolute,join}from"node:path";import{liveInstallOwner,ownerMode,ownerModeSetting}from"./owner-mode.js";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{assignmentOf}from"./assignment.js";import{projectCheckSet,quickVerifyKey}from"./check-levels.js";import{recordActionWhole}from"./action-ledger.js";import{reproveApprover,verifyApproverStanding}from"./principal.js";import{asLocalOwner,localActNow,localBindingStands,localModeOn,LOCAL_OWNER_LAPSED}from"./local-owner.js";import{publishingOf}from"./pull-request-flow.js";import{readGit,wholeChangeBaseOf}from"./task-base.js";import{catchUpConflictOf}from"./revision-catch-up.js";import{checkPasskeyAction,consumePasskeyAction}from"./companion/passkey-gate.js";import{passkeyProofDetail}from"./companion/webauthn.js";import{deviceAccountStands,getPairedDevice}from"./companion/store.js";export const LAND_DESTINATION="land destination",LAND_INTENT="land intent",LAND_PROVED_ACTION="land proved",LAND_SETTLED="land settled",LAND_HANDOFF="land handoff",LAND_HANDOFF_SETTLED="land handoff settled";const LAND_WHEN_CLEAN_QUEUED="land when clean queued",LAND_WHEN_CLEAN_CANCELLED="land when clean cancelled";function checkBindingsOf(store,repo){return{full:store.liveVerifyCommand(repo)?.digest??null,quick:store.liveVerifyCommand(quickVerifyKey(repo))?.digest??null,setup:store.liveWorktreeSetup(repo)?.digest??null,access:String(store.projectCheckAccess(repo))}}const OID=/^[0-9a-f]{40}$/,refuse=(reason,message)=>({ok:!1,reason,message}),short=oid=>oid.slice(0,7),keyOf=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,16);export function landableBranch(name){return name===""||name==="HEAD"||name.startsWith("-")||name.length>100||!/^[A-Za-z0-9._/-]+$/.test(name)||name.startsWith("toolroll/")?!1:name.split("/").every(part=>part!==""&&!part.startsWith(".")&&!part.startsWith("-")&&!part.endsWith(".lock")&&!part.endsWith("."))&&!name.includes("..")}function commonDirOf(repo){try{const dotgit=join(realpathSync(repo),".git"),held=lstatSync(dotgit);return held.isDirectory()&&!held.isSymbolicLink()?realpathSync(dotgit):null}catch{return null}}function gitFor(repo,given){const git=hardenedGit(given??execRun,"build",{repo});return(args,cwd=repo,timeoutMs=6e4)=>git("git",args,{cwd,timeoutMs})}function rows(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail FROM action_ledger WHERE ${where} ORDER BY id DESC`).all(...args).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null"));return detail!==null&&typeof detail=="object"?[{id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail}]:[]}catch{return[]}})}function recordedDestination(store,repo){const row=rows(store,"repo = ? AND action = ? AND source = 'request'",[repo,LAND_DESTINATION])[0],ref=row?.detail.ref,common=row?.detail.common;return typeof ref=="string"&&typeof common=="string"?{ref,common}:null}function intentOf(row){const d=row.detail;if(d.v!==1||typeof d.ref!="string"||typeof d.old!="string"||typeof d.commit!="string"||!OID.test(d.old)||!OID.test(d.commit)||d.mode!=="files"&&d.mode!=="ref"||typeof d.key!="string"||d.kind!=="land"&&d.kind!=="undo")return null;const candidate=typeof d.candidate=="string"&&OID.test(d.candidate)?d.candidate:d.commit;return{id:row.id,at:row.at,repo:row.repo,task:row.task,run:row.run,kind:d.kind,ref:d.ref,old:d.old,commit:d.commit,candidate,mode:d.mode,key:d.key,reverts:typeof d.reverts=="number"||typeof d.reverts=="string"?d.reverts:null,fromHandoff:typeof d.fromHandoff=="number"?d.fromHandoff:null}}function intents(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail,repo,task_id,run_id FROM action_ledger WHERE ${where} AND action = ? ORDER BY id DESC`).all(...args,LAND_INTENT).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null")),one=intentOf({id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail,repo:String(row.repo),task:String(row.task_id),run:Number(row.run_id)});return one===null?[]:[one]}catch{return[]}})}function settledOf(store,intent){const row=rows(store,"action = ? AND outcome LIKE ?",[LAND_SETTLED,`${intent}:%`])[0];return row===void 0?null:{outcome:row.outcome.slice(String(intent).length+1),at:row.at,detail:row.detail}}export function landingOf(store,rootId){const all=intents(store,"task_id = ?",[rootId]),landed=all.find(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);if(landed===void 0)return null;const name=landed.fromHandoff!==null?`handoff:${landed.fromHandoff}`:`intent:${landed.id}`,undone=all.some(one=>one.kind==="undo"&&(one.reverts===name||one.reverts===landed.id)&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);return{intent:landed,at:settledOf(store,landed.id).at,undone}}async function treeProblem(git,commit){const listed=await git(["ls-tree","-r","-z","--full-tree",commit]);if(listed.code!==0)return"its files couldn't be read";for(const entry of listed.stdout.split("\0")){if(entry==="")continue;const match=/^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$/s.exec(entry);if(match===null)return"its files couldn't be read";const[,mode,,oid,path]=match;if(mode==="160000")return"it holds a submodule";if(path===".gitattributes"||path.endsWith("/.gitattributes")){const blob=await git(["cat-file","blob",oid]);if(blob.code!==0)return"its .gitattributes couldn't be read";if(/\b(filter|working-tree-encoding)\s*=/.test(blob.stdout)||/(^|\s)filter(\s|$)/m.test(blob.stdout))return"its files use a Git filter (like Git LFS) or an encoding"}if(path===".gitmodules")return"it holds a submodule"}return null}async function checkoutsOn(git,ref){const listed=await git(["worktree","list","--porcelain","-z"]);if(listed.code!==0)return null;const found=[];let path=null;for(const line of listed.stdout.split("\0"))if(line.startsWith("worktree "))path=line.slice(9);else if(line===`branch ${ref}`&&path!==null)try{found.push(realpathSync(path))}catch{found.push(path)}return found}const IN_PROGRESS_GIT_OPS=[["MERGE_HEAD","merge in progress"],["REBASE_HEAD","rebase in progress"],["rebase-merge","rebase in progress"],["rebase-apply","rebase in progress"],["CHERRY_PICK_HEAD","cherry-pick in progress"],["REVERT_HEAD","revert in progress"],["BISECT_LOG","bisect in progress"]];async function inProgressOpsOf(git,repo){const gitDir=await git(["rev-parse","--git-dir"]);if(gitDir.code!==0||gitDir.stdout.trim()==="")return{ok:!1};const resolvedGitDir=isAbsolute(gitDir.stdout.trim())?gitDir.stdout.trim():join(repo,gitDir.stdout.trim()),ops=[];for(const[marker,label]of IN_PROGRESS_GIT_OPS)existsSync(join(resolvedGitDir,marker))&&!ops.includes(label)&&ops.push(label);return{ok:!0,ops}}async function dirtyFilesOf(git,repo){const status=await git(["status","--porcelain=v1","-z","--untracked-files=normal"]);if(status.code!==0)return{ok:!1};const parts=status.stdout.split("\0"),files=[];for(let i=0;i<parts.length;i+=1){const entry=parts[i];if(entry===""||entry.length<4)continue;const x=entry[0],y=entry[1],path=entry.slice(3);path!==""&&files.push(path),(x==="R"||x==="C"||y==="R"||y==="C")&&i+1<parts.length&&(i+=1)}const ops=await inProgressOpsOf(git,repo);if(!ops.ok)return{ok:!1};for(const label of ops.ops)files.includes(label)||files.push(label);return{ok:!0,files}}const HEAD_LOCK_MARK="toolroll-land ";async function holdHeadLock(git){const dir=await git(["rev-parse","--absolute-git-dir"]);if(dir.code!==0||dir.stdout.trim()==="")return{ok:!1};const path=join(dir.stdout.trim(),"HEAD.lock");try{writeFileSync(path,`${HEAD_LOCK_MARK}${process.pid}
2
+ `,{flag:"wx",mode:420})}catch{return{ok:!1}}return{ok:!0,release:()=>{try{rmSync(path,{force:!0})}catch{}}}}export function releaseLeftoverHeadLock(gitDir){const path=join(gitDir,"HEAD.lock");try{readFileSync(path,"utf8").startsWith(HEAD_LOCK_MARK)&&rmSync(path,{force:!0})}catch{}}async function inspectInPlaceState(git,project,ref,old,commit){const symbolic=await git(["symbolic-ref","-q",ref]),refSymbolic=symbolic.code===0,refReadable=symbolic.code===1,atRead=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),refAt=atRead.code===0&&OID.test(atRead.stdout.trim())?atRead.stdout.trim():null,headSymRead=await git(["symbolic-ref","-q","HEAD"]),headSym=headSymRead.code===0?headSymRead.stdout.trim():null,headAtRead=await git(["rev-parse","--verify","-q","HEAD^{commit}"]),headAt=headAtRead.code===0&&OID.test(headAtRead.stdout.trim())?headAtRead.stdout.trim():null,checkouts=await checkoutsOn(git,ref);let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}const indexMatchesOld=(await git(["diff-index","--cached","--quiet",old])).code===0,indexMatchesCommit=(await git(["diff-index","--cached","--quiet",commit])).code===0,worktreeMatchesCommit=(await git(["diff-index","--quiet",commit])).code===0,dirty=await dirtyFilesOf(git,project.repo),ops=await inProgressOpsOf(git,project.repo);return{refSymbolic,refReadable,refAt,headSym,headAt,checkouts,repoReal,indexMatchesOld,indexMatchesCommit,worktreeMatchesCommit,dirtyFiles:dirty.ok?dirty.files:null,inProgressOps:ops.ok?ops.ops:null}}function isProvenInPlaceLanded(state,ref,commit){return!state.refSymbolic&&state.refReadable&&state.refAt===commit&&state.headSym===ref&&state.headAt===commit&&state.checkouts!==null&&state.checkouts.length===1&&state.checkouts[0]===state.repoReal&&state.indexMatchesCommit&&state.worktreeMatchesCommit&&state.inProgressOps!==null&&state.inProgressOps.length===0}function stateSummaryOf(state){return{refSymbolic:state.refSymbolic,refAt:state.refAt,headSym:state.headSym,headAt:state.headAt,indexMatchesOld:state.indexMatchesOld,indexMatchesCommit:state.indexMatchesCommit,worktreeMatchesCommit:state.worktreeMatchesCommit,dirtyCount:state.dirtyFiles?.length??null,inProgressOps:state.inProgressOps}}function toUnresolved(intent,settled){const words=typeof settled.detail.words=="string"&&settled.detail.words.trim()!==""?settled.detail.words:`An earlier landing on ${intent.ref.replace(/^refs\/heads\//,"")} stopped partway through. Choose how to resolve it below.`;return{intentId:intent.id,taskId:intent.task,runId:intent.run,repo:intent.repo,ref:intent.ref,branch:intent.ref.replace(/^refs\/heads\//,""),old:intent.old,commit:intent.commit,candidate:intent.candidate,words,at:settled.at}}function unresolvedLandingForRepo(store,repo){for(const intent of intents(store,"repo = ?",[repo])){const settled=settledOf(store,intent.id);if(settled?.outcome==="unresolved")return toUnresolved(intent,settled)}return null}export function unresolvedLandingOf(store,rootId){for(const intent of intents(store,"task_id = ?",[rootId])){const settled=settledOf(store,intent.id);if(settled?.outcome==="unresolved")return toUnresolved(intent,settled)}return null}function dirtyRefuse(branch,files){const shown=files.slice(0,5).map(shownName).join(", "),extra=files.length>5?` and ${files.length-5} more`:"";return{ok:!1,reason:"dirty",message:`${branch} is checked out with uncommitted changes in ${shown}${extra}. Choose "Land when clean" or "Open PR".`,dirtyFiles:files}}async function placeOf(git,project,ref,old){const branch=ref.slice(11),symbolic=await git(["symbolic-ref","-q",ref]);if(symbolic.code===0)return{kind:"problem",reason:"destination",message:`${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//,"")}), so Toolroll won't move it. Land it with git yourself.`};if(symbolic.code!==1)return{kind:"problem",reason:"git",message:`Toolroll couldn't read ${branch}.`};if(old!==null){const read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]);if(read.code!==0||read.stdout.trim()!==old)return{kind:"problem",reason:"moved",message:`${branch} moved since you looked. Look again, then land it.`}}const on=await checkoutsOn(git,ref);if(on===null)return{kind:"problem",reason:"git",message:"Toolroll couldn't list this project's checkouts."};if(on.length===0)return{kind:"free"};let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}if(on.length!==1||on[0]!==repoReal)return{kind:"problem",reason:"occupied",message:`${branch} is checked out in another folder, so Toolroll won't move it or suggest a command to run there. Switch that folder to another branch, then land it.`};const dirty=await dirtyFilesOf(git,project.repo);return dirty.ok?{kind:"folder",dirty:dirty.files}:{kind:"problem",reason:"git",message:"Toolroll couldn't check whether your project folder has uncommitted changes."}}function handoffRefOf(taskId,commit){return`refs/toolroll/land/${/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(taskId)&&!taskId.includes("..")&&!taskId.endsWith(".lock")&&!taskId.endsWith(".")?taskId:createHash("sha256").update(taskId).digest("hex").slice(0,16)}/${oidOrThrow(commit)}`}function projectOf(store,repo){if(repo===null||!store.knownRepos().includes(repo))return null;const common=commonDirOf(repo);return common===null?null:{repo,common}}export function publishesThroughPullRequests(store,repo){try{return publishingOf(store,repo).on||store.publicationGrantFor(repo)!==null}catch{return!0}}export const PULL_REQUESTS_INSTEAD="This project publishes through pull requests; open one from the task instead.";const ALREADY_MSG=(ref,commit)=>`Already on ${ref.replace(/^refs\/heads\//,"")} (${short(commit)}).`,MOVED_MSG=(branch,old)=>`${branch} moved on since this work started (it's at ${short(old)} now). Send it back: Toolroll builds it again on the current ${branch} with this work merged in, and its checks run on both together.`,CONFLICT_MSG=(branch,old,files,candidate)=>{const named=files.slice(0,3).map(one=>shownName(one)).join(", ");return`${branch} moved on since this work started (it's at ${short(old)} now), and its newer changes conflict with this work${named===""?"":` in ${named}${files.length>3?", …":""}`}. Toolroll can't merge them by itself. To land it, merge ${short(candidate)} into ${branch} yourself and resolve the conflicts, or file a new task on the current ${branch}.`};export function landingBranchOf(store,repo,fallback){const recorded=recordedDestination(store,repo);return recorded!==null&&recorded.common===commonDirOf(repo)?recorded.ref.slice(11):fallback}export async function readLanding(store,taskId,access,now,options){const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);if(assignment.repo!==null&&publishesThroughPullRequests(store,assignment.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,assignment.repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const unresolved=unresolvedLandingForRepo(store,project.repo);if(unresolved!==null)return{ok:!1,reason:"unresolved",message:unresolved.words,unresolved};const git=gitFor(project.repo,options.git);if(options.undo===!0)return readUndo(store,assignment.rootId,project,git,options);const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const later=assignment.completion.digest!==receipt.digest;if(later&&assignment.completion.historical!==!0)return refuse("checks","This result changed since you accepted it. Look at it again, then land it.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");const landed=landingOf(store,assignment.rootId);if(landed!==null&&!landed.undone&&landed.intent.candidate===candidate){const reverted=landedStanding(store,assignment.rootId,readGit)?.reverted===!0;return{ok:!0,landed:{at:landed.at,ref:landed.intent.ref,commit:landed.intent.commit,mode:landed.intent.mode,...reverted?{reverted}:{}}}}const checks=receipt.checks.status==="passed"?"passed":!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"?"none":null;if(checks===null)return receipt.checks.status==="failed"?refuse("checks",later?`Its checks failed when they ran again after you accepted it (${receipt.checks.detail.replace(/\.$/,"")}). It stays Complete; it can't land until they pass on its exact commit.`:"Its checks failed. Only work whose checks passed on its exact commit lands."):refuse("checks",later?"Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it.":"Its checks haven't passed on its exact commit. Run checks, then land it.");const destination=await destinationOf(store,project,git,options.into);if(!destination.ok)return destination;const run=store.getRun(receipt.runId),base=run===null||run.branch===null?null:wholeChangeBaseOf(store,run.taskRef,run.branch)??run.baseRevision,read=await planFor(git,project,destination,{kind:"land",taskId:receipt.taskId,rootId:assignment.rootId,runId:receipt.runId,receipt:receipt.digest,completion:assignment.completion.digest,candidate,checks,bindings:checkBindingsOf(store,project.repo)},{base,message:squashMessage(store.getTask(receipt.taskId)?.title??null,receipt.taskId),time:Math.max(0,Math.floor(Date.parse(assignment.completion.at)/1e3)||0),handedOff:handoffsOf(store,project.repo,assignment.rootId).filter(one=>one.candidate===candidate).map(one=>one.commit)},ownerMode(store,now)==="fast");if(!read.ok&&read.reason==="nothing"){const seen=recognisedOnBranch(store,project.repo,assignment.rootId,candidate,readGit);if(seen!==null&&seen.reverted)return refuse("nothing",`${seen.words}.`)}if(!read.ok&&read.reason==="moved"){const now2=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=now2.stdout.trim(),files=now2.code===0&&OID.test(old)?catchUpConflictOf(store,receipt.taskId,old):null;if(files!==null)return refuse("moved",CONFLICT_MSG(destination.ref.slice(11),old,files,candidate))}return read}export function landedLine(landed){return`Landed on ${landed.ref.replace(/^refs\/heads\//,"")} (${short(landed.commit)})${landed.reverted===!0?" · a later commit reverted it":""}.`}async function destinationOf(store,project,git,into){const recorded=recordedDestination(store,project.repo);if(into!==void 0){if(!landableBranch(into))return refuse("destination",`\`${into}\` isn't a branch Toolroll can land on.`);const ref2=`refs/heads/${into}`;return{ok:!0,ref:ref2,recorded:recorded?.ref===ref2&&recorded.common===project.common}}if(recorded!==null&&recorded.common===project.common)return{ok:!0,ref:recorded.ref,recorded:!0};const head=await git(["symbolic-ref","-q","HEAD"]),ref=head.stdout.trim();return head.code!==0||!ref.startsWith("refs/heads/")||!landableBranch(ref.slice(11))?refuse("destination","Your project folder isn't on a branch Toolroll can land on. Name one: --into <branch>."):{ok:!0,ref,recorded:!1}}const UNSAFE_MESSAGE=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]+/g;function squashMessage(title,taskId){const plain=text=>text.replace(UNSAFE_MESSAGE," ").replace(/\s+/g," ").trim(),line=plain(title??"").slice(0,200),id=plain(taskId).slice(0,100);return line===""?`Toolroll task ${id}`:`${line} (Toolroll task ${id})`}async function changesOf(git,old,candidate){const stat=await git(["diff","--numstat","-z","--no-renames","--no-ext-diff","--no-textconv",old,candidate]);if(stat.code!==0)return null;const files=[];let added=0,removed=0;for(const entry of stat.stdout.split("\0")){const match=/^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);match!==null&&(added+=match[1]==="-"?0:Number(match[1]),removed+=match[2]==="-"?0:Number(match[2]),files.push(match[3]))}return{files:files.slice(0,20),fileCount:files.length,added,removed}}async function planFor(git,project,destination,fixed,squashing=null,inPlace=!1){const{ref}=destination,branch=ref.slice(11),read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),old=read.stdout.trim();if(read.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);if(fixed.candidate!==null){if(old===fixed.candidate)return refuse("nothing",ALREADY_MSG(ref,old));const type=await git(["cat-file","-t",fixed.candidate]);if(type.code!==0||type.stdout.trim()!=="commit")return refuse("git",`This result's commit ${short(fixed.candidate)} is no longer in the project.`);for(const landed of[fixed.candidate,...squashing?.handedOff??[]])if((await git(["merge-base","--is-ancestor",landed,old])).code===0)return refuse("nothing",ALREADY_MSG(ref,landed));const ancestor=await git(["merge-base","--is-ancestor",old,fixed.candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const problem=await treeProblem(git,fixed.candidate)??await treeProblem(git,old);if(problem!==null)return refuse("unsupported",`This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`)}let squash=null;if(fixed.candidate!==null){const tree=await git(["rev-parse","--verify","-q",`${fixed.candidate}^{tree}`]),changes=await changesOf(git,old,fixed.candidate);if(tree.code!==0||!OID.test(tree.stdout.trim())||changes===null)return refuse("git",`Toolroll couldn't read what ${short(fixed.candidate)} changes.`);const message=squashing?.message??`Toolroll task ${fixed.taskId}`,time=squashing?.time??0,treeId=tree.stdout.trim();squash={policy:"squash",base:squashing?.base??null,commit:commitIdOf(squashBody(treeId,old,time,message)),tree:treeId,checkedTree:treeId,time,message,...changes}}const place=await placeOf(git,project,ref,old);if(place.kind==="problem")return refuse(place.reason,place.message);if(place.kind==="folder"&&fixed.kind==="undo"){const command=gitCommand(project.repo,["revert","--no-edit",`${oidOrThrow(fixed.reverts.old)}..${oidOrThrow(fixed.reverts.landed)}`]);return refuse("occupied",`${branch} is checked out in your project folder, so Toolroll won't touch its files. ${command===null?UNSAFE_FOLDER(`git revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`):`To do it yourself there: ${command}`}`)}if(place.kind==="folder"&&fixed.kind==="land"&&inPlace&&place.dirty.length>0)return dirtyRefuse(branch,place.dirty);const mode=place.kind==="free"?"ref":inPlace?"files":"handoff",plan={...fixed,squash,repo:project.repo,ref,branch,old,mode,recorded:destination.recorded};return{ok:!0,plan:{...plan,key:keyOf({v:1,...plan,common:project.common})}}}async function readUndo(store,rootId,project,git,options){const landed=landingOf(store,rootId);if(landed!==null&&landed.undone)return refuse("nothing","This landing was already undone.");const brought=landed===null?await broughtIn(store,git,project.repo,rootId):null,source=landed!==null?{key:landed.intent.key,task:landed.intent.task,run:landed.intent.run,ref:landed.intent.ref,old:landed.intent.old,commit:landed.intent.commit,name:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`}:brought===null?null:{key:brought.key,task:brought.task,run:brought.run,ref:brought.ref,old:brought.old,commit:brought.commit,name:`handoff:${brought.id}`};return source===null?refuse("nothing","This task hasn't landed, so there's nothing to undo."):planFor(git,project,{ref:source.ref,recorded:!0},{kind:"undo",taskId:source.task,rootId,runId:source.run,receipt:source.key,completion:source.key,candidate:null,checks:"none",reverts:{source:source.name,old:source.old,landed:source.commit},bindings:checkBindingsOf(store,project.repo)})}function landedCommits(store,rootId){return new Set(intents(store,"task_id = ?",[rootId]).filter(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0).map(one=>one.commit))}async function broughtIn(store,git,repo,rootId){const landed=landedCommits(store,rootId);for(const one of handoffsOf(store,repo,rootId))if(!landed.has(one.commit)&&(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code===0)return one;return null}function squashBody(tree,parent,time,message){const who=`Toolroll <land@toolroll.invalid> ${time} +0000`;return`tree ${tree}
2
3
  parent ${parent}
3
4
  author ${who}
4
5
  committer ${who}
5
6
 
6
7
  ${message}
7
- `}function commitIdOf(body){return createHash("sha1").update(`commit ${Buffer.byteLength(body,"utf8")}\0`).update(body,"utf8").digest("hex")}const UNSAFE_SHOWN=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\\]/g;export function shownName(name){return name.replace(UNSAFE_SHOWN,ch=>ch==="\\"?"\\\\":`\\u{${ch.codePointAt(0).toString(16)}}`)}export function landingWords(plan){const how=plan.mode==="handoff"?`your project folder has ${plan.branch} checked out, so Toolroll won't touch its files: Land makes the commit and shows the one git command that brings it in`:`no folder has ${plan.branch} checked out; only the branch moves`;if(plan.kind==="undo")return[`Undo the landing of ${short(plan.reverts.landed)} on ${plan.branch} in ${shownName(plan.repo)} (${how}).`,"A new commit reverts exactly what it changed; nothing is rewritten. No check runs on the undo."];const squash=plan.squash,names=squash.files.slice(0,3).map(shownName).join(", ")+(squash.fileCount>3?` and ${squash.fileCount-3} more`:"");return[`Lands 1 commit on ${plan.branch}: ${squash.fileCount===0?"no file changes":names} (+${squash.added} −${squash.removed}).`,`${short(squash.commit)} "${shownName(squash.message)}", on top of ${short(plan.old)} in ${shownName(plan.repo)} (${how}).`,plan.checks==="passed"?`Checks ran on these exact files: they passed on ${short(plan.candidate)}, and ${short(squash.commit)} carries the same tree.`:"No check ran: this project has no check command.",...plan.recorded?[]:[`Toolroll remembers ${plan.branch} as where this project's work lands.`]]}async function settleUnfinished(store,repo,now,options){if(projectOf(store,repo)===null)return;const git=gitFor(repo,options.git);for(const intent of intents(store,"repo = ?",[repo]).filter(one=>settledOf(store,one.id)===null)){const symbolic=await git(["symbolic-ref","-q",intent.ref]),at=(await git(["rev-parse","--verify","-q",`${intent.ref}^{commit}`])).stdout.trim();let outcome,words;symbolic.code!==1?(outcome="needs-person",words=`${intent.ref.replace(/^refs\/heads\//,"")} now points at another branch or can't be read. Look at ${repo} with git log.`):at===intent.old?(outcome="abandoned",words="It stopped before the branch moved; nothing changed."):at===intent.commit&&intent.mode==="files"?(outcome="needs-person",words=`The branch moved to ${short(intent.commit)}; check your folder's files with git status in ${repo}.`):at===intent.commit?(outcome="landed:recovered",words="It had finished; recorded now."):(outcome="needs-person",words=`The branch is at ${OID.test(at)?short(at):"an unreadable commit"} now, neither before nor after the landing. Look at ${repo} with git log.`),recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:intent.task,runId:intent.run,action:LAND_SETTLED,outcome:`${intent.id}:${outcome}`,source:"work"},{v:1,words})}}function standing(store,authority,repo){if(authority.kind==="local"){const local=localActNow(store,"land-task");return local===null?refuse("authority",LOCAL_OWNER_LAPSED):!verifyApproverStanding(store,local.account,local.accountGeneration,store.knownRepos().filter(one=>store.accountCanAccess(local.account,one))).ok||!store.accountCanAccess(local.account,repo)?refuse("authority",LOCAL_OWNER_LAPSED):{ok:!0,actor:`operator:${local.account}`}}if(!reproveApprover(store,authority.who).ok||!authority.who.repos.includes(repo)||!store.accountCanAccess(authority.who.name,repo))return refuse("authority","Your access changed. Sign in again.");if(authority.kind==="passkey"){const dev=getPairedDevice(store.handle,authority.proof.deviceId),identity=store.workspaceIdentity();if(dev===null||dev.revokedAt!==null||dev.activatedAt===null||dev.accountName!==authority.who.name||dev.recoveryGeneration!==identity.recoveryGeneration||!deviceAccountStands(dev,store.accountOf(authority.who.name)))return refuse("authority","This iPhone is no longer paired or your account changed.")}return{ok:!0,actor:`operator:${authority.who.name}`}}const projectLocks=new Map;async function locked(repo,body){const before=projectLocks.get(repo)??Promise.resolve();let release;const mine=new Promise(resolve=>{release=resolve}),chained=before.then(()=>mine);projectLocks.set(repo,chained),await before.catch(()=>{});try{return await body()}finally{release(),projectLocks.get(repo)===chained&&projectLocks.delete(repo)}}export async function land(store,taskId,input,authority,access,now,options){if(!/^[0-9a-f]{16}$/.test(input.key))return refuse("stale","That landing isn't the one on screen. Look again, then land it.");const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const named=input.into!==void 0&&landableBranch(input.into)?`refs/heads/${input.into}`:recordedDestination(store,repo)?.ref??null;return named!==null&&projectOf(store,repo)!==null&&(await gitFor(repo,options.git)(["symbolic-ref","-q",named])).code===0?refuse("destination",`${named.replace(/^refs\/heads\//,"")} points at another branch, so Toolroll won't move it. Land it with git yourself.`):locked(repo,async()=>{const done=intents(store,"repo = ? AND task_id IS NOT NULL",[repo]).find(one=>one.key===input.key);if(done!==void 0&&settledOf(store,done.id)?.outcome.startsWith("landed")===!0){const who=standing(store,authority,repo);return who.ok?{ok:!0,replayed:!0,kind:done.kind,ref:done.ref,branch:done.ref.slice(11),commit:done.commit,old:done.old,mode:done.mode,warning:null,handoff:null}:who}const handedOff=input.undo===!0?void 0:handoffRows(store,repo).find(one=>one.key===input.key);if(handedOff!==void 0){const who=standing(store,authority,repo);if(!who.ok)return who;const git2=gitFor(repo,options.git),there=await git2(["cat-file","-t",handedOff.commit]);return there.code!==0||there.stdout.trim()!=="commit"?refuse("git","The landing commit Toolroll kept for this is gone. Look again, then land it."):await keepAt(git2,handedOff.keep,handedOff.commit,`toolroll: landing commit for ${taskId}`)?(handedOff.settled||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:handedOff.task,runId:handedOff.run,action:LAND_HANDOFF_SETTLED,outcome:`${handedOff.id}:kept`,source:"work"},{v:1,keep:handedOff.keep,commit:handedOff.commit}),{ok:!0,replayed:handedOff.settled,kind:"land",ref:handedOff.ref,branch:handedOff.ref.slice(11),commit:handedOff.commit,old:handedOff.old,mode:"handoff",warning:null,handoff:{ref:handedOff.keep,command:handoffCommand(repo,handedOff.commit)}}):refuse("git","Toolroll couldn't keep the landing commit. Look again, then land it.")}await settleUnfinished(store,repo,now,options);const read=await readLanding(store,taskId,access,now,{...options,...input.into===void 0?{}:{into:input.into},...input.undo===!0?{undo:!0}:{}});if(!read.ok)return read;if(!("plan"in read))return refuse("nothing",read.landed.reverted===!0?landedLine(read.landed):ALREADY_MSG(read.landed.ref,read.landed.commit));const plan=read.plan;if(plan.key!==input.key)return refuse("stale","Something changed since you looked (the branch, the checks or the result). Look again, then land it.");const project=projectOf(store,plan.repo),git=gitFor(plan.repo,options.git),handoffSource=plan.kind==="undo"?/^handoff:(\d+)$/.exec(plan.reverts?.source??""):null;if(handoffSource!==null&&!await reconcileHandoff(store,git,plan.repo,plan.rootId,Number(handoffSource[1]),first.actor,now))return refuse("stale","That landing changed since you looked. Look again.");const stillStands=()=>{const who=standing(store,authority,plan.repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,plan.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);if(plan.kind==="land"){const again=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos},options.root);if(again?.state!=="complete"||again.receipt?.digest!==plan.receipt||again.completion?.digest!==plan.completion)return refuse("stale","This result changed since you looked. Look again, then land it.")}else{const landed=landingOf(store,plan.rootId),name=landed===null?null:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`;if(landed===null||landed.undone||name!==plan.reverts?.source)return refuse("stale","That landing changed since you looked. Look again.")}return JSON.stringify(checkBindingsOf(store,plan.repo))!==JSON.stringify(plan.bindings)?refuse("stale","The project's checks changed since you looked. Look again, then land it."):who},pre=standing(store,authority,plan.repo);if(!pre.ok)return pre;const landBinding={verb:"land",taskId,planKey:plan.key,into:input.into??null,undo:input.undo===!0},passkeyChecked=authority.kind!=="passkey"?null:checkPasskeyAction(store,{accountName:authority.who.name,repo:plan.repo,verb:"land",expectedBinding:landBinding,proof:authority.proof,now});if(passkeyChecked!==null&&!passkeyChecked.ok)return refuse("authority",passkeyChecked.message);const consumeLandPasskey=()=>{if(authority.kind!=="passkey"||passkeyChecked===null||!passkeyChecked.ok)return;const at=authority.clock(),consumed=consumePasskeyAction(store,passkeyChecked,{repo:plan.repo,now:at});if(!consumed.ok)throw new Refused(refuse("authority",consumed.message));store.recordAction({at:at.toISOString(),actor:authority.who.name,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_PROVED_ACTION,outcome:"passkey",source:"request",detail:passkeyProofDetail({at,generation:consumed.accountGeneration,digest:plan.key,verb:"land",credentialId:consumed.credentialId,pairedDeviceId:consumed.deviceId,be:consumed.be,bs:consumed.bs})})},made=plan.kind==="undo"?await revertCommit(git,plan,options.scratch):await squashCommit(git,plan,options.scratch);if(!made.ok)return made;const commit=made.commit,keep=handoffRefOf(plan.rootId,commit);if(plan.kind==="land"&&!await keepAt(git,keep,commit,`toolroll: landing commit for ${plan.taskId}`))return refuse("git","Toolroll made the landing commit but couldn't keep it. Nothing landed; look again, then land it.");if(plan.mode==="handoff"){const place2=await placeOf(git,project,plan.ref,plan.old);if(place2.kind!=="folder")return refuse(place2.kind==="problem"?place2.reason:"stale",place2.kind==="problem"?place2.message:"Your project folder changed since you looked. Look again, then land it.");let handoffId,replayed=!1;try{handoffId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);const earlier=handoffRows(store,plan.repo).find(one=>one.key===plan.key&&one.commit===commit);return earlier!==void 0?(replayed=earlier.settled,earlier.id):(consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF,outcome:"pending",source:"request"},{v:1,key:plan.key,ref:plan.ref,old:plan.old,commit,keep,folder:project.repo,policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,checks:plan.checks}))})}catch(error){if(error instanceof Refused)return error.result;throw error}const at=await git(["rev-parse","--verify","-q",`${keep}^{commit}`]);return at.code!==0||at.stdout.trim()!==commit?refuse("git","Toolroll couldn't keep the landing commit. Nothing landed; look again, then land it."):(replayed||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF_SETTLED,outcome:`${handoffId}:kept`,source:"work"},{v:1,keep,commit}),{ok:!0,replayed,kind:"land",ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"handoff",warning:null,handoff:{ref:keep,command:handoffCommand(project.repo,commit)}})}let intentId;try{intentId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);if(intents(store,"repo = ?",[plan.repo]).some(one=>settledOf(store,one.id)===null))throw new Refused(refuse("busy","Another landing in this project hasn't finished. Try again in a moment."));return consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:plan.kind,key:plan.key,ref:plan.ref,old:plan.old,commit,mode:"ref",...plan.reverts===void 0?{}:{reverts:plan.reverts.source},...plan.squash===null?{}:{policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,keep,checks:plan.checks}})})}catch(error){if(error instanceof Refused)return error.result;throw error}const settle=(outcome,words)=>recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_SETTLED,outcome:`${intentId}:${outcome}`,source:"work"},{v:1,words}),place=await placeOf(git,project,plan.ref,plan.old);if(place.kind!=="free"){const words=place.kind==="problem"?place.message:`${plan.branch} is checked out in your project folder now, so Toolroll won't move it. Look again, then land it.`;return settle("refused",words),refuse(place.kind==="problem"?place.reason:"occupied",words)}const last=store.transact(stillStands);if(!last.ok)return settle("refused",last.message),last;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words),refuse("moved",words)}return settle("landed",plan.kind==="undo"?"Undone.":"Landed."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"ref",warning:null,handoff:null}})}async function keepAt(git,ref,commit,why){const was=await git(["rev-parse","--verify","-q",ref]),old=was.code===0?was.stdout.trim():"0".repeat(40);return old===commit?!0:was.code===0&&!OID.test(old)?!1:(await git(["update-ref","--no-deref","-m",why,ref,commit,old])).code===0}async function reconcileHandoff(store,git,repo,rootId,id,actor,now){const one=handoffsOf(store,repo,rootId).find(row=>row.id===id);return one===void 0||(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code!==0?!1:store.transact(()=>{const recorded=intents(store,"task_id = ?",[rootId]).find(intent2=>intent2.fromHandoff===one.id);if(recorded!==void 0)return settledOf(store,recorded.id)?.outcome.startsWith("landed")===!0;if(landedCommits(store,rootId).has(one.commit))return!1;const intent=recordActionWhole(store.handle,{at:now.toISOString(),actor,repo,taskId:rootId,runId:one.run,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:"land",key:one.key,ref:one.ref,old:one.old,commit:one.commit,mode:"ref",policy:"squash",candidate:one.candidate,fromHandoff:one.id});return recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:rootId,runId:one.run,action:LAND_SETTLED,outcome:`${intent}:landed:brought-in`,source:"work"},{v:1,words:"The person brought in the landing commit Toolroll made; recorded as landed."}),!0})}function oidOrThrow(oid){if(!OID.test(oid))throw new Error("not a commit id");return oid}const UNSAFE_IN_COMMAND=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;export const unsafeInCommand=text=>UNSAFE_IN_COMMAND.test(text);export function gitCommand(folder,args){return UNSAFE_IN_COMMAND.test(folder)?null:["git","-C",`'${folder.replace(/'/g,"'\\''")}'`,...args].join(" ")}export const UNSAFE_FOLDER=what=>`Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;function handoffCommand(folder,commit){return gitCommand(folder,["merge","--ff-only",oidOrThrow(commit)])}export function handoffWords(handoff,commit){return handoff.command===null?UNSAFE_FOLDER(`git merge --ff-only ${commit}`):`To bring it in: ${handoff.command}`}function handoffRows(store,repo,taskId){return store.handle.prepare(`SELECT id,detail,task_id,run_id FROM action_ledger WHERE repo = ? AND action = ?${taskId===void 0?"":" AND task_id = ?"} ORDER BY id DESC`).all(...taskId===void 0?[repo,LAND_HANDOFF]:[repo,LAND_HANDOFF,taskId]).flatMap(row=>{try{const d=JSON.parse(String(row.detail??"null")),ok=d.v===1&&typeof d.key=="string"&&typeof d.ref=="string"&&typeof d.old=="string"&&OID.test(d.old)&&typeof d.commit=="string"&&OID.test(d.commit)&&typeof d.keep=="string"&&typeof d.folder=="string"&&typeof d.candidate=="string"&&OID.test(d.candidate),id=Number(row.id),settled=ok&&store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND outcome = ? LIMIT 1").get(LAND_HANDOFF_SETTLED,`${id}:kept`)!==void 0;return ok?[{id,task:String(row.task_id),run:Number(row.run_id),key:d.key,ref:d.ref,old:d.old,commit:d.commit,keep:d.keep,folder:d.folder,candidate:d.candidate,settled}]:[]}catch{return[]}})}export function handoffsOf(store,repo,taskId){return handoffRows(store,repo,taskId).filter(one=>one.settled)}export function keptHandoffOf(store,repo,rootId,candidate){if(candidate===null||!OID.test(candidate))return null;const one=handoffsOf(store,repo,rootId).find(row=>row.candidate===candidate);if(one===void 0)return null;const command=handoffCommand(one.folder,one.commit);return{commit:one.commit,branch:one.ref.replace(/^refs\/heads\//,""),command,words:handoffWords({command},one.commit)}}class Refused extends Error{result;constructor(result){super(result.message),this.result=result}}async function squashCommit(git,plan,scratch){const squash=plan.squash;if(squash.tree!==squash.checkedTree)return refuse("checks","The commit Toolroll would land doesn't carry the files its checks ran on. Nothing landed.");const verified=await git(["rev-parse","--verify","-q",`${plan.candidate}^{tree}`]);if(verified.code!==0||verified.stdout.trim()!==squash.checkedTree)return refuse("checks","The result's files aren't the ones its checks ran on any more. Nothing landed.");const folder=mkdtempSync(join(scratch??tmpdir(),"toolroll-land-"));let written;try{const file=join(folder,"commit");writeFileSync(file,squashBody(squash.tree,plan.old,squash.time,squash.message),{encoding:"utf8",mode:384,flag:"wx"}),written=await git(["hash-object","-t","commit","-w","--",file])}finally{rmSync(folder,{recursive:!0,force:!0})}const commit=written.stdout.trim();if(written.code!==0||commit!==squash.commit)return refuse("stale","The commit Toolroll would land isn't the one you read. Nothing landed; look again.");const shown=await git(["cat-file","commit",commit]),header=shown.stdout.split(`
8
+ `}function commitIdOf(body){return createHash("sha1").update(`commit ${Buffer.byteLength(body,"utf8")}\0`).update(body,"utf8").digest("hex")}const UNSAFE_SHOWN=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\\]/g;export function shownName(name){return name.replace(UNSAFE_SHOWN,ch=>ch==="\\"?"\\\\":`\\u{${ch.codePointAt(0).toString(16)}}`)}export function landingWords(plan){const how=plan.mode==="files"?`your project folder has ${plan.branch} checked out and clean; Land fast-forwards it in place`:plan.mode==="handoff"?`your project folder has ${plan.branch} checked out, so Toolroll won't touch its files: Land makes the commit and shows the one git command that brings it in`:`no folder has ${plan.branch} checked out; only the branch moves`;if(plan.kind==="undo")return[`Undo the landing of ${short(plan.reverts.landed)} on ${plan.branch} in ${shownName(plan.repo)} (${how}).`,"A new commit reverts exactly what it changed; nothing is rewritten. No check runs on the undo."];const squash=plan.squash,names=squash.files.slice(0,3).map(shownName).join(", ")+(squash.fileCount>3?` and ${squash.fileCount-3} more`:"");return[`Lands 1 commit on ${plan.branch}: ${squash.fileCount===0?"no file changes":names} (+${squash.added} −${squash.removed}).`,`${short(squash.commit)} "${shownName(squash.message)}", on top of ${short(plan.old)} in ${shownName(plan.repo)} (${how}).`,plan.checks==="passed"?`Checks ran on these exact files: they passed on ${short(plan.candidate)}, and ${short(squash.commit)} carries the same tree.`:"No check ran: this project has no check command.",...plan.recorded?[]:[`Toolroll remembers ${plan.branch} as where this project's work lands.`]]}async function settleUnfinished(store,repo,now,options){const project=projectOf(store,repo);if(project===null)return;const git=gitFor(repo,options.git);for(const intent of intents(store,"repo = ?",[repo]).filter(one=>settledOf(store,one.id)===null)){const branch=intent.ref.replace(/^refs\/heads\//,""),state=await inspectInPlaceState(git,project,intent.ref,intent.old,intent.commit);let outcome,words,extra={};!state.refReadable||state.refAt===null?(outcome="unresolved",words=`${branch} now points at another branch or can't be read. Choose how to resolve this unfinished landing below.`,extra={state:stateSummaryOf(state)}):state.refAt===intent.old?intent.mode==="files"&&state.headSym===intent.ref&&!state.indexMatchesOld?(outcome="unresolved",words=`A previous landing on ${branch} stopped before moving the branch, but your checkout index doesn't match ${short(intent.old)}. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}):(outcome="abandoned",words="It stopped before the branch moved; nothing changed."):state.refAt===intent.commit?intent.mode==="files"?isProvenInPlaceLanded(state,intent.ref,intent.commit)?(outcome="landed:recovered",words="It had finished in place; recorded now."):(outcome="unresolved",words=`${branch} moved to ${short(intent.commit)}, but your project folder's index or files don't match that commit yet. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}):(outcome="landed:recovered",words="It had finished; recorded now."):(outcome="unresolved",words=`${branch} is at ${short(state.refAt)} now, neither before nor after the unfinished landing. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}),recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:intent.task,runId:intent.run,action:LAND_SETTLED,outcome:`${intent.id}:${outcome}`,source:"work"},{v:1,words,...extra})}}export async function reconcileUnfinishedLandings(store,repo,authority,access,now,options){return access.repos!==null&&!access.repos.includes(repo)||!standing(store,authority,repo).ok?!1:(await locked(repo,async()=>{const project=projectOf(store,repo);return project!==null&&releaseLeftoverHeadLock(project.common),settleUnfinished(store,repo,now,options)}),!0)}export async function resolveUnresolvedLanding(store,taskId,action,authority,access,now,options,shown=null){const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;const project=projectOf(store,repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const rootId=store.taskFamilyOf(taskId,null,!0)?.root.id??taskId;return locked(repo,async()=>{await settleUnfinished(store,repo,now,options);const unresolved=unresolvedLandingOf(store,rootId)??unresolvedLandingForRepo(store,repo);if(unresolved===null)return{ok:!0,outcome:"already-clear",message:"No unfinished landing needs attention."};if(shown===null||shown.intentId!==unresolved.intentId||shown.commit!==unresolved.commit||shown.old!==unresolved.old)return{ok:!1,reason:"unresolved",message:"This page showed a different unfinished landing than the one there now; nothing changed. Look again, then choose.",unresolved};const git=gitFor(repo,options.git),settleNew=(outcome,words,extra={})=>store.transact(()=>{const who=standing(store,authority,repo);return who.ok?(recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo,taskId:unresolved.taskId,runId:unresolved.runId,action:LAND_SETTLED,outcome:`${unresolved.intentId}:${outcome}`,source:"request"},{v:1,words,...extra}),{ok:!0}):who});if(action==="dismiss"){const wrote=settleNew("dismissed","Cleared by operator; landing was not recorded as completed.");return wrote.ok?{ok:!0,outcome:"dismissed",message:"Cleared the unfinished landing notice. The task is not marked as landed."}:wrote}const state=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(action==="complete"){if(isProvenInPlaceLanded(state,unresolved.ref,unresolved.commit)){const wrote=settleNew("landed:recovered","Confirmed completed landing in place.");return wrote.ok?{ok:!0,outcome:"landed",message:`Confirmed landing on ${unresolved.branch} (${short(unresolved.commit)}).`}:wrote}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.commit&&state.headSym===unresolved.ref&&state.headAt===unresolved.commit&&state.checkouts!==null&&state.checkouts.length===1&&state.checkouts[0]===state.repoReal&&state.indexMatchesOld&&state.inProgressOps!==null&&state.inProgressOps.length===0){const checkBefore=standing(store,authority,repo);if(!checkBefore.ok)return checkBefore;const updated=await git(["read-tree","-m","-u",unresolved.old,unresolved.commit]),after=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(updated.code===0&&isProvenInPlaceLanded(after,unresolved.ref,unresolved.commit)){const wrote=settleNew("landed:recovered","Finished updating files in place and recorded the landing.");return wrote.ok?{ok:!0,outcome:"landed",message:`Finished landing on ${unresolved.branch} (${short(unresolved.commit)}).`}:wrote}return{ok:!1,reason:"unresolved",message:"Your project folder has local changes that stop this landing from finishing automatically. Choose Restore branch or Clear notice.",unresolved}}return{ok:!1,reason:"unresolved",message:"The branch or checkout state changed too far to finish this landing automatically. Choose Restore branch or Clear notice.",unresolved}}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.old&&(state.headSym!==unresolved.ref||state.indexMatchesOld)){const wrote=settleNew("abandoned","Confirmed branch is back at its previous commit.");return wrote.ok?{ok:!0,outcome:"rolled-back",message:`${unresolved.branch} is back at ${short(unresolved.old)}.`}:wrote}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.commit){const checkBefore=standing(store,authority,repo);if(!checkBefore.ok)return checkBefore;if(state.headSym===unresolved.ref&&state.indexMatchesCommit&&state.worktreeMatchesCommit&&state.inProgressOps!==null&&state.inProgressOps.length===0){if((await git(["read-tree","-m","-u",unresolved.commit,unresolved.old])).code!==0)return{ok:!1,reason:"unresolved",message:"Couldn't restore the project folder's files cleanly. Choose Clear notice if you want to handle it manually.",unresolved}}else if(state.headSym===unresolved.ref&&!state.indexMatchesOld)return{ok:!1,reason:"unresolved",message:"Your project folder has staged or modified files, so Toolroll won't overwrite them during rollback. Choose Clear notice after checking them.",unresolved};const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${unresolved.taskId}`,unresolved.ref,unresolved.old,unresolved.commit]),after=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(rolled.code===0&&after.refAt===unresolved.old&&(after.headSym!==unresolved.ref||after.indexMatchesOld)){const wrote=settleNew("abandoned",`Restored ${unresolved.branch} to ${short(unresolved.old)}.`);return wrote.ok?{ok:!0,outcome:"rolled-back",message:`Restored ${unresolved.branch} to ${short(unresolved.old)}.`}:wrote}}return{ok:!1,reason:"unresolved",message:`${unresolved.branch} moved past the unfinished landing, so Toolroll won't roll it back automatically. Choose Clear notice to clear this blocker.`,unresolved}})}function standing(store,authority,repo){if(authority.kind==="local"){const local=localActNow(store,"land-task");return local===null?refuse("authority",LOCAL_OWNER_LAPSED):!verifyApproverStanding(store,local.account,local.accountGeneration,store.knownRepos().filter(one=>store.accountCanAccess(local.account,one))).ok||!store.accountCanAccess(local.account,repo)?refuse("authority",LOCAL_OWNER_LAPSED):{ok:!0,actor:`operator:${local.account}`}}if(!reproveApprover(store,authority.who).ok||!authority.who.repos.includes(repo)||!store.accountCanAccess(authority.who.name,repo))return refuse("authority","Your access changed. Sign in again.");if(authority.kind==="passkey"){const dev=getPairedDevice(store.handle,authority.proof.deviceId),identity=store.workspaceIdentity();if(dev===null||dev.revokedAt!==null||dev.activatedAt===null||dev.accountName!==authority.who.name||dev.recoveryGeneration!==identity.recoveryGeneration||!deviceAccountStands(dev,store.accountOf(authority.who.name)))return refuse("authority","This iPhone is no longer paired or your account changed.")}return{ok:!0,actor:`operator:${authority.who.name}`}}const projectLocks=new Map;async function locked(repo,body){const before=projectLocks.get(repo)??Promise.resolve();let release;const mine=new Promise(resolve=>{release=resolve}),chained=before.then(()=>mine);projectLocks.set(repo,chained),await before.catch(()=>{});try{return await body()}finally{release(),projectLocks.get(repo)===chained&&projectLocks.delete(repo)}}export async function land(store,taskId,input,authority,access,now,options){if(!/^[0-9a-f]{16}$/.test(input.key))return refuse("stale","That landing isn't the one on screen. Look again, then land it.");const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const named=input.into!==void 0&&landableBranch(input.into)?`refs/heads/${input.into}`:recordedDestination(store,repo)?.ref??null;return named!==null&&projectOf(store,repo)!==null&&(await gitFor(repo,options.git)(["symbolic-ref","-q",named])).code===0?refuse("destination",`${named.replace(/^refs\/heads\//,"")} points at another branch, so Toolroll won't move it. Land it with git yourself.`):locked(repo,async()=>{const done=intents(store,"repo = ? AND task_id IS NOT NULL",[repo]).find(one=>one.key===input.key);if(done!==void 0&&settledOf(store,done.id)?.outcome.startsWith("landed")===!0){const who=standing(store,authority,repo);return who.ok?{ok:!0,replayed:!0,kind:done.kind,ref:done.ref,branch:done.ref.slice(11),commit:done.commit,old:done.old,mode:done.mode,warning:null,handoff:null}:who}const handedOff=input.undo===!0||input.requireInPlace===!0?void 0:handoffRows(store,repo).find(one=>one.key===input.key);if(handedOff!==void 0){const who=standing(store,authority,repo);if(!who.ok)return who;const git2=gitFor(repo,options.git),there=await git2(["cat-file","-t",handedOff.commit]);return there.code!==0||there.stdout.trim()!=="commit"?refuse("git","The landing commit Toolroll kept for this is gone. Look again, then land it."):await keepAt(git2,handedOff.keep,handedOff.commit,`toolroll: landing commit for ${taskId}`)?(handedOff.settled||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:handedOff.task,runId:handedOff.run,action:LAND_HANDOFF_SETTLED,outcome:`${handedOff.id}:kept`,source:"work"},{v:1,keep:handedOff.keep,commit:handedOff.commit}),{ok:!0,replayed:handedOff.settled,kind:"land",ref:handedOff.ref,branch:handedOff.ref.slice(11),commit:handedOff.commit,old:handedOff.old,mode:"handoff",warning:null,handoff:{ref:handedOff.keep,command:handoffCommand(repo,handedOff.commit)}}):refuse("git","Toolroll couldn't keep the landing commit. Look again, then land it.")}await settleUnfinished(store,repo,now,options);const read=await readLanding(store,taskId,access,now,{...options,...input.into===void 0?{}:{into:input.into},...input.undo===!0?{undo:!0}:{}});if(!read.ok)return read;if(!("plan"in read))return refuse("nothing",read.landed.reverted===!0?landedLine(read.landed):ALREADY_MSG(read.landed.ref,read.landed.commit));const plan=read.plan;if(plan.key!==input.key)return refuse("stale","Something changed since you looked (the branch, the checks or the result). Look again, then land it.");if(input.requireInPlace===!0&&(ownerMode(store,now)!=="fast"||plan.mode==="handoff"))return refuse("stale","In-place landing requires Fast mode; nothing landed.");const project=projectOf(store,plan.repo),git=gitFor(plan.repo,options.git),handoffSource=plan.kind==="undo"?/^handoff:(\d+)$/.exec(plan.reverts?.source??""):null;if(handoffSource!==null&&!await reconcileHandoff(store,git,plan.repo,plan.rootId,Number(handoffSource[1]),first.actor,now))return refuse("stale","That landing changed since you looked. Look again.");const stillStands=()=>{const who=standing(store,authority,plan.repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,plan.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);if(plan.kind==="land"){const again=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos},options.root);if(again?.state!=="complete"||again.receipt?.digest!==plan.receipt||again.completion?.digest!==plan.completion)return refuse("stale","This result changed since you looked. Look again, then land it.")}else{const landed=landingOf(store,plan.rootId),name=landed===null?null:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`;if(landed===null||landed.undone||name!==plan.reverts?.source)return refuse("stale","That landing changed since you looked. Look again.")}return JSON.stringify(checkBindingsOf(store,plan.repo))!==JSON.stringify(plan.bindings)?refuse("stale","The project's checks changed since you looked. Look again, then land it."):who},pre=standing(store,authority,plan.repo);if(!pre.ok)return pre;const landBinding={verb:"land",taskId,planKey:plan.key,into:input.into??null,undo:input.undo===!0},passkeyChecked=authority.kind!=="passkey"?null:checkPasskeyAction(store,{accountName:authority.who.name,repo:plan.repo,verb:"land",expectedBinding:landBinding,proof:authority.proof,now});if(passkeyChecked!==null&&!passkeyChecked.ok)return refuse("authority",passkeyChecked.message);const consumeLandPasskey=()=>{if(authority.kind!=="passkey"||passkeyChecked===null||!passkeyChecked.ok)return;const at=authority.clock(),consumed=consumePasskeyAction(store,passkeyChecked,{repo:plan.repo,now:at});if(!consumed.ok)throw new Refused(refuse("authority",consumed.message));store.recordAction({at:at.toISOString(),actor:authority.who.name,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_PROVED_ACTION,outcome:"passkey",source:"request",detail:passkeyProofDetail({at,generation:consumed.accountGeneration,digest:plan.key,verb:"land",credentialId:consumed.credentialId,pairedDeviceId:consumed.deviceId,be:consumed.be,bs:consumed.bs})})},made=plan.kind==="undo"?await revertCommit(git,plan,options.scratch):await squashCommit(git,plan,options.scratch);if(!made.ok)return made;const commit=made.commit,keep=handoffRefOf(plan.rootId,commit);if(plan.kind==="land"&&!await keepAt(git,keep,commit,`toolroll: landing commit for ${plan.taskId}`))return refuse("git","Toolroll made the landing commit but couldn't keep it. Nothing landed; look again, then land it.");if(plan.mode==="handoff"){const place2=await placeOf(git,project,plan.ref,plan.old);if(place2.kind!=="folder")return refuse(place2.kind==="problem"?place2.reason:"stale",place2.kind==="problem"?place2.message:"Your project folder changed since you looked. Look again, then land it.");let handoffId,replayed=!1;try{handoffId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);const earlier=handoffRows(store,plan.repo).find(one=>one.key===plan.key&&one.commit===commit);return earlier!==void 0?(replayed=earlier.settled,earlier.id):(consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF,outcome:"pending",source:"request"},{v:1,key:plan.key,ref:plan.ref,old:plan.old,commit,keep,folder:project.repo,policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,checks:plan.checks}))})}catch(error){if(error instanceof Refused)return error.result;throw error}const at=await git(["rev-parse","--verify","-q",`${keep}^{commit}`]);return at.code!==0||at.stdout.trim()!==commit?refuse("git","Toolroll couldn't keep the landing commit. Nothing landed; look again, then land it."):(replayed||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF_SETTLED,outcome:`${handoffId}:kept`,source:"work"},{v:1,keep,commit}),{ok:!0,replayed,kind:"land",ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"handoff",warning:null,handoff:{ref:keep,command:handoffCommand(project.repo,commit)}})}let intentId;try{intentId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);if(intents(store,"repo = ?",[plan.repo]).some(one=>settledOf(store,one.id)===null))throw new Refused(refuse("busy","Another landing in this project hasn't finished. Try again in a moment."));return consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:plan.kind,key:plan.key,ref:plan.ref,old:plan.old,commit,mode:plan.mode,...plan.reverts===void 0?{}:{reverts:plan.reverts.source},...plan.squash===null?{}:{policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,keep,checks:plan.checks}})})}catch(error){if(error instanceof Refused)return error.result;throw error}const settle=(outcome,words,extra={})=>recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_SETTLED,outcome:`${intentId}:${outcome}`,source:"work"},{v:1,words,...extra}),place=await placeOf(git,project,plan.ref,plan.old);if(plan.mode==="files"){if(place.kind!=="folder"){const words2=place.kind==="problem"?place.message:`${plan.branch} is no longer checked out in your project folder. Look again, then land it.`;return settle("refused",words2),refuse(place.kind==="problem"?place.reason:"stale",words2)}if(place.dirty.length>0){const dirty=dirtyRefuse(plan.branch,place.dirty);return settle("refused",dirty.message),dirty}if(ownerMode(store,now)!=="fast"){const words2="Fast mode was turned off before landing in place; nothing landed. Look again, then land it.";return settle("refused",words2),refuse("stale",words2)}const headSymBefore=await git(["symbolic-ref","-q","HEAD"]),headAtBefore=await git(["rev-parse","--verify","-q","HEAD^{commit}"]),idxBefore=await git(["diff-index","--cached","--quiet",plan.old]);if(headSymBefore.code!==0||headSymBefore.stdout.trim()!==plan.ref||headAtBefore.code!==0||headAtBefore.stdout.trim()!==plan.old||idxBefore.code!==0){const words2="Your project folder's branch or index changed before landing; nothing landed. Look again, then land it.";return settle("refused",words2),refuse(idxBefore.code!==0?"dirty":"stale",words2)}const last2=store.transact(stillStands);if(!last2.ok)return settle("refused",last2.message),last2;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words2=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words2),refuse("moved",words2)}const headLock=await holdHeadLock(git),headSymMid=await git(["symbolic-ref","-q","HEAD"]),idxMid=await git(["diff-index","--cached","--quiet",plan.old]);if(!headLock.ok||headSymMid.code!==0||headSymMid.stdout.trim()!==plan.ref||idxMid.code!==0){headLock.ok&&headLock.release();const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${plan.taskId}`,plan.ref,plan.old,commit]),midState=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(rolled.code===0&&midState.refAt===plan.old){const words3="Your project folder switched branches or staged changes while landing, so nothing landed. Look again, then land it.";return settle("refused",words3),refuse("stale",words3)}const words2=`Landing on ${plan.branch} stopped after updating the branch because your project folder switched branches or staged changes. Resolve it below.`;settle("unresolved",words2,{state:stateSummaryOf(midState)});const unresolved2=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words2,...unresolved2===void 0?{}:{unresolved:unresolved2}}}const updated=await git(["read-tree","-m","-u",plan.old,commit]);if(headLock.release(),updated.code!==0){const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${plan.taskId}`,plan.ref,plan.old,commit]),failState=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(rolled.code===0&&failState.refAt===plan.old&&(failState.headSym!==plan.ref||failState.indexMatchesOld)){const words3="Your project folder changed while landing, so nothing landed. Look again, then land it.";return settle("refused",words3),refuse(failState.dirtyFiles!==null&&failState.dirtyFiles.length>0?"dirty":"stale",words3)}const words2=`Landing on ${plan.branch} stopped partway through (${plan.branch} moved to ${short(commit)}, but your checkout files couldn't all be updated). Resolve it below.`;settle("unresolved",words2,{state:stateSummaryOf(failState)});const unresolved2=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words2,...unresolved2===void 0?{}:{unresolved:unresolved2}}}const after=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(isProvenInPlaceLanded(after,plan.ref,commit))return settle("landed","Landed in place."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"files",warning:null,handoff:null};const words=`Landing on ${plan.branch} wrote changes, but the final checkout state didn't match ${short(commit)} cleanly. Resolve it below.`;settle("unresolved",words,{state:stateSummaryOf(after)});const unresolved=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words,...unresolved===void 0?{}:{unresolved}}}if(place.kind!=="free"){const words=place.kind==="problem"?place.message:`${plan.branch} is checked out in your project folder now. Look again, then land it.`;return settle("refused",words),refuse(place.kind==="problem"?place.reason:"occupied",words)}const last=store.transact(stillStands);if(!last.ok)return settle("refused",last.message),last;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words),refuse("moved",words)}return settle("landed",plan.kind==="undo"?"Undone.":"Landed."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"ref",warning:null,handoff:null}})}async function keepAt(git,ref,commit,why){const was=await git(["rev-parse","--verify","-q",ref]),old=was.code===0?was.stdout.trim():"0".repeat(40);return old===commit?!0:was.code===0&&!OID.test(old)?!1:(await git(["update-ref","--no-deref","-m",why,ref,commit,old])).code===0}async function reconcileHandoff(store,git,repo,rootId,id,actor,now){const one=handoffsOf(store,repo,rootId).find(row=>row.id===id);return one===void 0||(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code!==0?!1:store.transact(()=>{const recorded=intents(store,"task_id = ?",[rootId]).find(intent2=>intent2.fromHandoff===one.id);if(recorded!==void 0)return settledOf(store,recorded.id)?.outcome.startsWith("landed")===!0;if(landedCommits(store,rootId).has(one.commit))return!1;const intent=recordActionWhole(store.handle,{at:now.toISOString(),actor,repo,taskId:rootId,runId:one.run,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:"land",key:one.key,ref:one.ref,old:one.old,commit:one.commit,mode:"ref",policy:"squash",candidate:one.candidate,fromHandoff:one.id});return recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:rootId,runId:one.run,action:LAND_SETTLED,outcome:`${intent}:landed:brought-in`,source:"work"},{v:1,words:"The person brought in the landing commit Toolroll made; recorded as landed."}),!0})}function oidOrThrow(oid){if(!OID.test(oid))throw new Error("not a commit id");return oid}const UNSAFE_IN_COMMAND=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;export const unsafeInCommand=text=>UNSAFE_IN_COMMAND.test(text);export function gitCommand(folder,args){return UNSAFE_IN_COMMAND.test(folder)?null:["git","-C",`'${folder.replace(/'/g,"'\\''")}'`,...args].join(" ")}export const UNSAFE_FOLDER=what=>`Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;function handoffCommand(folder,commit){return gitCommand(folder,["merge","--ff-only",oidOrThrow(commit)])}export function handoffWords(handoff,commit){return handoff.command===null?UNSAFE_FOLDER(`git merge --ff-only ${commit}`):`To bring it in: ${handoff.command}`}function handoffRows(store,repo,taskId){return store.handle.prepare(`SELECT id,detail,task_id,run_id FROM action_ledger WHERE repo = ? AND action = ?${taskId===void 0?"":" AND task_id = ?"} ORDER BY id DESC`).all(...taskId===void 0?[repo,LAND_HANDOFF]:[repo,LAND_HANDOFF,taskId]).flatMap(row=>{try{const d=JSON.parse(String(row.detail??"null")),ok=d.v===1&&typeof d.key=="string"&&typeof d.ref=="string"&&typeof d.old=="string"&&OID.test(d.old)&&typeof d.commit=="string"&&OID.test(d.commit)&&typeof d.keep=="string"&&typeof d.folder=="string"&&typeof d.candidate=="string"&&OID.test(d.candidate),id=Number(row.id),settled=ok&&store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND outcome = ? LIMIT 1").get(LAND_HANDOFF_SETTLED,`${id}:kept`)!==void 0;return ok?[{id,task:String(row.task_id),run:Number(row.run_id),key:d.key,ref:d.ref,old:d.old,commit:d.commit,keep:d.keep,folder:d.folder,candidate:d.candidate,settled}]:[]}catch{return[]}})}export function handoffsOf(store,repo,taskId){return handoffRows(store,repo,taskId).filter(one=>one.settled)}export function keptHandoffOf(store,repo,rootId,candidate){if(candidate===null||!OID.test(candidate))return null;const one=handoffsOf(store,repo,rootId).find(row=>row.candidate===candidate);if(one===void 0)return null;const command=handoffCommand(one.folder,one.commit);return{commit:one.commit,branch:one.ref.replace(/^refs\/heads\//,""),command,words:handoffWords({command},one.commit)}}class Refused extends Error{result;constructor(result){super(result.message),this.result=result}}async function squashCommit(git,plan,scratch){const squash=plan.squash;if(squash.tree!==squash.checkedTree)return refuse("checks","The commit Toolroll would land doesn't carry the files its checks ran on. Nothing landed.");const verified=await git(["rev-parse","--verify","-q",`${plan.candidate}^{tree}`]);if(verified.code!==0||verified.stdout.trim()!==squash.checkedTree)return refuse("checks","The result's files aren't the ones its checks ran on any more. Nothing landed.");const folder=mkdtempSync(join(scratch??tmpdir(),"toolroll-land-"));let written;try{const file=join(folder,"commit");writeFileSync(file,squashBody(squash.tree,plan.old,squash.time,squash.message),{encoding:"utf8",mode:384,flag:"wx"}),written=await git(["hash-object","-t","commit","-w","--",file])}finally{rmSync(folder,{recursive:!0,force:!0})}const commit=written.stdout.trim();if(written.code!==0||commit!==squash.commit)return refuse("stale","The commit Toolroll would land isn't the one you read. Nothing landed; look again.");const shown=await git(["cat-file","commit",commit]),header=shown.stdout.split(`
8
9
 
9
10
  `)[0]??"",parents=header.split(`
10
11
  `).filter(line=>line.startsWith("parent ")).map(line=>line.slice(7));return shown.code!==0||!header.startsWith(`tree ${squash.checkedTree}
@@ -12,4 +13,22 @@ ${message}
12
13
  `).filter(line=>line.startsWith(":")),keys=[];for(const line of lines){const match=/^:(\d{6}) (\d{6}) ([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) [A-Z]\d*\t(.+)$/.exec(line);if(match===null)return null;keys.push(`${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]}`)}return keys.sort()},own=read(repo,["diff-tree","-r","--no-renames","--no-abbrev","--no-commit-id","--no-ext-diff","--no-textconv",landing.commit]),mine=own===null?null:changes(own);if(mine===null||mine.length===0)return!1;const inverse=mine.map(key=>{const[modes,path]=key.split(" "),[m1,m2,s1,s2]=modes.split(" ");return`${m2} ${m1} ${s2} ${s1} ${path}`}).sort().join(`
13
14
  `),later=read(repo,["log","--no-show-signature","--no-merges","--ancestry-path","-n","50","--format=%x01%H","--raw","--no-renames","--no-abbrev","--no-ext-diff","--no-textconv",`${landing.commit}..${ref}`]);return later===null?!1:later.split("").slice(1).some(entry=>changes(entry.slice(entry.indexOf(`
14
15
  `)+1))?.join(`
15
- `)===inverse)}export function recognisedOnBranch(store,repo,rootId,candidate,read){if(candidate===null||!OID.test(candidate))return null;const ref=recordedDestination(store,repo)?.ref??null??(()=>{const head=read(repo,["symbolic-ref","-q","HEAD"]);return head!==null&&head.startsWith("refs/heads/")?head:null})();if(ref===null||!landableBranch(ref.slice(11)))return null;const handed=handoffsOf(store,repo,rootId).filter(one=>one.candidate===candidate&&one.ref===ref),found=[{commit:candidate,old:null},...handed.map(one=>({commit:one.commit,old:one.old}))].find(one=>read(repo,["merge-base","--is-ancestor",one.commit,ref])!==null);if(found===void 0)return null;const reverted=found.old!==null&&revertedOnBranch(repo,ref,{old:found.old,commit:found.commit},read),where=`Landed on ${ref.slice(11)} (${short(found.commit)})`;return{words:reverted?`${where} · a later commit reverted it`:where,reverted}}export function landingHistoryOf(store,repo,rootId,candidate,read){const record=landingOf(store,rootId);if(record===null||record.undone){const onBranch=recognisedOnBranch(store,repo,rootId,candidate,read);if(onBranch!==null)return{...onBranch,landed:!0,recorded:!1}}const standing2=landedStanding(store,rootId,read);return standing2===null?null:{...standing2,landed:record!==null&&!record.undone&&candidate!==null&&record.intent.candidate===candidate,recorded:!0}}export function broughtInOnBranch(store,repo,rootId,read){const landed=landedCommits(store,rootId);return handoffsOf(store,repo,rootId).some(one=>!landed.has(one.commit)&&read(repo,["merge-base","--is-ancestor",one.commit,one.ref])!==null)}
16
+ `)===inverse)}export function recognisedOnBranch(store,repo,rootId,candidate,read){if(candidate===null||!OID.test(candidate))return null;const ref=recordedDestination(store,repo)?.ref??null??(()=>{const head=read(repo,["symbolic-ref","-q","HEAD"]);return head!==null&&head.startsWith("refs/heads/")?head:null})();if(ref===null||!landableBranch(ref.slice(11)))return null;const handed=handoffsOf(store,repo,rootId).filter(one=>one.candidate===candidate&&one.ref===ref),found=[{commit:candidate,old:null},...handed.map(one=>({commit:one.commit,old:one.old}))].find(one=>read(repo,["merge-base","--is-ancestor",one.commit,ref])!==null);if(found===void 0)return null;const reverted=found.old!==null&&revertedOnBranch(repo,ref,{old:found.old,commit:found.commit},read),where=`Landed on ${ref.slice(11)} (${short(found.commit)})`;return{words:reverted?`${where} · a later commit reverted it`:where,reverted}}export function landingHistoryOf(store,repo,rootId,candidate,read){const record=landingOf(store,rootId);if(record===null||record.undone){const onBranch=recognisedOnBranch(store,repo,rootId,candidate,read);if(onBranch!==null)return{...onBranch,landed:!0,recorded:!1}}const standing2=landedStanding(store,rootId,read);return standing2===null?null:{...standing2,landed:record!==null&&!record.undone&&candidate!==null&&record.intent.candidate===candidate,recorded:!0}}export function broughtInOnBranch(store,repo,rootId,read){const landed=landedCommits(store,rootId);return handoffsOf(store,repo,rootId).some(one=>!landed.has(one.commit)&&read(repo,["merge-base","--is-ancestor",one.commit,one.ref])!==null)}function readPendingRow(raw){if(raw===void 0)return null;const kind=raw.authority_kind;return kind!=="person"&&kind!=="local"&&kind!=="passkey"?null:{taskId:String(raw.task_id),repo:String(raw.repo),ref:String(raw.ref),candidate:String(raw.candidate),receipt:String(raw.receipt),completion:String(raw.completion),bindingsJson:String(raw.bindings_json),requestedBy:String(raw.requested_by),requestedAt:String(raw.requested_at),accountGen:Number(raw.account_gen),authorityKind:kind,localGen:raw.local_gen==null?null:Number(raw.local_gen),lastError:raw.last_error==null?null:String(raw.last_error),lastTryAt:raw.last_try_at==null?null:String(raw.last_try_at)}}export function pendingLocalLandOf(store,taskId){return readPendingRow(store.handle.prepare("SELECT * FROM pending_local_land WHERE task_id = ?").get(taskId))}export async function queueLandWhenClean(store,taskId,input,authority,access,now,options){if(authority.kind==="passkey")return refuse("authority","Land when clean isn't available for one-time passkey requests.");if(ownerMode(store,now)!=="fast")return refuse("stale","Land when clean is only available in Fast mode.");const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);const repo=assignment.repo;if(repo===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const who=standing(store,authority,repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");if(!(receipt.checks.status==="passed"||!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"))return refuse("checks","Only work whose checks passed on its exact commit lands.");const git=gitFor(project.repo,options.git),destination=await destinationOf(store,project,git,input.into);if(!destination.ok)return destination;const branch=destination.ref.slice(11),oldRead=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=oldRead.stdout.trim();if(oldRead.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);const ancestor=await git(["merge-base","--is-ancestor",old,candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const bindingsJson=JSON.stringify(checkBindingsOf(store,project.repo)),stamp=now.toISOString();let pending;try{pending=store.transact(()=>{const modeNow=ownerModeSetting(store,now);if(modeNow.mode!=="fast"||modeNow.owner===null)throw new Refused(refuse("stale","Land when clean is only available in Fast mode."));const again=standing(store,authority,repo);if(!again.ok)throw new Refused(again);const accountName=again.actor.replace(/^operator:/,"");if(modeNow.owner!==accountName)throw new Refused(refuse("authority","Only the install owner can queue Land when clean."));const account=store.accountOf(accountName);if(account===null||account.revokedAt!==null||account.role!=="approver")throw new Refused(refuse("authority","Your access changed. Sign in again."));let accountGen=account.generation,localGen=null;if(authority.kind==="local"){const local=localActNow(store,"land-task");if(local===null||local.account!==accountName)throw new Refused(refuse("authority",LOCAL_OWNER_LAPSED));accountGen=local.accountGeneration,localGen=local.localGeneration}else accountGen=authority.who.generation;return store.handle.prepare(`
17
+ INSERT INTO pending_local_land
18
+ (task_id, repo, ref, candidate, receipt, completion, bindings_json, requested_by, requested_at, account_gen, authority_kind, local_gen, last_error, last_try_at)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
20
+ ON CONFLICT(task_id) DO UPDATE SET
21
+ repo = excluded.repo,
22
+ ref = excluded.ref,
23
+ candidate = excluded.candidate,
24
+ receipt = excluded.receipt,
25
+ completion = excluded.completion,
26
+ bindings_json = excluded.bindings_json,
27
+ requested_by = excluded.requested_by,
28
+ requested_at = excluded.requested_at,
29
+ account_gen = excluded.account_gen,
30
+ authority_kind = excluded.authority_kind,
31
+ local_gen = excluded.local_gen,
32
+ last_error = NULL,
33
+ last_try_at = NULL
34
+ `).run(taskId,project.repo,destination.ref,candidate,receipt.digest,assignment.completion.digest,bindingsJson,accountName,stamp,accountGen,authority.kind,localGen),store.recordAction({at:stamp,actor:again.actor,repo:project.repo,taskId:assignment.rootId,runId:receipt.runId,action:LAND_WHEN_CLEAN_QUEUED,outcome:destination.ref,source:"work",detail:`${short(candidate)} queued to land on ${branch} once clean (${authority.kind})`}),pendingLocalLandOf(store,taskId)})}catch(error){if(error instanceof Refused)return error.result;throw error}return{ok:!0,pending,message:`Queued to land on ${branch} automatically once your project folder is clean.`}}function readLocalModeRow(store){const row=store.handle.prepare("SELECT owner, generation, enabled, initialized_at, changed_at FROM local_mode WHERE id = 1").get();return row===void 0?null:{owner:String(row.owner),generation:Number(row.generation),enabled:Number(row.enabled)===1,initializedAt:String(row.initialized_at),changedAt:String(row.changed_at)}}export async function runPendingLocalLands(store,now,options){const pendingRows=store.handle.prepare("SELECT * FROM pending_local_land ORDER BY requested_at ASC").all().map(readPendingRow).filter(one=>one!==null),landed=[],waiting=[],cancelled=[],cancelRow=(row,why)=>{store.transact(()=>{store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),store.recordAction({at:now.toISOString(),actor:"toolroll",repo:row.repo,taskId:row.taskId,runId:null,action:LAND_WHEN_CLEAN_CANCELLED,outcome:"cancelled",source:"work",detail:why.slice(0,500)})}),cancelled.push(row.taskId)};for(const row of pendingRows){if(publishesThroughPullRequests(store,row.repo)){cancelRow(row,PULL_REQUESTS_INSTEAD);continue}const modeNow=ownerModeSetting(store,now),live=liveInstallOwner(store,now);if(modeNow.mode!=="fast"||!live.ok||live.owner!==row.requestedBy){cancelRow(row,"Fast mode is off or ownership changed since Land when clean was requested.");continue}if(row.authorityKind!=="person"&&row.authorityKind!=="local"){cancelRow(row,"Saved authority kind can't be retried automatically.");continue}const verified=verifyApproverStanding(store,row.requestedBy,row.accountGen,[row.repo]);if(!verified.ok){cancelRow(row,"Approver standing or account generation changed.");continue}if(row.authorityKind==="local"){const localMode=readLocalModeRow(store);if(row.localGen===null||!localModeOn(store)||!localBindingStands(localMode,{account:row.requestedBy,localGeneration:row.localGen})){cancelRow(row,LOCAL_OWNER_LAPSED);continue}}await locked(row.repo,()=>settleUnfinished(store,row.repo,now,options));const unresolved=unresolvedLandingForRepo(store,row.repo);if(unresolved!==null){store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(unresolved.words,now.toISOString(),row.taskId),waiting.push(row.taskId);continue}const branch=row.ref.startsWith("refs/heads/")?row.ref.slice(11):row.ref,read=await readLanding(store,row.taskId,{repos:[row.repo]},now,{...options,into:branch});if(!read.ok){if(read.reason==="dirty"||read.reason==="unresolved"){store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(read.message,now.toISOString(),row.taskId),waiting.push(row.taskId);continue}if(read.reason==="nothing"){store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId);continue}cancelRow(row,read.message);continue}if(!("plan"in read)){store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId);continue}const plan=read.plan;if(plan.mode==="handoff"){cancelRow(row,"In-place landing is no longer available (Fast mode is off).");continue}if(plan.candidate!==row.candidate||plan.receipt!==row.receipt||plan.completion!==row.completion||plan.ref!==row.ref||JSON.stringify(plan.bindings)!==row.bindingsJson){cancelRow(row,"The task result, destination, or project checks changed since Land when clean was requested.");continue}const done=row.authorityKind==="local"?await asLocalOwner({account:row.requestedBy,localGeneration:row.localGen,accountGeneration:row.accountGen,transport:"browser",act:"land-task",sessionHash:null,request:null},()=>land(store,row.taskId,{key:plan.key,into:branch,requireInPlace:!0},{kind:"local"},{repos:[row.repo]},now,options)):await land(store,row.taskId,{key:plan.key,into:branch,requireInPlace:!0},{kind:"person",who:verified.who},{repos:[row.repo]},now,options);done.ok?done.handoff!==null||done.mode==="handoff"?cancelRow(row,"Landing produced a manual handoff instead of completing in place."):(store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId)):done.reason==="dirty"||done.reason==="unresolved"?(store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(done.message,now.toISOString(),row.taskId),waiting.push(row.taskId)):cancelRow(row,done.message)}return{landed,waiting,cancelled}}
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";import{currentActor}from"./actor.js";import{activeRemote}from"./remote-run.js";export function authorityOf(value){return value==="full"||value==="local-owner"?value:null}export const LOCAL_OWNER_ACTS=Object.freeze(["file-task","lead-send","approve-plan","build-now","answer-question","stop-run","pause-run","resume-run","complete-task","land-task","request-revision","archive-task","add-project","choose-default-agent","mark-seen","watch-agent","read","routing-turn-off","dismiss-suggestion","trial-stop","code-map-switch","skill-library","memory-review","request-plan","retry-build","run-checks","view-preference","take-over","start-thread","reply-thread","stop-thread","end-thread","check-agents","agent-sign-in","agent-install","change-models","task-sizing-switch","flexible-switch","ship-thread","cancel-ship","save-thread","flexible-sign-in-save","flexible-sign-in-check","flexible-sign-in-clear","project-flexible","project-network","project-live-view","change-task-agents","trigger-pause","trigger-resume","trigger-run","direct-chat-start","direct-chat-send","direct-chat-stop","direct-chat-manage","direct-chat-ship","manage-directions","shared-browser"]),LOCAL_PASSWORD_ACTS=new Set(["flexible-switch","flexible-sign-in-save","flexible-sign-in-check","project-flexible","project-network","project-live-view"]);const ACT_SET=new Set(LOCAL_OWNER_ACTS);export function localOwnerAct(value){return typeof value=="string"&&ACT_SET.has(value)}export const LOCAL_OWNER_PROPOSALS=Object.freeze({task:"allow",answer:"allow",steer:"allow",cancel:"allow",hold:"allow",unhold:"allow",action:"allow",task_action:"allow",next:"refuse",reserve:"refuse",scope:"refuse",repair:"refuse",agents:"refuse",review:"allow",control:"refuse"}),OPERATION_KINDS=new Set(["action","task_action"]);export function localOwnerMayConfirm(kind,act=null){return typeof kind!="string"||!Object.prototype.hasOwnProperty.call(LOCAL_OWNER_PROPOSALS,kind)||LOCAL_OWNER_PROPOSALS[kind]!=="allow"?!1:OPERATION_KINDS.has(kind)?localOwnerAct(act):!0}export function localBindingStands(mode,binding){return mode!==null&&mode.enabled&&binding.localGeneration!==null&&mode.generation===binding.localGeneration&&mode.owner===binding.account}const localOwnerScope=new AsyncLocalStorage;export function currentLocalOwner(){return localOwnerScope.getStore()??null}export function localOwnerInFlight(principal){return principal.request===null||!principal.request.ended}export function asLocalOwner(principal,body){return localOwnerScope.run(Object.freeze({...principal}),body)}export function withLocalAct(act,body){const current=currentLocalOwner();return current===null?body():localOwnerScope.run(Object.freeze({...current,act}),body)}const terminalRequest=new AsyncLocalStorage;export function runAsLocalOwner(fn){return terminalRequest.run(!0,fn)}export function localOwnerRequested(){return terminalRequest.getStore()===!0}export const PROPOSAL_LOCAL_ACTS=Object.freeze({task:"file-task",answer:"answer-question",steer:"lead-send",cancel:"stop-run",hold:"pause-run",unhold:"resume-run",action:null,task_action:null,next:null,reserve:null,scope:null,repair:null,agents:null,review:"request-revision",control:null}),CHAT_ACTION_LOCAL_ACTS=Object.freeze({plugin_install:"skill-library",skill_import:null,skill_enable:null,skill_disable:null,skill_restore:null,skill_test:null,knowledge_instructions:null,knowledge_save:null,knowledge_remove:null,knowledge_restore:null,tool_add:null,tool_remove:null,flow_create:null,flow_starter:null,sweep_file:null,sweep_cancel_rest:null,flow_edit:null,flow_card_add:null,flow_card_move:null,flow_card_approve:null,flow_card_send_back:null,flow_card_choose:null,flow_card_cancel:null,flow_card_comment:null,flow_card_assign:null,flow_card_watch:null,flow_script_save:null,flow_trigger_add:null,flow_trigger_pause:null,flow_trigger_resume:null,flow_trigger_remove:null,flow_browser:null,flow_browser_off:null,subagent_create:null,subagent_soul:null,subagent_state:null,subagent_note:null,subagent_ask:null,subagent_answer:null,subagent_tools:null,subagent_memory:null,subagent_routine:null,subagent_undo:null,kit_setup:null,decision_record:null,decision_retire:null,lead_about_you:null,mode_revoke:null,flow_unattended_off:null,flow_archive:null,provider_resume:null,worker_note:null,lead_identity:null,task_archive:null,task_restore:null,incident_resolve:null,memory_decide:null,finding_send:null,finding_resend:null,task_reopen:null,revision_accept:null,revision_reject:null,flow_unattended:null,suggestion_not_now:"dismiss-suggestion",trial_stop:"trial-stop",code_map_switch:"code-map-switch",code_map_holdout_end:null,scope_approve:"approve-plan",result_accept:"complete-task",task_cancel:"stop-run",task_resume:"resume-run",task_start:"build-now",direct_chat_start:"direct-chat-start",direct_chat_reply:"direct-chat-send",direct_chat_promote:"file-task",direct_chat_ship:"direct-chat-ship",task_handoff:"change-task-agents",workflow_orchestrate:"file-task"}),CHAT_TASK_ACTION_LOCAL_ACTS=Object.freeze({stop:"stop-run",resume:"resume-run",retry:null,plan:null,wait_for:null,stop_waiting:null,run_checks:null,run_full_checks:null,add_tests:null});export function proposalLocalAct(kind,operation){if(typeof kind!="string"||!Object.prototype.hasOwnProperty.call(PROPOSAL_LOCAL_ACTS,kind))return null;const own=table=>typeof operation=="string"&&Object.prototype.hasOwnProperty.call(table,operation)?table[operation]??null:null,act=kind==="action"?own(CHAT_ACTION_LOCAL_ACTS):kind==="task_action"?own(CHAT_TASK_ACTION_LOCAL_ACTS):PROPOSAL_LOCAL_ACTS[kind];return act!==null&&localOwnerMayConfirm(kind,act)?act:null}export function localOwnerRefusal(passwordSet,returnTo){return passwordSet?{message:"Sign in with your password to do this.",action:"Sign in with your password",href:`/login?return=${encodeURIComponent(returnTo)}`}:{message:"Set a password to do this.",action:"Set a password",href:returnTo==="/"?"/password/set":`/password/set?next=${encodeURIComponent(returnTo)}`}}export function localModeOn(store){const row=store.handle.prepare("SELECT enabled FROM local_mode WHERE id = 1").get();return row!==void 0&&Number(row.enabled)===1}export function localOwnerStandsNow(store,principal){const mode=store.handle.prepare("SELECT owner, generation, enabled FROM local_mode WHERE id = 1").get();if(mode===void 0||Number(mode.enabled)!==1||Number(mode.generation)!==principal.localGeneration||String(mode.owner)!==principal.account)return!1;const account=store.accountOf(principal.account);return account===null||account.revokedAt!==null||account.role!=="approver"||account.generation!==principal.accountGeneration?!1:principal.sessionHash===null||store.webSession(principal.sessionHash)!==null}export const LOCAL_OWNER_LAPSED="This local sign-in no longer stands. Run `toolroll` to sign in again.",LOCAL_MODE_CONFINES="Turn off local mode first.",LOCAL_OWNER_ELSEWHERE="This sign-in works only on the computer running Toolroll. To use Toolroll from here, set a password on that computer (run `toolroll password set`) and sign in with it.";export function localActNow(store,act){if(activeRemote()!==null||currentActor()?.lead===!0)return null;const local=currentLocalOwner();return local===null||local.act!==act||!localOwnerInFlight(local)||!localOwnerStandsNow(store,local)?null:local}
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{currentActor}from"./actor.js";import{activeRemote}from"./remote-run.js";export function authorityOf(value){return value==="full"||value==="local-owner"?value:null}export const LOCAL_OWNER_ACTS=Object.freeze(["file-task","lead-send","approve-plan","build-now","answer-question","stop-run","pause-run","resume-run","complete-task","land-task","request-revision","archive-task","add-project","choose-default-agent","mark-seen","watch-agent","read","routing-turn-off","dismiss-suggestion","trial-stop","code-map-switch","skill-library","memory-review","request-plan","retry-build","run-checks","view-preference","take-over","start-thread","reply-thread","stop-thread","end-thread","check-agents","agent-sign-in","agent-install","change-models","task-sizing-switch","flexible-switch","ship-thread","cancel-ship","save-thread","flexible-sign-in-save","flexible-sign-in-check","flexible-sign-in-clear","project-flexible","project-network","project-live-view","change-task-agents","trigger-pause","trigger-resume","trigger-run","direct-chat-start","direct-chat-send","direct-chat-stop","direct-chat-manage","direct-chat-ship","manage-directions","shared-browser","mode-sign","check-agent","pr-merge","project-check-access","project-sandbox","start-release"]),LOCAL_PASSWORD_ACTS=new Set(["flexible-switch","flexible-sign-in-save","flexible-sign-in-check","project-flexible","project-network","project-live-view"]),FAST_ONLY_LOCAL_ACTS=new Set(["mode-sign","check-agent","pr-merge","project-check-access","project-sandbox","start-release"]);const ACT_SET=new Set(LOCAL_OWNER_ACTS);export function localOwnerAct(value){return typeof value=="string"&&ACT_SET.has(value)}export const LOCAL_OWNER_PROPOSALS=Object.freeze({task:"allow",answer:"allow",steer:"allow",cancel:"allow",hold:"allow",unhold:"allow",action:"allow",task_action:"allow",next:"refuse",reserve:"refuse",scope:"refuse",repair:"refuse",agents:"refuse",review:"allow",control:"refuse"}),OPERATION_KINDS=new Set(["action","task_action"]);export function localOwnerMayConfirm(kind,act=null){return typeof kind!="string"||!Object.prototype.hasOwnProperty.call(LOCAL_OWNER_PROPOSALS,kind)||LOCAL_OWNER_PROPOSALS[kind]!=="allow"?!1:OPERATION_KINDS.has(kind)?localOwnerAct(act):!0}export function localBindingStands(mode,binding){return mode!==null&&mode.enabled&&binding.localGeneration!==null&&mode.generation===binding.localGeneration&&mode.owner===binding.account}const localOwnerScope=new AsyncLocalStorage;export function currentLocalOwner(){return localOwnerScope.getStore()??null}export function localOwnerInFlight(principal){return principal.request===null||!principal.request.ended}export function asLocalOwner(principal,body){return localOwnerScope.run(Object.freeze({...principal}),body)}export function withLocalAct(act,body){const current=currentLocalOwner();return current===null?body():localOwnerScope.run(Object.freeze({...current,act}),body)}const terminalRequest=new AsyncLocalStorage;export function runAsLocalOwner(fn){return terminalRequest.run(!0,fn)}export function localOwnerRequested(){return terminalRequest.getStore()===!0}export const PROPOSAL_LOCAL_ACTS=Object.freeze({task:"file-task",answer:"answer-question",steer:"lead-send",cancel:"stop-run",hold:"pause-run",unhold:"resume-run",action:null,task_action:null,next:null,reserve:null,scope:null,repair:null,agents:null,review:"request-revision",control:null}),CHAT_ACTION_LOCAL_ACTS=Object.freeze({plugin_install:"skill-library",skill_import:null,skill_enable:null,skill_disable:null,skill_restore:null,skill_test:null,knowledge_instructions:null,knowledge_save:null,knowledge_remove:null,knowledge_restore:null,tool_add:null,tool_remove:null,flow_create:null,flow_starter:null,sweep_file:null,sweep_cancel_rest:null,flow_edit:null,flow_card_add:null,flow_card_move:null,flow_card_approve:null,flow_card_send_back:null,flow_card_choose:null,flow_card_cancel:null,flow_card_comment:null,flow_card_assign:null,flow_card_watch:null,flow_script_save:null,flow_trigger_add:null,flow_trigger_pause:null,flow_trigger_resume:null,flow_trigger_remove:null,flow_browser:null,flow_browser_off:null,subagent_create:null,subagent_soul:null,subagent_state:null,subagent_note:null,subagent_ask:null,subagent_answer:null,subagent_tools:null,subagent_memory:null,subagent_routine:null,subagent_undo:null,kit_setup:null,decision_record:null,decision_retire:null,lead_about_you:null,mode_revoke:null,flow_unattended_off:null,flow_archive:null,provider_resume:null,worker_note:null,lead_identity:null,task_archive:null,task_restore:null,incident_resolve:null,memory_decide:null,finding_send:null,finding_resend:null,task_reopen:null,revision_accept:null,revision_reject:null,flow_unattended:null,suggestion_not_now:"dismiss-suggestion",trial_stop:"trial-stop",code_map_switch:"code-map-switch",code_map_holdout_end:null,scope_approve:"approve-plan",result_accept:"complete-task",task_cancel:"stop-run",task_resume:"resume-run",task_start:"build-now",direct_chat_start:"direct-chat-start",direct_chat_reply:"direct-chat-send",direct_chat_promote:"file-task",direct_chat_ship:"direct-chat-ship",task_handoff:"change-task-agents",workflow_orchestrate:"file-task",release_start:"start-release"}),CHAT_TASK_ACTION_LOCAL_ACTS=Object.freeze({stop:"stop-run",resume:"resume-run",retry:null,plan:null,wait_for:null,stop_waiting:null,run_checks:null,run_full_checks:null,add_tests:null});export function proposalLocalAct(kind,operation){if(typeof kind!="string"||!Object.prototype.hasOwnProperty.call(PROPOSAL_LOCAL_ACTS,kind))return null;const own=table=>typeof operation=="string"&&Object.prototype.hasOwnProperty.call(table,operation)?table[operation]??null:null,act=kind==="action"?own(CHAT_ACTION_LOCAL_ACTS):kind==="task_action"?own(CHAT_TASK_ACTION_LOCAL_ACTS):PROPOSAL_LOCAL_ACTS[kind];return act!==null&&localOwnerMayConfirm(kind,act)?act:null}export function localOwnerRefusal(passwordSet,returnTo){return passwordSet?{message:"Sign in with your password to do this.",action:"Sign in with your password",href:`/login?return=${encodeURIComponent(returnTo)}`}:{message:"Set a password to do this.",action:"Set a password",href:returnTo==="/"?"/password/set":`/password/set?next=${encodeURIComponent(returnTo)}`}}export function localModeOn(store){const row=store.handle.prepare("SELECT enabled FROM local_mode WHERE id = 1").get();return row!==void 0&&Number(row.enabled)===1}export function localOwnerStandsNow(store,principal){const mode=store.handle.prepare("SELECT owner, generation, enabled FROM local_mode WHERE id = 1").get();if(mode===void 0||Number(mode.enabled)!==1||Number(mode.generation)!==principal.localGeneration||String(mode.owner)!==principal.account)return!1;const account=store.accountOf(principal.account);return account===null||account.revokedAt!==null||account.role!=="approver"||account.generation!==principal.accountGeneration?!1:principal.sessionHash===null||store.webSession(principal.sessionHash)!==null}export const LOCAL_OWNER_LAPSED="This local sign-in no longer stands. Run `toolroll` to sign in again.",LOCAL_MODE_CONFINES="Turn off local mode first.",LOCAL_OWNER_ELSEWHERE="This sign-in works only on the computer running Toolroll. To use Toolroll from here, set a password on that computer (run `toolroll password set`) and sign in with it.";export function localActNow(store,act){if(activeRemote()!==null||currentActor()?.lead===!0)return null;const local=currentLocalOwner();return local===null||local.act!==act||!localOwnerInFlight(local)||!localOwnerStandsNow(store,local)?null:local}
@@ -1 +1 @@
1
- import{execFileSync}from"node:child_process";import{createHash}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import{hostname}from"node:os";const defaultRun=(file,args)=>execFileSync(file,args,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});export function hashMachineId(source,raw){return createHash("sha256").update(`toolroll machine identity v1\0${source}\0${raw.trim().toLowerCase()}`).digest("hex").slice(0,32)}export function readMachineIdentity(readers={}){const platform=readers.platform??process.platform,readFile=readers.readFile??(path=>readFileSync(path,"utf8")),exists=readers.exists??existsSync,run=readers.run??defaultRun;try{if(platform==="darwin"){const raw=/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(run("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"]))?.[1];return raw===void 0||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)?{ok:!1,reason:"malformed",detail:"ioreg named no IOPlatformUUID"}:{ok:!0,id:hashMachineId("darwin-platform-uuid",raw),source:"darwin-platform-uuid"}}if(platform==="linux"){if(exists("/.dockerenv")||exists("/run/.containerenv"))return{ok:!1,reason:"container",detail:"a container's machine-id can be shared with other containers"};let raw=null;for(const path of["/etc/machine-id","/var/lib/dbus/machine-id"])try{raw=readFile(path).trim();break}catch{}return raw===null?{ok:!1,reason:"unreadable",detail:"no machine-id could be read"}:!/^[0-9a-f]{32}$/i.test(raw)||/^0+$/.test(raw)?{ok:!1,reason:"malformed",detail:"the machine-id was not 32 hex digits"}:{ok:!0,id:hashMachineId("linux-machine-id",raw),source:"linux-machine-id"}}if(platform==="win32"){const out=run("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]),raw=/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(out)?.[1];return raw===void 0?{ok:!1,reason:"malformed",detail:"the registry named no MachineGuid"}:{ok:!0,id:hashMachineId("win32-machine-guid",raw),source:"win32-machine-guid"}}return{ok:!1,reason:"unsupported-platform",detail:`${platform} exposes no machine identity this build trusts`}}catch(error){return{ok:!1,reason:"unreadable",detail:`the machine identity could not be read: ${error instanceof Error?error.message:String(error)}`}}}const SYSTEM_CONFIGURATION_PREFERENCES="/Library/Preferences/SystemConfiguration/preferences.plist";export function readConfiguredHostNames(readers={}){if((readers.platform??process.platform)!=="darwin")return[];const run=readers.run??defaultRun,names=[],one=key=>{try{const value=run("/usr/bin/plutil",["-extract",key,"raw","-o","-",SYSTEM_CONFIGURATION_PREFERENCES]).trim();return/^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/.test(value)?value:null}catch{return null}},host=one("System.System.HostName");host!==null&&names.push(host);const local=one("System.Network.HostNames.LocalHostName");return local!==null&&!local.includes(".")&&names.push(`${local}.local`),names}let cachedIdentity=null,cachedConfigured=null;const remembered=new Map;function machineIdentity(){return cachedIdentity===null&&(cachedIdentity=readMachineIdentity()),cachedIdentity}export function currentMachineId(){const identity=machineIdentity();return identity.ok?identity.id:null}export function injectMachineIdentity(identity,configured=identity===null?null:[]){cachedIdentity=identity,cachedConfigured=configured,remembered.clear()}export function rememberHostAliases(id,hosts){let set=remembered.get(id);set===void 0&&remembered.set(id,set=new Set);for(const host of hosts)host!==""&&set.add(host)}export function liveHostAliases(){return cachedConfigured===null&&(cachedConfigured=readConfiguredHostNames()),[...new Set([hostname(),...cachedConfigured])]}export function thisMachine(extra=[]){const id=currentMachineId(),hosts=new Set(liveHostAliases());if(id!==null){for(const host of remembered.get(id)??[])hosts.add(host);for(const host of extra)hosts.add(host)}return{id,hosts:[...hosts]}}export function isThisMachine(witness,here=thisMachine()){return witness.machineId!==null&&witness.machineId!==void 0?here.id!==null&&witness.machineId===here.id:here.hosts.includes(witness.host)}export function sameMachineHost(seen,here=hostname(),machineId){return machineId!=null?here===hostname()&&isThisMachine({host:seen,machineId}):seen===here?!0:here===hostname()&&isThisMachine({host:seen})}
1
+ import{execFileSync}from"node:child_process";import{createHash}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import{hostname}from"node:os";import{withoutLeadTokenEnv}from"./names.js";const defaultRun=(file,args)=>execFileSync(file,args,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"],env:withoutLeadTokenEnv(process.env)});export function hashMachineId(source,raw){return createHash("sha256").update(`toolroll machine identity v1\0${source}\0${raw.trim().toLowerCase()}`).digest("hex").slice(0,32)}export function readMachineIdentity(readers={}){const platform=readers.platform??process.platform,readFile=readers.readFile??(path=>readFileSync(path,"utf8")),exists=readers.exists??existsSync,run=readers.run??defaultRun;try{if(platform==="darwin"){const raw=/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(run("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"]))?.[1];return raw===void 0||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)?{ok:!1,reason:"malformed",detail:"ioreg named no IOPlatformUUID"}:{ok:!0,id:hashMachineId("darwin-platform-uuid",raw),source:"darwin-platform-uuid"}}if(platform==="linux"){if(exists("/.dockerenv")||exists("/run/.containerenv"))return{ok:!1,reason:"container",detail:"a container's machine-id can be shared with other containers"};let raw=null;for(const path of["/etc/machine-id","/var/lib/dbus/machine-id"])try{raw=readFile(path).trim();break}catch{}return raw===null?{ok:!1,reason:"unreadable",detail:"no machine-id could be read"}:!/^[0-9a-f]{32}$/i.test(raw)||/^0+$/.test(raw)?{ok:!1,reason:"malformed",detail:"the machine-id was not 32 hex digits"}:{ok:!0,id:hashMachineId("linux-machine-id",raw),source:"linux-machine-id"}}if(platform==="win32"){const out=run("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]),raw=/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(out)?.[1];return raw===void 0?{ok:!1,reason:"malformed",detail:"the registry named no MachineGuid"}:{ok:!0,id:hashMachineId("win32-machine-guid",raw),source:"win32-machine-guid"}}return{ok:!1,reason:"unsupported-platform",detail:`${platform} exposes no machine identity this build trusts`}}catch(error){return{ok:!1,reason:"unreadable",detail:`the machine identity could not be read: ${error instanceof Error?error.message:String(error)}`}}}const SYSTEM_CONFIGURATION_PREFERENCES="/Library/Preferences/SystemConfiguration/preferences.plist";export function readConfiguredHostNames(readers={}){if((readers.platform??process.platform)!=="darwin")return[];const run=readers.run??defaultRun,names=[],one=key=>{try{const value=run("/usr/bin/plutil",["-extract",key,"raw","-o","-",SYSTEM_CONFIGURATION_PREFERENCES]).trim();return/^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/.test(value)?value:null}catch{return null}},host=one("System.System.HostName");host!==null&&names.push(host);const local=one("System.Network.HostNames.LocalHostName");return local!==null&&!local.includes(".")&&names.push(`${local}.local`),names}let cachedIdentity=null,cachedConfigured=null;const remembered=new Map;function machineIdentity(){return cachedIdentity===null&&(cachedIdentity=readMachineIdentity()),cachedIdentity}export function currentMachineId(){const identity=machineIdentity();return identity.ok?identity.id:null}export function injectMachineIdentity(identity,configured=identity===null?null:[]){cachedIdentity=identity,cachedConfigured=configured,remembered.clear()}export function rememberHostAliases(id,hosts){let set=remembered.get(id);set===void 0&&remembered.set(id,set=new Set);for(const host of hosts)host!==""&&set.add(host)}export function liveHostAliases(){return cachedConfigured===null&&(cachedConfigured=readConfiguredHostNames()),[...new Set([hostname(),...cachedConfigured])]}export function thisMachine(extra=[]){const id=currentMachineId(),hosts=new Set(liveHostAliases());if(id!==null){for(const host of remembered.get(id)??[])hosts.add(host);for(const host of extra)hosts.add(host)}return{id,hosts:[...hosts]}}export function isThisMachine(witness,here=thisMachine()){return witness.machineId!==null&&witness.machineId!==void 0?here.id!==null&&witness.machineId===here.id:here.hosts.includes(witness.host)}export function sameMachineHost(seen,here=hostname(),machineId){return machineId!=null?here===hostname()&&isThisMachine({host:seen,machineId}):seen===here?!0:here===hostname()&&isThisMachine({host:seen})}