toolroll 0.9.134 → 0.9.136

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 +45 -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
package/dist/operate.js CHANGED
@@ -1,4 +1,20 @@
1
- import{fetchLocalSkillBundle}from"./plugin-bundle-source.js";import{installSkillBundle,listSkillBundles,removeSkillBundle,rollbackSkillBundle,sweepSkillBundleUpdates}from"./skill-library.js";import{FLEXIBLE_CANDIDATE_FIXED,FLEXIBLE_FILED_PREFIX,flexibleMergeRefusal}from"./agent-thread/guards.js";import{readPiConfiguredModels}from"./agent-thread/providers.js";import{executeTaskHandoff}from"./agent-handoff.js";import{CARD_HELP,CONFIG_HELP,FLOWS_HELP,LEAD_HELP,MODELS_HELP}from"./cli-help.js";import{legacyLiveLogPath,liveLogPath,liveSubLogPath}from"./live.js";import{parseLiveRecords}from"./live-records.js";import{clearResolvedAgentRequests,fileAgentRequest,listAgentRequests,resolveAgentRequest,waitForAgentRequest}from"./agent-requests.js";import{readStoredGeminiStatus,refreshSubscriptions}from"./subscription-usage.js";import{liveCommandsShown}from"./live-detail.js";import{directChatArmedPass,flexibleArmedPass,flexibleSavedWords,flexibleUncommittedFiles,saveFlexibleBranch}from"./agent-thread/ship.js";import{closeFlexibleThread,flexibleShipNeedsFor,flexibleThreadRecords,flexibleThreadShipTerms,flexibleThreadTitleOf,latestFlexibleShip,removeFlexibleThreadCopy,shipFlexibleThread,stopFlexibleThreadsEverywhere}from"./agent-thread/session.js";import{CARD_SOURCES}from"./card-catalog.js";import{runCardCommand}from"./card-cli.js";import{CARD_PANEL_VALUE_FLAGS,isPanelCardCliInvocation,runPanelCardCommand}from"./panels.js";import{mintSecret}from"./secret-mint.js";import{ACP_AGENTS,ACP_PROVIDER_IDS,isAcpProvider,isKeyedProvider,ownSignInOf}from"./acp-agents.js";import{inspectAcpAgent}from"./acp-inspect.js";import{runAcpChecks}from"./acp-check.js";import{verifyLaunch}from"./acp-attest.js";import{notificationClaimHeld,claimNotifications,finalizeNotification,notificationCommandEnv,notificationDestination}from"./notification-delivery.js";import{adapterPolicy}from"./server/route-policy.js";import{UNSENT_REPLY_MS}from"./telegram.js";import{checkPublicCommand}from"./public-check.js";import{leadNameOf}from"./lead-identity.js";import{modelName,quickLeadModel}from"./lead-route.js";import{maybeTriggerRepair}from"./dispose.js";import{CHECK_LEVEL_HINTS,CHECK_LEVEL_WORDS,isCheckLevel,liveQuickCommand,projectCheckLevel,quickVerifyKey,setProjectCheckLevel,setTaskCheckLevel,suggestQuickCommand}from"./check-levels.js";import{fileAddTestsTask,requestFollowUpChecks,runFollowUpCheck,runWaitingChecks}from"./result-follow-ups.js";import{runBatchChecks}from"./batch-checks.js";import{BATCH_HINT,BATCH_WINDOW_MS,projectBatchChecks,setProjectBatchChecks}from"./batch-policy.js";import{buildReviewPass}from"./build-review.js";import{buildReviewLines,buildReviewOf}from"./review-switch.js";import{steerDestinationWords,steerStandingOf,steerStandingWords}from"./steer-status.js";import{utcMinute}from"./when.js";import{parseProtectedPaths,rulesSummary}from"./approval-policy.js";import{evidencePack,exportDay,ledgerExportChunks,standaloneEvidenceHtml}from"./evidence-pack.js";import{matchesOutsideCheckpoint}from"./ledger-chain.js";import{CLEANUP_CHOICES,bytesWords,cleanupWords,diskBytes,idleCleanupWords,idleWords,parseCleanup,parseIdle,storageReport}from"./storage.js";import{removeStaleTestTemp,tempRoots,testTempFolders}from"./test-temp.js";import{storageSweepSupervisor}from"./storage-sweep-process.js";import{idleStorageSweep,sweepSchedule,sweepScheduleWords}from"./storage-sweep-schedule.js";import{lastSweep,saveSweep,sweepDetails,sweepWords as storageSweepWords}from"./storage-sweep.js";import{removeShared,sharedDepsRoot,sharedUse,unusedShared}from"./shared-deps.js";import{cleanLandedBacklog,gitOf,landedBacklog,reconcileLanded,BACKLOG_DAYS}from"./landed-cleanup.js";import{accessOf,applyTidy,approverStandsNow,withinLens,familyRepoOf,releaseFactsFor,runTidy,tidyDays,tidyDigest,tidyGroups,tidyPreview,TIDY_DEFAULT_DAYS,TIDY_PASS_LIMIT}from"./tidy.js";import{personProof}from"./person-proof.js";import{RemoteMains}from"./remote-main.js";import{checkoutPlan,cleanCheckouts,discardCheckout,finishedCheckouts,slimKeptCheckouts,whyWords}from"./checkout-cleanup.js";import{closeOutCheckouts,closeOutRuns,stoppedWords}from"./run-closeout.js";import{proveFinishedRunsStopped,proveRunStopped}from"./stop-proof.js";import{LIFECYCLE_RETENTION_DAYS,NOTIFICATION_RETENTION_WORDS,notificationLifecyclePreview}from"./notification-retention.js";import{MIN_DAYS,RETENTION_KINDS,countWords,dailyRetention,isRetentionKind,lastSweepAt,parsePeriod,periodLabel,periodWords,retentionPlan,sweepWords}from"./retention.js";import{checkPolicy,parseList,policyParts}from"./policy.js";import{billingOf,budgetHoldWords,budgetLabel,budgetStates,monthNamed,monthOf,spendCsv,spendItems,subagentNames,usd as spendUsd}from"./spend.js";import{buildExport,exportSummary,exportZip,writeExportFolder}from"./export.js";import{startBudgetAlerts}from"./budget-alerts.js";import{runTokensCommand}from"./tokens-cli.js";import{startTokenNotices}from"./token-notices.js";import{liftAuthPause,openAuthPauses,signInGate,signInWords,startSignInProbes}from"./provider-auth.js";import{createConnectionChecker}from"./provider-connection.js";import{agentsSignedOutLines,checkIntegrations,integrationsBrokenLine,integrationsNow,renderIntegrations}from"./integrations.js";import{buildHandoff,handoffLines,loginAccount,runOnboard}from"./agent-onboard.js";import{autoSelectFirstRunDefault,detectFirstRunAgents,formatFirstRunAgentsTable}from"./first-run-detect.js";import{backupFiles,backupFolderOf,backupOwner,backupNow,restoreDatabase,startBackups}from"./backup.js";import{startLiveBackups}from"./live-backup.js";import{pushLimitSink}from"./provider-limits.js";import{filingSizing,installFilingSizer,ownerSizer,refineFiledSizing,setTaskSizing,settleSizings,taskSizingSetting}from"./task-sizing.js";import{tierLines,tierReport}from"./tier-report.js";import{savingsLines,savingsReportOrError}from"./route-savings.js";import{limitsView}from"./settings-data.js";import{codexSignedInNow,startCodexLimits}from"./codex-limits.js";import{packageVersion,startMonitoring,targetOf}from"./monitoring.js";import{origin,readMonitoring}from"./monitoring-settings.js";import{logEvent}from"./log.js";import{FLOW_EVERY_MS,flowHousekeeping,moveCards,moveCardsAfter}from"./flow-cadence.js";import{NO_YOUIYOUX_PASS,youiyouxOnboardLine}from"./youiyoux-intake.js";import{readHooksBase,scheduleFromWords}from"./flow-triggers.js";import{sendSubagentSummaries}from"./subagent-admin.js";import{runRequestedUndos,sendSubagentWeeklies}from"./subagent-week.js";import{refreshConnections}from"./mcp-connect.js";import{releaseCheckPurposeFor,releaseTermsFor}from"./release-carry.js";import{approveReleaseCard,journalMatchesPlane,releaseApprovalCard,releaseCardLines,releaseTaskOf,waitingJournals}from"./release-approval.js";import{journalFile}from"./release.js";import{refreshTrustedMains,settleReleaseChecks}from"./nightly-check.js";import{refreshCodeMaps}from"./code-map-build.js";import{sweepDeliveries}from"./code-map-admission.js";import{runMapCommand}from"./code-map-cli.js";import{githubNightlyRepos,readGithubNightlies}from"./nightly-github.js";import{exec as releaseExec,githubReads}from"./release-adapters.js";import{releaseTools}from"./release-git.js";import{SECRETS_FIRST,startToolSecrets,toolSecretStorage}from"./project-tools.js";import{followDiscord}from"./discord.js";import{followTeams}from"./teams.js";import{followSlack}from"./slack.js";import{validateScopeText}from"./task-text.js";import{runMemoryCommand}from"./memory-cli.js";import{runFlakyCommand}from"./flaky-cli.js";import{backfillMemoryUse}from"./memory-use.js";import{scheduledTidy}from"./memory-tidy.js";import{CI_READ_EVERY_MS,ciCursorKey,ciRepositoriesOf,observeCiAttempts}from"./flaky-ci.js";import{runKnowledgeApply,runKnowledgeCommand}from"./knowledge-cli.js";import{FLOWS_VALUE_FLAGS,runFlowsCommand}from"./flows-cli.js";import{approvalSummaryFor,approvalSummaryOf,describeScope,summaryContextOf,summaryLines}from"./approval-summary.js";import{runAssignmentCommand}from"./assignment-adapters.js";import{applyProjectProfile,runProjectCommand}from"./project-cli.js";import{passwordFreeOwner,passwordFreeShell,passwordFreeShellWords,proveTaskBuildsStopped,pullRequestLines,runLocalCompletion,runLocalRevision,runTaskMergeCommand,runTaskOutcomeCommand}from"./task-outcome-cli.js";import{applyPendingAgentChanges,planAgainAsLocalOwner,requestPlanAsLocalOwner,retryAsLocalOwner}from"./local-owner-acts.js";import{withTaskAlias}from"./task-aliases.js";import{checklistLines,landedNowOf,mergeChecklistOf}from"./merge-checklist.js";import{landedRowsOf}from"./landed-rows.js";import{taskReviewBrief,renderReviewBrief}from"./task-review-brief.js";import{homedir,hostname}from"node:os";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForTaskRef}from"./check-recovery-hold.js";import{currentRuntime,driftWords,releaseStalledUpdate,serviceDriftHere,waitingUpdate}from"./toolroll-update.js";import{dur}from"./design/kit.js";import{requeueEligibility,checkoutIdle,setCheckoutIdle,leadQuickAnswersOn,setLeadQuickAnswers,openStore,openStoreReadOnly,openStoreNoMigrate,initLocalMode,localModeCandidate,consoleServingNow,consoleComponent,consoleRowForPort,openConsoleRows,enrollOwnerPassword,installationCreatedBy,laptopPortOf,recordLaptopPort,localModeOf,localOwnerBinding,archiveTaskFamily,restoreTaskFamily,shipChecksForTask,elapsedSeconds,CONCURRENT_WRITER_WAIT_MS,isDatabaseBusy,briefly,databasePath,BUILT_IN,parseCapabilityKey,verifiedAuthor,isDigestTime,predecessorWatches,RESULT_SCREENSHOTS,reportLifecycle,beatLifecycle}from"./store.js";import{createHash,randomBytes,randomInt,randomUUID}from"node:crypto";import{claimInstance,clearInstance,instanceRunDir,openInstanceSocket,prepareRunDir,proveLiveConsole}from"./console-instance.js";import{backgroundOff,backgroundOn,backgroundShow,laptopStatus,laptopStop,restartOwnBuilder}from"./laptop-background.js";import{authorizePlanUnderMode}from"./plan-auto.js";import{ghDispatchAdapter,mirrorTaskId,syncPass}from"./sync.js";import{LIVE_FILE_BOUND,LIVE_RETAIN_MS,sweepLiveLogs}from"./live.js";import{addRepos,removeRepos,updateRepos,loadRepos,loadProjectRegistry,updateProjectRegistry,registryRemovals}from"./repos.js";import{deleteProject,holdingsWords,projectHoldings,projectRunning,PROJECT_RECOVERY_DELETE_MESSAGE}from"./project-delete.js";import{pushPass}from"./push.js";import{chmodSync,closeSync,constants as fsConstants,existsSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,readSync,realpathSync,renameSync,unlinkSync,writeSync,writeFileSync}from"node:fs";import{BRANCH_PREFIX,envValue,existingOrFirst,taskBranches}from"./names.js";import{claimActor,currentActor,withActor}from"./actor.js";import{parseLeadToken}from"./api-tokens.js";import{MAX_NETWORK_HOSTS,normalizeHost}from"./egress.js";import{isWritesMode,writesWords}from"./writes-mode.js";import{linuxFenceAvailable,macosFenceAvailable}from"./agent-fence.js";import{parseMachLookup,parseReadDeny,readDenyWords}from"./project-sandbox.js";import{LOCAL_POLICY}from"./surface.js";import{handoffWords,land,landedLine,landingBranchOf,landingWords,publishesThroughPullRequests,PULL_REQUESTS_INSTEAD,readLanding}from"./local-landing.js";import{catchUpMergeOf,catchUpRevision,recordCatchUp}from"./revision-catch-up.js";import{asLocalOwner,currentLocalOwner,localActNow,LOCAL_OWNER_LAPSED,LOCAL_MODE_CONFINES,localModeOn,localOwnerRefusal,localOwnerRequested}from"./local-owner.js";import{CHECK_ACCESS_WARNINGS,checkAccessRunsAs,checkAccessWords,isCheckAccess,signInHostsMissing,signInsUnavailableWords,widerThan}from"./check-access.js";import{CLI_PASSWORD_SOURCE,withPasswordSource}from"./sign-in-guard.js";import{ledgerSpent,NO_SAFE_OPENER,openSignInLink,platformOpener}from"./sign-in-page.js";import{admissionRecorded,admitProject,commandLineActor}from"./project-admission.js";import{leadClaim,leadSay,noteLeadWork}from"./lead-voice.js";import{createConnection as createNetConnection,createServer as createNetServer}from"node:net";import{fileURLToPath}from"node:url";import{superviseController}from"./controller-supervisor.js";import{buildIdentity,memoryChannel,RoleGenerations,roleMessage}from"./up-processes.js";import{checkedEnvelopeJson as envelopeJson}from"./contracts/cli.js";import{auditCommand}from"./audit-cli.js";import{closedQuestionWords,hasDisguisedText,validateNote}from"./decision.js";import{readVerifiedArtifact,readVerifiedReport,storeEvidence}from"./evidence.js";import{contractChangesOf,decodePlanContractRecord,describeContractChanges,encodePlannerSource,plannerSourceOf}from"./planner-source.js";function planContractLines(store,evidenceRoot,taskId){const ref=store.lookupRef(taskId);if(ref===null||ref.plan!=="drafted")return[];const artifact=store.latestPlanContractArtifact(ref.id);if(artifact===null)return[];let record;try{const verified=readVerifiedArtifact(evidenceRoot,artifact);if(!verified.ok)return[` filed contract: record does not verify — ${verified.problem} (run ${artifact.run})`];record=decodePlanContractRecord(verified.content)}catch{return[` filed contract: record could not be read (run ${artifact.run})`]}if(record===null)return[` filed contract: record is not the JSON it was sealed as (run ${artifact.run})`];const scope=store.getScope(taskId),stale=scope!==null&&contractChangesOf(record.proposed,scope).length>0?" (the scope was edited after this draft)":"";return record.filed===null?[` filed contract: none — the planner drafted every term from the title and repository${stale}`]:record.changes.length===0?[` filed contract: preserved exactly by the plan — approval binds the terms you filed${stale}`]:[` filed contract: AMENDED by the plan — ${record.changes.length} change${record.changes.length===1?"":"s"}; approval binds the amended terms${stale}`,` why: ${record.amendment??"(the planner stated no reason)"}`,...describeContractChanges(record.changes).map(line=>` ${line}`)]}import{verdictWords as proofVerdictWords,manualReviewCriterionOf,matrixWords,plainReasonWords,semanticCoverage,coverageWords}from"./proof.js";import{probeRepo}from"./probe.js";import{agentlessFirstRun,buildersFor,diagnoseTaskDispatch,diagnosisIsDispatchable,NO_AGENT_TITLE,scopeApprovedForDispatch}from"./dispatch.js";import{createDecisionServer,SIGN_IN_LINK_MS}from"./serve.js";import{warmWorkspaceRenderer}from"./workspace-ssr.js";import{readTailnetNames}from"./tailnet.js";import{daemonLaunchCommand,daemonStatus,installReplacingLegacy,installedLegacyDaemon,planDaemon,uninstallDaemon,awaitFreshHeartbeat}from"./daemon.js";import{bridgePass,clearBotToken,createTransport,followBridge,hashPairingCode,loadBotToken,mintPairingCode,networkFence,networkFenceLine,redactToken,saveBotToken,PAIRING_TTL_MS,TOKEN_ENV,telegramHookSecret,telegramPushUrl}from"./telegram.js";import{projectIdentities}from"./project-identity.js";import{lookIdentities}from"./folder-look.js";import{scanRepo}from"./capscan.js";import{computeGaps,describeCapability}from"./gaps.js";import{ask as promptAsk,askHidden as promptHidden,confirm as promptConfirm,interactive as promptInteractive,underAgent}from"./prompt.js";import{runLeadCli,answerContextLines}from"./lead-cli.js";import{liveTerminalWanted,processTerminal}from"./lead-cli-live.js";import{confirmCoordinatorProposal,dismissCoordinatorProposal}from"./lead-doors.js";import{verifyApproverByPassword as approverByPassword,verifyApproverStanding}from"./principal.js";import{activeRemote,REMOTE_MESSAGES,REMOTE_REFUSED_FLAGS,REMOTE_SCOPES,RemoteRefusal,remoteAllows,remoteLensOf,remoteProjectOf,remoteRowOf,remoteSecret,reproveRemote,withRemote}from"./operate-remote.js";import{projectAuthority}from"./project-access.js";import{authorizedProject,canonicalProject,projectName,resolveCeiling}from"./project.js";import{tally,spendLine}from"./summary.js";import{describePublicationGrant,observeChecks,publishPass,sweepMerges}from"./publish.js";import{checkPublishing,publishingOf,savePublishing,followPullRequests,newestPullRequestOf}from"./pull-request-flow.js";import{starterOf,startersFor,switchOnStarter}from"./flow-starters.js";import{acquire,acquireIfReady,heartbeat,release,reap,currentClaim,DEFAULT_LEASE_MS,SYNC_MAX_AGE_MS,finalize}from"./claim.js";import{moveTask}from"./task-moves.js";import{disposeBuildOutcome,holdStaleApproval,regateTask}from"./dispose.js";import{proposeGrant,describeGrant,describeWithheld,permits,MUTATION_CLASSES,DEFAULT_MUTATIONS}from"./grant.js";import{builtIn,guarded}from"./backend.js";import{register,authenticate,heartbeat as heartbeatRunner,isAlive,recoverDead,recoveredAnything,acquireWatchLeaseAuthed,renewWatchLeaseAuthed,addRunnerReposAuthed,removeRunnerRepoAuthed,registerRunnerIfIdle,retireRunnerIfCurrent,drainRunnerIfCurrent,drainOf,RUNNER_HEARTBEAT_MS,MAX_WATCH_LEASE_MS,normalizeRunnerName,validRunnerName,canonicalRepos,RUNNER_NAME_MAX,RUNNER_CAPACITY_MAX,parseRunnerCapacity,hashToken as hashRunnerToken}from"./runner.js";import{processIdentityProblem}from"./process-identity.js";import{openAddress}from"./browser-open.js";import{credentialDigest,recordedHolderProvedGone,processGone,processStart,readRunnerProcessRecord,runnerProcessFile,sealRunnerProcessRecord,writeRunnerProcessRecord}from"./runner-process.js";import{stopProcessTree}from"./process-tree.js";import{mintCoordinator,revokeCoordinator,listCoordinators}from"./coordinator.js";import{serveMcp}from"./mcp.js";import{createInterface}from"node:readline";import{hashPassword}from"./scope.js";import{noticeDueOnce,CONTAINMENT_NOTICE_FACT,passwordResetRefusal,resetAccountPassword}from"./store.js";import{propose,approve,addApprover,authenticateAccount,authenticateApprover as passwordApprover,approvalOf,hashToken as hashApproverToken,modeFilingCoverage,acceptanceLinesToInput,parseAcceptanceCriteria,splitAcceptanceRubric,rubricIsPlaceholder,isCommitSha,credentialProof,rememberedLogin,personApprovalOf}from"./scope.js";import{CHAT_APPROVE_ALL,presetTerms,modeTermsJson,modeDigestOf,modeTermsFromJson,modeWords,MODE_MAX_DAYS}from"./modes.js";import{WorktreePool}from"./worktree.js";import{baseStandingWords,freshBaseFor,taskBaseOf}from"./task-base.js";import{requestTaskStop,resumeTaskStop,taskControlOf}from"./task-control.js";import{worktreeAdoptionNotice}from"./worktree-notices.js";import{workIndexPage,workIndexTask,WorkIndexCursorError}from"./work-index.js";import{readExecutorOf}from"./read-executor.js";import{parseWorkView}from"./workspace-projection.js";import{taskWorkSummaryOf}from"./work-summary.js";import{assignmentOf,assignmentBrief,syncAssignmentHandoffs,localCompletionRefusal}from"./assignment.js";import{completedByOf}from"./task-status.js";import{createScheduledFlow,describeSchedule,parseSchedule}from"./flow-schedule.js";import{fileTaskProposal,validateTaskText}from"./proposal.js";import{TEMPLATES,templateByName}from"./templates.js";import{isDirectChatProvider,isSubscriptionChatProvider,priceOf,PRICED_MODELS}from"./converse.js";import{clearFallbackChain,dispatchEntryOf,entryMovesOnWords,entryWords,fallbackSettingOf,parseEntry,reconcileWalks,setFallbackChain,setPaidGrant}from"./fallback.js";import{resolvePhaseAgent,resolveScopeProfile,resolveRouteCandidates,routeOfTask,INSTALLATION_SCOPE}from"./agentconfig.js";import{applyModelChoices}from"./model-choices.js";import{isTaskSize,legOf,projectRoute,readinessRefuses,routeDigestOf,routeWords,TASK_SIZES,PHASES as ROUTE_PHASES}from"./phase-routing.js";import{routeWorkerModel}from"./model-routing.js";import{observeProviderReadiness,reportProviderReadinessAuthed}from"./runner.js";import{retryVanishedWhenStopped}from"./vanished-retry.js";import{requestMissingRechecks}from"./check-only.js";import{checkRepairOfRun,resumeParkedRepairs,startCheckRepair}from"./check-repair.js";import{capturesCommand,evidenceCommand,failingFirstCommand,findingCommand,handoverCommand}from"./follow-through-cli.js";import{recordBuilderWish}from"./builder-restart.js";import{expireFastStarts,fastRefusalWords,fastStartBuild,keepGrownChange,prepareFastStart}from"./fast-start.js";import{fastTermsLines}from"./fast-terms.js";import{resumeAllowedReleases}from"./release-next.js";import{RELEASE_CHECK_WAIT,runningReleaseCheck}from"./release-quiet.js";import{closeStillRestarting,noteRestarted,noteStillRestarting,STILL_RESTARTING_AFTER_MS}from"./builder-notice.js";import{sweepOrphanedReleases}from"./release-resume.js";import{fileGithubItem,readGithubItem}from"./github-import.js";import{runRelease}from"./release.js";import{releaseAdapters}from"./release-adapters.js";import{proposeNetworkChanges,routeChangeOf,routeLegacyPlans}from"./route-change.js";import{installModeNow,sessionStandsIn}from"./install-mode.js";import{parseDemoUrl,projectDemoUrl,saveProjectDemo}from"./project-demo.js";import{effectiveConcurrency,maySlotTake,parseProjectConcurrency,PROJECT_CONCURRENCY_DEFAULT,ProjectPasses,projectConcurrency,saveProjectConcurrency,savedProjectConcurrency}from"./project-concurrency.js";import{activeWebhookTargets,webhookPass,LEGACY_WEBHOOK_WARNING,loadWebhookTargets,effectivePrimary,isMessagingChannel,loadConsoleUrl,phoneOrigin,readUpConsoleUrl,saveConsoleUrl,savePrimary,UP_CONSOLE_FILE}from"./webhooks.js";import{auditOf,inspectionOf,isProviderId,MONEY_CAPABILITIES,PROVIDER_IDS,validModelId,validateSpec,ALL_CREDENTIAL_ENV}from"./provider.js";import{attestProvider,attestationOf,versionInRange}from"./attest.js";import{build,proveApprovedProfile}from"./builder.js";import{plan as planTask}from"./planner.js";import{attachTmux,elapsedWords,openInTmux,PEEK_TAIL_LINES,runPeek,snapshotLiveRuns}from"./peek-cli.js";import{scout as scoutTask}from"./scout.js";import{profileDigestOf}from"./scope.js";import{PROVIDER_KEY_ENV,clearProviderKey,keyStatus,readAuthMode,readAuthModeStrict,readProviderKey,saveProviderKey,setAuthMode,verifyProviderKey,verdictWords}from"./keys.js";import{forgetOpenRouterKey,saveOpenRouterKey}from"./openrouter-key.js";import{run,terminateLiveProviders,liveProviderCount,run as execRun}from"./exec.js";import{hardenedGit,lazyFetchSafeGit,noLazyFetch,PARTIAL_CLONE_REFUSAL}from"./teardown-git.js";import{installedGitFloorProblem}from"./git-floor.js";import{noticeGitIncidents}from"./git-incident.js";import{containmentNotice,containmentStatus,currentContainment,describeContainment,resolveContainment}from"./containment.js";import{readPulls}from"./pulls.js";import{startMaintenance,busyRetryAfter}from"./maintenance.js";import{WakePoker,wakeHubFor}from"./wake-hub.js";import{livePin,modelWatchPass}from"./model-catalog.js";import{runModelsCommand}from"./models-cli.js";import{ALL_PROJECTS,chatApprovalSettings,chatApprovalWords,setChatApproval}from"./chat-approval.js";import{updateAdmissionPaused,UPDATE_PAUSED}from"./update-gate.js";import{abortablePause}from"./chat-follow.js";import{endAfterExitProof,watchdogVerdict}from"./shutdown-proof.js";import{loopEndRecovery,relaunchAdmission,relaunchDelayMs,LOOP_STABLE_MS,RELAUNCH_WAIT_WORDS}from"./loop-recovery.js";import{beads}from"./beads.js";import{githubIssues}from"./issues.js";import{installationStatus,renderInstallationStatus,renderTaskWait,repairStaleStatuses,taskWaitSnapshot}from"./lead-status.js";import{latestRelease,newerRelease,notifySecurityRelease,notifyVersionLive,recordRunnerVersion,startUpdateChecks,updateLine}from"./releases.js";import{installMethod}from"./install-method.js";import{PACKAGE_VERSION}from"./version.js";import{machineActing}from"./scope.js";import{enableFlexible,FLEXIBLE_LAPSE_WORDS,FLEXIBLE_LEVEL_WORDS,FLEXIBLE_UNAVAILABLE,flexibleAvailable,flexibleSetting,flexibleStanding,flexibleTermsWords,isFlexibleLevel,lowerFlexible,proposedFlexibleTerms,setFlexibleSetting,turnFlexibleOff}from"./agent-thread/guards.js";import{flexibleSignInStatus,looksLikeClaudeCredential,recheckFlexibleSignIn,removeFlexibleSignIn,saveFlexibleSignIn,setupTokenFromPaste,signInCheckWords,statusCheck,tidyFlexibleSignIns}from"./agent-thread/sign-in.js";import{reevaluateResultRecords}from"./route-results.js";import{holdRuleOff,routeRulesPass,taskEvidenceWords}from"./route-rules.js";import{ruleHoldOf}from"./route-store.js";import{wasInterrupted}from"./run-ending.js";import{loginFileOf,migrateLegacyLogin,removeStaleSavedLogin,savedLoginFile,writableLoginFile}from"./login-secrets.js";import{runWords}from"./needs-you.js";export const EXIT={ok:0,failed:1,usage:2,refused:3};const STATES=["queued","running","done","failed","cancelled"];export const TASK_HELP=`toolroll task: create, inspect, hand off, and ship tasks
1
+ import{fetchLocalSkillBundle}from"./plugin-bundle-source.js";import{installSkillBundle,listSkillBundles,removeSkillBundle,rollbackSkillBundle,sweepSkillBundleUpdates}from"./skill-library.js";import{FLEXIBLE_CANDIDATE_FIXED,FLEXIBLE_FILED_PREFIX,flexibleMergeRefusal}from"./agent-thread/guards.js";import{readPiConfiguredModels}from"./agent-thread/providers.js";import{executeTaskHandoff}from"./agent-handoff.js";import{CARD_HELP,configHelp,FLOWS_HELP,LEAD_HELP,MODELS_HELP}from"./cli-help.js";import{legacyLiveLogPath,liveLogPath,liveSubLogPath}from"./live.js";import{parseLiveRecords}from"./live-records.js";import{clearResolvedAgentRequests,fileAgentRequest,listAgentRequests,resolveAgentRequest,waitForAgentRequest}from"./agent-requests.js";import{readStoredGeminiStatus,refreshSubscriptions}from"./subscription-usage.js";import{liveCommandsShown}from"./live-detail.js";import{directChatArmedPass,flexibleArmedPass,flexibleSavedWords,flexibleUncommittedFiles,saveFlexibleBranch}from"./agent-thread/ship.js";import{closeFlexibleThread,flexibleShipNeedsFor,flexibleThreadRecords,flexibleThreadShipTerms,flexibleThreadTitleOf,latestFlexibleShip,removeFlexibleThreadCopy,shipFlexibleThread,stopFlexibleThreadsEverywhere}from"./agent-thread/session.js";import{CARD_SOURCES}from"./card-catalog.js";import{runCardCommand}from"./card-cli.js";import{CARD_PANEL_VALUE_FLAGS,isPanelCardCliInvocation,runPanelCardCommand}from"./panels.js";import{mintSecret}from"./secret-mint.js";import{ACP_AGENTS,ACP_PROVIDER_IDS,isAcpProvider,isKeyedProvider,ownSignInOf}from"./acp-agents.js";import{resolveAcpAgentForRunner,runnerPathOf}from"./acp-inspect.js";import{runAcpChecks}from"./acp-check.js";import{verifyLaunch}from"./acp-attest.js";import{notificationClaimHeld,claimNotifications,finalizeNotification,notificationCommandEnv,notificationDestination}from"./notification-delivery.js";import{adapterPolicy}from"./server/route-policy.js";import{UNSENT_REPLY_MS}from"./telegram.js";import{checkPublicCommand}from"./public-check.js";import{leadNameOf}from"./lead-identity.js";import{modelName,quickLeadModel}from"./lead-route.js";import{maybeTriggerRepair}from"./dispose.js";import{CHECK_LEVEL_HINTS,CHECK_LEVEL_WORDS,isCheckLevel,liveQuickCommand,projectCheckLevel,quickVerifyKey,setProjectCheckLevel,setTaskCheckLevel,suggestQuickCommand}from"./check-levels.js";import{fileAddTestsTask,requestFollowUpChecks,runFollowUpCheck,runWaitingChecks}from"./result-follow-ups.js";import{runBatchChecks}from"./batch-checks.js";import{BATCH_HINT,BATCH_WINDOW_MS,projectBatchChecks,setProjectBatchChecks}from"./batch-policy.js";import{buildReviewPass}from"./build-review.js";import{buildReviewLines,buildReviewOf}from"./review-switch.js";import{steerDestinationWords,steerStandingOf,steerStandingWords}from"./steer-status.js";import{utcMinute}from"./when.js";import{parseProtectedPaths,rulesSummary}from"./approval-policy.js";import{evidencePack,exportDay,ledgerExportChunks,standaloneEvidenceHtml}from"./evidence-pack.js";import{matchesOutsideCheckpoint}from"./ledger-chain.js";import{CLEANUP_CHOICES,bytesWords,cleanupWords,diskBytes,idleCleanupWords,idleWords,parseCleanup,parseIdle,storageReport}from"./storage.js";import{removeStaleTestTemp,tempRoots,testTempFolders}from"./test-temp.js";import{storageSweepSupervisor}from"./storage-sweep-process.js";import{idleStorageSweep,sweepSchedule,sweepScheduleWords}from"./storage-sweep-schedule.js";import{lastSweep,saveSweep,sweepDetails,sweepWords as storageSweepWords}from"./storage-sweep.js";import{removeShared,sharedDepsRoot,sharedUse,unusedShared}from"./shared-deps.js";import{cleanLandedBacklog,gitOf,landedBacklog,reconcileLanded,BACKLOG_DAYS}from"./landed-cleanup.js";import{accessOf,applyTidy,approverStandsNow,withinLens,familyRepoOf,releaseFactsFor,runTidy,tidyDays,tidyDigest,tidyGroups,tidyPreview,TIDY_DEFAULT_DAYS,TIDY_PASS_LIMIT}from"./tidy.js";import{personProof}from"./person-proof.js";import{RemoteMains}from"./remote-main.js";import{checkoutPlan,cleanCheckouts,discardCheckout,finishedCheckouts,slimKeptCheckouts,whyWords}from"./checkout-cleanup.js";import{closeOutCheckouts,closeOutRuns,stoppedWords}from"./run-closeout.js";import{proveFinishedRunsStopped,proveRunStopped}from"./stop-proof.js";import{LIFECYCLE_RETENTION_DAYS,NOTIFICATION_RETENTION_WORDS,notificationLifecyclePreview}from"./notification-retention.js";import{MIN_DAYS,RETENTION_KINDS,countWords,dailyRetention,isRetentionKind,lastSweepAt,parsePeriod,periodLabel,periodWords,retentionPlan,sweepWords}from"./retention.js";import{checkPolicy,parseList,policyParts}from"./policy.js";import{billingOf,budgetHoldWords,budgetLabel,budgetStates,monthNamed,monthOf,spendCsv,spendItems,subagentNames,usd as spendUsd}from"./spend.js";import{buildExport,exportSummary,exportZip,writeExportFolder}from"./export.js";import{startBudgetAlerts}from"./budget-alerts.js";import{runTokensCommand}from"./tokens-cli.js";import{startTokenNotices}from"./token-notices.js";import{liftAuthPause,openAuthPauses,signInGate,signInWords,startSignInProbes}from"./provider-auth.js";import{createConnectionChecker}from"./provider-connection.js";import{agentsSignedOutLines,checkIntegrations,integrationsBrokenLine,integrationsNow,renderIntegrations}from"./integrations.js";import{buildHandoff,handoffLines,loginAccount,runOnboard}from"./agent-onboard.js";import{autoSelectFirstRunDefault,detectFirstRunAgents,formatFirstRunAgentsTable}from"./first-run-detect.js";import{backupFiles,backupFolderOf,backupOwner,backupNow,restoreDatabase,startBackups}from"./backup.js";import{startLiveBackups}from"./live-backup.js";import{pushLimitSink}from"./provider-limits.js";import{filingSizing,installFilingSizer,ownerSizer,refineFiledSizing,setTaskSizing,settleSizings,taskSizingSetting}from"./task-sizing.js";import{tierLines,tierReport}from"./tier-report.js";import{savingsLines,savingsReportOrError}from"./route-savings.js";import{limitsView}from"./settings-data.js";import{codexSignedInNow,startCodexLimits}from"./codex-limits.js";import{packageVersion,startMonitoring,targetOf}from"./monitoring.js";import{origin,readMonitoring}from"./monitoring-settings.js";import{logEvent}from"./log.js";import{FLOW_EVERY_MS,flowHousekeeping,moveCards,moveCardsAfter}from"./flow-cadence.js";import{NO_YOUIYOUX_PASS,youiyouxOnboardLine}from"./youiyoux-intake.js";import{readHooksBase,scheduleFromWords}from"./flow-triggers.js";import{sendSubagentSummaries}from"./subagent-admin.js";import{runRequestedUndos,sendSubagentWeeklies}from"./subagent-week.js";import{refreshConnections}from"./mcp-connect.js";import{releaseCheckPurposeFor,releaseTermsFor}from"./release-carry.js";import{approveReleaseCard,journalMatchesPlane,releaseApprovalCard,releaseCardLines,releaseTaskOf,waitingJournals}from"./release-approval.js";import{journalFile}from"./release.js";import{refreshTrustedMains,settleReleaseChecks}from"./nightly-check.js";import{refreshCodeMaps}from"./code-map-build.js";import{sweepDeliveries}from"./code-map-admission.js";import{runMapCommand}from"./code-map-cli.js";import{githubNightlyRepos,readGithubNightlies}from"./nightly-github.js";import{exec as releaseExec,githubReads}from"./release-adapters.js";import{releaseTools}from"./release-git.js";import{SECRETS_FIRST,startToolSecrets,toolSecretStorage}from"./project-tools.js";import{followDiscord}from"./discord.js";import{followTeams}from"./teams.js";import{followSlack}from"./slack.js";import{validateScopeText}from"./task-text.js";import{runMemoryCommand}from"./memory-cli.js";import{runFlakyCommand}from"./flaky-cli.js";import{backfillMemoryUse}from"./memory-use.js";import{scheduledTidy}from"./memory-tidy.js";import{CI_READ_EVERY_MS,ciCursorKey,ciRepositoriesOf,observeCiAttempts}from"./flaky-ci.js";import{runKnowledgeApply,runKnowledgeCommand}from"./knowledge-cli.js";import{FLOWS_VALUE_FLAGS,runFlowsCommand}from"./flows-cli.js";import{approvalSummaryFor,approvalSummaryOf,describeScope,summaryContextOf,summaryLines}from"./approval-summary.js";import{runAssignmentCommand}from"./assignment-adapters.js";import{applyProjectProfile,runProjectCommand}from"./project-cli.js";import{passwordFreeOwner,passwordFreeShell,passwordFreeShellWords,proveTaskBuildsStopped,pullRequestLines,runLocalCompletion,runLocalRevision,runTaskMergeCommand,runTaskOutcomeCommand}from"./task-outcome-cli.js";import{applyPendingAgentChanges,planAgainAsLocalOwner,requestPlanAsLocalOwner,retryAsLocalOwner}from"./local-owner-acts.js";import{withTaskAlias}from"./task-aliases.js";import{checklistLines,landedNowOf,mergeChecklistOf}from"./merge-checklist.js";import{landedRowsOf}from"./landed-rows.js";import{taskReviewBrief,renderReviewBrief}from"./task-review-brief.js";import{homedir,hostname}from"node:os";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForTaskRef}from"./check-recovery-hold.js";import{currentRuntime,driftWords,releaseStalledUpdate,serviceDriftHere,waitingUpdate}from"./toolroll-update.js";import{dur}from"./design/kit.js";import{requeueEligibility,checkoutIdle,setCheckoutIdle,leadQuickAnswersOn,setLeadQuickAnswers,openStore,openStoreReadOnly,openStoreNoMigrate,initLocalMode,localModeCandidate,consoleServingNow,consoleComponent,consoleRowForPort,openConsoleRows,enrollOwnerPassword,installationCreatedBy,laptopPortOf,recordLaptopPort,localModeOf,localOwnerBinding,archiveTaskFamily,restoreTaskFamily,shipChecksForTask,elapsedSeconds,CONCURRENT_WRITER_WAIT_MS,isDatabaseBusy,briefly,databasePath,BUILT_IN,parseCapabilityKey,verifiedAuthor,isDigestTime,predecessorWatches,RESULT_SCREENSHOTS,reportLifecycle,beatLifecycle}from"./store.js";import{createHash,randomBytes,randomInt,randomUUID}from"node:crypto";import{claimInstance,clearInstance,instanceRunDir,openInstanceSocket,prepareRunDir,proveLiveConsole}from"./console-instance.js";import{backgroundOff,backgroundOn,backgroundShow,laptopStatus,laptopStop,restartOwnBuilder}from"./laptop-background.js";import{authorizePlanUnderMode}from"./plan-auto.js";import{ghDispatchAdapter,mirrorTaskId,syncPass}from"./sync.js";import{LIVE_FILE_BOUND,LIVE_RETAIN_MS,sweepLiveLogs}from"./live.js";import{addRepos,removeRepos,updateRepos,loadRepos,loadProjectRegistry,updateProjectRegistry,registryRemovals}from"./repos.js";import{deleteProject,holdingsWords,projectHoldings,projectRunning,PROJECT_RECOVERY_DELETE_MESSAGE}from"./project-delete.js";import{pushPass}from"./push.js";import{chmodSync,closeSync,constants as fsConstants,existsSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,readSync,realpathSync,renameSync,unlinkSync,writeSync,writeFileSync}from"node:fs";import{BRANCH_PREFIX,envValue,existingOrFirst,taskBranches}from"./names.js";import{claimActor,currentActor,withActor}from"./actor.js";import{parseLeadToken}from"./api-tokens.js";import{MAX_NETWORK_HOSTS,normalizeHost}from"./egress.js";import{isWritesMode,writesWords}from"./writes-mode.js";import{linuxFenceAvailable,macosFenceAvailable}from"./agent-fence.js";import{parseMachLookup,parseReadDeny,readDenyWords}from"./project-sandbox.js";import{LOCAL_POLICY}from"./surface.js";import{handoffWords,land,landedLine,landingBranchOf,landingWords,publishesThroughPullRequests,PULL_REQUESTS_INSTEAD,readLanding,runPendingLocalLands}from"./local-landing.js";import{catchUpMergeOf,catchUpRevision,recordCatchUp}from"./revision-catch-up.js";import{asLocalOwner,currentLocalOwner,localActNow,LOCAL_OWNER_LAPSED,LOCAL_MODE_CONFINES,localModeOn,localOwnerRefusal,localOwnerRequested}from"./local-owner.js";import{CHECK_ACCESS_WARNINGS,checkAccessRunsAs,checkAccessWords,isCheckAccess,signInHostsMissing,signInsUnavailableWords,widerThan}from"./check-access.js";import{CLI_PASSWORD_SOURCE,withPasswordSource}from"./sign-in-guard.js";import{ledgerSpent,NO_SAFE_OPENER,openSignInLink,platformOpener}from"./sign-in-page.js";import{admissionRecorded,admitProject,commandLineActor}from"./project-admission.js";import{leadClaim,leadSay,noteLeadWork}from"./lead-voice.js";import{createConnection as createNetConnection,createServer as createNetServer}from"node:net";import{fileURLToPath}from"node:url";import{superviseController}from"./controller-supervisor.js";import{buildIdentity,memoryChannel,RoleGenerations,roleMessage}from"./up-processes.js";import{checkedEnvelopeJson as envelopeJson}from"./contracts/cli.js";import{auditCommand}from"./audit-cli.js";import{closedQuestionWords,hasDisguisedText,validateNote}from"./decision.js";import{readVerifiedArtifact,readVerifiedReport,storeEvidence}from"./evidence.js";import{contractChangesOf,decodePlanContractRecord,describeContractChanges,encodePlannerSource,plannerSourceOf}from"./planner-source.js";function planContractLines(store,evidenceRoot,taskId){const ref=store.lookupRef(taskId);if(ref===null||ref.plan!=="drafted")return[];const artifact=store.latestPlanContractArtifact(ref.id);if(artifact===null)return[];let record;try{const verified=readVerifiedArtifact(evidenceRoot,artifact);if(!verified.ok)return[` filed contract: record does not verify — ${verified.problem} (run ${artifact.run})`];record=decodePlanContractRecord(verified.content)}catch{return[` filed contract: record could not be read (run ${artifact.run})`]}if(record===null)return[` filed contract: record is not the JSON it was sealed as (run ${artifact.run})`];const scope=store.getScope(taskId),stale=scope!==null&&contractChangesOf(record.proposed,scope).length>0?" (the scope was edited after this draft)":"";return record.filed===null?[` filed contract: none — the planner drafted every term from the title and repository${stale}`]:record.changes.length===0?[` filed contract: preserved exactly by the plan — approval binds the terms you filed${stale}`]:[` filed contract: AMENDED by the plan — ${record.changes.length} change${record.changes.length===1?"":"s"}; approval binds the amended terms${stale}`,` why: ${record.amendment??"(the planner stated no reason)"}`,...describeContractChanges(record.changes).map(line=>` ${line}`)]}import{verdictWords as proofVerdictWords,manualReviewCriterionOf,matrixWords,plainReasonWords,semanticCoverage,coverageWords}from"./proof.js";import{probeRepo}from"./probe.js";import{agentlessFirstRun,buildersFor,diagnoseTaskDispatch,diagnosisIsDispatchable,NO_AGENT_TITLE,scopeApprovedForDispatch}from"./dispatch.js";import{createDecisionServer,SIGN_IN_LINK_MS}from"./serve.js";import{warmWorkspaceRenderer}from"./workspace-ssr.js";import{readTailnetNames}from"./tailnet.js";import{daemonLaunchCommand,daemonStatus,installReplacingLegacy,installedLegacyDaemon,planDaemon,uninstallDaemon,awaitFreshHeartbeat}from"./daemon.js";import{bridgePass,clearBotToken,createTransport,followBridge,hashPairingCode,loadBotToken,mintPairingCode,networkFence,networkFenceLine,redactToken,saveBotToken,PAIRING_TTL_MS,TOKEN_ENV,telegramHookSecret,telegramPushUrl}from"./telegram.js";import{projectIdentities}from"./project-identity.js";import{lookIdentities}from"./folder-look.js";import{scanRepo}from"./capscan.js";import{computeGaps,describeCapability}from"./gaps.js";import{ask as promptAsk,askHidden as promptHidden,confirm as promptConfirm,interactive as promptInteractive,underAgent}from"./prompt.js";import{runLeadCli,answerContextLines}from"./lead-cli.js";import{liveTerminalWanted,processTerminal}from"./lead-cli-live.js";import{confirmCoordinatorProposal,dismissCoordinatorProposal}from"./lead-doors.js";import{verifyApproverByPassword as approverByPassword,verifyApproverStanding}from"./principal.js";import{activeRemote,REMOTE_MESSAGES,REMOTE_REFUSED_FLAGS,REMOTE_SCOPES,RemoteRefusal,remoteAllows,remoteLensOf,remoteProjectOf,remoteRowOf,remoteSecret,reproveRemote,withRemote}from"./operate-remote.js";import{projectAuthority}from"./project-access.js";import{authorizedProject,canonicalProject,projectName,resolveCeiling}from"./project.js";import{tally,spendLine}from"./summary.js";import{describePublicationGrant,observeChecks,publishPass,sweepMerges}from"./publish.js";import{checkPublishing,publishingOf,savePublishing,followPullRequests,newestPullRequestOf}from"./pull-request-flow.js";import{starterOf,startersFor,switchOnStarter}from"./flow-starters.js";import{acquire,acquireIfReady,heartbeat,release,reap,currentClaim,DEFAULT_LEASE_MS,SYNC_MAX_AGE_MS,finalize}from"./claim.js";import{moveTask}from"./task-moves.js";import{disposeBuildOutcome,holdStaleApproval,regateTask}from"./dispose.js";import{proposeGrant,describeGrant,describeWithheld,permits,MUTATION_CLASSES,DEFAULT_MUTATIONS}from"./grant.js";import{builtIn,guarded}from"./backend.js";import{register,authenticate,heartbeat as heartbeatRunner,isAlive,recoverDead,recoveredAnything,acquireWatchLeaseAuthed,renewWatchLeaseAuthed,addRunnerReposAuthed,removeRunnerRepoAuthed,registerRunnerIfIdle,retireRunnerIfCurrent,drainRunnerIfCurrent,drainOf,RUNNER_HEARTBEAT_MS,MAX_WATCH_LEASE_MS,normalizeRunnerName,validRunnerName,canonicalRepos,RUNNER_NAME_MAX,RUNNER_CAPACITY_MAX,parseRunnerCapacity,hashToken as hashRunnerToken}from"./runner.js";import{processIdentityProblem}from"./process-identity.js";import{openAddress}from"./browser-open.js";import{credentialDigest,recordedHolderProvedGone,processGone,processStart,readRunnerProcessRecord,runnerProcessFile,sealRunnerProcessRecord,writeRunnerProcessRecord}from"./runner-process.js";import{stopProcessTree}from"./process-tree.js";import{mintCoordinator,revokeCoordinator,listCoordinators}from"./coordinator.js";import{serveMcp}from"./mcp.js";import{createInterface}from"node:readline";import{hashPassword}from"./scope.js";import{noticeDueOnce,CONTAINMENT_NOTICE_FACT,passwordResetRefusal,resetAccountPassword}from"./store.js";import{propose,approve,addApprover,authenticateAccount,authenticateApprover as passwordApprover,approvalOf,hashToken as hashApproverToken,modeFilingCoverage,acceptanceLinesToInput,parseAcceptanceCriteria,splitAcceptanceRubric,rubricIsPlaceholder,isCommitSha,credentialProof,rememberedLogin,personApprovalOf}from"./scope.js";import{CHAT_APPROVE_ALL,presetTerms,modeTermsJson,modeDigestOf,modeTermsFromJson,modeWords,MODE_MAX_DAYS}from"./modes.js";import{WorktreePool}from"./worktree.js";import{baseStandingWords,freshBaseFor,taskBaseOf}from"./task-base.js";import{requestTaskStop,resumeTaskStop,taskControlOf}from"./task-control.js";import{worktreeAdoptionNotice}from"./worktree-notices.js";import{workIndexPage,workIndexTask,WorkIndexCursorError}from"./work-index.js";import{readExecutorOf}from"./read-executor.js";import{parseWorkView}from"./workspace-projection.js";import{taskWorkSummaryOf}from"./work-summary.js";import{assignmentOf,assignmentBrief,syncAssignmentHandoffs,localCompletionRefusal}from"./assignment.js";import{completedByOf}from"./task-status.js";import{createScheduledFlow,describeSchedule,parseSchedule}from"./flow-schedule.js";import{fileTaskProposal,validateTaskText}from"./proposal.js";import{TEMPLATES,templateByName}from"./templates.js";import{isDirectChatProvider,isSubscriptionChatProvider,priceOf,PRICED_MODELS}from"./converse.js";import{clearFallbackChain,dispatchEntryOf,entryMovesOnWords,entryWords,fallbackSettingOf,parseEntry,reconcileWalks,setFallbackChain,setPaidGrant}from"./fallback.js";import{resolvePhaseAgent,resolveScopeProfile,resolveRouteCandidates,routeOfTask,INSTALLATION_SCOPE}from"./agentconfig.js";import{applyModelChoices}from"./model-choices.js";import{isTaskSize,legOf,projectRoute,readinessRefuses,routeDigestOf,routeWords,TASK_SIZES,PHASES as ROUTE_PHASES}from"./phase-routing.js";import{routeWorkerModel}from"./model-routing.js";import{observeProviderReadiness,reportProviderReadinessAuthed}from"./runner.js";import{retryVanishedWhenStopped}from"./vanished-retry.js";import{requestMissingRechecks}from"./check-only.js";import{checkRepairOfRun,resumeParkedRepairs,startCheckRepair}from"./check-repair.js";import{capturesCommand,evidenceCommand,failingFirstCommand,findingCommand,handoverCommand}from"./follow-through-cli.js";import{recordBuilderWish}from"./builder-restart.js";import{expireFastStarts,fastAcceptance,fastRefusalWords,fastStartBuild,keepGrownChange,prepareFastStart}from"./fast-start.js";import{fastTermsLines}from"./fast-terms.js";import{resumeAllowedReleases}from"./release-next.js";import{RELEASE_CHECK_WAIT,runningReleaseCheck}from"./release-quiet.js";import{closeStillRestarting,noteRestarted,noteStillRestarting,STILL_RESTARTING_AFTER_MS}from"./builder-notice.js";import{sweepOrphanedReleases}from"./release-resume.js";import{fileGithubItem,readGithubItem}from"./github-import.js";import{runRelease}from"./release.js";import{releaseAdapters}from"./release-adapters.js";import{eligibleModelChangeTasks,proposeNetworkChanges,rerouteReplyWords,rerouteWaitingTasks,routeChangeOf,routeLegacyPlans}from"./route-change.js";import{ownerMode}from"./owner-mode.js";import{installModeNow,sessionStandsIn}from"./install-mode.js";import{parseDemoUrl,projectDemoUrl,saveProjectDemo}from"./project-demo.js";import{effectiveConcurrency,maySlotTake,parseProjectConcurrency,PROJECT_CONCURRENCY_DEFAULT,ProjectPasses,projectConcurrency,saveProjectConcurrency,savedProjectConcurrency}from"./project-concurrency.js";import{activeWebhookTargets,webhookPass,LEGACY_WEBHOOK_WARNING,loadWebhookTargets,effectivePrimary,isMessagingChannel,loadConsoleUrl,phoneOrigin,readUpConsoleUrl,saveConsoleUrl,savePrimary,UP_CONSOLE_FILE}from"./webhooks.js";import{auditOf,inspectionOf,isProviderId,MONEY_CAPABILITIES,PROVIDER_IDS,validModelId,validateSpec,ALL_CREDENTIAL_ENV}from"./provider.js";import{attestProvider,attestationOf,versionInRange}from"./attest.js";import{build,proveApprovedProfile}from"./builder.js";import{plan as planTask}from"./planner.js";import{attachTmux,elapsedWords,openInTmux,PEEK_TAIL_LINES,runPeek,snapshotLiveRuns}from"./peek-cli.js";import{scout as scoutTask}from"./scout.js";import{profileDigestOf}from"./scope.js";import{PROVIDER_KEY_ENV,clearProviderKey,keyStatus,readAuthMode,readAuthModeStrict,readProviderKey,saveProviderKey,setAuthMode,verifyProviderKey,verdictWords}from"./keys.js";import{forgetOpenRouterKey,saveOpenRouterKey}from"./openrouter-key.js";import{run,terminateLiveProviders,liveProviderCount,run as execRun}from"./exec.js";import{hardenedGit,lazyFetchSafeGit,noLazyFetch,PARTIAL_CLONE_REFUSAL}from"./teardown-git.js";import{installedGitFloorProblem}from"./git-floor.js";import{noticeGitIncidents}from"./git-incident.js";import{containmentNotice,containmentStatus,currentContainment,describeContainment,resolveContainment}from"./containment.js";import{readPulls}from"./pulls.js";import{startMaintenance,busyRetryAfter}from"./maintenance.js";import{WakePoker,wakeHubFor}from"./wake-hub.js";import{livePin,modelWatchPass}from"./model-catalog.js";import{runModelsCommand}from"./models-cli.js";import{ALL_PROJECTS,chatApprovalSettings,chatApprovalWords,setChatApproval}from"./chat-approval.js";import{updateAdmissionPaused,UPDATE_PAUSED}from"./update-gate.js";import{abortablePause}from"./chat-follow.js";import{endAfterExitProof,watchdogVerdict}from"./shutdown-proof.js";import{loopEndRecovery,relaunchAdmission,relaunchDelayMs,LOOP_STABLE_MS,RELAUNCH_WAIT_WORDS}from"./loop-recovery.js";import{beads}from"./beads.js";import{githubIssues}from"./issues.js";import{installationStatus,renderInstallationStatus,renderTaskWait,repairStaleStatuses,taskWaitSnapshot}from"./lead-status.js";import{latestRelease,newerRelease,notifySecurityRelease,notifyVersionLive,recordRunnerVersion,startUpdateChecks,updateLine}from"./releases.js";import{installMethod}from"./install-method.js";import{PACKAGE_VERSION}from"./version.js";import{machineActing}from"./scope.js";import{enableFlexible,FLEXIBLE_LAPSE_WORDS,FLEXIBLE_LEVEL_WORDS,FLEXIBLE_UNAVAILABLE,flexibleAvailable,flexibleSetting,flexibleStanding,flexibleTermsWords,isFlexibleLevel,lowerFlexible,proposedFlexibleTerms,setFlexibleSetting,turnFlexibleOff}from"./agent-thread/guards.js";import{flexibleSignInStatus,looksLikeClaudeCredential,recheckFlexibleSignIn,removeFlexibleSignIn,saveFlexibleSignIn,setupTokenFromPaste,signInCheckWords,statusCheck,tidyFlexibleSignIns}from"./agent-thread/sign-in.js";import{reevaluateResultRecords}from"./route-results.js";import{holdRuleOff,routeRulesPass,taskEvidenceWords}from"./route-rules.js";import{ruleHoldOf}from"./route-store.js";import{wasInterrupted}from"./run-ending.js";import{loginFileOf,migrateLegacyLogin,removeStaleSavedLogin,savedLoginFile,writableLoginFile}from"./login-secrets.js";import{runWords}from"./needs-you.js";export const EXIT={ok:0,failed:1,usage:2,refused:3};const STATES=["queued","running","done","failed","cancelled"];export const TASK_ADD_HELP=`toolroll task add "<title>" [options]
2
+
3
+ --goal <text> what the task should accomplish (--body is an alias)
4
+ --plan request a plan before coding
5
+ --just-code skip planning
6
+ --repo <folder> the task's repository
7
+ --id <id> choose the task id
8
+ --replaces <id> replace an earlier task
9
+ --checks quick|full|off
10
+ --report deliver a report instead of a branch
11
+ --backend <name> file in an external tracker (title only)
12
+ --key <key> retry the same filing safely
13
+ --as <name> --token <token>
14
+ --db <file> --json --help
15
+
16
+ Choose at most one of --plan and --just-code. A goal also becomes a manual-review acceptance criterion.
17
+ Filing does not approve the scope.`,TASK_HELP=`toolroll task: create, inspect, hand off, and ship tasks
2
18
 
3
19
  toolroll task add "<change>" --repo . queue a task (--plan to review plan first; --checks quick|full|off)
4
20
  toolroll task list [--view <v>] list tasks (needs-you, ready, running, queued, completed, archived)
@@ -192,7 +208,7 @@ External trackers — build what a tracker nominates, under local approvals
192
208
  commands as you on this computer can
193
209
  reset it, as they could read the
194
210
  saved first password
195
- toolroll task scope <id> --goal <what success is>
211
+ toolroll task scope <id> --goal <what success is> --acceptance "<statement>|<evidence,kinds>"
196
212
  [--not <text>] [--touches a,b] [--budget-usd <n>]
197
213
  toolroll task approve <id> the yes — interactive, or
198
214
  --yes --digest <d> --terms <key> --as <you> --token <t>
@@ -349,10 +365,11 @@ Agents — which provider and model each phase runs on
349
365
  what coordinators proposed over the MCP gateway; confirming runs the
350
366
  same door the console runs, under your password
351
367
  toolroll config show [--repo <path>]
352
- toolroll config set <phase> --provider claude|codex|openrouter
368
+ toolroll config set <phase> --provider <p>
353
369
  [--model <m>] [--repo <path>] --as <you> --token <t>
354
- phases: plan | build | repair. The
355
- repo form is a project override;
370
+ providers: ${PROVIDER_IDS.join(", ")}
371
+ phases: plan | build | repair | review.
372
+ The repo form is a project override;
356
373
  without it, installation-wide.
357
374
  Repair's PROVIDER always inherits
358
375
  the build it mends.
@@ -452,17 +469,17 @@ Options
452
469
 
453
470
  Exit codes
454
471
  0 it happened 2 bad usage
455
- 1 something broke 3 ran fine, the answer is no`,TASK_ACTIONS=["add","new","keep","list","show","log","send","handoff","attach","wait","state","block","unblock","next","steer","pause","continue","assign","reopen","scope","approve","hold","unhold","require","requeue","regate","plan","review","accept","repair","route","stop","resume","complete","revise","merge","ask","checks","add-tests","archive","restore","tidy","ship","ready","handover","before-after","failing-first","land"],PUBLISH_ACTIONS=["setup","grant","revoke","status","unblock","rearm","merge","refire"],CONFIG_ACTIONS=["show","set","clear"],APPROVER_ACTIONS=["list","add"],PEOPLE_ACTIONS=["list","invite","projects","revoke"],KEYS_ACTIONS=["status","set","clear","verify","auth"],SECRET_VALUE_FLAGS=new Set(["token","password"]),OPERATE_VALUE_FLAGS=new Set(["key","db","runner","ttl","state","flow","on","reason","until","id","backend","build","from","allow","selector","paths","credentials","repo","token","capacity","agents","goal","not","touches","acceptance","candidate","by","digest","terms","as","branch","pool","base","model","turns","max","cap","probe","kind","expires","cmd","since","repair-model","choose","choice","claim","revision","note","max-open-decisions","name","days","publication","auto-approve","review-auto","port","host","allow-host","for","tick-every","bridge-every","reconcile-every","incarnation","say","ceiling-usd","cap-usd","incident","into","case","k","world","deny","abandon","token-file","bin","poll","github","remote","head-prefix","password","not-requester","protect","protect-paths","checkpoint","out","from","to","month","usd","person","subagent","teammate","providers","models","tools","project-root","schedule","ceiling","require","provider","plan-model","plan-provider","public-url","editor","command","timeout-seconds","setup-digest","stop-grace","title","name","every","lines","label","reviewers","limit","role","key-file","weekly-usd","daily-turns","per-hour","token-file","budget-usd","build-usd","sync-max-age","merge-method","phase","tier","clear-phase","size","risky","run","containment","agent","path","line","action","from-review","from-check","task","starter","template","steps","about","language","timeout-minutes","body","description","zone","option","except","token-env","after","repair-max-attempts","consumer","batch","feedback","source","view","cursor","why","supersedes","decision","sessions","timeout","replaced-by","replaces","quick","level","checks","task","access","projects","overlap","token-name","request","read-deny","mach","default","release","despite"]),OPERATE_BOOLEAN_FLAGS=new Set(["finish","preview","diagnostic","keep","no-carry","from-main","full-check","rehearsal","json","yes","all","brief","local","history","latest-watch","dry-run","file","clear","follow","ready","all-tasks","inbound-only","help","undo","anyone","allow-dispatch","allow-merge","merge-delete-branch","no-open","single-process","laptop","web","remove","no-verify","no-follow","end","report","off","tmux","self-heal","plan-auto","chat-approve","full-access","repair-auto","review-retry-auto","no-local","html","csv","alerts-only","open","allowlist","allow-paid","no-paid","zip","saved","pull-request","checked","landed","verbose","revoke","anyway","also","password-stdin","now","preview","apply","no-check","check","wait","live","sub","list"]);const PROJECT_NETWORK_VALUE_FLAGS=new Set(["remove","local"]);export function parseOperateArgs(argv,ownValues=new Set){const positional=[],flags=new Map,repoList=[],wantsValue=new Set([...OPERATE_VALUE_FLAGS,...ownValues]),booleans=new Set([...OPERATE_BOOLEAN_FLAGS].filter(name=>!ownValues.has(name)));for(let index=0;index<argv.length;index++){const argument=argv[index];if(!argument.startsWith("--")){if(argument==="-h"){flags.set("help",!0);continue}if(argument==="-f"){flags.set("follow",!0);continue}positional.push(argument);continue}const equals=argument.indexOf("="),name=argument.slice(2,equals===-1?void 0:equals);if(booleans.has(name)){if(equals!==-1)return{error:`--${name} does not take a value`};flags.set(name,!0);continue}if(!wantsValue.has(name))return{error:`unknown option --${name} — add --help to any queue command for the whole surface`};const value=equals===-1?argv[++index]:argument.slice(equals+1),namesFlag=one=>{const flag2=one.slice(2).split("=")[0];return booleans.has(flag2)||wantsValue.has(flag2)};if(value===void 0||equals===-1&&value.startsWith("--")&&(!SECRET_VALUE_FLAGS.has(name)||namesFlag(value)))return{error:`--${name} needs a value`};if(flags.set(name,name==="param"&&typeof flags.get(name)=="string"?`${flags.get(name)}
456
- ${value}`:value),name==="repo")for(const one of value.split(",").map(part=>part.trim()).filter(part=>part!==""))repoList.push(one)}return{positional,flags,repoList}}export async function runOperate(command,argv,write,options={}){return command==="task"&&(argv=withTaskAlias(["task",...argv]).slice(1)),withPasswordSource(CLI_PASSWORD_SOURCE,()=>rememberedLogin.run({login:null},()=>runOperateLocal(command,argv,write,options)))}async function runOperateLocal(command,argv,write,options={}){const parsed=parseOperateArgs(argv,ownValueFlags(command,argv));if("error"in parsed)return fail(write,argv.includes("--json"),command,"usage",parsed.error,EXIT.usage);const{positional,flags}=parsed,json=flags.has("json");if(flags.has("help")){const helpText=command==="task"&&positional.length===0?TASK_HELP:command==="plugin"?`toolroll plugin list | install <github-url|folder> | update [id] | rollback <id> | remove <id> | validate <folder>
457
- Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:command==="lead"?LEAD_HELP:command==="card"?CARD_HELP:command==="config"?CONFIG_HELP:command==="models"?MODELS_HELP:OPERATE_HELP;return write(json?envelopeJson({ok:!0,command:"help",help:helpText}):helpText),EXIT.ok}if(localOwnerRequested()&&localOwnerRowAct(command,positional,flags)===null)return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const file=text(flags,"db")??options.databaseFile??databasePath(process.env,homedir()),now=options.now??new Date;try{applyProjectProfile(command,positional,flags,file)}catch(error){return fail(write,json,command,"configuration",describe(error),EXIT.refused)}try{const containment=resolveContainment(text(flags,"containment"));if(!containment.ok)return fail(write,json,command,"usage",containment.problem,EXIT.usage)}catch(error){return fail(write,json,command,"usage",describe(error),EXIT.usage)}if(command==="mcp")return mcpCommand(file,flags,write,json);if(command==="serve"&&positional[0]==="check-public")return checkPublicCommand(flags,{write,json,envelope:envelopeJson,...options.publicProbe===void 0?{}:{probe:options.publicProbe}});if(command==="restore")return restoreCommand(file,positional,flags,write,json,now);if(command==="plugin"&&positional[0]==="validate")return positional.length!==2?fail(write,json,"plugin validate","usage","toolroll plugin validate <folder>",EXIT.usage):validatePluginCommand(file,positional[1],write,json);let store;try{const laptop=command==="up"&&flags.has("laptop")&&options.upRole===void 0;store=options.openDatabase!==void 0?options.openDatabase(file):openStore(file,laptop?{createdBy:"laptop"}:{})}catch(error){return databaseFailure(write,json,command,file,error)}if(file!==":memory:"&&startToolSecrets(store,file,()=>new Date,{eager:SECRETS_FIRST.has(command)}),localOwnerRequested()||shellActsAsLocalOwner(store,command,positional,flags,options)){const admitted=localOwnerCommand(store,command,positional,flags);if(!admitted.ok)return store.close(),fail(write,json,command,"refused",admitted.message,EXIT.refused);try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now},options,run2=>asLocalOwner(admitted.principal,run2))}finally{store.close()}}const presentedFlag=text(flags,"token"),flagLead=presentedFlag!==void 0&&parseLeadToken(presentedFlag)!==null,envLead=envValue(process.env,"LEAD_TOKEN"),presented=flagLead?presentedFlag:LEAD_COMMANDS.has(command)&&envLead!==void 0&&envLead!==""?envLead:void 0;let actor=null;if(presented!==void 0){if(!LEAD_COMMANDS.has(command))return store.close(),fail(write,json,command,"usage",`A lead token works for ${[...LEAD_COMMANDS].filter(one=>one!=="lead").join(", ")}. Use your own sign-in for ${command}.`,EXIT.usage);const lead=store.leadFor(presented);if(lead===null)return store.close(),fail(write,json,command,"unauthenticated","That lead token is not valid (revoked, replaced, or its owner can no longer approve). The owner mints a new one with: toolroll lead token",EXIT.refused);flagLead&&flags.delete("token"),actor={account:lead.owner,lead:!0}}try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now,...actor===null?{}:{leadToken:presented}},options,run2=>LEAD_COMMANDS.has(command)?withActor(actor,run2):run2())}finally{store.close()}}async function dispatchOn(command,positional,flags,repoList,base,options,enter){const{store,write,json,file,now}=base,dropLimitSink=pushLimitSink(reading=>store.recordProviderLimits(reading,new Date)),sizer=options.filingSizer??(process.env.VITEST!==void 0||envValue(process.env,"NO_TASK_CLASSIFIER")!==void 0||store.isDemo()?null:ownerSizer()),dropSizer=sizer===null?()=>{}:installFilingSizer(sizer),clock=options.now===void 0?()=>new Date:()=>now;try{return await enter(()=>dispatch(command,positional,flags,{...base.leadToken===void 0?{}:{leadToken:base.leadToken},store,write,json,repoList,now,clock,evidenceRoot:join(dirname(file),"evidence"),databaseFile:file,...injectedSeams(options),telegramTokenFile:join(dirname(file),"telegram-token"),...upNeedsOneProcess(options)?{upOneProcess:!0}:{},...activeRemote()===null?{}:{principal:activeRemote()}}))}catch(error){return error instanceof RemoteRefusal?fail(write,json,command,error.reason,error.message,EXIT.refused):isDatabaseBusy(error)?databaseFailure(write,json,command,file,error):fail(write,json,command,"failed",describe(error),EXIT.failed)}finally{await settleSizings(),dropSizer(),dropLimitSink()}}export async function runOperateAs(argv,opts){const{principal,store,write}=opts,source=opts.source==="mcp"?"mcp":"api",options=opts.options??{},now=options.now??new Date;argv=[...withTaskAlias(argv)];const[root="",...rest]=argv,json=rest.includes("--json");let invocation=root,tokenName=null;const tool=source==="mcp"&&typeof opts.tool=="string"&&/^[a-z][a-z0-9_]{0,40}$/.test(opts.tool)?opts.tool:null,record=(outcome,repo,taskId,why)=>{store.recordAction({at:(options.now??new Date).toISOString(),actor:principal.account,repo,taskId,runId:null,action:`remote command: ${invocation===""?"(none)":invocation}`.slice(0,200),outcome,source,detail:`token ${tokenName??principal.tokenId}${why===null?"":` · ${why}`}${tool===null?"":` · tool ${tool}`}`})},refuse=(reason,message,repo=null,taskId=null)=>(record("refused",repo,taskId,reason),fail(write,json,invocation===""?"remote":invocation,reason,message,EXIT.refused)),proved=reproveRemote(store,principal,now);if(!proved.ok)return refuse("unauthenticated",REMOTE_MESSAGES.stale);tokenName=proved.tokenName;const firstFlag=rest.findIndex(one=>one.startsWith("-")),row=remoteRowOf(root,firstFlag===-1?rest:rest.slice(0,firstFlag));if(row===null)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(invocation=row.invocation,row.remote==="step-up")return refuse("step-up",REMOTE_MESSAGES["step-up"]);const scope=REMOTE_SCOPES.get(row.invocation);if(row.remote!=="yes"||scope===void 0)return refuse("not-remote",REMOTE_MESSAGES.no);const parsed=parseOperateArgs(rest,ownValueFlags(root,rest));if("error"in parsed)return refuse("usage",parsed.error);if(remoteRowOf(root,parsed.positional)?.invocation!==row.invocation)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},row.mutation!=="none"?"act":"read").ok||proved.scope==="read"&&row.mutation!=="none")return refuse("read-only",REMOTE_MESSAGES.read);if([...parsed.flags.keys()].some(name=>REMOTE_REFUSED_FLAGS.has(name)))return refuse("usage",REMOTE_MESSAGES.credential);const allows=repo=>remoteAllows(store,principal,repo),project=remoteProjectOf(store,{allows},scope,parsed.positional,parsed.repoList,row.invocation,parsed.flags,opts.files??{});if(!project.ok)return refuse(project.reason,project.message);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},void 0,source2=>source2==="adapter"&&(project.repo===null||allows(project.repo))).ok)return refuse("forbidden",REMOTE_MESSAGES.no);const key=text(parsed.flags,"key");key!==void 0&&row.invocation!=="task revise"&&parsed.flags.set("key",`remote:${createHash("sha256").update(JSON.stringify([principal.account,row.invocation,project.repo,project.taskId,key])).digest("hex")}`);const file=store.databaseFile()??options.databaseFile;if(file===void 0)return refuse("failed","The server's database has no file.",project.repo,project.taskId);let filed=null;const run2=Object.freeze({account:principal.account,scope:proved.scope,tokenName:proved.tokenName,source,secret:remoteSecret(),allows,lens:remoteLensOf(store,scope,allows),noteTask:taskId=>{filed=taskId},files:Object.freeze({...opts.files})});record("requested",project.repo,project.taskId,null);let code;try{code=await withRemote(run2,()=>dispatchOn(root,parsed.positional,parsed.flags,parsed.repoList,{store,write,json,file,now},options,go=>withActor({account:principal.account,lead:!1},()=>projectAuthority.run({actor:principal.account,repo:project.repo},go))))}catch(error){throw record("failed",project.repo,filed??project.taskId,null),error}return record(code===EXIT.ok?"done":code===EXIT.refused?"refused":code===EXIT.usage?"usage":"failed",project.repo,filed??project.taskId,null),code}function remoteFile(remote,path){if(Object.prototype.hasOwnProperty.call(remote.files,path))return remote.files[path];throw new RemoteRefusal("usage",REMOTE_MESSAGES.files)}const LEAD_COMMANDS=new Set(["plugin","task","assignment","status","ready","brief","peek","check-progress","notifications","lead"]),SEAMS=["tempRoots","desktopIdentity","inferProjectFromCwd","additionalProjectRepos","agentRunner","gitRunner","telegramTransport","telegramEnv","publishExec","dispatchAdapter","flowTriggerIo","flowStepIo","flowEveryMs","watchHeartbeatMs","loopRelaunchMs","platform","fenceAvailable","flowFetch","integrationIo","shouldStop","leadSeams","waitSleep","releaseIo","installBin","onboardSeams","upSeams","laptopSeams","easySeams","upRole","folderLook","underAgent"];function registryPathOf(context){return join(dirname(context.databaseFile),"repos.json")}function telegramReadProjects(context){return async()=>{const loaded=await loadProjectRegistry(registryPathOf(context));if("error"in loaded)throw new Error("project registry unavailable");return loaded.repos}}function telegramCanDeliver(context,token){return()=>loadBotToken(process.env,context.telegramTokenFile)?.token===token&&effectivePrimary(process.env,dirname(context.databaseFile),!0).channel==="telegram"}function telegramConversation(context,options={}){return{evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner===void 0?{}:{subscriptionRunner:context.leadSeams.subscriptionRunner},phoneOrigin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:options.serverOrigin??null})}}function noteBaseStanding(store,runId,standing,main,now){if(standing==null)return;const commits=count=>`${count} commit${count===1?"":"s"}`;if(standing.moved!==null)store.addRunNote(runId,"Toolroll",`Started from current ${main} (${standing.main.slice(0,8)}). The branch had no commits or changes of its own and was ${commits(standing.moved.behind)} behind at ${standing.moved.from.slice(0,8)}.`,now);else if(standing.kept!==null&&standing.behind>0){const why=standing.kept==="has commits"?"it has commits of its own":standing.kept==="has changes"?"it has uncommitted changes":"its checkout is not on the task branch";store.addRunNote(runId,"Toolroll",`Based on an older ${main}: ${standing.head.slice(0,8)} is ${commits(standing.behind)} behind. It was not moved because ${why}.`,now)}}function revisionSourceHead(store,evidenceRoot,taskRef,revisionOf){const source=store.revisionSourceOf(taskRef),sourceRun=source===null?null:store.getRun(source.sourceRun);if(source===null||sourceRun===null||store.externalIdFor(sourceRun.taskRef)!==revisionOf||sourceRun.headRevision===null)return{ok:!1,problem:"the revision source has no matching sealed head"};try{const verified=readVerifiedArtifact(evidenceRoot,source.briefArtifact),brief=verified.ok?JSON.parse(verified.content.toString("utf8")):null;return brief===null||brief.head!==sourceRun.headRevision||brief.sourceScopeDigest!==sourceRun.scopeDigest?{ok:!1,problem:"the revision brief no longer binds the source head and scope"}:{ok:!0,head:sourceRun.headRevision}}catch{return{ok:!1,problem:"the revision source brief cannot be verified"}}}async function dispatch(command,positional,flags,context){const handler=Object.prototype.hasOwnProperty.call(COMMANDS,command)?COMMANDS[command]:void 0;return handler===void 0?fail(context.write,context.json,command,"usage",`unknown command \`${command}\``,EXIT.usage):handler(positional,flags,context)}function openBackend(name,store,repo){return name===BUILT_IN?builtIn(store):name==="beads"?guarded(beads({repo}),{store,repo}):name==="github-issues"?guarded(githubIssues({repo}),{store,repo}):null}function repoFrom(flags){if(activeRemote()!==null&&text(flags,"repo")===void 0)throw new RemoteRefusal("unknown-project",REMOTE_MESSAGES.project);return resolve(text(flags,"repo")??process.cwd())}async function readyCommand(flags,context){const{store,write,json,now}=context,backendName=text(flags,"backend")??BUILT_IN;if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"ready","usage",`no backend \`${backendName}\``,EXIT.usage);const result=await backend.listReady();if(!result.ok)return fail(write,json,"ready",result.reason,result.message,EXIT.failed);const tasks=result.value;if(json)return write(envelopeJson({ok:tasks.length>0,command:"ready",...tasks.length>0?{}:{reason:"empty",message:"nothing is ready to dispatch"},backend:backendName,count:tasks.length,tasks})),tasks.length>0?EXIT.ok:EXIT.refused;if(tasks.length===0)return write(`Nothing is ready in ${backendName}.`),EXIT.refused;write(`${tasks.length} ready in ${backendName}:`);for(const task of tasks)write(` ${task.id} ${task.title}`);return EXIT.ok}const lens=context.principal?.lens??null,ready=store.listReady(now).filter(ref=>lens===null||ref.repo!==null&&lens.includes(ref.repo)),described=ready.map(ref=>describeRef(store,ref,now)),dispatchableCount=described.filter(one=>diagnosisIsDispatchable(one.dispatch)).length,pauses=openAuthPauses(store);if(json)return write(envelopeJson({ok:ready.length>0,command:"ready",...ready.length>0?{}:{reason:"empty",message:"nothing is task-locally ready"},count:ready.length,dispatchableCount,signIn:pauses.map(one=>({provider:one.provider,message:signInWords(one),since:one.openedAt})),tasks:described})),ready.length>0?EXIT.ok:EXIT.refused;for(const one of pauses)write(signInWords(one));if(ready.length===0)return write("Nothing is ready to dispatch."),EXIT.refused;write(`${ready.length} task-local candidate${ready.length===1?"":"s"} (${dispatchableCount} can dispatch with the fleet as it stands):`);for(const ref of ready){const task=store.getTask(ref.externalId),diagnosis=diagnoseTaskDispatch(store,ref.externalId,now);write(` ${ref.externalId} ${task===null?"":task.title}${ref.assignedRunner===null?"":` (reserved for ${ref.assignedRunner})`}${diagnosis===null?"":` — ${diagnosis.code==="signed-out"?diagnosis.summary:diagnosis.summary.toLowerCase()}`}`)}return EXIT.ok}function describeRef(store,ref,now){const task=store.getTask(ref.externalId);return{id:ref.externalId,ref:ref.id,backend:ref.backend,title:task?.title??null,state:task?.state??null,reservedFor:ref.assignedRunner??null,claim:currentClaim(store,ref.id,now),dispatch:diagnoseTaskDispatch(store,ref.externalId,now)}}function claimCommand(positional,flags,context){const{store,write,json,now}=context,id=positional[0],runner=text(flags,"runner");if(id===void 0)return fail(write,json,"claim","usage","which task? `toolroll claim <id> --runner <name> --token <token>`",EXIT.usage);if(runner===void 0)return fail(write,json,"claim","usage","--runner names who is taking it",EXIT.usage);const token=text(flags,"token");if(token===void 0)return fail(write,json,"claim","usage","--token proves the runner is who it says",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"claim",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const backend=text(flags,"backend")??BUILT_IN;if(backend===BUILT_IN&&store.getTask(id)===null)return fail(write,json,"claim","unknown-task",`no task \`${id}\``,EXIT.refused);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,"claim","usage","--ttl takes whole seconds",EXIT.usage);if(backend!==BUILT_IN){const repo=resolve(text(flags,"repo")??process.cwd()),verdict=permits(store.grantFor(repo,backend),{repo,backend,mutation:"transition",origin:store.originOf(backend,id)});if(!verdict.ok)return fail(write,json,"claim",verdict.reason,verdict.message,EXIT.refused)}const ref=store.refFor(backend,id),result=claimAndMarkRunning(store,backend,id,ref.id,runner,{now,token,ttlMs:ttl,mutation:mutationFrom(flags,now)});return result.ok?succeed(write,json,"claim",{lease:result.claim,reclaimed:result.reclaimed},()=>[`Claimed ${id} as ${runner}.`,` lease ${result.claim.leaseId}`,` expires ${result.claim.expiresAt}`]):result.reason==="reserved"?fail(write,json,"claim","reserved",`${id} is reserved for ${result.reservedFor} — only that worker takes it`,EXIT.refused,{reservedFor:result.reservedFor}):result.reason==="external"?fail(write,json,"claim","external",{"stale-mirror":"this tracker item has not been seen recently — run `toolroll sync` first","external-closed":"the tracker closed this — reopen it first, or leave it be","dispatch-revoked":"this tracker's building permission was revoked or narrowed","plane-blocked":"this tracker's plane marker could not be verified — building is paused"}[result.detail]??"external work is not dispatchable right now",EXIT.refused,{detail:result.detail}):result.reason==="mode-ended"?fail(write,json,"claim","mode-ended",result.message,EXIT.refused):result.reason==="unauthenticated"?fail(write,json,"claim","unauthenticated",describeAuth(result.detail,runner),EXIT.refused):result.reason==="unplaced"?fail(write,json,"claim","unplaced","this task has no repository — preserve its history and file a replacement with `task add <title> --repo <path>`, then approve the new scope",EXIT.refused):result.reason==="unauthorized-repo"?fail(write,json,"claim","unauthorized-repo",`this runner is not bound to ${result.repo} — \`runner bind\` adds it`,EXIT.refused):result.reason==="coordinator-filed"?fail(write,json,"claim","coordinator-filed","a coordinator filed this — nothing runs until the operator signs its scope",EXIT.refused):result.reason==="sweep-limit"?fail(write,json,"claim","sweep-limit",`its sweep already has ${result.limit} running at once — it starts when one finishes`,EXIT.refused,{sweep:result.sweep,limit:result.limit}):result.reason==="watch-custody"?fail(write,json,"claim","watch-custody","This worker no longer holds the project; restart the watch",EXIT.refused):result.reason==="archived"?fail(write,json,"claim","archived",`${id} is put away — restore it with \`toolroll task restore ${id}\` first`,EXIT.refused):result.reason==="draining"?fail(write,json,"claim","draining",`Toolroll is restarting (draining): ${runner} takes no new work until it is back (by ${result.until})`,EXIT.refused,{until:result.until}):result.reason==="closed"?fail(write,json,"claim","closed",closedClaimWords(store,id,result.state,now),EXIT.refused,{state:result.state}):result.reason==="no-task"?fail(write,json,"claim","no-task",`no task \`${id}\``,EXIT.refused):fail(write,json,"claim",result.reason,`held by ${result.by} until ${result.until}`,EXIT.refused,{holder:result.by,until:result.until})}function leaseCommand(command,positional,flags,context){const{store,write,json,now}=context,name=command==="release"?"worker release":command,lease=positional[0];if(lease===void 0)return fail(write,json,name,"usage",`which lease? \`toolroll ${name} <lease>\``,EXIT.usage);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,name,"usage","--ttl takes whole seconds",EXIT.usage);const result=command==="heartbeat"?heartbeat(store,lease,now,ttl):releaseToQueue(store,lease,now);if(!result.ok){if(result.reason==="closed")return fail(write,json,name,"closed",`this lease ran out and its task is ${result.state} now, so it can't be renewed; stop rather than retry`,EXIT.refused,{state:result.state});const message=result.reason==="fenced"?"superseded — another runner holds this task now; stop rather than retry":"no such lease";return fail(write,json,name,result.reason,message,EXIT.refused)}return succeed(write,json,name,{lease:result.claim},()=>[command==="heartbeat"?`Still yours until ${result.claim.expiresAt}.`:`Released ${result.claim.leaseId}.`])}function reapCommand(context){const{store,write,json,now}=context,reaped=reap(store,now);if(json)return write(envelopeJson({ok:!0,command:"reap",count:reaped.length,released:reaped})),EXIT.ok;if(reaped.length===0)return write("No leases had run out."),EXIT.ok;write(`Released ${reaped.length}:`);for(const claim of reaped)write(` ${claim.leaseId} held by ${claim.runner}`);return EXIT.ok}async function runnerCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const runners=store.listRunners().map(one=>({...one,alive:isAlive(one,now)}));if(json)return write(envelopeJson({ok:!0,command:"runner list",count:runners.length,runners})),EXIT.ok;if(runners.length===0)return write("No runners registered."),write(" toolroll runner register <name>"),EXIT.ok;for(const one of runners)write(` ${one.name} ${one.alive?"alive":"not answering"} last heard ${one.heartbeatAt}`);return EXIT.ok}if(action==="register"){if(name===void 0)return fail(write,json,"runner register","usage","a runner needs a name",EXIT.usage);const capacity=Number(text(flags,"capacity")??"1");if(!Number.isInteger(capacity)||capacity<1)return fail(write,json,"runner register","usage","--capacity is a whole number of tasks",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner register","usage","`runner register <name> --repo <path> --as <you> --token <t>` — adding a builder is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner register",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner register","usage","--repo names at least one repository this runner may build — authority binds at the mint",EXIT.usage);const tokenFile=text(flags,"token-file");if(tokenFile!==void 0&&existsSync(tokenFile))return fail(write,json,"runner register","token-file-exists",`${tokenFile} already exists — remove it first if that worker is gone, or name another file`,EXIT.refused);const{runner,token,reclaimed}=register(store,{name,host:hostname(),capacity,repos,now,mutation:mutationFrom(flags,now)});if(tokenFile!==void 0)try{writeFileSync(tokenFile,`${token}
472
+ 1 something broke 3 ran fine, the answer is no`,TASK_ACTIONS=["add","new","keep","list","show","log","send","handoff","attach","wait","state","block","unblock","next","steer","pause","continue","assign","reopen","scope","approve","hold","unhold","require","requeue","regate","plan","review","accept","repair","route","stop","resume","complete","revise","merge","ask","checks","add-tests","archive","restore","tidy","ship","ready","handover","before-after","failing-first","land"],PUBLISH_ACTIONS=["setup","grant","revoke","status","unblock","rearm","merge","refire"],CONFIG_ACTIONS=["show","set","clear"],APPROVER_ACTIONS=["list","add"],PEOPLE_ACTIONS=["list","invite","projects","revoke"],KEYS_ACTIONS=["status","set","clear","verify","auth"],SECRET_VALUE_FLAGS=new Set(["token","password"]),OPERATE_VALUE_FLAGS=new Set(["key","db","runner","ttl","state","flow","on","reason","until","id","backend","build","from","allow","selector","paths","credentials","repo","token","capacity","agents","goal","not","touches","acceptance","candidate","by","digest","terms","as","branch","pool","base","model","turns","max","cap","probe","kind","expires","cmd","since","repair-model","choose","choice","claim","revision","note","max-open-decisions","name","days","publication","auto-approve","review-auto","port","host","allow-host","for","tick-every","bridge-every","reconcile-every","incarnation","say","ceiling-usd","cap-usd","incident","into","case","k","world","deny","abandon","token-file","bin","poll","github","remote","head-prefix","password","not-requester","protect","protect-paths","checkpoint","out","from","to","month","usd","person","subagent","teammate","providers","models","tools","project-root","schedule","ceiling","require","provider","plan-model","plan-provider","public-url","editor","command","timeout-seconds","setup-digest","stop-grace","title","name","every","lines","label","reviewers","limit","role","key-file","weekly-usd","daily-turns","per-hour","token-file","budget-usd","build-usd","sync-max-age","merge-method","phase","tier","clear-phase","size","risky","run","containment","agent","path","line","action","from-review","from-check","task","starter","template","steps","about","language","timeout-minutes","body","description","zone","option","except","token-env","after","repair-max-attempts","consumer","batch","feedback","source","view","cursor","why","supersedes","decision","sessions","timeout","replaced-by","replaces","quick","level","checks","task","access","projects","overlap","token-name","request","read-deny","mach","default","release","despite"]),OPERATE_BOOLEAN_FLAGS=new Set(["plan","just-code","finish","preview","diagnostic","keep","no-carry","from-main","full-check","rehearsal","json","yes","all","brief","local","history","latest-watch","dry-run","file","clear","follow","ready","all-tasks","inbound-only","help","undo","anyone","allow-dispatch","allow-merge","merge-delete-branch","no-open","single-process","laptop","web","remove","no-verify","no-follow","end","report","off","tmux","self-heal","plan-auto","chat-approve","full-access","repair-auto","review-retry-auto","no-local","html","csv","alerts-only","open","allowlist","allow-paid","no-paid","zip","saved","pull-request","checked","landed","verbose","revoke","anyway","also","reroute","password-stdin","now","preview","apply","no-check","check","wait","live","sub","list"]);const PROJECT_NETWORK_VALUE_FLAGS=new Set(["remove","local"]);export function parseOperateArgs(argv,ownValues=new Set){const positional=[],flags=new Map,repoList=[],wantsValue=new Set([...OPERATE_VALUE_FLAGS,...ownValues]),booleans=new Set([...OPERATE_BOOLEAN_FLAGS].filter(name=>!ownValues.has(name)));for(let index=0;index<argv.length;index++){const argument=argv[index];if(!argument.startsWith("--")){if(argument==="-h"){flags.set("help",!0);continue}if(argument==="-f"){flags.set("follow",!0);continue}positional.push(argument);continue}const equals=argument.indexOf("="),name=argument.slice(2,equals===-1?void 0:equals);if(booleans.has(name)){if(equals!==-1)return{error:`--${name} does not take a value`};flags.set(name,!0);continue}if(!wantsValue.has(name))return{error:`unknown option --${name} — add --help to any queue command for the whole surface`};const value=equals===-1?argv[++index]:argument.slice(equals+1),namesFlag=one=>{const flag2=one.slice(2).split("=")[0];return booleans.has(flag2)||wantsValue.has(flag2)};if(value===void 0||equals===-1&&value.startsWith("--")&&(!SECRET_VALUE_FLAGS.has(name)||namesFlag(value)))return{error:`--${name} needs a value`};if(flags.set(name,name==="param"&&typeof flags.get(name)=="string"?`${flags.get(name)}
473
+ ${value}`:value),name==="repo")for(const one of value.split(",").map(part=>part.trim()).filter(part=>part!==""))repoList.push(one)}return{positional,flags,repoList}}export async function runOperate(command,argv,write,options={}){return command==="task"&&(argv=withTaskAlias(["task",...argv]).slice(1)),withPasswordSource(CLI_PASSWORD_SOURCE,()=>rememberedLogin.run({login:null},()=>runOperateLocal(command,argv,write,options)))}async function runOperateLocal(command,argv,write,options={}){const parsed=parseOperateArgs(argv,ownValueFlags(command,argv));if("error"in parsed)return fail(write,argv.includes("--json"),command,"usage",parsed.error,EXIT.usage);const{positional,flags}=parsed,json=flags.has("json");if(flags.has("help")){const helpText=command==="task"&&(positional.length===0||positional[0]==="add")?positional[0]==="add"?TASK_ADD_HELP:TASK_HELP:command==="plugin"?`toolroll plugin list | install <github-url|folder> | update [id] | rollback <id> | remove <id> | validate <folder>
474
+ Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:command==="lead"?LEAD_HELP:command==="card"?CARD_HELP:command==="config"?configHelp(PROVIDER_IDS):command==="models"?MODELS_HELP:OPERATE_HELP;return write(json?envelopeJson({ok:!0,command:"help",help:helpText}):helpText),EXIT.ok}if(localOwnerRequested()&&localOwnerRowAct(command,positional,flags)===null)return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const file=text(flags,"db")??options.databaseFile??databasePath(process.env,homedir()),now=options.now??new Date;try{applyProjectProfile(command,positional,flags,file)}catch(error){return fail(write,json,command,"configuration",describe(error),EXIT.refused)}try{const containment=resolveContainment(text(flags,"containment"));if(!containment.ok)return fail(write,json,command,"usage",containment.problem,EXIT.usage)}catch(error){return fail(write,json,command,"usage",describe(error),EXIT.usage)}if(command==="mcp")return mcpCommand(file,flags,write,json);if(command==="serve"&&positional[0]==="check-public")return checkPublicCommand(flags,{write,json,envelope:envelopeJson,...options.publicProbe===void 0?{}:{probe:options.publicProbe}});if(command==="restore")return restoreCommand(file,positional,flags,write,json,now);if(command==="plugin"&&positional[0]==="validate")return positional.length!==2?fail(write,json,"plugin validate","usage","toolroll plugin validate <folder>",EXIT.usage):validatePluginCommand(file,positional[1],write,json);let store;try{const laptop=command==="up"&&flags.has("laptop")&&options.upRole===void 0;store=options.openDatabase!==void 0?options.openDatabase(file):openStore(file,laptop?{createdBy:"laptop"}:{})}catch(error){return databaseFailure(write,json,command,file,error)}if(file!==":memory:"&&startToolSecrets(store,file,()=>new Date,{eager:SECRETS_FIRST.has(command)}),localOwnerRequested()||shellActsAsLocalOwner(store,command,positional,flags,options)){const admitted=localOwnerCommand(store,command,positional,flags);if(!admitted.ok)return store.close(),fail(write,json,command,"refused",admitted.message,EXIT.refused);try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now},options,run2=>asLocalOwner(admitted.principal,run2))}finally{store.close()}}const presentedFlag=text(flags,"token"),flagLead=presentedFlag!==void 0&&parseLeadToken(presentedFlag)!==null,envLead=envValue(process.env,"LEAD_TOKEN"),presented=flagLead?presentedFlag:LEAD_COMMANDS.has(command)&&envLead!==void 0&&envLead!==""?envLead:void 0;let actor=null;if(presented!==void 0){if(!LEAD_COMMANDS.has(command))return store.close(),fail(write,json,command,"usage",`A lead token works for ${[...LEAD_COMMANDS].filter(one=>one!=="lead").join(", ")}. Use your own sign-in for ${command}.`,EXIT.usage);const lead=store.leadFor(presented);if(lead===null)return store.close(),fail(write,json,command,"unauthenticated","That lead token is not valid (revoked, replaced, or its owner can no longer approve). The owner mints a new one with: toolroll lead token",EXIT.refused);flagLead&&flags.delete("token"),actor={account:lead.owner,lead:!0}}try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now,...actor===null?{}:{leadToken:presented}},options,run2=>LEAD_COMMANDS.has(command)?withActor(actor,run2):run2())}finally{store.close()}}async function dispatchOn(command,positional,flags,repoList,base,options,enter){const{store,write,json,file,now}=base,dropLimitSink=pushLimitSink(reading=>store.recordProviderLimits(reading,new Date)),sizer=options.filingSizer??(process.env.VITEST!==void 0||envValue(process.env,"NO_TASK_CLASSIFIER")!==void 0||store.isDemo()?null:ownerSizer()),dropSizer=sizer===null?()=>{}:installFilingSizer(sizer),clock=options.now===void 0?()=>new Date:()=>now;try{return await enter(()=>dispatch(command,positional,flags,{...base.leadToken===void 0?{}:{leadToken:base.leadToken},store,write,json,repoList,now,clock,evidenceRoot:join(dirname(file),"evidence"),databaseFile:file,...injectedSeams(options),telegramTokenFile:join(dirname(file),"telegram-token"),...upNeedsOneProcess(options)?{upOneProcess:!0}:{},...activeRemote()===null?{}:{principal:activeRemote()}}))}catch(error){return error instanceof RemoteRefusal?fail(write,json,command,error.reason,error.message,EXIT.refused):isDatabaseBusy(error)?databaseFailure(write,json,command,file,error):fail(write,json,command,"failed",describe(error),EXIT.failed)}finally{await settleSizings(),dropSizer(),dropLimitSink()}}export async function runOperateAs(argv,opts){const{principal,store,write}=opts,source=opts.source==="mcp"?"mcp":"api",options=opts.options??{},now=options.now??new Date;argv=[...withTaskAlias(argv)];const[root="",...rest]=argv,json=rest.includes("--json");let invocation=root,tokenName=null;const tool=source==="mcp"&&typeof opts.tool=="string"&&/^[a-z][a-z0-9_]{0,40}$/.test(opts.tool)?opts.tool:null,record=(outcome,repo,taskId,why)=>{store.recordAction({at:(options.now??new Date).toISOString(),actor:principal.account,repo,taskId,runId:null,action:`remote command: ${invocation===""?"(none)":invocation}`.slice(0,200),outcome,source,detail:`token ${tokenName??principal.tokenId}${why===null?"":` · ${why}`}${tool===null?"":` · tool ${tool}`}`})},refuse=(reason,message,repo=null,taskId=null)=>(record("refused",repo,taskId,reason),fail(write,json,invocation===""?"remote":invocation,reason,message,EXIT.refused)),proved=reproveRemote(store,principal,now);if(!proved.ok)return refuse("unauthenticated",REMOTE_MESSAGES.stale);tokenName=proved.tokenName;const firstFlag=rest.findIndex(one=>one.startsWith("-")),row=remoteRowOf(root,firstFlag===-1?rest:rest.slice(0,firstFlag));if(row===null)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(invocation=row.invocation,row.remote==="step-up")return refuse("step-up",REMOTE_MESSAGES["step-up"]);const scope=REMOTE_SCOPES.get(row.invocation);if(row.remote!=="yes"||scope===void 0)return refuse("not-remote",REMOTE_MESSAGES.no);const parsed=parseOperateArgs(rest,ownValueFlags(root,rest));if("error"in parsed)return refuse("usage",parsed.error);if(remoteRowOf(root,parsed.positional)?.invocation!==row.invocation)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},row.mutation!=="none"?"act":"read").ok||proved.scope==="read"&&row.mutation!=="none")return refuse("read-only",REMOTE_MESSAGES.read);if([...parsed.flags.keys()].some(name=>REMOTE_REFUSED_FLAGS.has(name)))return refuse("usage",REMOTE_MESSAGES.credential);const allows=repo=>remoteAllows(store,principal,repo),project=remoteProjectOf(store,{allows},scope,parsed.positional,parsed.repoList,row.invocation,parsed.flags,opts.files??{});if(!project.ok)return refuse(project.reason,project.message);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},void 0,source2=>source2==="adapter"&&(project.repo===null||allows(project.repo))).ok)return refuse("forbidden",REMOTE_MESSAGES.no);const key=text(parsed.flags,"key");key!==void 0&&row.invocation!=="task revise"&&parsed.flags.set("key",`remote:${createHash("sha256").update(JSON.stringify([principal.account,row.invocation,project.repo,project.taskId,key])).digest("hex")}`);const file=store.databaseFile()??options.databaseFile;if(file===void 0)return refuse("failed","The server's database has no file.",project.repo,project.taskId);let filed=null;const run2=Object.freeze({account:principal.account,scope:proved.scope,tokenName:proved.tokenName,source,secret:remoteSecret(),allows,lens:remoteLensOf(store,scope,allows),noteTask:taskId=>{filed=taskId},files:Object.freeze({...opts.files})});record("requested",project.repo,project.taskId,null);let code;try{code=await withRemote(run2,()=>dispatchOn(root,parsed.positional,parsed.flags,parsed.repoList,{store,write,json,file,now},options,go=>withActor({account:principal.account,lead:!1},()=>projectAuthority.run({actor:principal.account,repo:project.repo},go))))}catch(error){throw record("failed",project.repo,filed??project.taskId,null),error}return record(code===EXIT.ok?"done":code===EXIT.refused?"refused":code===EXIT.usage?"usage":"failed",project.repo,filed??project.taskId,null),code}function remoteFile(remote,path){if(Object.prototype.hasOwnProperty.call(remote.files,path))return remote.files[path];throw new RemoteRefusal("usage",REMOTE_MESSAGES.files)}const LEAD_COMMANDS=new Set(["plugin","task","assignment","status","ready","brief","peek","check-progress","notifications","lead"]),SEAMS=["tempRoots","desktopIdentity","inferProjectFromCwd","additionalProjectRepos","agentRunner","gitRunner","telegramTransport","telegramEnv","publishExec","dispatchAdapter","flowTriggerIo","flowStepIo","flowEveryMs","watchHeartbeatMs","loopRelaunchMs","platform","fenceAvailable","flowFetch","integrationIo","shouldStop","leadSeams","waitSleep","releaseIo","installBin","onboardSeams","upSeams","laptopSeams","easySeams","upRole","folderLook","underAgent"];function registryPathOf(context){return join(dirname(context.databaseFile),"repos.json")}function telegramReadProjects(context){return async()=>{const loaded=await loadProjectRegistry(registryPathOf(context));if("error"in loaded)throw new Error("project registry unavailable");return loaded.repos}}function telegramCanDeliver(context,token){return()=>loadBotToken(process.env,context.telegramTokenFile)?.token===token&&effectivePrimary(process.env,dirname(context.databaseFile),!0).channel==="telegram"}function telegramConversation(context,options={}){return{evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner===void 0?{}:{subscriptionRunner:context.leadSeams.subscriptionRunner},phoneOrigin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:options.serverOrigin??null})}}function noteBaseStanding(store,runId,standing,main,now){if(standing==null)return;const commits=count=>`${count} commit${count===1?"":"s"}`;if(standing.moved!==null)store.addRunNote(runId,"Toolroll",`Started from current ${main} (${standing.main.slice(0,8)}). The branch had no commits or changes of its own and was ${commits(standing.moved.behind)} behind at ${standing.moved.from.slice(0,8)}.`,now);else if(standing.kept!==null&&standing.behind>0){const why=standing.kept==="has commits"?"it has commits of its own":standing.kept==="has changes"?"it has uncommitted changes":"its checkout is not on the task branch";store.addRunNote(runId,"Toolroll",`Based on an older ${main}: ${standing.head.slice(0,8)} is ${commits(standing.behind)} behind. It was not moved because ${why}.`,now)}}function revisionSourceHead(store,evidenceRoot,taskRef,revisionOf){const source=store.revisionSourceOf(taskRef),sourceRun=source===null?null:store.getRun(source.sourceRun);if(source===null||sourceRun===null||store.externalIdFor(sourceRun.taskRef)!==revisionOf||sourceRun.headRevision===null)return{ok:!1,problem:"the revision source has no matching sealed head"};try{const verified=readVerifiedArtifact(evidenceRoot,source.briefArtifact),brief=verified.ok?JSON.parse(verified.content.toString("utf8")):null;return brief===null||brief.head!==sourceRun.headRevision||brief.sourceScopeDigest!==sourceRun.scopeDigest?{ok:!1,problem:"the revision brief no longer binds the source head and scope"}:{ok:!0,head:sourceRun.headRevision}}catch{return{ok:!1,problem:"the revision source brief cannot be verified"}}}async function dispatch(command,positional,flags,context){const handler=Object.prototype.hasOwnProperty.call(COMMANDS,command)?COMMANDS[command]:void 0;return handler===void 0?fail(context.write,context.json,command,"usage",`unknown command \`${command}\``,EXIT.usage):handler(positional,flags,context)}function openBackend(name,store,repo){return name===BUILT_IN?builtIn(store):name==="beads"?guarded(beads({repo}),{store,repo}):name==="github-issues"?guarded(githubIssues({repo}),{store,repo}):null}function repoFrom(flags){if(activeRemote()!==null&&text(flags,"repo")===void 0)throw new RemoteRefusal("unknown-project",REMOTE_MESSAGES.project);return resolve(text(flags,"repo")??process.cwd())}async function readyCommand(flags,context){const{store,write,json,now}=context,backendName=text(flags,"backend")??BUILT_IN;if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"ready","usage",`no backend \`${backendName}\``,EXIT.usage);const result=await backend.listReady();if(!result.ok)return fail(write,json,"ready",result.reason,result.message,EXIT.failed);const tasks=result.value;if(json)return write(envelopeJson({ok:tasks.length>0,command:"ready",...tasks.length>0?{}:{reason:"empty",message:"nothing is ready to dispatch"},backend:backendName,count:tasks.length,tasks})),tasks.length>0?EXIT.ok:EXIT.refused;if(tasks.length===0)return write(`Nothing is ready in ${backendName}.`),EXIT.refused;write(`${tasks.length} ready in ${backendName}:`);for(const task of tasks)write(` ${task.id} ${task.title}`);return EXIT.ok}const lens=context.principal?.lens??null,ready=store.listReady(now).filter(ref=>lens===null||ref.repo!==null&&lens.includes(ref.repo)),described=ready.map(ref=>describeRef(store,ref,now)),dispatchableCount=described.filter(one=>diagnosisIsDispatchable(one.dispatch)).length,pauses=openAuthPauses(store);if(json)return write(envelopeJson({ok:ready.length>0,command:"ready",...ready.length>0?{}:{reason:"empty",message:"nothing is task-locally ready"},count:ready.length,dispatchableCount,signIn:pauses.map(one=>({provider:one.provider,message:signInWords(one),since:one.openedAt})),tasks:described})),ready.length>0?EXIT.ok:EXIT.refused;for(const one of pauses)write(signInWords(one));if(ready.length===0)return write("Nothing is ready to dispatch."),EXIT.refused;write(`${ready.length} task-local candidate${ready.length===1?"":"s"} (${dispatchableCount} can dispatch with the fleet as it stands):`);for(const ref of ready){const task=store.getTask(ref.externalId),diagnosis=diagnoseTaskDispatch(store,ref.externalId,now);write(` ${ref.externalId} ${task===null?"":task.title}${ref.assignedRunner===null?"":` (reserved for ${ref.assignedRunner})`}${diagnosis===null?"":` — ${diagnosis.code==="signed-out"?diagnosis.summary:diagnosis.summary.toLowerCase()}`}`)}return EXIT.ok}function describeRef(store,ref,now){const task=store.getTask(ref.externalId);return{id:ref.externalId,ref:ref.id,backend:ref.backend,title:task?.title??null,state:task?.state??null,reservedFor:ref.assignedRunner??null,claim:currentClaim(store,ref.id,now),dispatch:diagnoseTaskDispatch(store,ref.externalId,now)}}function claimCommand(positional,flags,context){const{store,write,json,now}=context,id=positional[0],runner=text(flags,"runner");if(id===void 0)return fail(write,json,"claim","usage","which task? `toolroll claim <id> --runner <name> --token <token>`",EXIT.usage);if(runner===void 0)return fail(write,json,"claim","usage","--runner names who is taking it",EXIT.usage);const token=text(flags,"token");if(token===void 0)return fail(write,json,"claim","usage","--token proves the runner is who it says",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"claim",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const backend=text(flags,"backend")??BUILT_IN;if(backend===BUILT_IN&&store.getTask(id)===null)return fail(write,json,"claim","unknown-task",`no task \`${id}\``,EXIT.refused);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,"claim","usage","--ttl takes whole seconds",EXIT.usage);if(backend!==BUILT_IN){const repo=resolve(text(flags,"repo")??process.cwd()),verdict=permits(store.grantFor(repo,backend),{repo,backend,mutation:"transition",origin:store.originOf(backend,id)});if(!verdict.ok)return fail(write,json,"claim",verdict.reason,verdict.message,EXIT.refused)}const ref=store.refFor(backend,id),result=claimAndMarkRunning(store,backend,id,ref.id,runner,{now,token,ttlMs:ttl,mutation:mutationFrom(flags,now)});return result.ok?succeed(write,json,"claim",{lease:result.claim,reclaimed:result.reclaimed},()=>[`Claimed ${id} as ${runner}.`,` lease ${result.claim.leaseId}`,` expires ${result.claim.expiresAt}`]):result.reason==="reserved"?fail(write,json,"claim","reserved",`${id} is reserved for ${result.reservedFor} — only that worker takes it`,EXIT.refused,{reservedFor:result.reservedFor}):result.reason==="external"?fail(write,json,"claim","external",{"stale-mirror":"this tracker item has not been seen recently — run `toolroll sync` first","external-closed":"the tracker closed this — reopen it first, or leave it be","dispatch-revoked":"this tracker's building permission was revoked or narrowed","plane-blocked":"this tracker's plane marker could not be verified — building is paused"}[result.detail]??"external work is not dispatchable right now",EXIT.refused,{detail:result.detail}):result.reason==="mode-ended"?fail(write,json,"claim","mode-ended",result.message,EXIT.refused):result.reason==="unauthenticated"?fail(write,json,"claim","unauthenticated",describeAuth(result.detail,runner),EXIT.refused):result.reason==="unplaced"?fail(write,json,"claim","unplaced","this task has no repository — preserve its history and file a replacement with `task add <title> --repo <path>`, then approve the new scope",EXIT.refused):result.reason==="unauthorized-repo"?fail(write,json,"claim","unauthorized-repo",`this runner is not bound to ${result.repo} — \`runner bind\` adds it`,EXIT.refused):result.reason==="coordinator-filed"?fail(write,json,"claim","coordinator-filed","a coordinator filed this — nothing runs until the operator signs its scope",EXIT.refused):result.reason==="sweep-limit"?fail(write,json,"claim","sweep-limit",`its sweep already has ${result.limit} running at once — it starts when one finishes`,EXIT.refused,{sweep:result.sweep,limit:result.limit}):result.reason==="watch-custody"?fail(write,json,"claim","watch-custody","This worker no longer holds the project; restart the watch",EXIT.refused):result.reason==="archived"?fail(write,json,"claim","archived",`${id} is put away — restore it with \`toolroll task restore ${id}\` first`,EXIT.refused):result.reason==="draining"?fail(write,json,"claim","draining",`Toolroll is restarting (draining): ${runner} takes no new work until it is back (by ${result.until})`,EXIT.refused,{until:result.until}):result.reason==="closed"?fail(write,json,"claim","closed",closedClaimWords(store,id,result.state,now),EXIT.refused,{state:result.state}):result.reason==="no-task"?fail(write,json,"claim","no-task",`no task \`${id}\``,EXIT.refused):fail(write,json,"claim",result.reason,`held by ${result.by} until ${result.until}`,EXIT.refused,{holder:result.by,until:result.until})}function leaseCommand(command,positional,flags,context){const{store,write,json,now}=context,name=command==="release"?"worker release":command,lease=positional[0];if(lease===void 0)return fail(write,json,name,"usage",`which lease? \`toolroll ${name} <lease>\``,EXIT.usage);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,name,"usage","--ttl takes whole seconds",EXIT.usage);const result=command==="heartbeat"?heartbeat(store,lease,now,ttl):releaseToQueue(store,lease,now);if(!result.ok){if(result.reason==="closed")return fail(write,json,name,"closed",`this lease ran out and its task is ${result.state} now, so it can't be renewed; stop rather than retry`,EXIT.refused,{state:result.state});const message=result.reason==="fenced"?"superseded — another runner holds this task now; stop rather than retry":"no such lease";return fail(write,json,name,result.reason,message,EXIT.refused)}return succeed(write,json,name,{lease:result.claim},()=>[command==="heartbeat"?`Still yours until ${result.claim.expiresAt}.`:`Released ${result.claim.leaseId}.`])}function reapCommand(context){const{store,write,json,now}=context,reaped=reap(store,now);if(json)return write(envelopeJson({ok:!0,command:"reap",count:reaped.length,released:reaped})),EXIT.ok;if(reaped.length===0)return write("No leases had run out."),EXIT.ok;write(`Released ${reaped.length}:`);for(const claim of reaped)write(` ${claim.leaseId} held by ${claim.runner}`);return EXIT.ok}async function runnerCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const runners=store.listRunners().map(one=>({...one,alive:isAlive(one,now)}));if(json)return write(envelopeJson({ok:!0,command:"runner list",count:runners.length,runners})),EXIT.ok;if(runners.length===0)return write("No runners registered."),write(" toolroll runner register <name>"),EXIT.ok;for(const one of runners)write(` ${one.name} ${one.alive?"alive":"not answering"} last heard ${one.heartbeatAt}`);return EXIT.ok}if(action==="register"){if(name===void 0)return fail(write,json,"runner register","usage","a runner needs a name",EXIT.usage);const capacity=Number(text(flags,"capacity")??"1");if(!Number.isInteger(capacity)||capacity<1)return fail(write,json,"runner register","usage","--capacity is a whole number of tasks",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner register","usage","`runner register <name> --repo <path> --as <you> --token <t>` — adding a builder is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner register",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner register","usage","--repo names at least one repository this runner may build — authority binds at the mint",EXIT.usage);const tokenFile=text(flags,"token-file");if(tokenFile!==void 0&&existsSync(tokenFile))return fail(write,json,"runner register","token-file-exists",`${tokenFile} already exists — remove it first if that worker is gone, or name another file`,EXIT.refused);const{runner,token,reclaimed}=register(store,{name,host:hostname(),capacity,repos,now,mutation:mutationFrom(flags,now)});if(tokenFile!==void 0)try{writeFileSync(tokenFile,`${token}
458
475
  `,{mode:384,flag:"wx"}),chmodSync(tokenFile,384)}catch(error){return fail(write,json,"runner register","token-file",`registered ${runner.name}, but the token could not be written to ${tokenFile} (${describe(error)}) — register again with a writable path`,EXIT.failed,{runner,reclaimed})}return succeed(write,json,"runner register",{runner,...tokenFile===void 0?{token}:{tokenFile},reclaimed},()=>[`Registered ${runner.name} on ${runner.host}, capacity ${runner.capacity}.`,"",...tokenFile===void 0?[` token ${token}`,"","That token is shown once and is not stored — only a hash of it is."]:[` token written to ${tokenFile} (owner-only) — \`toolroll watch --runner ${runner.name} --token-file ${tokenFile} --repo <path>\` uses it.`,"","The token is not stored anywhere else — only a hash of it is."],"If it is lost, register again to mint a new one.",...reclaimed===null?[]:["",`A previous ${runner.name} was still holding work; it has been taken back:`,...reclaimed.claims.map(lease=>` claim ${lease}`),...reclaimed.worktrees.map(path=>` worktree ${path} (unverified)`)]])}if(action==="heartbeat"){const token=text(flags,"token");if(name===void 0||token===void 0)return fail(write,json,"runner heartbeat","usage","`runner heartbeat <name> --token <token>`",EXIT.usage);const result=heartbeatRunner(store,name,token,now);return result.ok?succeed(write,json,"runner heartbeat",{runner:result.runner},()=>[`${name} checked in.`]):fail(write,json,"runner heartbeat",result.reason,describeAuth(result.reason,name),EXIT.refused)}if(action==="reap"){const recovered=recoverDead(store,now).filter(recoveredAnything);if(json)return write(envelopeJson({ok:!0,command:"runner reap",recovered})),EXIT.ok;if(recovered.length===0)return write("Every runner is answering, or held nothing."),EXIT.ok;for(const one of recovered){write(`${one.runner} is not answering — took back:`);for(const lease of one.claims)write(` claim ${lease}`);for(const id of one.runs)write(` run #${id} (finished as interrupted)`);for(const id of one.requeued)write(` task ${id} (requeued)`);for(const path of one.worktrees)write(` worktree ${path} (unverified)`)}return EXIT.ok}if(action==="retire"){if(name===void 0)return fail(write,json,"runner retire","usage","which runner?",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);return acting===null||!verified?.ok?refuseApprover(context,"runner retire",verified,"`runner retire <name> --as <you> --token <t>` — retiring a builder is an approver's act",name):store.retireRunner(name,now,mutationFrom(flags,now))?succeed(write,json,"runner retire",{name},()=>[`${name} is retired.`]):fail(write,json,"runner retire","unknown",`no runner \`${name}\``,EXIT.refused)}if(action==="bind"){if(name===void 0)return fail(write,json,"runner bind","usage","which runner?",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner bind","usage","`runner bind <name> --repo <path> --as <you> --token <t>` — choosing a builder's projects is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner bind",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner bind","usage","--repo names at least one repository",EXIT.usage);const bound=store.bindRunnerRepos(name,canonicalRepos(repos),now);return bound.ok?succeed(write,json,"runner bind",{name,repos:bound.repos},()=>[`${name} may build in:`,...bound.repos.map(one=>` ${one}`)]):fail(write,json,"runner bind",bound.reason,describeAuth(bound.reason,name),EXIT.refused)}if(action==="capacity"){const given=positional[2];if(name===void 0||given===void 0||positional.length>3)return fail(write,json,"runner capacity","usage","`runner capacity <name> <n> --as <you> --token <t>`",EXIT.usage);const capacity=parseRunnerCapacity(given,{allowZero:!0});if(capacity===null)return fail(write,json,"runner capacity","usage",`capacity is a whole number of tasks, 0 to ${RUNNER_CAPACITY_MAX}; 0 stops new builds`,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(write,json,"runner capacity","refused","An instance operator changes a worker's capacity: pass --as and --token (or use the remembered login).",EXIT.refused);const changed=store.setRunnerCapacity(name,capacity,acting.name,now);if(!changed.ok)return fail(write,json,"runner capacity",changed.reason,changed.reason==="retired"?`${name} is retired`:`no runner \`${name}\``,EXIT.refused);const running=store.liveClaimCount(name,now);return changed.after===0?succeed(write,json,"runner capacity",{name,before:changed.before,after:changed.after,running},()=>[`${name} takes no new builds. ${running===0?"Nothing is running.":`${running} running task(s) will finish.`}`,`Resume with: toolroll runner capacity ${name} <1-${RUNNER_CAPACITY_MAX}>`]):succeed(write,json,"runner capacity",{name,before:changed.before,after:changed.after,running},()=>[changed.before===changed.after?`${name} already runs up to ${changed.after} at once.`:`${name} now runs up to ${changed.after} at once (was ${changed.before}).`,...running>changed.after?[`It is running ${running} now; those carry on, and it takes nothing new until fewer than ${changed.after} are running.`]:[]])}return fail(write,json,"runner","usage",`unknown \`runner ${action}\` — try list, register, bind, capacity, heartbeat, reap, retire`,EXIT.usage)}async function coordinatorCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const rows=listCoordinators(store);if(json)return write(envelopeJson({ok:!0,command:"coordinator list",coordinators:rows})),EXIT.ok;if(rows.length===0)return write("No coordinators. `toolroll coordinator mint <name> --repo <path> --as <you> --token <t>`"),EXIT.ok;for(const one of rows){const state=one.revokedAt===null?`${one.perHour}/h`:"revoked";write(` ${one.name}#${one.cid.slice(0,4)} ${state} ${one.repos.join(", ")} last filed ${one.lastFiledAt??"never"}`)}return EXIT.ok}if(action==="mint"){if(name===void 0)return fail(write,json,"coordinator mint","usage","a coordinator needs a name",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"coordinator mint","usage","`coordinator mint <name> --repo <path> --as <you> --token <t>` — minting your lead's credential is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"coordinator mint",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"coordinator mint","usage","--repo names at least one repository this coordinator may file into",EXIT.usage);const perHourGiven=text(flags,"per-hour"),perHour=perHourGiven===void 0?void 0:Number(perHourGiven),daysGiven=text(flags,"days"),days=daysGiven===void 0?void 0:Number(daysGiven),made=mintCoordinator(store,{name,repos,...perHour===void 0?{}:{perHour},...days===void 0?{}:{days},by:acting.name,now});if(!made.ok){const said={"bad-name":"a coordinator name is 1-32 characters of a-z, 0-9, and dashes","name-taken":`a live coordinator already answers to \`${name}\` — revoke it first, or pick another name`,"bad-rate":"--per-hour is a whole number from 1 to 60, and --days from 1 to 365","no-repos":"--repo names at least one repository"};return fail(write,json,"coordinator mint",made.reason,said[made.reason]??made.reason,made.reason==="name-taken"?EXIT.refused:EXIT.usage)}return succeed(write,json,"coordinator mint",{cid:made.cid,token:made.token,repos:made.repos},()=>[`Minted ${name}#${made.cid.slice(0,4)} — may file into:`,...made.repos.map(one=>` ${one}`),"",` token ${made.token}`,"",`It expires in ${days??90} days: mint a new one before then.`,"That token is shown once and is not stored — only a hash of it is.","Give it to the MCP server via a 0600 token file or TOOLROLL_COORDINATOR."])}if(action==="revoke"){if(name===void 0)return fail(write,json,"coordinator revoke","usage","which coordinator? (`coordinator list` shows cids)",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"coordinator revoke",verified,"`coordinator revoke <cid> --as <you> --token <t>` — revoking is an approver's act",name);const revoked=revokeCoordinator(store,name,acting.name,now);if(!revoked.ok){const said=revoked.reason==="unknown"?`no coordinator \`${name}\` — \`coordinator list\` shows cids`:"already revoked";return fail(write,json,"coordinator revoke",revoked.reason,said,EXIT.refused)}return succeed(write,json,"coordinator revoke",{cid:name},()=>[`${name} is revoked — its filings stand, its token does not.`])}return fail(write,json,"coordinator","usage",`unknown \`coordinator ${action}\` — try list, mint, revoke`,EXIT.usage)}async function mcpCommand(file,flags,write,json){const said=message=>(json?write(envelopeJson({ok:!1,command:"mcp",reason:"refused",message})):process.stderr.write(`${message}
459
476
  `),EXIT.refused),fromFile=text(flags,"token-file"),fromEnv=envValue(process.env,"COORDINATOR");if(fromFile!==void 0&&fromEnv!==void 0&&fromEnv!=="")return said("both --token-file and TOOLROLL_COORDINATOR are set — pick one");let token;if(fromFile!==void 0){let fd;try{fd=openSync(fromFile,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK)}catch{return said(`${fromFile}: cannot open (missing, or a symlink — the token file must be the real file)`)}try{const stat=fstatSync(fd);if(!stat.isFile())return said(`${fromFile}: not a regular file`);if(stat.uid!==process.getuid?.())return said(`${fromFile}: owned by somebody else`);if((stat.mode&4095)!==384)return said(`${fromFile}: mode must be exactly 0600 — special bits included`);if(stat.size>4096)return said(`${fromFile}: too large for a token file`);const buffer=Buffer.alloc(4096),read=readSync(fd,buffer,0,4096,0);token=buffer.subarray(0,read).toString("utf8").trim()}finally{closeSync(fd)}}else if(fromEnv!==void 0&&fromEnv!=="")token=fromEnv.trim();else return said("no credential — pass --token-file <path> (0600) or set TOOLROLL_COORDINATOR");process.umask?.(63);const door=openStoreNoMigrate(file);if(!door.ok)return said(door.message);const store=door.store;startToolSecrets(store,file,()=>new Date,{eager:!1});for(const suffix of["","-wal","-shm"])try{chmodSync(`${file}${suffix}`,384)}catch{}try{chmodSync(dirname(file),448)}catch{}if(store.isDemo())return store.close(),said("demo console — no gateway");let enrolled=null;try{const loaded=await loadRepos(registryPathOf({databaseFile:file}));"error"in loaded||(enrolled=loaded.repos)}catch{enrolled=null}return await new Promise(resolvePromise=>{let lineHandler=()=>{},eofHandler=()=>{};const reader=createInterface({input:process.stdin,terminal:!1});reader.on("line",line=>lineHandler(line)),reader.on("close",()=>eofHandler());const outcome=serveMcp(store,token,{onLine:handler=>{lineHandler=handler},onEof:handler=>{eofHandler=handler},write:line=>process.stdout.write(`${line}
460
477
  `),log:line=>process.stderr.write(`${line}
461
- `),exit:code=>{reader.close(),store.close(),resolvePromise(code)}},void 0,enrolled,join(dirname(file),"evidence"));outcome.ok||(reader.close(),store.close(),resolvePromise(said(outcome.message)))})}function describeAuth(reason,name){return reason==="unknown"?`no runner \`${name}\` — register it first`:reason==="retired"?`${name} has been retired`:reason==="expired"?`${name}'s token expired a year after it registered — register it again`:"that token does not match"}async function buildCommand(positional,flags,context){const{store,write,json,now}=context,demoFence=refuseDemo(context,"build");if(demoFence!==null)return demoFence;const id=positional[0];if(id!==void 0&&store.mirrorByTask(id)!==null)return fail(write,json,"build","external-task","external work dispatches through tick/watch — the completion gate lives there",EXIT.refused);const runner=text(flags,"runner"),token=text(flags,"token"),branch=text(flags,"branch");if(id===void 0||runner===void 0||token===void 0||branch===void 0)return fail(write,json,"build","usage","`toolroll build <id> --runner <name> --token <t> --branch <b> --repo <path>`",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"build",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"build","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);if(store.getTask(id)===null)return fail(write,json,"build","unknown-task",`No task ${id}.`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),ref=store.refFor(BUILT_IN,id),worktrees=new WorktreePool(store,{root:pool}),leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now,...text(flags,"base")===void 0?{}:{base:text(flags,"base")}});if(!leased.ok)return fail(write,json,"build",leased.reason,leased.message,EXIT.refused);const held=currentClaim(store,ref.id,now),standaloneModel=text(flags,"model"),authority=store.routeAuthorityFor(ref.id,"builder",{provider:"claude",model:standaloneModel??null});if(authority!==null&&!authority.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",`${id}: ${authority.problem}`,EXIT.refused);const standaloneMode=readAuthModeStrict(authority===null?"claude":authority.stamp.provider);if(!standaloneMode.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","auth-mode",`${id}: ${standaloneMode.problem}`,EXIT.refused);const standaloneProvider=authority===null?"claude":authority.stamp.provider,standaloneHold=store.budgetGate(now)({...store.budgetSubject(ref.id),agents:[{provider:standaloneProvider,billing:standaloneMode.mode==="api-key"?"api-key":billingOf(standaloneProvider,store.handle)}]});if(standaloneHold.over!==null)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","budget",`${id}: ${budgetHoldWords(standaloneHold,monthOf(now).name)}`,EXIT.refused);let runId;try{runId=store.startRun({taskRef:ref.id,leaseId:held?.leaseId??"unclaimed",runner,branch,worktree:leased.worktree.path,...authority===null?{}:{provider:authority.stamp.provider,route:authority.stamp},...standaloneModel===void 0?{}:{model:standaloneModel},now})}catch(error){return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",error instanceof Error?error.message:String(error),EXIT.refused)}const result=await build(store,{taskId:id,taskRef:ref.id,runner,...held===null?{}:{leaseId:held.leaseId},runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now,clock:context.clock,...text(flags,"model")===void 0?{}:{model:text(flags,"model")},...text(flags,"repair-model")===void 0?{}:{repairModel:text(flags,"repair-model")},...text(flags,"turns")===void 0?{}:{maxTurns:Number(text(flags,"turns"))},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}}),handedBack=await worktrees.release(leased.worktree.path,now),disposition=disposeBuildOutcome({store,policy:"standalone",leaseId:held?.leaseId,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:"claude",model:text(flags,"model")??null,worktreePath:leased.worktree.path,clock:context.clock},result);if(result.ok&&result.parked!==void 0)return disposition.kind!=="parked"?fail(write,json,"build","fenced",`${id} parked, but the lease was gone before the decision could be sealed`,EXIT.refused,{worktree:leased.worktree.path}):succeed(write,json,"build",{parked:!0,decision:disposition.decisionId,worktree:leased.worktree.path},()=>[`${id} parked a decision instead of guessing.`,` decision ${disposition.decisionId} — \`toolroll decide ${disposition.decisionId}\``,` worktree ${leased.worktree.path} (work in progress preserved)`]);if(!result.ok){const broke=result.reason==="agent"||result.reason==="agent-reported"||result.reason==="no-op"||result.reason==="no-handoff"||result.reason==="moved-head"||result.reason==="timeout"||result.reason==="git"||result.reason==="malformed-decision";return fail(write,json,"build",result.reason,result.message,broke?EXIT.failed:EXIT.refused,{worktree:leased.worktree.path})}return succeed(write,json,"build",{...result,worktree:leased.worktree.path,clean:handedBack.ok},()=>[result.committed?`Built ${id} and committed to ${branch}.`:`${id}: no change needed — the agent said so and the tree agrees.`,` worktree ${leased.worktree.path}`,"",result.summary,"","Nothing has been pushed. Look at the branch before it goes anywhere."])}function flowIoOf(context,pool,git,base){const dir=dirname(context.databaseFile);return{triggers:{gh:context.flowTriggerIo?.gh??run,fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,shell:context.flowTriggerIo?.shell??context.flowStepIo?.shell??run,scratch:context.flowTriggerIo?.scratch??context.flowStepIo?.scratch??join(pool,"flow-checks"),...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},replies:{fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},steps:{gh:context.flowStepIo?.gh??run,git:context.flowStepIo?.git??(git===run?hardenedGit(run):git),shell:context.flowStepIo?.shell??run,fetch:context.flowStepIo?.fetch??fetch,dir:context.flowStepIo?.dir??dir,scratch:context.flowStepIo?.scratch??join(pool,"flow-checks"),base,...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}},...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot},youiyouxGit:gitOf(context.gitRunner)}}async function tickCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"tick");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token");if(runner===void 0||token===void 0)return fail(write,json,"tick","usage","`toolroll tick --runner <name> --token <t> --repo <path> [--max <n>] [--base <ref>]`",EXIT.usage);const auth=heartbeatRunner(store,runner,token,clock());if(!auth.ok)return fail(write,json,"tick",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);if(updateAdmissionPaused(store.raw()))return fail(write,json,"tick","updating",UPDATE_PAUSED,EXIT.refused);const maxGiven=text(flags,"max"),maxAsked=maxGiven===void 0?1:Number(maxGiven);if(!Number.isInteger(maxAsked)||maxAsked<=0)return fail(write,json,"tick","usage","--max takes a whole number of tasks",EXIT.usage);const max=flags.has("yield-builds")?0:maxAsked,buildsOnly=flags.has("builds-only"),syncAgeGiven=text(flags,"sync-max-age"),syncMaxAgeMs=syncAgeGiven===void 0?SYNC_MAX_AGE_MS:Number(syncAgeGiven)*1e3;if(!Number.isInteger(syncMaxAgeMs)||syncMaxAgeMs<=0)return fail(write,json,"tick","usage","--sync-max-age takes whole seconds",EXIT.usage);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"tick","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),model=text(flags,"model"),repairModel=text(flags,"repair-model"),providerFlag=text(flags,"provider"),planModel=text(flags,"plan-model"),planProvider=text(flags,"plan-provider"),turns=text(flags,"turns"),leaseTtlMs=DEFAULT_LEASE_MS,git=context.gitRunner??run,worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),watchOwner=text(flags,"incarnation");watchOwner!==void 0&&!buildsOnly&&await runAcpChecks({store,runner,token,pool:worktrees,clock,watch:{repo:canonicalProject(repo)??resolve(repo),owner:watchOwner},progress:line=>{json||write(line)}});let base=text(flags,"base");if(base===void 0){const head=await git("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return fail(write,json,"tick","git",`${repo} has no branch checked out — say --base explicitly`,EXIT.refused);base=head.stdout.trim()}await probeRepo(store,repo,runner,clock()),applyPendingAgentChanges(store,clock());const housekeeping=buildsOnly?null:await flowHousekeeping(store,repo,clock,flowIoOf(context,pool,git,base),()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0),triggerPass=housekeeping?.triggers??{added:0,checked:0,problems:[]},replyPass=housekeeping?.replies??{read:0,taken:0,problem:null},stepPass=housekeeping?.steps??{ran:0,problems:[]},flowPass=housekeeping?.flows??{moved:0,filed:[],problems:[]};if(!buildsOnly)try{sendSubagentSummaries(store,repo,clock()),sendSubagentWeeklies(store,repo,clock())}catch(error){flowPass.problems.push(`subagent summaries: ${error instanceof Error?error.message:"could not send"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{await runRequestedUndos(store,{},clock())}catch(error){flowPass.problems.push(`subagent undo: ${error instanceof Error?error.message:"could not run"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{flowPass.problems.push(...(await refreshConnections(store,[repo],clock(),context.flowStepIo?.fetch===void 0?{}:{fetcher:context.flowStepIo.fetch})).problems)}catch(error){flowPass.problems.push(`tool sign-ins: ${error instanceof Error?error.message:"could not renew"}`)}let settled=0;const settleFinished=()=>{const finished=dispatched.slice(settled).filter(one=>one.outcome!=="skipped").map(one=>one.id);if(settled=dispatched.length,finished.length===0)return;const after=moveCardsAfter(store,repo,finished,clock(),context.evidenceRoot);flowPass.moved+=after.moved,flowPass.filed.push(...after.filed),flowPass.problems.push(...after.problems)};store.sweepCeremonyNonces(clock());let budgetGate=null;const budgetHold=(taskRef,agents)=>(budgetGate??=store.budgetGate(clock()))({...store.budgetSubject(taskRef),agents}),budgetWords=hold=>budgetHoldWords(hold,monthOf(clock()).name),policyHold=agents=>{for(const agent of agents)if("profile"in agent){const verdict=store.runPolicy(agent.profile);if(!verdict.ok)return verdict.message}else{const refused=agent.session!==void 0?store.sessionPolicyRefusal(agent.provider,agent.model,agent.session):store.agentPolicyRefusal(agent.provider,agent.model);if(refused!==null)return refused}return null},ready=store.listReady(clock(),runner),considered=ready.length,dispatched=[];reconcileWalks(store,clock());const MIRROR_WORDS={"stale-mirror":"its tracker has not been synced recently — `toolroll sync` restores freshness","external-closed":"the tracker closed it — reopen it there, then `toolroll task reopen`","dispatch-revoked":"the tracker's building permission was revoked or narrowed","plane-blocked":"the tracker's plane marker could not be verified — building is paused"};for(const skippedMirror of store.ineligibleMirrors(repo,clock(),syncMaxAgeMs))dispatched.push({id:skippedMirror.taskId,outcome:"skipped",reason:skippedMirror.why}),store.enqueueNotification({source:{taskRef:store.lookupRef(skippedMirror.taskId)?.id??-1},dedupeKey:`mirror:${skippedMirror.taskId}:${skippedMirror.why}`,kind:"external-skipped",subject:`${skippedMirror.taskId} cannot dispatch`,body:MIRROR_WORDS[skippedMirror.why]??"the tracker item is not dispatchable right now"},clock());let built=0,parked=0,broke=0;const attestedThisPass=new Map;let untakenTrial=null;for(const ref of ready){if(settleFinished(),untakenTrial?.giveBack(),untakenTrial=null,built>=max)continue;if(context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0)break;const id=ref.externalId;if(ref.repo!==null&&ref.repo!==repo){dispatched.push({id,outcome:"skipped",reason:"other-repo"});continue}const scopeApproved=scopeApprovedForDispatch(store,ref.id,clock()),wantsPlan=ref.plan==="requested"&&!scopeApproved,wantsScout=ref.deliverable==="report"&&scopeApproved;if(!wantsPlan&&!scopeApproved){dispatched.push({id,outcome:"skipped",reason:"unapproved"});continue}const agentless=agentlessFirstRun(store,ref,wantsPlan,[runner]);if(agentless!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:agentless.words});continue}const taskRoute=routeOfTask(store,id,ref,clock());if(taskRoute!==null&&taskRoute.kind==="unreadable"){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:taskRoute.problem});continue}const route=taskRoute!==null&&taskRoute.kind==="route"?taskRoute:null;if(wantsPlan&&route!==null&&route.source==="proposed"){const working=store.workingPlanRouteOf(id);if(!working.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${working.problem}`});continue}}const planLeg=route===null?null:legOf(route.route,"plan"),fallback=route!==null&&route.source==="approved"&&!wantsPlan&&!wantsScout?dispatchEntryOf(store,ref.id,id,clock()):null;if(fallback!==null&&"problem"in fallback){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${fallback.problem}`});continue}const sealedBuildLeg=route!==null&&route.source==="approved"?fallback!==null?{provider:fallback.entry.profile.provider,model:fallback.entry.profile.model,chosen:"fallback"}:legOf(route.route,"build"):null;if(wantsPlan&&planLeg!==null&&(planProvider!==void 0||planModel!==void 0||providerFlag!==void 0||model!==void 0)){const flaggedProvider=planProvider??providerFlag,flaggedModel=planModel??model;if(flaggedProvider!==void 0&&flaggedProvider!==planLeg.provider||flaggedModel!==void 0&&flaggedModel!==planLeg.model){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`the pass flags name ${flaggedProvider??planLeg.provider}${flaggedModel===void 0?"":` · ${flaggedModel}`} but ${id}'s planner is ${planLeg.provider} · ${planLeg.model} — flags cannot reroute a task; override the plan phase with \`task route\``});continue}}const resolution=wantsPlan?planLeg!==null?resolvePhaseAgent(store,"plan",repo,{provider:planLeg.provider,model:planLeg.model}):resolvePhaseAgent(store,"plan",repo,{provider:ref.planProvider??planProvider??providerFlag,model:ref.planProvider!==null?ref.planModel??void 0:planModel??model}):sealedBuildLeg!==null?resolvePhaseAgent(store,"build",repo,{provider:sealedBuildLeg.provider,model:sealedBuildLeg.model},ref):resolvePhaseAgent(store,"build",repo,{provider:providerFlag,model},ref);if(!resolution.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:resolution.problem});continue}const routedDecision=wantsPlan&&(planLeg!==null?planLeg.chosen==="override"||planLeg.chosen==="pinned":ref.planProvider!==null||planProvider!==void 0||planModel!==void 0||providerFlag!==void 0||model!==void 0)||!wantsPlan&&(sealedBuildLeg!==null||resolution.source==="pinned"||resolution.source==="flag")?null:routeWorkerModel(store,{taskKind:ref.sizing?.size==="small"?wantsPlan?"single-file-edit":"simple-fix":"multi-file-build",provider:resolution.spec.provider,fallbackModel:resolution.spec.model,now:clock()}),spec=routedDecision!==null&&routedDecision.steppedDown?{provider:resolution.spec.provider,model:routedDecision.model}:resolution.spec,brokenMode=readAuthModeStrict(spec.provider);if(!brokenMode.ok){dispatched.push({id,outcome:"skipped",reason:"auth-mode",detail:brokenMode.problem});continue}const gate=signInGate(store,[spec.provider],clock(),ref.id);if(gate.waiting!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:signInWords(gate.waiting)});continue}untakenTrial=gate;const governingLeg=wantsPlan?planLeg:sealedBuildLeg;if(governingLeg!==null&&(spec.provider!==governingLeg.provider||spec.model!==governingLeg.model)){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: the ${wantsPlan?"plan":"build"} leg names ${governingLeg.provider} · ${governingLeg.model} but resolution produced ${spec.provider} · ${spec.model??"(no model)"} — nothing substitutes`});continue}const routeStamp=phase=>{if(governingLeg===null||route===null||phase==="plan"&&route.source==="live"){const legacy=store.routeAuthorityFor(ref.id,phase==="plan"?"planner":"builder",{provider:spec.provider,model:spec.model});return legacy!==null&&legacy.ok?legacy.stamp:null}return{routeDigest:routeDigestOf(route.route),phase,provider:spec.provider,model:spec.model,chosen:governingLeg.chosen}};if(!wantsPlan&&!wantsScout&&route===null){const legacyStamp=routeStamp("build");if(legacyStamp!==null&&(legacyStamp.provider!==spec.provider||legacyStamp.model!==spec.model)){const message=`${id}: the sealed profile builds on ${legacyStamp.provider} · ${legacyStamp.model??"(no model)"} but today's routing resolved ${spec.provider} · ${spec.model??"(no model)"} — nothing runs on it (stale-approval)`;holdStaleApproval(store,{taskRef:ref.id,taskId:id,message},clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:message});continue}}if(!wantsPlan&&!wantsScout){const ruleHeld=ruleHoldOf(store,id);if(ruleHeld!==null){holdRuleOff(store,ref.id,ruleHeld.model,clock()),dispatched.push({id,outcome:"skipped",reason:"rule-switched-off",detail:`${id}: results for ${ruleHeld.model} dropped after this was approved — approve it again or re-file it`});continue}}{const unavailable=store.runnerReadinessOf(runner,spec.provider);if(unavailable!==null&&readinessRefuses(unavailable,fallback?.entry.authMode??(brokenMode.ok?brokenMode.mode:"subscription"))){const observed=`${unavailable.provider} is reported unavailable on ${runner} (${unavailable.reason}; observed ${unavailable.observedAt})`;dispatched.push({id,outcome:"skipped",reason:"provider-unavailable",detail:`${observed} — nothing substitutes for a routed provider: override the phase with \`task route\` or restore the provider and report readiness again`});continue}}const skipProviders=wantsPlan||fallback!==null?[spec.provider]:[store.getScope(id)?.approvedProfile?.provider].filter(one=>one!=null);let unattestedLane=null;for(const candidate of new Set(skipProviders)){if(isAcpProvider(candidate)){const checked=store.acpAttestationFor(candidate,runner),verified=checked===null?null:verifyLaunch(checked.launch);if(checked===null){unattestedLane=`${ACP_AGENTS[candidate].name} isn't checked on ${runner} — run \`toolroll agents check ${candidate}\` there`;break}if(verified!==null&&!verified.ok){unattestedLane=verified.problem;break}continue}if(attestationOf(candidate)===null)continue;let verdict=attestedThisPass.get(candidate);if(verdict===void 0&&(verdict=await attestProvider(candidate,inspectionOf(candidate).binary),attestedThisPass.set(candidate,verdict)),verdict!==null&&!verdict.ok){unattestedLane=verdict.problem;break}}if(unattestedLane!==null){dispatched.push({id,outcome:"skipped",reason:"provider-unattested",detail:unattestedLane});continue}{const sealed=wantsPlan||wantsScout?null:fallback?.entry.profile??store.getScope(id)?.approvedProfile??null,refused=policyHold([sealed!==null?{profile:sealed}:{provider:spec.provider,model:spec.model,...wantsPlan?{session:"planning"}:wantsScout?{session:"scouting"}:{}}]);if(refused!==null){dispatched.push({id,outcome:"skipped",reason:"policy",detail:refused});continue}}const sealedModel=store.getScope(id)?.approvedProfile?.model??null,budgeted=budgetHold(ref.id,fallback?.paid===!0?[{provider:spec.provider,billing:"api-key"}]:[...new Set([spec.provider,...skipProviders])].map(provider=>isAcpProvider(provider)||provider==="pi"?store.agentFor(provider,provider===spec.provider?spec.model??sealedModel:sealedModel,runner):store.agentsFor([provider])[0]));if(budgeted.over!==null){dispatched.push({id,outcome:"skipped",reason:"budget",detail:budgetWords(budgeted)});continue}if(!wantsPlan&&runningReleaseCheck(store,clock(),ref.id)!==null){dispatched.push({id,outcome:"skipped",reason:"release-check",detail:RELEASE_CHECK_WAIT});continue}if(repo!==null){const railed=store.reserveModeRail(repo,1,clock());if(!railed.ok){dispatched.push({id,outcome:"skipped",reason:railed.rail,detail:railed.detail});continue}}const claimed=acquireIfReady(store,ref.id,runner,{...wantsPlan?{dispatchRole:"planner"}:wantsScout?{dispatchRole:"scout"}:{},now:clock(),token,ttlMs:leaseTtlMs,syncMaxAgeMs,repo,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...fallback!==null?{authMode:fallback.entry.authMode}:brokenMode.ok&&(brokenMode.mode==="api-key"||brokenMode.mode==="subscription")?{authMode:brokenMode.mode}:{},...text(flags,"incarnation")===void 0?{}:{incarnation:text(flags,"incarnation")}});if(claimed.ok&&(untakenTrial=null),!claimed.ok){if(claimed.reason==="capability"&&"message"in claimed){const key=/needs (\S+)/.exec(claimed.message)?.[1],parsed=key===void 0?null:parseCapabilityKey(key);if(parsed!==null){const home=ref.repo??repo;store.enqueueNotification({source:{taskRef:ref.id},dedupeKey:`gap:${home}:${parsed.kind}:${parsed.name}`,kind:"gap",pushClass:"attention",link:"/caps",subject:`${key} blocks work in ${home}`,body:`${id} (and possibly others) cannot dispatch: ${claimed.message}. \`toolroll gaps --repo ${home}\``},clock())}}dispatched.push({id,outcome:"skipped",reason:claimed.reason,..."message"in claimed&&claimed.reason==="capability"?{detail:claimed.message}:{}});continue}const lease=claimed.claim.leaseId;if(wantsPlan){const answers=store.answeredDecisionsFor(id).map(one=>({question:one.question,choice:one.choice??"",note:one.note})),sourced=plannerSourceOf(store,context.evidenceRoot,id,answers);if(!sourced.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:`planner-source-${sourced.reason}`,detail:sourced.message});continue}const planBranch=await existingOrFirst([`toolroll-plan/${id}`,`standing-orders-plan/${id}`],async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),revised=ref.revisionOf===null?null:revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);if(revised!==null&&!revised.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:revised.problem});continue}const planLeased=await worktrees.lease({repo,branch:planBranch,runner,taskRef:ref.id,now:clock(),base:revised?.head??base,reuseBranch:!0,reclaim:{evidenceRoot:context.evidenceRoot},...freshBaseFor(store,id,planBranch,base)});if(!planLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:planLeased.reason}),broke++;continue}const planStamp=routeStamp("plan"),planRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"planner",provider:spec.provider,branch:planBranch,worktree:planLeased.worktree.path,...spec.model===null?{}:{model:spec.model},now:clock(),...planStamp===null?{}:{route:planStamp}});noteBaseStanding(store,planRunId,planLeased.base,base,clock());let sourceArtifact;try{sourceArtifact=storeEvidence(store,context.evidenceRoot,planRunId,"plan-contract","planner-source.json",encodePlannerSource(sourced.source),`planner source ${sourced.source.sourceDigest.slice(0,12)} — the filed request quoted into the brief, recorded before spend (${sourced.bytes} bytes)`,clock(),{captureStatus:"ok"})}catch(error){await worktrees.release(planLeased.worktree.path,clock());const unrecorded=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:"failure",message:`the planner's source could not be recorded: ${error instanceof Error?error.message:String(error)}`,now:clock()});dispatched.push({id,outcome:"failed",reason:"evidence"}),unrecorded.ok||release(store,lease,clock()),broke++;continue}store.stampRun(planRunId,{scopeDigest:sourced.source.contract.scope?.digest??""}),budgetGate=null;const outcome=await planTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:planRunId,worktree:planLeased.worktree.path,branch:planBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(planLeased.worktree.path,runner,pid,planLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers,source:sourced.source,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});if(await worktrees.release(planLeased.worktree.path,clock()),outcome.ok&&"parked"in outcome){const sealed=finalize(store,lease,{kind:"park",runId:planRunId,taskId:id,decision:outcome.parked.decision,artifactIds:outcome.parked.artifactIds,repairRunId:outcome.parked.repairRunId,now:clock()});sealed.ok?(store.resetPlanStrikes(ref.id),dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`}),parked++):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}if(outcome.ok){const sealed=finalize(store,lease,{kind:"plan",runId:planRunId,taskId:id,plan:outcome.drafted.plan,artifact:outcome.drafted.artifact,repairRunId:outcome.drafted.repairRunId,source:sourced.source,sourceArtifact,evidenceRoot:context.evidenceRoot,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"planned",...sealed.changes===0?{}:{detail:`${sealed.changes} contract change${sealed.changes===1?"":"s"} proposed${sealed.amendment===null?"":" with an amendment"}`}})):sealed.reason==="stale-source"||sealed.reason==="source-invalid"?dispatched.push({id,outcome:"skipped",reason:sealed.reason,detail:sealed.detail}):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:outcome.kind,...outcome.kind==="malformed"?{malformed:outcome.reason==="malformed-decision"?"decision":"plan"}:{},message:outcome.message,code:outcome.reason,...outcome.kind==="malformed"&&outcome.problems!==void 0?{problems:outcome.problems.map(problem=>problem.message)}:{},...outcome.agentSaid===void 0?{}:{agentSaid:outcome.agentSaid},now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`});continue}dispatched.push({id,outcome:"failed",reason:outcome.reason}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}if(wantsScout){const scoutBranch=`toolroll-scout/${id}/${randomBytes(4).toString("hex")}`,scopeRow=store.getScope(id),proof=proveApprovedProfile(scopeRow,{provider:spec.provider,model:spec.model??void 0,maxTurns:void 0,timeoutMs:void 0,skipPermissions:!1});if(!proof.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:proof.message});continue}const scoutLeased=await worktrees.lease({repo,branch:scoutBranch,runner,taskRef:ref.id,now:clock(),base});if(!scoutLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:scoutLeased.reason}),broke++;continue}const scoutStamp=routeStamp("build")??{routeDigest:`profile:${profileDigestOf(proof.effective.profile)}`,phase:"build",provider:spec.provider,model:proof.effective.model,chosen:"legacy"},scoutRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"scout",provider:spec.provider,branch:scoutBranch,worktree:scoutLeased.worktree.path,model:proof.effective.model,now:clock(),route:scoutStamp});store.stampRun(scoutRunId,{scopeDigest:scopeRow?.approvedDigest??"",profileDigest:profileDigestOf(proof.effective.profile)});const scoutAnswers=store.answeredDecisionsFor(id,6).map(one=>({question:one.question,choice:one.choice??"",note:one.note}));budgetGate=null;const scouted=await scoutTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,goal:scopeRow?.goal??"",outOfScope:scopeRow?.outOfScope??null,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:scoutRunId,worktree:scoutLeased.worktree.path,branch:scoutBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(scoutLeased.worktree.path,runner,pid,scoutLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers:scoutAnswers,demoUrl:projectDemoUrl(context.databaseFile,repo),provider:spec.provider,model:proof.effective.model,...proof.effective.maxTurns===void 0?{}:{maxTurns:proof.effective.maxTurns},timeoutMs:proof.effective.timeoutMs,...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});await worktrees.release(scoutLeased.worktree.path,clock());const discarded=await worktrees.discard(scoutLeased.worktree.path,clock()),leftover=discarded.ok?{}:{detail:`checkout kept: ${discarded.message}`};if(scouted.ok&&"parked"in scouted){const sealed=finalize(store,lease,{kind:"park",runId:scoutRunId,taskId:id,decision:scouted.parked.decision,artifactIds:scouted.parked.artifactIds,now:clock()});sealed.ok?(dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`,...leftover}),parked++):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}if(scouted.ok){const sealed=finalize(store,lease,{kind:"scout",runId:scoutRunId,taskId:id,report:scouted.reported.report,artifact:scouted.reported.artifact,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"reported",...leftover})):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover}):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"scout-failure",runId:scoutRunId,taskId:id,failure:scouted.kind,...scouted.kind==="malformed"?{malformed:scouted.reason==="malformed-decision"?"decision":"report"}:{},message:scouted.message,now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover});continue}dispatched.push({id,outcome:"failed",reason:scouted.reason,...leftover}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}const branch=await existingOrFirst(taskBranches(id),async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),exists=await git("git",["rev-parse","--verify","--quiet",`refs/heads/${branch}`],{cwd:repo});let buildBase=base,caughtUp=null;if(ref.revisionOf!==null){const source=revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);let problem=source.ok?null:source.problem;if(source.ok)if(exists.code!==0&&text(flags,"base")===void 0){if(buildBase=source.head,!publishesThroughPullRequests(store,repo)){const onto=landingBranchOf(store,repo,base),result2=await catchUpRevision(hardenedGit(git,"build",{repo}),repo,source.head,onto,id,clock());caughtUp={head:source.head,onto,result:result2},result2.kind==="merged"&&(buildBase=result2.commit)}}else{const descendant=exists.code===0?branch:base,ancestry=await lazyFetchSafeGit(git)("git",[...noLazyFetch(),"-c","protocol.allow=never","--no-replace-objects","merge-base","--is-ancestor",source.head,descendant],{cwd:repo});if(ancestry.code!==0)problem=ancestry.stderr.includes(PARTIAL_CLONE_REFUSAL)?PARTIAL_CLONE_REFUSAL:"the requested revision base does not contain its source head";else if(exists.code===0&&store.latestBranchBaseMove(ref.id,branch)===null&&store.firstBuilderBase(ref.id,branch)===null&&!publishesThroughPullRequests(store,repo)){const tip=exists.stdout.trim(),main=await catchUpMergeOf(hardenedGit(git,"build",{repo}),repo,tip,source.head,landingBranchOf(store,repo,base));main!==null&&store.recordBranchBaseMove(ref.id,branch,tip,main,clock())}}if(problem!==null){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:problem});continue}}const leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now:clock(),...exists.code===0?{}:{base:buildBase},reclaim:{evidenceRoot:context.evidenceRoot},...exists.code===0?freshBaseFor(store,id,branch,base):{}});if(caughtUp!==null&&caughtUp.result.kind==="merged"){const merged=caughtUp.result,at=leased.ok&&leased.created?await hardenedGit(git,"build",{repo})("git",["rev-parse","--verify","-q",`refs/heads/${branch}^{commit}`],{cwd:repo}):null;if(at!==null&&at.code===0&&at.stdout.trim()===merged.commit)store.recordBranchBaseMove(ref.id,branch,merged.commit,merged.main,clock());else if(leased.ok&&leased.created){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:"git",detail:"Toolroll couldn't confirm the new branch stands at its merge of main; it tries again."}),broke++;continue}else caughtUp={...caughtUp,result:{kind:"unavailable"}}}if(!leased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:leased.reason}),broke++;continue}const buildStamp=routeStamp("build");let runId;try{if(leased.resumedFromRun!==void 0){if(buildStamp===null)throw new Error(`${id}: the recovered attempt presents no build authority`);const admittedRecovered=store.admitRecoveredBuilder({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},recoveredFrom:leased.resumedFromRun,now:clock(),route:buildStamp});if(!admittedRecovered.ok)throw new Error(admittedRecovered.problem);runId=admittedRecovered.runId}else runId=store.startRun({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},now:clock(),...buildStamp===null?{}:{route:buildStamp}})}catch(error){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"admission-refused",detail:error instanceof Error?error.message:String(error)});continue}noteBaseStanding(store,runId,leased.base,base,clock()),caughtUp!==null&&leased.created&&recordCatchUp(store,{repo,taskId:id,runId,branch,head:caughtUp.head,onto:caughtUp.onto},caughtUp.result,clock()),leased.resumedFromRun!==void 0&&store.addRunNote(runId,"Toolroll",`Recovered the ${leased.recoveryKind==="completed"?"completed source draft":"work-in-progress draft"} from interrupted attempt #${leased.resumedFromRun}. This fresh attempt is reviewing and verifying it; the safety patch is retained.`,clock());const scopeBudget=store.getScope(id)?.budgetMicrousd??null,backstop=store.getSpendDefaults()?.buildPerRunMicrousd??null,budgetLeft=budgeted.remainingMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag!==null?Math.max(1,budgeted.remainingMicrousd):null,capMicrousd=[scopeBudget,backstop,budgetLeft].reduce((least,one)=>one===null?least:least===null?one:Math.min(least,one),null);if(capMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag===null){store.finishRun(runId,{outcome:"refused",reason:"budget-unenforceable",now:clock()}),release(store,lease,clock()),await worktrees.release(leased.worktree.path,clock()),dispatched.push({id,outcome:"skipped",reason:"budget-unenforceable"});continue}budgetGate=null;const result=await build(store,{taskId:id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now:clock(),clock,...capMicrousd===null?{}:{maxBudgetUsd:capMicrousd/1e6},onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(leased.worktree.path,runner,pid,leased.worktree.leaseEpoch)},provider:spec.provider,...spec.model===null?{}:{model:spec.model},...repairModel===void 0?{}:{repairModel},...turns===void 0?{}:{maxTurns:Number(turns)},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner},...context.shouldStop===void 0?{}:{shouldStop:context.shouldStop},...leased.resumedFromRun===void 0?{}:{recoveredDraftRun:leased.resumedFromRun},...leased.recoveryKind===void 0?{}:{recoveredDraftKind:leased.recoveryKind}});await worktrees.release(leased.worktree.path,clock());const disposition=disposeBuildOutcome({store,policy:"tick",leaseId:lease,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:spec.provider,model:spec.model,worktreePath:leased.worktree.path,evidenceRoot:context.evidenceRoot,clock},result);switch(disposition.kind){case"parked":dispatched.push({id,outcome:"parked",reason:`decision:${disposition.decisionId}`,worktree:leased.worktree.path}),parked++;break;case"park-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"disowned":dispatched.push({id,outcome:"failed",reason:"external-closed",branch,worktree:leased.worktree.path}),broke++;break;case"built":dispatched.push({id,outcome:"built",committed:disposition.committed,branch,worktree:leased.worktree.path}),built++;break;case"built-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",branch,worktree:leased.worktree.path}),broke++;break;case"skipped":dispatched.push({id,outcome:"skipped",reason:disposition.reason});break;case"fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"malformed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?"malformed-decision":"fenced",worktree:leased.worktree.path}),broke++;break;case"failed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?disposition.disposition==="auth-expired"?"auth-expired — requeued, sign-in needed":disposition.disposition==="fallback"?"out of plan — moved to the next approved agent":`${disposition.failureClass}${disposition.disposition==="backoff"?` — retry ${disposition.strikes}/3`:disposition.disposition==="stalled"?" — stalled":disposition.closedState!==null?` — the task was already ${disposition.closedState}, so it stays ${disposition.closedState}`:""}`:"fenced",...result.ok?{}:{detail:result.message.slice(0,200)},worktree:leased.worktree.path}),disposition.sealed&&disposition.disposition==="fallback"||broke++;break;case"recorded":break;case"stopped":dispatched.push({id,outcome:"stopped",reason:`stop:${disposition.stopRun}`,branch,worktree:leased.worktree.path});break;case"handed-back":dispatched.push({id,outcome:"stopped",reason:"service-stop",detail:result.ok?"":result.message.slice(0,200),branch,worktree:leased.worktree.path});break;case"invariant":dispatched.push({id,outcome:"failed",reason:disposition.reason}),broke++;break}}if(untakenTrial?.giveBack(),!buildsOnly&&authenticate(store,runner,token).ok){const reviewed=await buildReviewPass(store,{runner,token,repos:auth.runner.repos,clock,root:context.evidenceRoot,...text(flags,"incarnation")===void 0?{}:{watchIncarnation:text(flags,"incarnation")},...context.agentRunner===void 0?{}:{agent:context.agentRunner},shouldStop:()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0});for(const one of reviewed)dispatched.push({id:`review of run ${one.run}`,outcome:one.outcome==="not-reviewed"?"not-reviewed":"reviewed",reason:one.detail})}buildsOnly||syncAssignmentHandoffs(store,clock(),auth.runner.repos,context.evidenceRoot),settleFinished();const replied=replyPass.taken>0||replyPass.problem!==null,requestPass=housekeeping?.youiyoux??NO_YOUIYOUX_PASS,requested=requestPass.filed+requestPass.copied+requestPass.decided+requestPass.problems.length>0,flows=flowPass.moved+flowPass.filed.length+flowPass.problems.length+triggerPass.added+triggerPass.problems.length+stepPass.ran+stepPass.problems.length===0&&!replied&&!requested?{}:{flows:{...flowPass,...triggerPass.added+triggerPass.problems.length===0?{}:{triggers:triggerPass},...requested?{youiyoux:requestPass}:{},...stepPass.ran+stepPass.problems.length===0?{}:{steps:stepPass},...replied?{replies:replyPass}:{}}},summary=()=>{const lines=[`Considered ${considered}, built ${built}, parked ${parked}, broke ${broke}.`];for(const entry of dispatched){const detail=entry.outcome==="built"?entry.committed===!0?`committed to ${entry.branch}`:"no changes reported; see the result's proof status":entry.outcome==="parked"?`${entry.reason} — \`toolroll decide\``:entry.reason??"";lines.push(` ${entry.id.padEnd(24)} ${entry.outcome} ${detail}`.trimEnd())}return built>0&&lines.push("","Nothing has been pushed. Look at the branches before they go anywhere."),parked>0&&lines.push("",`${parked} decision${parked===1?"":"s"} waiting — \`toolroll decide\`, or \`toolroll brief\`.`),lines};return broke>0?fail(write,json,"tick","build-failed",`${broke} of ${dispatched.length} dispatched tasks broke`,EXIT.failed,{considered,dispatched}):built>0||parked>0||dispatched.some(one=>one.outcome==="planned"||one.outcome==="reported"||one.outcome==="reviewed"||one.outcome==="not-reviewed")?succeed(write,json,"tick",{considered,dispatched,...flows},summary):considered===0?fail(write,json,"tick","empty","nothing is ready",EXIT.refused,{considered,dispatched,...flows}):fail(write,json,"tick","nothing-dispatched","everything ready is waiting on a person or held by somebody else",EXIT.refused,{considered,dispatched,...flows})}async function reconcileCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"reconcile");if(demoFence!==null)return demoFence;const repo=repoFrom(flags),pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),syncReports=[];for(const dispatchGrant of store.listGrants().filter(one=>one.dispatch===!0&&one.remoteRepo!=null&&one.repo===repo))syncReports.push(await syncPass(store,dispatchGrant,context.dispatchAdapter??ghDispatchAdapter(),clock));for(const report of syncReports)report.outcome==="failed"||report.outcome==="blocked"?store.enqueueEpisode(`sync:${report.remoteRepo}`,{source:{project:repo},kind:"sync-failed",pushClass:"attention",link:"/system",subject:`syncing ${report.remoteRepo} ${report.outcome==="blocked"?"is blocked":"failed"}`,body:`${report.detail??"the pass did not finish"} — external work keeps its last verified state and stops dispatching past its freshness window.`},clock().toISOString(),clock()):store.resolveEpisodes(`sync:${report.remoteRepo}`,clock());const recovered=recoverDead(store,clock()),closedRuns=await closeOutRuns(store,clock,{repo});store.recordFinishedRunExits(clock()),store.settleUnspawnedWitnesses(clock()),await proveFinishedRunsStopped(store,clock),store.settleQuiescentStops(clock()),applyPendingAgentChanges(store,clock()),retryVanishedWhenStopped(store,clock()),expireFastStarts(store,clock()),routeLegacyPlans(store,clock());try{releaseStalledUpdate(dirname(context.databaseFile),clock())}catch{}for(const one of recovered){for(const leaseId of one.claims)store.enqueueNotification({source:{taskRef:Number(store.handle.prepare("SELECT task_ref FROM claim WHERE lease_id = ?").get(leaseId)?.task_ref??-1)},dedupeKey:`recover:${leaseId}`,kind:"runner-recovered",subject:`${one.runner} went dead holding work`,body:`Its claims were requeued and its worktrees handed back unverified. Lease ${leaseId}.`},clock());for(const runId of one.runs)store.enqueueNotification({source:{run:runId},dedupeKey:`recover-run:${runId}`,kind:"runner-recovered",subject:`${one.runner} went dead mid-attempt`,body:`Run #${runId} was still open with no live lease; it is now finished as interrupted. Check this task's current state in the console.`,link:`/r/${runId}`},clock())}const reaped=reap(store,clock()),liveSwept=sweepLiveLogs(store,context.evidenceRoot,clock());try{store.sweepRunActivity(clock(),LIVE_RETAIN_MS,LIVE_FILE_BOUND)}catch{}const worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),adoption=await worktrees.adopt(repo,clock());if(adoption.ok){const now=clock(),notice=worktreeAdoptionNotice(repo,adoption.adopted,now);notice!==null&&store.enqueueNotification(notice,now)}if(!adoption.ok)return fail(write,json,"reconcile","git",adoption.message,EXIT.failed,{recovered,reaped:reaped.map(claim=>claim.leaseId)});let landed={completed:[],steps:[]};const remotes=new RemoteMains(store,context.gitRunner,context.evidenceRoot);try{landed=await reconcileLanded(store,worktrees,gitOf(context.gitRunner),remotes,repo,context.evidenceRoot,clock)}catch{}finally{remotes.close()}const landedGone=landed.steps.filter(one=>one.outcome==="removed");let tidied=[];try{tidied=runTidy(store,clock(),releaseFactsFor(context.databaseFile),TIDY_PASS_LIMIT,{principal:"operator",repos:[repo],includeUnplaced:!1})}catch{}try{reevaluateResultRecords(store,canonicalProject(repo)??resolve(repo),context.evidenceRoot,clock())}catch{}try{routeRulesPass(store,canonicalProject(repo)??resolve(repo),clock())}catch{}const closedCheckouts=await closeOutCheckouts(store,clock,finishedCheckouts(store,clock(),repo)),pruned=await cleanCheckouts(store,worktrees,clock,{manual:!1,actor:"worker",repo}),slimmed=await slimKeptCheckouts(store,worktrees,clock,{actor:"worker",repo});let retention=null;try{retention=dailyRetention(store,context.evidenceRoot,clock())}catch{retention=null}const retained=retention===null?[]:retention.counts.filter(one=>one.count>0);let storageSwept=null;if(context.sweepOwner!==void 0)try{storageSwept=idleStorageSweep(store,{databaseFile:context.databaseFile,pool:worktrees,tempRoots:context.tempRoots??tempRoots(),owner:context.sweepOwner},clock)}catch{storageSwept=null}const swept=storageSwept===null?[]:storageSwept.parts.filter(one=>one.count>0),nothing=retained.length===0&&swept.length===0&&recovered.length===0&&reaped.length===0&&adoption.adopted.length===0&&adoption.forgotten.length===0&&pruned.removed.length===0&&closedRuns.length===0&&closedCheckouts.length===0&&slimmed.slimmed.length===0&&landed.completed.length===0&&landedGone.length===0&&tidied.length===0&&liveSwept.removed.length===0;return succeed(write,json,"reconcile",{recovered,reaped:reaped.map(claim=>claim.leaseId),adopted:adoption.adopted,forgotten:adoption.forgotten,checkoutsRemoved:pruned.removed.map(one=>one.path),checkoutsKept:pruned.kept,processesStopped:[...closedRuns.map(one=>({run:one.runId,pids:one.done.stopped.map(row=>row.pid)})),...closedCheckouts.map(one=>({checkout:one.path,pids:one.done.stopped.map(row=>row.pid)}))],checkoutsSlimmed:slimmed.slimmed.map(one=>one.path),landed:{completed:landed.completed,steps:landed.steps},tidied:tidied.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),liveViewsSwept:liveSwept.removed.length,retention:retention===null?null:{counts:retention.counts,freedBytes:retention.freed},storageSweep:storageSwept},()=>nothing?["Nothing to reconcile. Everything is where it should be."]:[...recovered.map(one=>`Recovered ${one.runner}: ${one.claims.length} claim(s) requeued, ${one.worktrees.length} worktree(s) handed back unverified.`),...reaped.length===0?[]:[`Reaped ${reaped.length} expired lease(s).`],...adoption.adopted.map(path=>`Adopted ${path} — released, unverified, somebody should look.`),...adoption.forgotten.map(path=>`Forgot ${path} — its directory is gone.`),...pruned.removed.length===0?[]:[`Removed ${pruned.removed.length} finished task checkout(s), about ${bytesWords(pruned.freed)}; their branches stay.`],...closedRuns.map(one=>`Run #${one.runId} ended; stopped ${stoppedWords(one.done)}.`),...closedCheckouts.map(one=>`${one.path}: its task finished; stopped ${stoppedWords(one.done)}.`),...landed.completed.length===0?[]:[`Marked ${landed.completed.length} landed result(s) complete: ${landed.completed.join(", ")}.`],...tidied.length===0?[]:[`Put away ${tidied.length} old task(s): ${tidied.map(one=>one.taskId).join(", ")}.`],...landedGone.length===0?[]:[`Removed landed work: ${landedGone.filter(one=>one.kind==="checkout").length} checkout(s), ${landedGone.filter(one=>one.kind==="branch").length} local branch(es).`],...slimmed.slimmed.length===0?[]:[`Dropped dependencies and build output from ${slimmed.slimmed.length} kept checkout(s), about ${bytesWords(slimmed.slimmed.reduce((sum,one)=>sum+one.bytes,0))}.`],...liveSwept.removed.length===0?[]:[`Cleared ${liveSwept.removed.length} finished live view(s).`],...retention===null||retained.length===0?[]:[`Retention removed ${sweepWords(retention.counts,retention.freed)}.`],...storageSwept===null||swept.length===0?[]:[`Storage sweep: ${storageSweepWords(storageSwept.parts)}`]])}function gapsCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),gaps=computeGaps(store,repo,clock());if(json)return write(envelopeJson({ok:!0,command:"gaps",repo,gaps})),gaps.length===0?EXIT.ok:EXIT.refused;if(gaps.length===0)return write(`No gaps for ${repo}. Everything recorded is verified.`),EXIT.ok;for(const gap of gaps){const freed=gap.unblocks.length>0?`fills → ${gap.unblocks.length} task(s) start: ${gap.unblocks.join(", ")}`:gap.alsoBlocks.length>0?`part of what holds: ${gap.alsoBlocks.join(", ")}`:"nothing queued needs it yet";write(` ${gap.key.padEnd(28)} ${gap.state}`),write(` ${freed}`),write(` verify: ${gap.verify}`),write(` ${gap.instructions}`)}return EXIT.refused}async function briefCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),episode=flags.has("latest-watch")?store.latestWatchEpisode(repo):null;if(flags.has("latest-watch")&&episode===null)return fail(write,json,"brief","no-watch","no watch episode recorded for this repo yet — run `toolroll watch` first",EXIT.refused);const since=episode?.startedAt??text(flags,"since")??new Date(clock().getTime()-1440*6e4).toISOString();let runs=store.runsSince(since);episode!==null&&(runs=runs.filter(one=>one.runner===episode.runner&&(episode.endedAt===null||one.startedAt<=episode.endedAt)));const{built,failed,refused,cutDown,invoked,measured,spend,tokens}=tally(runs),gaps=computeGaps(store,repo,clock()),pending=store.pendingForAttention(),decisions=store.listDecisions("unanswered"),incidents=store.openIncidents(),stranded=store.strandedTasks();let review;if(flags.has("local"))review={state:"not-read",why:"--local, the network was not asked"};else{const read=await readPulls(repo);review=read.problems.length>0&&read.pulls.length===0?{state:"not-read",why:read.problems[0]??"unreadable"}:{state:"read",pulls:read.pulls.map(one=>({number:one.number,title:one.title}))}}if(json)return write(envelopeJson({ok:!0,command:"brief",repo,since,episode,tally:{built,failed,refused,cutDown},economics:{invocations:invoked.length,measured:measured.length,costUsd:spend,tokens},gaps,review,outboxPending:pending.length,decide:decisions,incidents,stranded})),EXIT.ok;const lines=[`toolroll — the report ─ ${repo}`];episode!==null&&lines.push(` episode watch #${episode.id} on ${episode.runner} · ${episode.startedAt} → ${episode.endedAt??"never ended — it is running, or it died without saying"}`),lines.push(` runs ${built.length} built · ${failed.length} failed · ${refused.length} refused${cutDown.length>0?` · ${cutDown.length} cut down mid-flight`:""}`);const proofVerdicts=store.proofVerdictsFor(built.map(one=>one.id));for(const one of built){const verdict=proofVerdicts.get(one.id),accepted=verdict!==void 0&&store.proofAcceptance(one.id)!==null,proofNote=verdict===void 0||accepted||verdict.verdict!=="short"&&verdict.verdict!=="refuted"?"":` — ${proofVerdictWords(verdict.verdict,verdict.reasons).word}`;lines.push(` ${one.taskId.padEnd(20)} ${one.committed===!0?`committed to ${one.branch}`:"changed nothing, which is a real answer"}${proofNote}`)}for(const one of failed)lines.push(` ${one.taskId.padEnd(20)} failed: ${one.reason??"?"}${one.worktree===null?"":` — work kept in ${one.worktree}`}`);for(const one of cutDown)lines.push(` ${one.taskId.padEnd(20)} never finished — the process died with it; \`task show ${one.taskId}\``);if(lines.push(` spend ${spendLine({built,failed,refused,cutDown,invoked,measured,spend,tokens})}`),gaps.length>0){const best=gaps[0];lines.push(` ▸ BLOCKED ${gaps.length} gap(s)${best.unblocks.length>0?` — filling ${best.key} starts ${best.unblocks.length} task(s)`:""}`);for(const gap of gaps)lines.push(` ${gap.key.padEnd(28)} ${gap.state}`);lines.push(` → toolroll gaps --repo ${repo}`)}if(lines.push(review.state==="read"?` ▸ REVIEW ${review.pulls.length} PR(s)${review.pulls.length>0?"":" — nothing waits"}`:` ▸ REVIEW not read — ${review.why}`),review.state==="read")for(const pull of review.pulls)lines.push(` #${pull.number} ${pull.title}`);if(pending.length>0&&lines.push(` ▸ OUTBOX ${pending.length} undelivered — toolroll outbox list`),decisions.length>0){const overdue=decisions.filter(one=>one.state==="expired").length;lines.push(` ▸ DECIDE ${decisions.length} waiting${overdue>0?` (${overdue} overdue)`:""} — toolroll decide`);for(const one of decisions)lines.push(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}`)}else lines.push(" ▸ DECIDE nothing waits on you");if(stranded.length>0){lines.push(` ▸ STRANDED ${stranded.length} task(s) behind failed blockers — they will never become ready on their own`);for(const one of stranded)lines.push(` ${one.id.padEnd(20)} waits on ${one.blockedBy.join(", ")} — \`toolroll task requeue ${one.blockedBy[0]}\``)}if(incidents.length>0){lines.push(` ▸ INCIDENTS ${incidents.length} unresolved — these do not age out`);for(const incident of incidents)lines.push(` ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} — read run ${incident.run}'s evidence, then \`toolroll incident resolve ${incident.id}\``)}return write(lines.join(`
462
- `)),EXIT.ok}async function decideCommand(positional,flags,context){const{store,write,json,clock}=context;store.expireOverdueDecisions(clock());const[idText]=positional;if(idText===void 0){const waiting=store.listDecisions("unanswered");if(json)return write(envelopeJson({ok:!0,command:"decide",waiting})),waiting.length===0?EXIT.ok:EXIT.refused;if(waiting.length===0)return write("Nothing waits on you. No decisions were parked."),EXIT.ok;for(const one of waiting){const overdue=one.state==="expired"?" OVERDUE":"";write(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}${overdue}`),write(` options: ${one.options.map(option=>option.id).join(" · ")} recommended: ${one.recommendation}`)}return write(""),write(" → toolroll decide <id> the whole screen"),write(" → toolroll decide <id> --choose <option> --as <you> --token <t>"),EXIT.refused}const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"decide","usage","`toolroll decide [<id>] [--choose <option>]`",EXIT.usage);const decision=store.getDecision(id);if(decision===null)return fail(write,json,"decide","unknown-decision",`no decision ${id}`,EXIT.refused);const choice=text(flags,"choose");if(choice===void 0){const evidence=store.evidenceFor(id),run2=store.getRun(decision.run),taskId=run2===null?"?":store.externalIdFor(run2.taskRef)??"?";if(json)return write(envelopeJson({ok:!0,command:"decide",decision,taskId,evidence})),EXIT.ok;write(`${taskId} — ${decision.supersededReason!==null?"CLOSED":decision.state.toUpperCase()}${decision.deadline===null?"":` · deadline ${decision.deadline}`}`),write(""),write(` ${decision.recap}`),write(""),write(` ${decision.question}`),write("");for(const option of decision.options){const marks=[option.id===decision.recommendation?"recommended":"",option.reversible?"reversible":"IRREVERSIBLE"].filter(mark=>mark!=="").join(" · ");write(` [${option.id}] ${option.label} (${marks})`),write(` ${option.consequence}`)}if(decision.state==="answered"&&(write(""),write(decision.supersededReason!==null?` ${closedQuestionWords(decision.supersededReason)} (${decision.answeredAt})`:` answered: ${decision.choice} by ${decision.answeredBy} at ${decision.answeredAt}${decision.note===null?"":` — ${decision.note}`}`)),evidence.length>0){write("");for(const artifact of evidence)write(` evidence ${artifact.kind.padEnd(14)} ${artifact.key}${artifact.truncated?" (truncated)":""}`)}return decision.state!=="answered"&&(write(""),write(` → toolroll decide ${id} --choose <option> --as <you> --token <t>`)),EXIT.ok}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"decide",verified,"answering takes `--as <you> --token <t>` — who decided is recorded, not asserted",String(id));const{name:asWho}=acting,note=text(flags,"note"),answered=store.answerDecision({id,choice,by:asWho,via:"cli",...note===void 0?{}:{note}},clock(),mutationFrom(flags,clock()));if(!answered.ok){const why=answered.reason==="bad-option"?`"${choice}" is not one of this decision's options — \`toolroll decide ${id}\` shows them`:answered.reason==="already-answered"?`decision ${id} was already answered differently — "decided" is not negotiable; park a new task if the answer must change`:answered.reason==="closed"?`decision ${id}: ${closedQuestionWords(store.getDecision(id)?.supersededReason??"cancelled")} Nothing to answer.`:answered.reason==="bad-note"?"the note is too long or carries control characters":`no decision ${id}`;return fail(write,json,"decide",answered.reason,why,EXIT.refused)}return succeed(write,json,"decide",{decision:answered.decision,duplicate:answered.duplicate===!0},()=>answered.duplicate===!0?[`Decision ${id} was already answered with ${choice} — nothing changed.`]:[`Decided: ${choice} for decision ${id}, as ${asWho}.`,"The task returns to the ready set; the next tick resumes it with your answer in hand."])}export async function startConsole(options){const{context}=options,rehearsal=options.rehearsal===!0;rehearsal||noticeGitIncidents(context.store,context.clock);const identities=projectIdentities(context.folderLook),server=createDecisionServer({identities,store:context.store,backgroundChecks:!rehearsal,...rehearsal?{rehearsal:!0}:{},...context.desktopIdentity===void 0?{}:{desktopIdentity:context.desktopIdentity},...context.additionalProjectRepos===void 0||options.currentRepos===void 0?{}:{additionalProjectRepos:options.currentRepos},evidenceRoot:context.evidenceRoot,clock:context.clock,telegramTokenFile:context.telegramTokenFile,configDir:dirname(context.databaseFile),browserAssetCache:join(dirname(context.databaseFile),"browser-assets"),...options.localRunner===void 0?{}:{localRunner:options.localRunner},poolRoot:options.poolRoot,...options.allowedHosts===void 0?{}:{allowedHosts:options.allowedHosts},tailnetNames:rehearsal?(async()=>[]):context.tailnetNames??(()=>readTailnetNames()),leadByDefault:!0,...options.setupCode===void 0?{}:{setupCode:options.setupCode},...options.repos===void 0?{}:{repos:options.repos},...options.projectRoots===void 0?{}:{projectRoots:options.projectRoots},...options.currentRepos===void 0?{}:{currentRepos:options.currentRepos},...options.admittedRepos===void 0?{}:{admittedRepos:options.admittedRepos},...options.publicUrl===void 0?{}:{publicUrl:options.publicUrl},...options.registryPath===void 0?{}:{registryPath:options.registryPath},...options.upConsole===void 0?{}:{upConsole:options.upConsole},...options.editorLinks===void 0?{}:{editorLinks:options.editorLinks},...options.instanceSecret===void 0?{}:{instanceSecret:options.instanceSecret},...options.draining===void 0?{}:{draining:options.draining},...options.keyEpoch===void 0?{}:{keyEpoch:options.keyEpoch},browserKey:!0});await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>resolve2())}).catch(error=>{throw new Error(`could not listen on ${options.host}:${options.port} — ${describe(error)}`)});const bound=server.address(),port=typeof bound=="object"&&bound!==null?bound.port:options.port,shown=options.host==="0.0.0.0"||options.host==="::"?"localhost":options.host;if(setImmediate(warmWorkspaceRenderer),rehearsal)return{server,port,url:`http://${shown}:${port}/`};consoleIdentitiesInBackground(identities,[...options.repos??[],...options.projectRoots??[],...context.store.listProjects().map(one=>one.path),...context.store.knownRepos()]);const stopMonitoring=startMonitoring({store:context.store,settings:()=>readMonitoring(dirname(context.databaseFile)),instance:options.publicUrl??hostname(),version:packageVersion()}),signIns=createConnectionChecker({store:context.store}),besideConsole=[stopMonitoring,startBudgetAlerts(context.store),startTokenNotices(context.store),startSignInProbes(context.store,signIns),startBackups(context.store,context.databaseFile),startCodexLimits(context.store,()=>codexSignedInNow(signIns)),startUpdateChecks(context.store,dirname(context.databaseFile),PACKAGE_VERSION,installMethod(context.installBin).updateCommand,context.releaseIo??{})];return server.on("close",()=>{for(const stop of besideConsole)stop()}),{server,port,url:`http://${shown}:${port}/`}}async function serveCommand(flags,context){const{store,write,json}=context,portGiven=text(flags,"port"),port=Number(portGiven??4180),rehearsal=flags.get("rehearsal")===!0;if(portGiven!==void 0&&(!Number.isInteger(port)||port<(rehearsal?0:1)||port>=65536))return fail(write,json,"serve","usage","--port is a whole number under 65536",EXIT.usage);const host=text(flags,"host")??"127.0.0.1";if(rehearsal&&(host!=="127.0.0.1"||["allow-host","public-url","runner","editor","repo","project-root"].some(one=>flags.has(one))))return fail(write,json,"serve","usage","--rehearsal serves 127.0.0.1 only, with no --allow-host, --public-url, --runner, --editor, --repo or --project-root",EXIT.usage);const allow=text(flags,"allow-host"),repoFlag=text(flags,"repo"),rootFlag=text(flags,"project-root"),localRunner=text(flags,"runner"),poolRoot=text(flags,"pool")??join(dirname(context.databaseFile),"worktrees"),publicUrl=text(flags,"public-url"),editor=text(flags,"editor");if(editor!==void 0&&editor!=="vscode")return fail(write,json,"serve","usage","--editor supports: vscode",EXIT.usage);if(editor!==void 0&&localRunner===void 0)return fail(write,json,"serve","usage","--editor needs --runner <name> — links bind to the worktrees this machine's runner owns",EXIT.usage);const setupCode=store.listApprovers().length===0?String(randomInt(1e5,1e6)):void 0,console_=await startConsole({context,host,port,...rehearsal?{rehearsal:!0}:{},...setupCode===void 0?{}:{setupCode},...localRunner===void 0?{}:{localRunner},...publicUrl===void 0?{}:{publicUrl},...editor===void 0?{}:{editorLinks:"vscode"},registryPath:registryPathOf(context),poolRoot,...allow===void 0?{}:{allowedHosts:allow.split(",")},...repoFlag===void 0?{}:{repos:repoFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")},...rootFlag===void 0?{}:{projectRoots:rootFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")}}),server=console_.server,actual=console_.port,serveLifecycle=serveConsoleLifecycle(store,host,actual,context.clock);return serveLifecycle===null?(await closeServedConsole(server),fail(write,json,"serve","lifecycle","Toolroll couldn't record that this console is running, so it didn't start. Check the database, then run it again.",EXIT.refused)):(json?write(envelopeJson({ok:!0,command:"serve",host,port:actual,...setupCode===void 0?{}:{setupCode}})):setupCode!==void 0?(write(`The console is on http://${host}:${actual}/`),write(`No account yet. Open http://${host==="0.0.0.0"?"localhost":host}:${actual}/login and enter setup code ${setupCode} to create the first one.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")):(write(`The console is on http://${host}:${actual}/ — sign in with your username and password.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")),await new Promise(resolve2=>{const stop=()=>server.close(()=>resolve2());process.once("SIGINT",stop),process.once("SIGTERM",stop)}),serveLifecycle(),EXIT.ok)}async function requeueTask(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task requeue","usage","`toolroll task requeue <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"task requeue","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task requeue",verified,"requeueing takes `--as <you> --token <t>` — who overrode the stall is recorded, not asserted",id);const{name:asWho}=acting,result=store.requeueTask(id,asWho,clock());if(!result.ok){const why={"unknown-task":`no task ${id}`,"not-stalled":`${id} has nothing to rerun: it is queued or running, or it finished without a rejected result`,claimed:`a runner holds ${id} right now — wait for the attempt to end, or stop it`,"accepted-result":`${id}'s last result was accepted; change it through a revision, not a rerun`,published:`${id}'s last result is published; revise it through its pull request`,moved:`${id} changed since its page was read; read it again`,stale:`${id} changed since its page was read; read it again`,archived:`${id} is put away — restore it with \`toolroll task restore ${id}\` first`};return fail(write,json,"task requeue",result.reason,why[result.reason],EXIT.refused)}return succeed(write,json,"task requeue",{id,resolvedIncidents:result.resolvedIncidents,rejectedRun:result.rejectedRun},()=>[result.rejectedRun!==null?`${id} is queued again: attempt #${result.rejectedRun} was not accepted, so the next attempt continues on the same branch under the current scope. Re-scope first if the candidate changed.`:`${id} is queued again${result.resolvedIncidents>0?`, ${result.resolvedIncidents} incident(s) resolved`:""}. Strikes cleared; the next pass may take it.`])}async function regateTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task regate","usage","`toolroll task regate <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task regate",verified,"rerunning the check takes `--as <you> --token <t>` — the rerun scope is approved in your name",id);const result=regateTask(store,id,clock(),{kind:"operator",name:acting.name,token:acting.token});return result.ok?succeed(write,json,"task regate",{id,run:result.run,head:result.head},()=>[`${id} is queued again: the approved check runs on commit ${result.head.slice(0,7)}, the same files attempt #${result.run} checked, with no agent. A fresh review follows.`]):fail(write,json,"task regate",result.reason,result.message,EXIT.refused)}async function planTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task plan","usage","`toolroll task plan <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task plan",verified,"planning takes `--as <you> --token <t>` — it dispatches an agent that spends",id);if(store.getTask(id)===null)return fail(write,json,"task plan","refused",`no task ${id}`,EXIT.refused);const ref=store.refFor(BUILT_IN,id),pinProvider=text(flags,"provider"),pinModel=text(flags,"model");if(pinProvider!==void 0){if(!isProviderId(pinProvider))return fail(write,json,"task plan","usage",`unknown provider \`${pinProvider}\``,EXIT.usage);if(pinModel===void 0||pinModel==="")return fail(write,json,"task plan","usage","a plan pin names an exact --model with --provider — approvals bind exact routing",EXIT.usage);const valid=validateSpec({provider:pinProvider,model:pinModel});if(!valid.ok)return fail(write,json,"task plan","invalid",valid.problem,EXIT.usage);if(!store.setPlanPins(ref.id,pinProvider,pinModel,clock()).ok)return fail(write,json,"task plan","refused","a planner holds this task right now — the pin would reroute a live spend",EXIT.refused)}else if(pinModel!==void 0)return fail(write,json,"task plan","usage","--model rides --provider for a plan pin",EXIT.usage);const result=store.requestPlan(ref.id,clock());if(!result.ok)return fail(write,json,"task plan","refused",result.reason,EXIT.refused);const autoPlan=authorizePlanUnderMode(store,id,acting.name,clock());return succeed(write,json,"task plan",{id,autoPlan,...pinProvider===void 0?{}:{planProvider:pinProvider,planModel:pinModel??null}},()=>[`${id} will be planned before it is built: the next pass dispatches a planner${pinProvider===void 0?"":` on ${pinProvider}${pinModel===void 0?"":` · ${pinModel}`}`}.`,autoPlan?"An unchanged, verified plan can auto-approve under your signed mode. Amendments and questions still wait for you.":"Its questions reach you like any decision; its plan lands as a scope for you to edit and approve."])}async function reviewTaskCommand(positional,flags,context){const{store,write,json}=context;if(flags.has("brief")){const allowed=new Set(["brief","all","run","json","db","as","token"]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,"task review","usage",`--${name} is not a task review --brief option.`,EXIT.usage);const task=positional[0],selected=flags.get("run");if(positional.length!==1||!task||task.length>64||/[\x00-\x1f\x7f]/.test(task)||selected!==void 0&&(typeof selected!="string"||!/^[1-9]\d*$/.test(selected)||!Number.isSafeInteger(Number(selected))))return fail(write,json,"task review","usage","Use toolroll task review <task> --brief [--run <id>] [--all] [--json].",EXIT.usage);let viewer=currentActor()?.account??null;if(viewer===null&&(flags.has("as")||flags.has("token"))){const acting=await askCredentials(flags,context);if(acting===null||!authenticateApprover(store,acting.name,acting.token).ok)return fail(write,json,"task review","unauthenticated","That sign-in is not valid.",EXIT.refused);viewer=acting.name}const repos=viewer===null?null:store.knownRepos().filter(repo=>store.accountCanAccess(viewer,repo)),result=taskReviewBrief(store,task,context.evidenceRoot,context.now,{principal:"operator",repos,includeUnplaced:viewer===null},{...selected===void 0?{}:{run:Number(selected)},all:flags.has("all"),secrets:[context.leadToken??"",text(flags,"token")??""]});return result.ok?succeed(write,json,"task review",{brief:result.brief},()=>renderReviewBrief(result.brief)):fail(write,json,"task review",result.reason,result.message,EXIT.refused)}if(flags.has("run")||flags.has("all"))return fail(write,json,"task review","usage","--run and --all require --brief.",EXIT.usage);const[runText]=positional,runId=Number(runText??"");if(runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task review","usage","`toolroll task review <run-id>`",EXIT.usage);const review=buildReviewOf(store,runId);return review!==null?succeed(write,json,"task review",{run:runId,review},()=>[`Run ${runId}`,...buildReviewLines(review)]):fail(write,json,"task review","model-review-retired",`Run ${runId} has no automatic review. Manual review requests have been removed; a project's builds are reviewed automatically when its switch is on (\`toolroll review on --repo <path>\`). Inspect the saved work and checks, then give feedback or request a revision.`,EXIT.refused)}async function incidentCommand(positional,flags,context){const{store,write,json,clock}=context,[action,idText]=positional;if(action===void 0||action==="list"){const incidents=store.openIncidents();if(json)return write(envelopeJson({ok:!0,command:"incident list",incidents})),incidents.length===0?EXIT.ok:EXIT.refused;if(incidents.length===0)return write("No unresolved incidents."),EXIT.ok;for(const incident of incidents)write(` ${String(incident.id).padEnd(4)} ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} run ${incident.run}`);return write(""),write(" → toolroll incident resolve <id> --as <you> --token <t>"),EXIT.refused}if(action!=="resolve")return fail(write,json,"incident","usage","`toolroll incident [list|resolve <id>]`",EXIT.usage);const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"incident resolve","usage","`toolroll incident resolve <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"incident resolve","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"incident resolve",verified,"resolving takes `--as <you> --token <t>` — who looked is recorded, not asserted",String(id));const{name:asWho}=acting;return store.resolveIncident(id,asWho,clock())?succeed(write,json,"incident resolve",{id,by:asWho},()=>[`Resolved incident ${id}, as ${asWho}. The task's hold is lifted; the next tick may take it.`]):fail(write,json,"incident resolve","unknown-or-resolved",`no unresolved incident ${id}`,EXIT.refused)}async function webhookCommand(positional,_flags,context){const{write,json}=context,dir=dirname(context.databaseFile),[action,which,value]=positional,telegramConfigured=loadBotToken(process.env,context.telegramTokenFile)!==null;if(action===void 0||action==="status"){const consoleUrl=loadConsoleUrl(process.env,dir),primary=effectivePrimary(process.env,dir,telegramConfigured);if(json)return write(envelopeJson({ok:!0,command:"webhook status",configured:primary.configured,primary:primary.channel,implicit:primary.implicit,consoleUrl})),EXIT.ok;write(`Messaging${primary.configured.length===0?": nothing configured":""}`);for(const channel of primary.configured)write(` ${channel.padEnd(8)} connected${channel===primary.channel?" ← receives alerts":" (silent — not primary)"}`);return primary.implicit&&primary.channel!==null&&(write(` ! several services are connected and none was chosen — ${primary.channel} receives alerts by default.`),write(" Choose: toolroll webhook primary telegram|slack|discord")),write(` links ${consoleUrl??"NOT SET — messages will carry no console link; toolroll webhook set console-url http://host:port"}`),EXIT.ok}if(action==="primary")return which===void 0||!isMessagingChannel(which)?fail(write,json,"webhook primary","usage","primary is one of telegram, slack, discord",EXIT.usage):effectivePrimary(process.env,dir,telegramConfigured).configured.includes(which)?(savePrimary(dir,which),succeed(write,json,"webhook primary",{primary:which},()=>[`Alerts now go to ${which}. ${which==="telegram"?"Buttons and replies work there as always.":"Telegram (if configured) still accepts taps and replies — it just stops sending alerts."}`])):fail(write,json,"webhook primary","unconfigured",`${which} is not configured — set it up first, then choose it`,EXIT.refused);if(action!=="set"||which!=="console-url"||value===void 0)return fail(write,json,"webhook","usage","`toolroll webhook [status|primary <service>|set console-url <url>]`",EXIT.usage);const saved=saveConsoleUrl(dir,value);return saved.ok?succeed(write,json,"webhook set",{which},()=>[`Console links will open ${value.replace(/\/+$/,"")}.`]):fail(write,json,"webhook set","invalid",saved.message,EXIT.usage)}function resumeProviderCommand(positional,flags,context){const{store,write,json}=context,command="providers resume",provider=positional[0];if(provider===void 0||!isProviderId(provider)||positional.length>1)return fail(write,json,command,"usage",`Use \`toolroll providers resume <${PROVIDER_IDS.join("|")}>\`.`,EXIT.usage);const who=text(flags,"as")??process.env.USER??"operator",lifted=liftAuthPause(store,provider,"person",who,context.clock());return lifted===null?succeed(write,json,command,{provider,resumed:0,paused:!1},()=>[`${provider} is not paused.`]):succeed(write,json,command,{provider,resumed:lifted.resumed,paused:!1},()=>[`${provider} resumed — ${lifted.resumed} ${lifted.resumed===1?"task":"tasks"} can start again.`])}async function providersCommand(flags,context){const{store,write,json}=context,probe=context.gitRunner??run,configured=new Map;for(const scope of[INSTALLATION_SCOPE])for(const row of store.listPhaseConfig(scope))configured.set(row.provider,[...configured.get(row.provider)??[],row.phase]);const probed=await Promise.all(PROVIDER_IDS.map(async id=>{const facts=inspectionOf(id);if(isAcpProvider(id)){const seen=inspectAcpAgent(id),version2={code:seen.found?0:127,stdout:seen.found?seen.package?.version??"":"",stderr:"",notFound:!seen.found,timedOut:!1};return{id,facts,version:version2,installed:seen.found,identity:seen.found?`not checked on this computer — run \`toolroll agents check ${id}\``:null}}const version=await probe(facts.binary,["--version"],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV}),installed=version.code===0&&!version.notFound;let identity=null;if(installed&&facts.identityProbe!==null){const asked=await probe(facts.binary,[...facts.identityProbe],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV});identity=asked.code===0?asked.stdout.trim().split(`
478
+ `),exit:code=>{reader.close(),store.close(),resolvePromise(code)}},void 0,enrolled,join(dirname(file),"evidence"));outcome.ok||(reader.close(),store.close(),resolvePromise(said(outcome.message)))})}function describeAuth(reason,name){return reason==="unknown"?`no runner \`${name}\` — register it first`:reason==="retired"?`${name} has been retired`:reason==="expired"?`${name}'s token expired a year after it registered — register it again`:"that token does not match"}async function buildCommand(positional,flags,context){const{store,write,json,now}=context,demoFence=refuseDemo(context,"build");if(demoFence!==null)return demoFence;const id=positional[0];if(id!==void 0&&store.mirrorByTask(id)!==null)return fail(write,json,"build","external-task","external work dispatches through tick/watch — the completion gate lives there",EXIT.refused);const runner=text(flags,"runner"),token=text(flags,"token"),branch=text(flags,"branch");if(id===void 0||runner===void 0||token===void 0||branch===void 0)return fail(write,json,"build","usage","`toolroll build <id> --runner <name> --token <t> --branch <b> --repo <path>`",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"build",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"build","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);if(store.getTask(id)===null)return fail(write,json,"build","unknown-task",`No task ${id}.`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),ref=store.refFor(BUILT_IN,id),worktrees=new WorktreePool(store,{root:pool}),leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now,...text(flags,"base")===void 0?{}:{base:text(flags,"base")}});if(!leased.ok)return fail(write,json,"build",leased.reason,leased.message,EXIT.refused);const held=currentClaim(store,ref.id,now),standaloneModel=text(flags,"model"),authority=store.routeAuthorityFor(ref.id,"builder",{provider:"claude",model:standaloneModel??null});if(authority!==null&&!authority.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",`${id}: ${authority.problem}`,EXIT.refused);const standaloneMode=readAuthModeStrict(authority===null?"claude":authority.stamp.provider);if(!standaloneMode.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","auth-mode",`${id}: ${standaloneMode.problem}`,EXIT.refused);const standaloneProvider=authority===null?"claude":authority.stamp.provider,standaloneHold=store.budgetGate(now)({...store.budgetSubject(ref.id),agents:[{provider:standaloneProvider,billing:standaloneMode.mode==="api-key"?"api-key":billingOf(standaloneProvider,store.handle)}]});if(standaloneHold.over!==null)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","budget",`${id}: ${budgetHoldWords(standaloneHold,monthOf(now).name)}`,EXIT.refused);let runId;try{runId=store.startRun({taskRef:ref.id,leaseId:held?.leaseId??"unclaimed",runner,branch,worktree:leased.worktree.path,...authority===null?{}:{provider:authority.stamp.provider,route:authority.stamp},...standaloneModel===void 0?{}:{model:standaloneModel},now})}catch(error){return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",error instanceof Error?error.message:String(error),EXIT.refused)}const result=await build(store,{taskId:id,taskRef:ref.id,runner,...held===null?{}:{leaseId:held.leaseId},runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now,clock:context.clock,...text(flags,"model")===void 0?{}:{model:text(flags,"model")},...text(flags,"repair-model")===void 0?{}:{repairModel:text(flags,"repair-model")},...text(flags,"turns")===void 0?{}:{maxTurns:Number(text(flags,"turns"))},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}}),handedBack=await worktrees.release(leased.worktree.path,now),disposition=disposeBuildOutcome({store,policy:"standalone",leaseId:held?.leaseId,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:"claude",model:text(flags,"model")??null,worktreePath:leased.worktree.path,clock:context.clock},result);if(result.ok&&result.parked!==void 0)return disposition.kind!=="parked"?fail(write,json,"build","fenced",`${id} parked, but the lease was gone before the decision could be sealed`,EXIT.refused,{worktree:leased.worktree.path}):succeed(write,json,"build",{parked:!0,decision:disposition.decisionId,worktree:leased.worktree.path},()=>[`${id} parked a decision instead of guessing.`,` decision ${disposition.decisionId} — \`toolroll decide ${disposition.decisionId}\``,` worktree ${leased.worktree.path} (work in progress preserved)`]);if(!result.ok){const broke=result.reason==="agent"||result.reason==="agent-reported"||result.reason==="no-op"||result.reason==="no-handoff"||result.reason==="moved-head"||result.reason==="timeout"||result.reason==="git"||result.reason==="malformed-decision";return fail(write,json,"build",result.reason,result.message,broke?EXIT.failed:EXIT.refused,{worktree:leased.worktree.path})}return succeed(write,json,"build",{...result,worktree:leased.worktree.path,clean:handedBack.ok},()=>[result.committed?`Built ${id} and committed to ${branch}.`:`${id}: no change needed — the agent said so and the tree agrees.`,` worktree ${leased.worktree.path}`,"",result.summary,"","Nothing has been pushed. Look at the branch before it goes anywhere."])}function flowIoOf(context,pool,git,base){const dir=dirname(context.databaseFile);return{triggers:{gh:context.flowTriggerIo?.gh??run,fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,shell:context.flowTriggerIo?.shell??context.flowStepIo?.shell??run,scratch:context.flowTriggerIo?.scratch??context.flowStepIo?.scratch??join(pool,"flow-checks"),...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},replies:{fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},steps:{gh:context.flowStepIo?.gh??run,git:context.flowStepIo?.git??(git===run?hardenedGit(run):git),shell:context.flowStepIo?.shell??run,fetch:context.flowStepIo?.fetch??fetch,dir:context.flowStepIo?.dir??dir,scratch:context.flowStepIo?.scratch??join(pool,"flow-checks"),base,...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}},...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot},youiyouxGit:gitOf(context.gitRunner)}}async function tickCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"tick");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token");if(runner===void 0||token===void 0)return fail(write,json,"tick","usage","`toolroll tick --runner <name> --token <t> --repo <path> [--max <n>] [--base <ref>]`",EXIT.usage);const auth=heartbeatRunner(store,runner,token,clock());if(!auth.ok)return fail(write,json,"tick",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);if(updateAdmissionPaused(store.raw()))return fail(write,json,"tick","updating",UPDATE_PAUSED,EXIT.refused);const maxGiven=text(flags,"max"),maxAsked=maxGiven===void 0?1:Number(maxGiven);if(!Number.isInteger(maxAsked)||maxAsked<=0)return fail(write,json,"tick","usage","--max takes a whole number of tasks",EXIT.usage);const max=flags.has("yield-builds")?0:maxAsked,buildsOnly=flags.has("builds-only"),syncAgeGiven=text(flags,"sync-max-age"),syncMaxAgeMs=syncAgeGiven===void 0?SYNC_MAX_AGE_MS:Number(syncAgeGiven)*1e3;if(!Number.isInteger(syncMaxAgeMs)||syncMaxAgeMs<=0)return fail(write,json,"tick","usage","--sync-max-age takes whole seconds",EXIT.usage);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"tick","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),model=text(flags,"model"),repairModel=text(flags,"repair-model"),providerFlag=text(flags,"provider"),planModel=text(flags,"plan-model"),planProvider=text(flags,"plan-provider"),turns=text(flags,"turns"),leaseTtlMs=DEFAULT_LEASE_MS,git=context.gitRunner??run,worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),watchOwner=text(flags,"incarnation");watchOwner!==void 0&&!buildsOnly&&await runAcpChecks({store,runner,token,pool:worktrees,clock,watch:{repo:canonicalProject(repo)??resolve(repo),owner:watchOwner},progress:line=>{json||write(line)}});let base=text(flags,"base");if(base===void 0){const head=await git("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return fail(write,json,"tick","git",`${repo} has no branch checked out — say --base explicitly`,EXIT.refused);base=head.stdout.trim()}await probeRepo(store,repo,runner,clock()),applyPendingAgentChanges(store,clock());const housekeeping=buildsOnly?null:await flowHousekeeping(store,repo,clock,flowIoOf(context,pool,git,base),()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0),triggerPass=housekeeping?.triggers??{added:0,checked:0,problems:[]},replyPass=housekeeping?.replies??{read:0,taken:0,problem:null},stepPass=housekeeping?.steps??{ran:0,problems:[]},flowPass=housekeeping?.flows??{moved:0,filed:[],problems:[]};if(!buildsOnly)try{sendSubagentSummaries(store,repo,clock()),sendSubagentWeeklies(store,repo,clock())}catch(error){flowPass.problems.push(`subagent summaries: ${error instanceof Error?error.message:"could not send"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{await runRequestedUndos(store,{},clock())}catch(error){flowPass.problems.push(`subagent undo: ${error instanceof Error?error.message:"could not run"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{flowPass.problems.push(...(await refreshConnections(store,[repo],clock(),context.flowStepIo?.fetch===void 0?{}:{fetcher:context.flowStepIo.fetch})).problems)}catch(error){flowPass.problems.push(`tool sign-ins: ${error instanceof Error?error.message:"could not renew"}`)}let settled=0;const settleFinished=()=>{const finished=dispatched.slice(settled).filter(one=>one.outcome!=="skipped").map(one=>one.id);if(settled=dispatched.length,finished.length===0)return;const after=moveCardsAfter(store,repo,finished,clock(),context.evidenceRoot);flowPass.moved+=after.moved,flowPass.filed.push(...after.filed),flowPass.problems.push(...after.problems)};store.sweepCeremonyNonces(clock());let budgetGate=null;const budgetHold=(taskRef,agents)=>(budgetGate??=store.budgetGate(clock()))({...store.budgetSubject(taskRef),agents}),budgetWords=hold=>budgetHoldWords(hold,monthOf(clock()).name),policyHold=agents=>{for(const agent of agents)if("profile"in agent){const verdict=store.runPolicy(agent.profile);if(!verdict.ok)return verdict.message}else{const refused=agent.session!==void 0?store.sessionPolicyRefusal(agent.provider,agent.model,agent.session):store.agentPolicyRefusal(agent.provider,agent.model);if(refused!==null)return refused}return null},ready=store.listReady(clock(),runner),considered=ready.length,dispatched=[];reconcileWalks(store,clock());const MIRROR_WORDS={"stale-mirror":"its tracker has not been synced recently — `toolroll sync` restores freshness","external-closed":"the tracker closed it — reopen it there, then `toolroll task reopen`","dispatch-revoked":"the tracker's building permission was revoked or narrowed","plane-blocked":"the tracker's plane marker could not be verified — building is paused"};for(const skippedMirror of store.ineligibleMirrors(repo,clock(),syncMaxAgeMs))dispatched.push({id:skippedMirror.taskId,outcome:"skipped",reason:skippedMirror.why}),store.enqueueNotification({source:{taskRef:store.lookupRef(skippedMirror.taskId)?.id??-1},dedupeKey:`mirror:${skippedMirror.taskId}:${skippedMirror.why}`,kind:"external-skipped",subject:`${skippedMirror.taskId} cannot dispatch`,body:MIRROR_WORDS[skippedMirror.why]??"the tracker item is not dispatchable right now"},clock());let built=0,parked=0,broke=0;const attestedThisPass=new Map;let untakenTrial=null;for(const ref of ready){if(settleFinished(),untakenTrial?.giveBack(),untakenTrial=null,built>=max)continue;if(context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0)break;const id=ref.externalId;if(ref.repo!==null&&ref.repo!==repo){dispatched.push({id,outcome:"skipped",reason:"other-repo"});continue}const scopeApproved=scopeApprovedForDispatch(store,ref.id,clock()),wantsPlan=ref.plan==="requested"&&!scopeApproved,wantsScout=ref.deliverable==="report"&&scopeApproved;if(!wantsPlan&&!scopeApproved){dispatched.push({id,outcome:"skipped",reason:"unapproved"});continue}const agentless=agentlessFirstRun(store,ref,wantsPlan,[runner]);if(agentless!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:agentless.words});continue}const taskRoute=routeOfTask(store,id,ref,clock());if(taskRoute!==null&&taskRoute.kind==="unreadable"){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:taskRoute.problem});continue}const route=taskRoute!==null&&taskRoute.kind==="route"?taskRoute:null;if(wantsPlan&&route!==null&&route.source==="proposed"){const working=store.workingPlanRouteOf(id);if(!working.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${working.problem}`});continue}}const planLeg=route===null?null:legOf(route.route,"plan"),fallback=route!==null&&route.source==="approved"&&!wantsPlan&&!wantsScout?dispatchEntryOf(store,ref.id,id,clock()):null;if(fallback!==null&&"problem"in fallback){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${fallback.problem}`});continue}const sealedBuildLeg=route!==null&&route.source==="approved"?fallback!==null?{provider:fallback.entry.profile.provider,model:fallback.entry.profile.model,chosen:"fallback"}:legOf(route.route,"build"):null;if(wantsPlan&&planLeg!==null&&(planProvider!==void 0||planModel!==void 0||providerFlag!==void 0||model!==void 0)){const flaggedProvider=planProvider??providerFlag,flaggedModel=planModel??model;if(flaggedProvider!==void 0&&flaggedProvider!==planLeg.provider||flaggedModel!==void 0&&flaggedModel!==planLeg.model){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`the pass flags name ${flaggedProvider??planLeg.provider}${flaggedModel===void 0?"":` · ${flaggedModel}`} but ${id}'s planner is ${planLeg.provider} · ${planLeg.model} — flags cannot reroute a task; override the plan phase with \`task route\``});continue}}const resolution=wantsPlan?planLeg!==null?resolvePhaseAgent(store,"plan",repo,{provider:planLeg.provider,model:planLeg.model}):resolvePhaseAgent(store,"plan",repo,{provider:ref.planProvider??planProvider??providerFlag,model:ref.planProvider!==null?ref.planModel??void 0:planModel??model}):sealedBuildLeg!==null?resolvePhaseAgent(store,"build",repo,{provider:sealedBuildLeg.provider,model:sealedBuildLeg.model},ref):resolvePhaseAgent(store,"build",repo,{provider:providerFlag,model},ref);if(!resolution.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:resolution.problem});continue}const routedDecision=!wantsPlan&&sealedBuildLeg===null&&route===null&&store.getScope(id)?.approvedProfile==null&&resolution.source!=="pinned"&&resolution.source!=="flag"?routeWorkerModel(store,{taskKind:ref.sizing?.size==="small"?"simple-fix":"multi-file-build",provider:resolution.spec.provider,fallbackModel:resolution.spec.model,now:clock()}):null,spec=routedDecision!==null&&routedDecision.steppedDown?{provider:resolution.spec.provider,model:routedDecision.model}:resolution.spec,brokenMode=readAuthModeStrict(spec.provider);if(!brokenMode.ok){dispatched.push({id,outcome:"skipped",reason:"auth-mode",detail:brokenMode.problem});continue}const gate=signInGate(store,[spec.provider],clock(),ref.id);if(gate.waiting!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:signInWords(gate.waiting)});continue}untakenTrial=gate;const governingLeg=wantsPlan?planLeg:sealedBuildLeg;if(governingLeg!==null&&(spec.provider!==governingLeg.provider||spec.model!==governingLeg.model)){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: the ${wantsPlan?"plan":"build"} leg names ${governingLeg.provider} · ${governingLeg.model} but resolution produced ${spec.provider} · ${spec.model??"(no model)"} — nothing substitutes`});continue}const routeStamp=phase=>{if(governingLeg===null||route===null||phase==="plan"&&route.source==="live"){const legacy=store.routeAuthorityFor(ref.id,phase==="plan"?"planner":"builder",{provider:spec.provider,model:spec.model});return legacy!==null&&legacy.ok?legacy.stamp:null}return{routeDigest:routeDigestOf(route.route),phase,provider:spec.provider,model:spec.model,chosen:governingLeg.chosen}};if(!wantsPlan&&!wantsScout&&route===null){const legacyStamp=routeStamp("build");if(legacyStamp!==null&&(legacyStamp.provider!==spec.provider||legacyStamp.model!==spec.model)){const message=`${id}: the sealed profile builds on ${legacyStamp.provider} · ${legacyStamp.model??"(no model)"} but today's routing resolved ${spec.provider} · ${spec.model??"(no model)"} — nothing runs on it (stale-approval)`;holdStaleApproval(store,{taskRef:ref.id,taskId:id,message},clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:message});continue}}if(!wantsPlan&&!wantsScout){const ruleHeld=ruleHoldOf(store,id);if(ruleHeld!==null){holdRuleOff(store,ref.id,ruleHeld.model,clock()),dispatched.push({id,outcome:"skipped",reason:"rule-switched-off",detail:`${id}: results for ${ruleHeld.model} dropped after this was approved — approve it again or re-file it`});continue}}{const unavailable=store.runnerReadinessOf(runner,spec.provider);if(unavailable!==null&&readinessRefuses(unavailable,fallback?.entry.authMode??(brokenMode.ok?brokenMode.mode:"subscription"))){const observed=`${unavailable.provider} is reported unavailable on ${runner} (${unavailable.reason}; observed ${unavailable.observedAt})`;dispatched.push({id,outcome:"skipped",reason:"provider-unavailable",detail:`${observed} — nothing substitutes for a routed provider: override the phase with \`task route\` or restore the provider and report readiness again`});continue}}const skipProviders=wantsPlan||fallback!==null?[spec.provider]:[store.getScope(id)?.approvedProfile?.provider].filter(one=>one!=null);let unattestedLane=null;for(const candidate of new Set(skipProviders)){if(isAcpProvider(candidate)){const checked=store.acpAttestationFor(candidate,runner),verified=checked===null?null:verifyLaunch(checked.launch);if(checked===null){unattestedLane=`${ACP_AGENTS[candidate].name} isn't checked on ${runner} — run \`toolroll agents check ${candidate}\` there`;break}if(verified!==null&&!verified.ok){unattestedLane=verified.problem;break}continue}if(attestationOf(candidate)===null)continue;let verdict=attestedThisPass.get(candidate);if(verdict===void 0&&(verdict=await attestProvider(candidate,inspectionOf(candidate).binary),attestedThisPass.set(candidate,verdict)),verdict!==null&&!verdict.ok){unattestedLane=verdict.problem;break}}if(unattestedLane!==null){dispatched.push({id,outcome:"skipped",reason:"provider-unattested",detail:unattestedLane});continue}{const sealed=wantsPlan||wantsScout?null:fallback?.entry.profile??store.getScope(id)?.approvedProfile??null,refused=policyHold([sealed!==null?{profile:sealed}:{provider:spec.provider,model:spec.model,...wantsPlan?{session:"planning"}:wantsScout?{session:"scouting"}:{}}]);if(refused!==null){dispatched.push({id,outcome:"skipped",reason:"policy",detail:refused});continue}}const sealedModel=store.getScope(id)?.approvedProfile?.model??null,budgeted=budgetHold(ref.id,fallback?.paid===!0?[{provider:spec.provider,billing:"api-key"}]:[...new Set([spec.provider,...skipProviders])].map(provider=>isAcpProvider(provider)||provider==="pi"?store.agentFor(provider,provider===spec.provider?spec.model??sealedModel:sealedModel,runner):store.agentsFor([provider])[0]));if(budgeted.over!==null){dispatched.push({id,outcome:"skipped",reason:"budget",detail:budgetWords(budgeted)});continue}if(!wantsPlan&&runningReleaseCheck(store,clock(),ref.id)!==null){dispatched.push({id,outcome:"skipped",reason:"release-check",detail:RELEASE_CHECK_WAIT});continue}if(repo!==null){const railed=store.reserveModeRail(repo,1,clock());if(!railed.ok){dispatched.push({id,outcome:"skipped",reason:railed.rail,detail:railed.detail});continue}}const claimed=acquireIfReady(store,ref.id,runner,{...wantsPlan?{dispatchRole:"planner"}:wantsScout?{dispatchRole:"scout"}:{},now:clock(),token,ttlMs:leaseTtlMs,syncMaxAgeMs,repo,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...fallback!==null?{authMode:fallback.entry.authMode}:brokenMode.ok&&(brokenMode.mode==="api-key"||brokenMode.mode==="subscription")?{authMode:brokenMode.mode}:{},...text(flags,"incarnation")===void 0?{}:{incarnation:text(flags,"incarnation")}});if(claimed.ok&&(untakenTrial=null),!claimed.ok){if(claimed.reason==="capability"&&"message"in claimed){const key=/needs (\S+)/.exec(claimed.message)?.[1],parsed=key===void 0?null:parseCapabilityKey(key);if(parsed!==null){const home=ref.repo??repo;store.enqueueNotification({source:{taskRef:ref.id},dedupeKey:`gap:${home}:${parsed.kind}:${parsed.name}`,kind:"gap",pushClass:"attention",link:"/caps",subject:`${key} blocks work in ${home}`,body:`${id} (and possibly others) cannot dispatch: ${claimed.message}. \`toolroll gaps --repo ${home}\``},clock())}}dispatched.push({id,outcome:"skipped",reason:claimed.reason,..."message"in claimed&&claimed.reason==="capability"?{detail:claimed.message}:{}});continue}const lease=claimed.claim.leaseId;if(wantsPlan){const answers=store.answeredDecisionsFor(id).map(one=>({question:one.question,choice:one.choice??"",note:one.note})),sourced=plannerSourceOf(store,context.evidenceRoot,id,answers);if(!sourced.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:`planner-source-${sourced.reason}`,detail:sourced.message});continue}const planBranch=await existingOrFirst([`toolroll-plan/${id}`,`standing-orders-plan/${id}`],async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),revised=ref.revisionOf===null?null:revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);if(revised!==null&&!revised.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:revised.problem});continue}const planLeased=await worktrees.lease({repo,branch:planBranch,runner,taskRef:ref.id,now:clock(),base:revised?.head??base,reuseBranch:!0,reclaim:{evidenceRoot:context.evidenceRoot},...freshBaseFor(store,id,planBranch,base)});if(!planLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:planLeased.reason}),broke++;continue}const planStamp=routeStamp("plan"),planRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"planner",provider:spec.provider,branch:planBranch,worktree:planLeased.worktree.path,...spec.model===null?{}:{model:spec.model},now:clock(),...planStamp===null?{}:{route:planStamp}});noteBaseStanding(store,planRunId,planLeased.base,base,clock());let sourceArtifact;try{sourceArtifact=storeEvidence(store,context.evidenceRoot,planRunId,"plan-contract","planner-source.json",encodePlannerSource(sourced.source),`planner source ${sourced.source.sourceDigest.slice(0,12)} — the filed request quoted into the brief, recorded before spend (${sourced.bytes} bytes)`,clock(),{captureStatus:"ok"})}catch(error){await worktrees.release(planLeased.worktree.path,clock());const unrecorded=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:"failure",message:`the planner's source could not be recorded: ${error instanceof Error?error.message:String(error)}`,now:clock()});dispatched.push({id,outcome:"failed",reason:"evidence"}),unrecorded.ok||release(store,lease,clock()),broke++;continue}store.stampRun(planRunId,{scopeDigest:sourced.source.contract.scope?.digest??""}),budgetGate=null;const outcome=await planTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:planRunId,worktree:planLeased.worktree.path,branch:planBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(planLeased.worktree.path,runner,pid,planLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers,source:sourced.source,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});if(await worktrees.release(planLeased.worktree.path,clock()),outcome.ok&&"parked"in outcome){const sealed=finalize(store,lease,{kind:"park",runId:planRunId,taskId:id,decision:outcome.parked.decision,artifactIds:outcome.parked.artifactIds,repairRunId:outcome.parked.repairRunId,now:clock()});sealed.ok?(store.resetPlanStrikes(ref.id),dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`}),parked++):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}if(outcome.ok){const sealed=finalize(store,lease,{kind:"plan",runId:planRunId,taskId:id,plan:outcome.drafted.plan,artifact:outcome.drafted.artifact,repairRunId:outcome.drafted.repairRunId,source:sourced.source,sourceArtifact,evidenceRoot:context.evidenceRoot,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"planned",...sealed.changes===0?{}:{detail:`${sealed.changes} contract change${sealed.changes===1?"":"s"} proposed${sealed.amendment===null?"":" with an amendment"}`}})):sealed.reason==="stale-source"||sealed.reason==="source-invalid"?dispatched.push({id,outcome:"skipped",reason:sealed.reason,detail:sealed.detail}):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:outcome.kind,...outcome.kind==="malformed"?{malformed:outcome.reason==="malformed-decision"?"decision":"plan"}:{},message:outcome.message,code:outcome.reason,...outcome.kind==="malformed"&&outcome.problems!==void 0?{problems:outcome.problems.map(problem=>problem.message)}:{},...outcome.agentSaid===void 0?{}:{agentSaid:outcome.agentSaid},now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`});continue}dispatched.push({id,outcome:"failed",reason:outcome.reason}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}if(wantsScout){const scoutBranch=`toolroll-scout/${id}/${randomBytes(4).toString("hex")}`,scopeRow=store.getScope(id),proof=proveApprovedProfile(scopeRow,{provider:spec.provider,model:spec.model??void 0,maxTurns:void 0,timeoutMs:void 0,skipPermissions:!1});if(!proof.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:proof.message});continue}const scoutLeased=await worktrees.lease({repo,branch:scoutBranch,runner,taskRef:ref.id,now:clock(),base});if(!scoutLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:scoutLeased.reason}),broke++;continue}const scoutStamp=routeStamp("build")??{routeDigest:`profile:${profileDigestOf(proof.effective.profile)}`,phase:"build",provider:spec.provider,model:proof.effective.model,chosen:"legacy"},scoutRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"scout",provider:spec.provider,branch:scoutBranch,worktree:scoutLeased.worktree.path,model:proof.effective.model,now:clock(),route:scoutStamp});store.stampRun(scoutRunId,{scopeDigest:scopeRow?.approvedDigest??"",profileDigest:profileDigestOf(proof.effective.profile)});const scoutAnswers=store.answeredDecisionsFor(id,6).map(one=>({question:one.question,choice:one.choice??"",note:one.note}));budgetGate=null;const scouted=await scoutTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,goal:scopeRow?.goal??"",outOfScope:scopeRow?.outOfScope??null,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:scoutRunId,worktree:scoutLeased.worktree.path,branch:scoutBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(scoutLeased.worktree.path,runner,pid,scoutLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers:scoutAnswers,demoUrl:projectDemoUrl(context.databaseFile,repo),provider:spec.provider,model:proof.effective.model,...proof.effective.maxTurns===void 0?{}:{maxTurns:proof.effective.maxTurns},timeoutMs:proof.effective.timeoutMs,...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});await worktrees.release(scoutLeased.worktree.path,clock());const discarded=await worktrees.discard(scoutLeased.worktree.path,clock()),leftover=discarded.ok?{}:{detail:`checkout kept: ${discarded.message}`};if(scouted.ok&&"parked"in scouted){const sealed=finalize(store,lease,{kind:"park",runId:scoutRunId,taskId:id,decision:scouted.parked.decision,artifactIds:scouted.parked.artifactIds,now:clock()});sealed.ok?(dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`,...leftover}),parked++):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}if(scouted.ok){const sealed=finalize(store,lease,{kind:"scout",runId:scoutRunId,taskId:id,report:scouted.reported.report,artifact:scouted.reported.artifact,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"reported",...leftover})):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover}):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"scout-failure",runId:scoutRunId,taskId:id,failure:scouted.kind,...scouted.kind==="malformed"?{malformed:scouted.reason==="malformed-decision"?"decision":"report"}:{},message:scouted.message,now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover});continue}dispatched.push({id,outcome:"failed",reason:scouted.reason,...leftover}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}const branch=await existingOrFirst(taskBranches(id),async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),exists=await git("git",["rev-parse","--verify","--quiet",`refs/heads/${branch}`],{cwd:repo});let buildBase=base,caughtUp=null;if(ref.revisionOf!==null){const source=revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);let problem=source.ok?null:source.problem;if(source.ok)if(exists.code!==0&&text(flags,"base")===void 0){if(buildBase=source.head,!publishesThroughPullRequests(store,repo)){const onto=landingBranchOf(store,repo,base),result2=await catchUpRevision(hardenedGit(git,"build",{repo}),repo,source.head,onto,id,clock());caughtUp={head:source.head,onto,result:result2},result2.kind==="merged"&&(buildBase=result2.commit)}}else{const descendant=exists.code===0?branch:base,ancestry=await lazyFetchSafeGit(git)("git",[...noLazyFetch(),"-c","protocol.allow=never","--no-replace-objects","merge-base","--is-ancestor",source.head,descendant],{cwd:repo});if(ancestry.code!==0)problem=ancestry.stderr.includes(PARTIAL_CLONE_REFUSAL)?PARTIAL_CLONE_REFUSAL:"the requested revision base does not contain its source head";else if(exists.code===0&&store.latestBranchBaseMove(ref.id,branch)===null&&store.firstBuilderBase(ref.id,branch)===null&&!publishesThroughPullRequests(store,repo)){const tip=exists.stdout.trim(),main=await catchUpMergeOf(hardenedGit(git,"build",{repo}),repo,tip,source.head,landingBranchOf(store,repo,base));main!==null&&store.recordBranchBaseMove(ref.id,branch,tip,main,clock())}}if(problem!==null){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:problem});continue}}const leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now:clock(),...exists.code===0?{}:{base:buildBase},reclaim:{evidenceRoot:context.evidenceRoot},...exists.code===0?freshBaseFor(store,id,branch,base):{}});if(caughtUp!==null&&caughtUp.result.kind==="merged"){const merged=caughtUp.result,at=leased.ok&&leased.created?await hardenedGit(git,"build",{repo})("git",["rev-parse","--verify","-q",`refs/heads/${branch}^{commit}`],{cwd:repo}):null;if(at!==null&&at.code===0&&at.stdout.trim()===merged.commit)store.recordBranchBaseMove(ref.id,branch,merged.commit,merged.main,clock());else if(leased.ok&&leased.created){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:"git",detail:"Toolroll couldn't confirm the new branch stands at its merge of main; it tries again."}),broke++;continue}else caughtUp={...caughtUp,result:{kind:"unavailable"}}}if(!leased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:leased.reason}),broke++;continue}const buildStamp=routeStamp("build");let runId;try{if(leased.resumedFromRun!==void 0){if(buildStamp===null)throw new Error(`${id}: the recovered attempt presents no build authority`);const admittedRecovered=store.admitRecoveredBuilder({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},recoveredFrom:leased.resumedFromRun,now:clock(),route:buildStamp});if(!admittedRecovered.ok)throw new Error(admittedRecovered.problem);runId=admittedRecovered.runId}else runId=store.startRun({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},now:clock(),...buildStamp===null?{}:{route:buildStamp}})}catch(error){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"admission-refused",detail:error instanceof Error?error.message:String(error)});continue}noteBaseStanding(store,runId,leased.base,base,clock()),caughtUp!==null&&leased.created&&recordCatchUp(store,{repo,taskId:id,runId,branch,head:caughtUp.head,onto:caughtUp.onto},caughtUp.result,clock()),leased.resumedFromRun!==void 0&&store.addRunNote(runId,"Toolroll",`Recovered the ${leased.recoveryKind==="completed"?"completed source draft":"work-in-progress draft"} from interrupted attempt #${leased.resumedFromRun}. This fresh attempt is reviewing and verifying it; the safety patch is retained.`,clock());const scopeBudget=store.getScope(id)?.budgetMicrousd??null,backstop=store.getSpendDefaults()?.buildPerRunMicrousd??null,budgetLeft=budgeted.remainingMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag!==null?Math.max(1,budgeted.remainingMicrousd):null,capMicrousd=[scopeBudget,backstop,budgetLeft].reduce((least,one)=>one===null?least:least===null?one:Math.min(least,one),null);if(capMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag===null){store.finishRun(runId,{outcome:"refused",reason:"budget-unenforceable",now:clock()}),release(store,lease,clock()),await worktrees.release(leased.worktree.path,clock()),dispatched.push({id,outcome:"skipped",reason:"budget-unenforceable"});continue}budgetGate=null;const result=await build(store,{taskId:id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now:clock(),clock,...capMicrousd===null?{}:{maxBudgetUsd:capMicrousd/1e6},onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(leased.worktree.path,runner,pid,leased.worktree.leaseEpoch)},provider:spec.provider,...spec.model===null?{}:{model:spec.model},...repairModel===void 0?{}:{repairModel},...turns===void 0?{}:{maxTurns:Number(turns)},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner},...context.shouldStop===void 0?{}:{shouldStop:context.shouldStop},...leased.resumedFromRun===void 0?{}:{recoveredDraftRun:leased.resumedFromRun},...leased.recoveryKind===void 0?{}:{recoveredDraftKind:leased.recoveryKind}});await worktrees.release(leased.worktree.path,clock());const disposition=disposeBuildOutcome({store,policy:"tick",leaseId:lease,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:spec.provider,model:spec.model,worktreePath:leased.worktree.path,evidenceRoot:context.evidenceRoot,clock},result);switch(disposition.kind){case"parked":dispatched.push({id,outcome:"parked",reason:`decision:${disposition.decisionId}`,worktree:leased.worktree.path}),parked++;break;case"park-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"disowned":dispatched.push({id,outcome:"failed",reason:"external-closed",branch,worktree:leased.worktree.path}),broke++;break;case"built":dispatched.push({id,outcome:"built",committed:disposition.committed,branch,worktree:leased.worktree.path}),built++;break;case"built-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",branch,worktree:leased.worktree.path}),broke++;break;case"skipped":dispatched.push({id,outcome:"skipped",reason:disposition.reason});break;case"fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"malformed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?"malformed-decision":"fenced",worktree:leased.worktree.path}),broke++;break;case"failed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?disposition.disposition==="auth-expired"?"auth-expired — requeued, sign-in needed":disposition.disposition==="fallback"?"out of plan — moved to the next approved agent":`${disposition.failureClass}${disposition.disposition==="backoff"?` — retry ${disposition.strikes}/3`:disposition.disposition==="stalled"?" — stalled":disposition.closedState!==null?` — the task was already ${disposition.closedState}, so it stays ${disposition.closedState}`:""}`:"fenced",...result.ok?{}:{detail:result.message.slice(0,200)},worktree:leased.worktree.path}),disposition.sealed&&disposition.disposition==="fallback"||broke++;break;case"recorded":break;case"stopped":dispatched.push({id,outcome:"stopped",reason:`stop:${disposition.stopRun}`,branch,worktree:leased.worktree.path});break;case"handed-back":dispatched.push({id,outcome:"stopped",reason:"service-stop",detail:result.ok?"":result.message.slice(0,200),branch,worktree:leased.worktree.path});break;case"invariant":dispatched.push({id,outcome:"failed",reason:disposition.reason}),broke++;break}}if(untakenTrial?.giveBack(),!buildsOnly&&authenticate(store,runner,token).ok){const reviewed=await buildReviewPass(store,{runner,token,repos:auth.runner.repos,clock,root:context.evidenceRoot,...text(flags,"incarnation")===void 0?{}:{watchIncarnation:text(flags,"incarnation")},...context.agentRunner===void 0?{}:{agent:context.agentRunner},shouldStop:()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0});for(const one of reviewed)dispatched.push({id:`review of run ${one.run}`,outcome:one.outcome==="not-reviewed"?"not-reviewed":"reviewed",reason:one.detail})}buildsOnly||syncAssignmentHandoffs(store,clock(),auth.runner.repos,context.evidenceRoot),settleFinished();const replied=replyPass.taken>0||replyPass.problem!==null,requestPass=housekeeping?.youiyoux??NO_YOUIYOUX_PASS,requested=requestPass.filed+requestPass.copied+requestPass.decided+requestPass.problems.length>0,flows=flowPass.moved+flowPass.filed.length+flowPass.problems.length+triggerPass.added+triggerPass.problems.length+stepPass.ran+stepPass.problems.length===0&&!replied&&!requested?{}:{flows:{...flowPass,...triggerPass.added+triggerPass.problems.length===0?{}:{triggers:triggerPass},...requested?{youiyoux:requestPass}:{},...stepPass.ran+stepPass.problems.length===0?{}:{steps:stepPass},...replied?{replies:replyPass}:{}}},summary=()=>{const lines=[`Considered ${considered}, built ${built}, parked ${parked}, broke ${broke}.`];for(const entry of dispatched){const detail=entry.outcome==="built"?entry.committed===!0?`committed to ${entry.branch}`:"no changes reported; see the result's proof status":entry.outcome==="parked"?`${entry.reason} — \`toolroll decide\``:entry.reason??"";lines.push(` ${entry.id.padEnd(24)} ${entry.outcome} ${detail}`.trimEnd())}return built>0&&lines.push("","Nothing has been pushed. Look at the branches before they go anywhere."),parked>0&&lines.push("",`${parked} decision${parked===1?"":"s"} waiting — \`toolroll decide\`, or \`toolroll brief\`.`),lines};return broke>0?fail(write,json,"tick","build-failed",`${broke} of ${dispatched.length} dispatched tasks broke`,EXIT.failed,{considered,dispatched}):built>0||parked>0||dispatched.some(one=>one.outcome==="planned"||one.outcome==="reported"||one.outcome==="reviewed"||one.outcome==="not-reviewed")?succeed(write,json,"tick",{considered,dispatched,...flows},summary):considered===0?fail(write,json,"tick","empty","nothing is ready",EXIT.refused,{considered,dispatched,...flows}):fail(write,json,"tick","nothing-dispatched","everything ready is waiting on a person or held by somebody else",EXIT.refused,{considered,dispatched,...flows})}async function reconcileCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"reconcile");if(demoFence!==null)return demoFence;const repo=repoFrom(flags),pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),syncReports=[];for(const dispatchGrant of store.listGrants().filter(one=>one.dispatch===!0&&one.remoteRepo!=null&&one.repo===repo))syncReports.push(await syncPass(store,dispatchGrant,context.dispatchAdapter??ghDispatchAdapter(),clock));for(const report of syncReports)report.outcome==="failed"||report.outcome==="blocked"?store.enqueueEpisode(`sync:${report.remoteRepo}`,{source:{project:repo},kind:"sync-failed",pushClass:"attention",link:"/system",subject:`syncing ${report.remoteRepo} ${report.outcome==="blocked"?"is blocked":"failed"}`,body:`${report.detail??"the pass did not finish"} — external work keeps its last verified state and stops dispatching past its freshness window.`},clock().toISOString(),clock()):store.resolveEpisodes(`sync:${report.remoteRepo}`,clock());const recovered=recoverDead(store,clock()),closedRuns=await closeOutRuns(store,clock,{repo});store.recordFinishedRunExits(clock()),store.settleUnspawnedWitnesses(clock()),await proveFinishedRunsStopped(store,clock),store.settleQuiescentStops(clock()),applyPendingAgentChanges(store,clock()),retryVanishedWhenStopped(store,clock()),expireFastStarts(store,clock()),routeLegacyPlans(store,clock());try{releaseStalledUpdate(dirname(context.databaseFile),clock())}catch{}for(const one of recovered){for(const leaseId of one.claims)store.enqueueNotification({source:{taskRef:Number(store.handle.prepare("SELECT task_ref FROM claim WHERE lease_id = ?").get(leaseId)?.task_ref??-1)},dedupeKey:`recover:${leaseId}`,kind:"runner-recovered",subject:`${one.runner} went dead holding work`,body:`Its claims were requeued and its worktrees handed back unverified. Lease ${leaseId}.`},clock());for(const runId of one.runs)store.enqueueNotification({source:{run:runId},dedupeKey:`recover-run:${runId}`,kind:"runner-recovered",subject:`${one.runner} went dead mid-attempt`,body:`Run #${runId} was still open with no live lease; it is now finished as interrupted. Check this task's current state in the console.`,link:`/r/${runId}`},clock())}const reaped=reap(store,clock()),liveSwept=sweepLiveLogs(store,context.evidenceRoot,clock());try{store.sweepRunActivity(clock(),LIVE_RETAIN_MS,LIVE_FILE_BOUND)}catch{}const worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),adoption=await worktrees.adopt(repo,clock());if(adoption.ok){const now=clock(),notice=worktreeAdoptionNotice(repo,adoption.adopted,now);notice!==null&&store.enqueueNotification(notice,now)}if(!adoption.ok)return fail(write,json,"reconcile","git",adoption.message,EXIT.failed,{recovered,reaped:reaped.map(claim=>claim.leaseId)});let landed={completed:[],steps:[]};const remotes=new RemoteMains(store,context.gitRunner,context.evidenceRoot);try{landed=await reconcileLanded(store,worktrees,gitOf(context.gitRunner),remotes,repo,context.evidenceRoot,clock)}catch{}finally{remotes.close()}const landedGone=landed.steps.filter(one=>one.outcome==="removed");let tidied=[];try{tidied=runTidy(store,clock(),releaseFactsFor(context.databaseFile),TIDY_PASS_LIMIT,{principal:"operator",repos:[repo],includeUnplaced:!1})}catch{}try{reevaluateResultRecords(store,canonicalProject(repo)??resolve(repo),context.evidenceRoot,clock())}catch{}try{routeRulesPass(store,canonicalProject(repo)??resolve(repo),clock())}catch{}const closedCheckouts=await closeOutCheckouts(store,clock,finishedCheckouts(store,clock(),repo)),pruned=await cleanCheckouts(store,worktrees,clock,{manual:!1,actor:"worker",repo}),slimmed=await slimKeptCheckouts(store,worktrees,clock,{actor:"worker",repo});let retention=null;try{retention=dailyRetention(store,context.evidenceRoot,clock())}catch{retention=null}const retained=retention===null?[]:retention.counts.filter(one=>one.count>0);let storageSwept=null;if(context.sweepOwner!==void 0)try{storageSwept=idleStorageSweep(store,{databaseFile:context.databaseFile,pool:worktrees,tempRoots:context.tempRoots??tempRoots(),owner:context.sweepOwner},clock)}catch{storageSwept=null}const swept=storageSwept===null?[]:storageSwept.parts.filter(one=>one.count>0),nothing=retained.length===0&&swept.length===0&&recovered.length===0&&reaped.length===0&&adoption.adopted.length===0&&adoption.forgotten.length===0&&pruned.removed.length===0&&closedRuns.length===0&&closedCheckouts.length===0&&slimmed.slimmed.length===0&&landed.completed.length===0&&landedGone.length===0&&tidied.length===0&&liveSwept.removed.length===0;return succeed(write,json,"reconcile",{recovered,reaped:reaped.map(claim=>claim.leaseId),adopted:adoption.adopted,forgotten:adoption.forgotten,checkoutsRemoved:pruned.removed.map(one=>one.path),checkoutsKept:pruned.kept,processesStopped:[...closedRuns.map(one=>({run:one.runId,pids:one.done.stopped.map(row=>row.pid)})),...closedCheckouts.map(one=>({checkout:one.path,pids:one.done.stopped.map(row=>row.pid)}))],checkoutsSlimmed:slimmed.slimmed.map(one=>one.path),landed:{completed:landed.completed,steps:landed.steps},tidied:tidied.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),liveViewsSwept:liveSwept.removed.length,retention:retention===null?null:{counts:retention.counts,freedBytes:retention.freed},storageSweep:storageSwept},()=>nothing?["Nothing to reconcile. Everything is where it should be."]:[...recovered.map(one=>`Recovered ${one.runner}: ${one.claims.length} claim(s) requeued, ${one.worktrees.length} worktree(s) handed back unverified.`),...reaped.length===0?[]:[`Reaped ${reaped.length} expired lease(s).`],...adoption.adopted.map(path=>`Adopted ${path} — released, unverified, somebody should look.`),...adoption.forgotten.map(path=>`Forgot ${path} — its directory is gone.`),...pruned.removed.length===0?[]:[`Removed ${pruned.removed.length} finished task checkout(s), about ${bytesWords(pruned.freed)}; their branches stay.`],...closedRuns.map(one=>`Run #${one.runId} ended; stopped ${stoppedWords(one.done)}.`),...closedCheckouts.map(one=>`${one.path}: its task finished; stopped ${stoppedWords(one.done)}.`),...landed.completed.length===0?[]:[`Marked ${landed.completed.length} landed result(s) complete: ${landed.completed.join(", ")}.`],...tidied.length===0?[]:[`Put away ${tidied.length} old task(s): ${tidied.map(one=>one.taskId).join(", ")}.`],...landedGone.length===0?[]:[`Removed landed work: ${landedGone.filter(one=>one.kind==="checkout").length} checkout(s), ${landedGone.filter(one=>one.kind==="branch").length} local branch(es).`],...slimmed.slimmed.length===0?[]:[`Dropped dependencies and build output from ${slimmed.slimmed.length} kept checkout(s), about ${bytesWords(slimmed.slimmed.reduce((sum,one)=>sum+one.bytes,0))}.`],...liveSwept.removed.length===0?[]:[`Cleared ${liveSwept.removed.length} finished live view(s).`],...retention===null||retained.length===0?[]:[`Retention removed ${sweepWords(retention.counts,retention.freed)}.`],...storageSwept===null||swept.length===0?[]:[`Storage sweep: ${storageSweepWords(storageSwept.parts)}`]])}function gapsCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),gaps=computeGaps(store,repo,clock());if(json)return write(envelopeJson({ok:!0,command:"gaps",repo,gaps})),gaps.length===0?EXIT.ok:EXIT.refused;if(gaps.length===0)return write(`No gaps for ${repo}. Everything recorded is verified.`),EXIT.ok;for(const gap of gaps){const freed=gap.unblocks.length>0?`fills → ${gap.unblocks.length} task(s) start: ${gap.unblocks.join(", ")}`:gap.alsoBlocks.length>0?`part of what holds: ${gap.alsoBlocks.join(", ")}`:"nothing queued needs it yet";write(` ${gap.key.padEnd(28)} ${gap.state}`),write(` ${freed}`),write(` verify: ${gap.verify}`),write(` ${gap.instructions}`)}return EXIT.refused}async function briefCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),episode=flags.has("latest-watch")?store.latestWatchEpisode(repo):null;if(flags.has("latest-watch")&&episode===null)return fail(write,json,"brief","no-watch","no watch episode recorded for this repo yet — run `toolroll watch` first",EXIT.refused);const since=episode?.startedAt??text(flags,"since")??new Date(clock().getTime()-1440*6e4).toISOString();let runs=store.runsSince(since);episode!==null&&(runs=runs.filter(one=>one.runner===episode.runner&&(episode.endedAt===null||one.startedAt<=episode.endedAt)));const{built,failed,refused,cutDown,invoked,measured,spend,tokens}=tally(runs),gaps=computeGaps(store,repo,clock()),pending=store.pendingForAttention(),decisions=store.listDecisions("unanswered"),incidents=store.openIncidents(),stranded=store.strandedTasks();let review;if(flags.has("local"))review={state:"not-read",why:"--local, the network was not asked"};else{const read=await readPulls(repo);review=read.problems.length>0&&read.pulls.length===0?{state:"not-read",why:read.problems[0]??"unreadable"}:{state:"read",pulls:read.pulls.map(one=>({number:one.number,title:one.title}))}}if(json)return write(envelopeJson({ok:!0,command:"brief",repo,since,episode,tally:{built,failed,refused,cutDown},economics:{invocations:invoked.length,measured:measured.length,costUsd:spend,tokens},gaps,review,outboxPending:pending.length,decide:decisions,incidents,stranded})),EXIT.ok;const lines=[`toolroll — the report ─ ${repo}`];episode!==null&&lines.push(` episode watch #${episode.id} on ${episode.runner} · ${episode.startedAt} → ${episode.endedAt??"never ended — it is running, or it died without saying"}`),lines.push(` runs ${built.length} built · ${failed.length} failed · ${refused.length} refused${cutDown.length>0?` · ${cutDown.length} cut down mid-flight`:""}`);const proofVerdicts=store.proofVerdictsFor(built.map(one=>one.id));for(const one of built){const verdict=proofVerdicts.get(one.id),accepted=verdict!==void 0&&store.proofAcceptance(one.id)!==null,proofNote=verdict===void 0||accepted||verdict.verdict!=="short"&&verdict.verdict!=="refuted"?"":` — ${proofVerdictWords(verdict.verdict,verdict.reasons).word}`;lines.push(` ${one.taskId.padEnd(20)} ${one.committed===!0?`committed to ${one.branch}`:"changed nothing, which is a real answer"}${proofNote}`)}for(const one of failed)lines.push(` ${one.taskId.padEnd(20)} failed: ${one.reason??"?"}${one.worktree===null?"":` — work kept in ${one.worktree}`}`);for(const one of cutDown)lines.push(` ${one.taskId.padEnd(20)} never finished — the process died with it; \`task show ${one.taskId}\``);if(lines.push(` spend ${spendLine({built,failed,refused,cutDown,invoked,measured,spend,tokens})}`),gaps.length>0){const best=gaps[0];lines.push(` ▸ BLOCKED ${gaps.length} gap(s)${best.unblocks.length>0?` — filling ${best.key} starts ${best.unblocks.length} task(s)`:""}`);for(const gap of gaps)lines.push(` ${gap.key.padEnd(28)} ${gap.state}`);lines.push(` → toolroll gaps --repo ${repo}`)}if(lines.push(review.state==="read"?` ▸ REVIEW ${review.pulls.length} PR(s)${review.pulls.length>0?"":" — nothing waits"}`:` ▸ REVIEW not read — ${review.why}`),review.state==="read")for(const pull of review.pulls)lines.push(` #${pull.number} ${pull.title}`);if(pending.length>0&&lines.push(` ▸ OUTBOX ${pending.length} undelivered — toolroll outbox list`),decisions.length>0){const overdue=decisions.filter(one=>one.state==="expired").length;lines.push(` ▸ DECIDE ${decisions.length} waiting${overdue>0?` (${overdue} overdue)`:""} — toolroll decide`);for(const one of decisions)lines.push(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}`)}else lines.push(" ▸ DECIDE nothing waits on you");if(stranded.length>0){lines.push(` ▸ STRANDED ${stranded.length} task(s) behind failed blockers — they will never become ready on their own`);for(const one of stranded)lines.push(` ${one.id.padEnd(20)} waits on ${one.blockedBy.join(", ")} — \`toolroll task requeue ${one.blockedBy[0]}\``)}if(incidents.length>0){lines.push(` ▸ INCIDENTS ${incidents.length} unresolved — these do not age out`);for(const incident of incidents)lines.push(` ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} — read run ${incident.run}'s evidence, then \`toolroll incident resolve ${incident.id}\``)}return write(lines.join(`
479
+ `)),EXIT.ok}async function decideCommand(positional,flags,context){const{store,write,json,clock}=context;store.expireOverdueDecisions(clock());const[idText]=positional;if(idText===void 0){const waiting=store.listDecisions("unanswered");if(json)return write(envelopeJson({ok:!0,command:"decide",waiting})),waiting.length===0?EXIT.ok:EXIT.refused;if(waiting.length===0)return write("Nothing waits on you. No decisions were parked."),EXIT.ok;for(const one of waiting){const overdue=one.state==="expired"?" OVERDUE":"";write(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}${overdue}`),write(` options: ${one.options.map(option=>option.id).join(" · ")} recommended: ${one.recommendation}`)}return write(""),write(" → toolroll decide <id> the whole screen"),write(" → toolroll decide <id> --choose <option> --as <you> --token <t>"),EXIT.refused}const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"decide","usage","`toolroll decide [<id>] [--choose <option>]`",EXIT.usage);const decision=store.getDecision(id);if(decision===null)return fail(write,json,"decide","unknown-decision",`no decision ${id}`,EXIT.refused);const choice=text(flags,"choose");if(choice===void 0){const evidence=store.evidenceFor(id),run2=store.getRun(decision.run),taskId=run2===null?"?":store.externalIdFor(run2.taskRef)??"?";if(json)return write(envelopeJson({ok:!0,command:"decide",decision,taskId,evidence})),EXIT.ok;write(`${taskId} — ${decision.supersededReason!==null?"CLOSED":decision.state.toUpperCase()}${decision.deadline===null?"":` · deadline ${decision.deadline}`}`),write(""),write(` ${decision.recap}`),write(""),write(` ${decision.question}`),write("");for(const option of decision.options){const marks=[option.id===decision.recommendation?"recommended":"",option.reversible?"reversible":"IRREVERSIBLE"].filter(mark=>mark!=="").join(" · ");write(` [${option.id}] ${option.label} (${marks})`),write(` ${option.consequence}`)}if(decision.state==="answered"&&(write(""),write(decision.supersededReason!==null?` ${closedQuestionWords(decision.supersededReason)} (${decision.answeredAt})`:` answered: ${decision.choice} by ${decision.answeredBy} at ${decision.answeredAt}${decision.note===null?"":` — ${decision.note}`}`)),evidence.length>0){write("");for(const artifact of evidence)write(` evidence ${artifact.kind.padEnd(14)} ${artifact.key}${artifact.truncated?" (truncated)":""}`)}return decision.state!=="answered"&&(write(""),write(` → toolroll decide ${id} --choose <option> --as <you> --token <t>`)),EXIT.ok}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"decide",verified,"answering takes `--as <you> --token <t>` — who decided is recorded, not asserted",String(id));const{name:asWho}=acting,note=text(flags,"note"),answered=store.answerDecision({id,choice,by:asWho,via:"cli",...note===void 0?{}:{note}},clock(),mutationFrom(flags,clock()));if(!answered.ok){const why=answered.reason==="bad-option"?`"${choice}" is not one of this decision's options — \`toolroll decide ${id}\` shows them`:answered.reason==="already-answered"?`decision ${id} was already answered differently — "decided" is not negotiable; park a new task if the answer must change`:answered.reason==="closed"?`decision ${id}: ${closedQuestionWords(store.getDecision(id)?.supersededReason??"cancelled")} Nothing to answer.`:answered.reason==="bad-note"?"the note is too long or carries control characters":`no decision ${id}`;return fail(write,json,"decide",answered.reason,why,EXIT.refused)}return succeed(write,json,"decide",{decision:answered.decision,duplicate:answered.duplicate===!0},()=>answered.duplicate===!0?[`Decision ${id} was already answered with ${choice} — nothing changed.`]:[`Decided: ${choice} for decision ${id}, as ${asWho}.`,"The task returns to the ready set; the next tick resumes it with your answer in hand."])}export async function startConsole(options){const{context}=options,rehearsal=options.rehearsal===!0;rehearsal||noticeGitIncidents(context.store,context.clock);const identities=projectIdentities(context.folderLook),server=createDecisionServer({identities,store:context.store,backgroundChecks:!rehearsal,...rehearsal?{rehearsal:!0}:{},...context.desktopIdentity===void 0?{}:{desktopIdentity:context.desktopIdentity},...context.additionalProjectRepos===void 0||options.currentRepos===void 0?{}:{additionalProjectRepos:options.currentRepos},evidenceRoot:context.evidenceRoot,clock:context.clock,telegramTokenFile:context.telegramTokenFile,configDir:dirname(context.databaseFile),browserAssetCache:join(dirname(context.databaseFile),"browser-assets"),...options.localRunner===void 0?{}:{localRunner:options.localRunner},poolRoot:options.poolRoot,...options.allowedHosts===void 0?{}:{allowedHosts:options.allowedHosts},tailnetNames:rehearsal?(async()=>[]):context.tailnetNames??(()=>readTailnetNames()),leadByDefault:!0,...options.setupCode===void 0?{}:{setupCode:options.setupCode},...options.repos===void 0?{}:{repos:options.repos},...options.projectRoots===void 0?{}:{projectRoots:options.projectRoots},...options.currentRepos===void 0?{}:{currentRepos:options.currentRepos},...options.admittedRepos===void 0?{}:{admittedRepos:options.admittedRepos},...options.publicUrl===void 0?{}:{publicUrl:options.publicUrl},...options.registryPath===void 0?{}:{registryPath:options.registryPath},...options.upConsole===void 0?{}:{upConsole:options.upConsole},...options.editorLinks===void 0?{}:{editorLinks:options.editorLinks},...options.instanceSecret===void 0?{}:{instanceSecret:options.instanceSecret},...options.draining===void 0?{}:{draining:options.draining},...options.keyEpoch===void 0?{}:{keyEpoch:options.keyEpoch},browserKey:!0});await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>resolve2())}).catch(error=>{throw new Error(`could not listen on ${options.host}:${options.port} — ${describe(error)}`)});const bound=server.address(),port=typeof bound=="object"&&bound!==null?bound.port:options.port,shown=options.host==="0.0.0.0"||options.host==="::"?"localhost":options.host;if(setImmediate(warmWorkspaceRenderer),rehearsal)return{server,port,url:`http://${shown}:${port}/`};consoleIdentitiesInBackground(identities,[...options.repos??[],...options.projectRoots??[],...context.store.listProjects().map(one=>one.path),...context.store.knownRepos()]);const stopMonitoring=startMonitoring({store:context.store,settings:()=>readMonitoring(dirname(context.databaseFile)),instance:options.publicUrl??hostname(),version:packageVersion()}),signIns=createConnectionChecker({store:context.store}),besideConsole=[stopMonitoring,startBudgetAlerts(context.store),startTokenNotices(context.store),startSignInProbes(context.store,signIns),startBackups(context.store,context.databaseFile),startCodexLimits(context.store,()=>codexSignedInNow(signIns)),startUpdateChecks(context.store,dirname(context.databaseFile),PACKAGE_VERSION,installMethod(context.installBin).updateCommand,context.releaseIo??{})];return server.on("close",()=>{for(const stop of besideConsole)stop()}),{server,port,url:`http://${shown}:${port}/`}}async function serveCommand(flags,context){const{store,write,json}=context,portGiven=text(flags,"port"),port=Number(portGiven??4180),rehearsal=flags.get("rehearsal")===!0;if(portGiven!==void 0&&(!Number.isInteger(port)||port<(rehearsal?0:1)||port>=65536))return fail(write,json,"serve","usage","--port is a whole number under 65536",EXIT.usage);const host=text(flags,"host")??"127.0.0.1";if(rehearsal&&(host!=="127.0.0.1"||["allow-host","public-url","runner","editor","repo","project-root"].some(one=>flags.has(one))))return fail(write,json,"serve","usage","--rehearsal serves 127.0.0.1 only, with no --allow-host, --public-url, --runner, --editor, --repo or --project-root",EXIT.usage);const allow=text(flags,"allow-host"),repoFlag=text(flags,"repo"),rootFlag=text(flags,"project-root"),localRunner=text(flags,"runner"),poolRoot=text(flags,"pool")??join(dirname(context.databaseFile),"worktrees"),publicUrl=text(flags,"public-url"),editor=text(flags,"editor");if(editor!==void 0&&editor!=="vscode")return fail(write,json,"serve","usage","--editor supports: vscode",EXIT.usage);if(editor!==void 0&&localRunner===void 0)return fail(write,json,"serve","usage","--editor needs --runner <name> — links bind to the worktrees this machine's runner owns",EXIT.usage);const setupCode=store.listApprovers().length===0?String(randomInt(1e5,1e6)):void 0,console_=await startConsole({context,host,port,...rehearsal?{rehearsal:!0}:{},...setupCode===void 0?{}:{setupCode},...localRunner===void 0?{}:{localRunner},...publicUrl===void 0?{}:{publicUrl},...editor===void 0?{}:{editorLinks:"vscode"},registryPath:registryPathOf(context),poolRoot,...allow===void 0?{}:{allowedHosts:allow.split(",")},...repoFlag===void 0?{}:{repos:repoFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")},...rootFlag===void 0?{}:{projectRoots:rootFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")}}),server=console_.server,actual=console_.port,serveLifecycle=serveConsoleLifecycle(store,host,actual,context.clock);return serveLifecycle===null?(await closeServedConsole(server),fail(write,json,"serve","lifecycle","Toolroll couldn't record that this console is running, so it didn't start. Check the database, then run it again.",EXIT.refused)):(json?write(envelopeJson({ok:!0,command:"serve",host,port:actual,...setupCode===void 0?{}:{setupCode}})):setupCode!==void 0?(write(`The console is on http://${host}:${actual}/`),write(`No account yet. Open http://${host==="0.0.0.0"?"localhost":host}:${actual}/login and enter setup code ${setupCode} to create the first one.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")):(write(`The console is on http://${host}:${actual}/ — sign in with your username and password.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")),await new Promise(resolve2=>{const stop=()=>server.close(()=>resolve2());process.once("SIGINT",stop),process.once("SIGTERM",stop)}),serveLifecycle(),EXIT.ok)}async function requeueTask(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task requeue","usage","`toolroll task requeue <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"task requeue","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task requeue",verified,"requeueing takes `--as <you> --token <t>` — who overrode the stall is recorded, not asserted",id);const{name:asWho}=acting,result=store.requeueTask(id,asWho,clock());if(!result.ok){const why={"unknown-task":`no task ${id}`,"not-stalled":`${id} has nothing to rerun: it is queued or running, or it finished without a rejected result`,claimed:`a runner holds ${id} right now — wait for the attempt to end, or stop it`,"accepted-result":`${id}'s last result was accepted; change it through a revision, not a rerun`,published:`${id}'s last result is published; revise it through its pull request`,moved:`${id} changed since its page was read; read it again`,stale:`${id} changed since its page was read; read it again`,archived:`${id} is put away — restore it with \`toolroll task restore ${id}\` first`};return fail(write,json,"task requeue",result.reason,why[result.reason],EXIT.refused)}return succeed(write,json,"task requeue",{id,resolvedIncidents:result.resolvedIncidents,rejectedRun:result.rejectedRun},()=>[result.rejectedRun!==null?`${id} is queued again: attempt #${result.rejectedRun} was not accepted, so the next attempt continues on the same branch under the current scope. Re-scope first if the candidate changed.`:`${id} is queued again${result.resolvedIncidents>0?`, ${result.resolvedIncidents} incident(s) resolved`:""}. Strikes cleared; the next pass may take it.`])}async function regateTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task regate","usage","`toolroll task regate <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task regate",verified,"rerunning the check takes `--as <you> --token <t>` — the rerun scope is approved in your name",id);const result=regateTask(store,id,clock(),{kind:"operator",name:acting.name,token:acting.token});return result.ok?succeed(write,json,"task regate",{id,run:result.run,head:result.head},()=>[`${id} is queued again: the approved check runs on commit ${result.head.slice(0,7)}, the same files attempt #${result.run} checked, with no agent. A fresh review follows.`]):fail(write,json,"task regate",result.reason,result.message,EXIT.refused)}async function planTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task plan","usage","`toolroll task plan <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task plan",verified,"planning takes `--as <you> --token <t>` — it dispatches an agent that spends",id);if(store.getTask(id)===null)return fail(write,json,"task plan","refused",`no task ${id}`,EXIT.refused);const ref=store.refFor(BUILT_IN,id),pinProvider=text(flags,"provider"),pinModel=text(flags,"model");if(pinProvider!==void 0){if(!isProviderId(pinProvider))return fail(write,json,"task plan","usage",`unknown provider \`${pinProvider}\``,EXIT.usage);if(pinModel===void 0||pinModel==="")return fail(write,json,"task plan","usage","a plan pin names an exact --model with --provider — approvals bind exact routing",EXIT.usage);const valid=validateSpec({provider:pinProvider,model:pinModel});if(!valid.ok)return fail(write,json,"task plan","invalid",valid.problem,EXIT.usage);if(!store.setPlanPins(ref.id,pinProvider,pinModel,clock()).ok)return fail(write,json,"task plan","refused","a planner holds this task right now — the pin would reroute a live spend",EXIT.refused)}else if(pinModel!==void 0)return fail(write,json,"task plan","usage","--model rides --provider for a plan pin",EXIT.usage);const result=store.requestPlan(ref.id,clock());if(!result.ok)return fail(write,json,"task plan","refused",result.reason,EXIT.refused);const autoPlan=authorizePlanUnderMode(store,id,acting.name,clock());return succeed(write,json,"task plan",{id,autoPlan,...pinProvider===void 0?{}:{planProvider:pinProvider,planModel:pinModel??null}},()=>[`${id} will be planned before it is built: the next pass dispatches a planner${pinProvider===void 0?"":` on ${pinProvider}${pinModel===void 0?"":` · ${pinModel}`}`}.`,autoPlan?"An unchanged, verified plan can auto-approve under your signed mode. Amendments and questions still wait for you.":"Its questions reach you like any decision; its plan lands as a scope for you to edit and approve."])}async function reviewTaskCommand(positional,flags,context){const{store,write,json}=context;if(flags.has("brief")){const allowed=new Set(["brief","all","run","json","db","as","token"]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,"task review","usage",`--${name} is not a task review --brief option.`,EXIT.usage);const task=positional[0],selected=flags.get("run");if(positional.length!==1||!task||task.length>64||/[\x00-\x1f\x7f]/.test(task)||selected!==void 0&&(typeof selected!="string"||!/^[1-9]\d*$/.test(selected)||!Number.isSafeInteger(Number(selected))))return fail(write,json,"task review","usage","Use toolroll task review <task> --brief [--run <id>] [--all] [--json].",EXIT.usage);let viewer=currentActor()?.account??null;if(viewer===null&&(flags.has("as")||flags.has("token"))){const acting=await askCredentials(flags,context);if(acting===null||!authenticateApprover(store,acting.name,acting.token).ok)return fail(write,json,"task review","unauthenticated","That sign-in is not valid.",EXIT.refused);viewer=acting.name}const repos=viewer===null?null:store.knownRepos().filter(repo=>store.accountCanAccess(viewer,repo)),result=taskReviewBrief(store,task,context.evidenceRoot,context.now,{principal:"operator",repos,includeUnplaced:viewer===null},{...selected===void 0?{}:{run:Number(selected)},all:flags.has("all"),secrets:[context.leadToken??"",text(flags,"token")??""]});return result.ok?succeed(write,json,"task review",{brief:result.brief},()=>renderReviewBrief(result.brief)):fail(write,json,"task review",result.reason,result.message,EXIT.refused)}if(flags.has("run")||flags.has("all"))return fail(write,json,"task review","usage","--run and --all require --brief.",EXIT.usage);const[runText]=positional,runId=Number(runText??"");if(runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task review","usage","`toolroll task review <run-id>`",EXIT.usage);const review=buildReviewOf(store,runId);return review!==null?succeed(write,json,"task review",{run:runId,review},()=>[`Run ${runId}`,...buildReviewLines(review)]):fail(write,json,"task review","model-review-retired",`Run ${runId} has no automatic review. Manual review requests have been removed; a project's builds are reviewed automatically when its switch is on (\`toolroll review on --repo <path>\`). Inspect the saved work and checks, then give feedback or request a revision.`,EXIT.refused)}async function incidentCommand(positional,flags,context){const{store,write,json,clock}=context,[action,idText]=positional;if(action===void 0||action==="list"){const incidents=store.openIncidents();if(json)return write(envelopeJson({ok:!0,command:"incident list",incidents})),incidents.length===0?EXIT.ok:EXIT.refused;if(incidents.length===0)return write("No unresolved incidents."),EXIT.ok;for(const incident of incidents)write(` ${String(incident.id).padEnd(4)} ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} run ${incident.run}`);return write(""),write(" → toolroll incident resolve <id> --as <you> --token <t>"),EXIT.refused}if(action!=="resolve")return fail(write,json,"incident","usage","`toolroll incident [list|resolve <id>]`",EXIT.usage);const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"incident resolve","usage","`toolroll incident resolve <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"incident resolve","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"incident resolve",verified,"resolving takes `--as <you> --token <t>` — who looked is recorded, not asserted",String(id));const{name:asWho}=acting;return store.resolveIncident(id,asWho,clock())?succeed(write,json,"incident resolve",{id,by:asWho},()=>[`Resolved incident ${id}, as ${asWho}. The task's hold is lifted; the next tick may take it.`]):fail(write,json,"incident resolve","unknown-or-resolved",`no unresolved incident ${id}`,EXIT.refused)}async function webhookCommand(positional,_flags,context){const{write,json}=context,dir=dirname(context.databaseFile),[action,which,value]=positional,telegramConfigured=loadBotToken(process.env,context.telegramTokenFile)!==null;if(action===void 0||action==="status"){const consoleUrl=loadConsoleUrl(process.env,dir),primary=effectivePrimary(process.env,dir,telegramConfigured);if(json)return write(envelopeJson({ok:!0,command:"webhook status",configured:primary.configured,primary:primary.channel,implicit:primary.implicit,consoleUrl})),EXIT.ok;write(`Messaging${primary.configured.length===0?": nothing configured":""}`);for(const channel of primary.configured)write(` ${channel.padEnd(8)} connected${channel===primary.channel?" ← receives alerts":" (silent — not primary)"}`);return primary.implicit&&primary.channel!==null&&(write(` ! several services are connected and none was chosen — ${primary.channel} receives alerts by default.`),write(" Choose: toolroll webhook primary telegram|slack|discord")),write(` links ${consoleUrl??"NOT SET — messages will carry no console link; toolroll webhook set console-url http://host:port"}`),EXIT.ok}if(action==="primary")return which===void 0||!isMessagingChannel(which)?fail(write,json,"webhook primary","usage","primary is one of telegram, slack, discord",EXIT.usage):effectivePrimary(process.env,dir,telegramConfigured).configured.includes(which)?(savePrimary(dir,which),succeed(write,json,"webhook primary",{primary:which},()=>[`Alerts now go to ${which}. ${which==="telegram"?"Buttons and replies work there as always.":"Telegram (if configured) still accepts taps and replies — it just stops sending alerts."}`])):fail(write,json,"webhook primary","unconfigured",`${which} is not configured — set it up first, then choose it`,EXIT.refused);if(action!=="set"||which!=="console-url"||value===void 0)return fail(write,json,"webhook","usage","`toolroll webhook [status|primary <service>|set console-url <url>]`",EXIT.usage);const saved=saveConsoleUrl(dir,value);return saved.ok?succeed(write,json,"webhook set",{which},()=>[`Console links will open ${value.replace(/\/+$/,"")}.`]):fail(write,json,"webhook set","invalid",saved.message,EXIT.usage)}function resumeProviderCommand(positional,flags,context){const{store,write,json}=context,command="providers resume",provider=positional[0];if(provider===void 0||!isProviderId(provider)||positional.length>1)return fail(write,json,command,"usage",`Use \`toolroll providers resume <${PROVIDER_IDS.join("|")}>\`.`,EXIT.usage);const who=text(flags,"as")??process.env.USER??"operator",lifted=liftAuthPause(store,provider,"person",who,context.clock());return lifted===null?succeed(write,json,command,{provider,resumed:0,paused:!1},()=>[`${provider} is not paused.`]):succeed(write,json,command,{provider,resumed:lifted.resumed,paused:!1},()=>[`${provider} resumed — ${lifted.resumed} ${lifted.resumed===1?"task":"tasks"} can start again.`])}async function providersCommand(flags,context){const{store,write,json}=context,probe=context.gitRunner??run,configured=new Map;for(const scope of[INSTALLATION_SCOPE])for(const row of store.listPhaseConfig(scope))configured.set(row.provider,[...configured.get(row.provider)??[],row.phase]);const probed=await Promise.all(PROVIDER_IDS.map(async id=>{const facts=inspectionOf(id);if(isAcpProvider(id)){const seen=resolveAcpAgentForRunner(id),version2={code:seen.found?0:127,stdout:seen.found?seen.package?.version??"":"",stderr:"",notFound:!seen.found,timedOut:!1};return{id,facts,version:version2,installed:seen.found,identity:seen.found?`not checked on this computer — run \`toolroll agents check ${id}\``:null}}const version=await probe(facts.binary,["--version"],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV}),installed=version.code===0&&!version.notFound;let identity=null;if(installed&&facts.identityProbe!==null){const asked=await probe(facts.binary,[...facts.identityProbe],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV});identity=asked.code===0?asked.stdout.trim().split(`
463
480
  `)[0]??null:"not logged in"}return{id,facts,version,installed,identity}})),report=[];for(const{id,facts,version,installed,identity}of probed){const lastSuccess=store.providerLastSuccess(id),keyPresent=facts.requiresEnv===null?null:(process.env[facts.requiresEnv]??"")!=="",installedVersion=installed?version.stdout.trim().split(`
464
481
  `)[0]??"":null;report.push({provider:id,binary:facts.binary,installed,version:installedVersion,identity,lastSuccessfulRun:lastSuccess,...keyPresent===null?{}:{keyPresent,keyEnv:facts.requiresEnv},measuresCost:facts.measuresCost,configuredPhases:configured.get(id)??[],audit:auditOf(id),...attestationOf(id)===null?{}:{attestation:{...attestationOf(id),installedInRange:installed&&versionInRange(version.stdout.trim().split(`
465
- `)[0]??"",attestationOf(id))}}})}let recorded=null;if(flags.has("report")){const runnerName=text(flags,"runner"),runnerToken=text(flags,"token");if(runnerName===void 0||runnerToken===void 0)return fail(write,json,"providers","usage","`toolroll providers --report --runner <name> --token <t>` records readiness under that runner",EXIT.usage);const observed=await observeProviderReadiness((file,args,options)=>probe(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)),reported=reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},context.clock());if(!reported.ok)return fail(write,json,"providers",reported.reason,describeAuth(reported.reason,runnerName),EXIT.refused);recorded=observed}if(json)return write(envelopeJson({ok:!0,command:"providers",providers:report,...recorded===null?{}:{readiness:recorded}})),EXIT.ok;if(recorded!==null){write(`readiness recorded for ${text(flags,"runner")??""}:`);for(const one of recorded)write(` ${one.provider.padEnd(11)}${one.state.toUpperCase()} — ${one.reason} [${one.probe}]`);write("")}for(const one of report){const name=String(one.provider);write(`${name}`),write(` installed ${one.installed===!0?`yes — ${String(one.version)}`:`no — \`${String(one.binary)}\` did not answer`}`),one.identity!==null&&one.identity!==void 0?write(` authenticated ${String(one.identity)} (probed just now, without spending)`):name==="claude"&&write(" authenticated not probed — no non-spending check exists; a real run is the proof"),write(` last success ${one.lastSuccessfulRun===null?"never on this installation":`${String(one.lastSuccessfulRun)} — login was valid then`}`),one.keyEnv!==void 0&&write(` ${String(one.keyEnv)} ${one.keyPresent===!0?"present (not validated — presence is not authorization)":"ABSENT — runs will fail until the runner exports it"}`),write(` cost ${one.measuresCost===!0?"measured in dollars per run":"tokens only — runs land as UNMEASURED; schedules with a weekly limit fail closed on them"}`);const phases=one.configuredPhases;phases.length>0&&write(` configured ${phases.join(", ")} (installation)`);const audit=one.audit;write(` transport ${audit.transport}${audit.initSignal==="none"?" — no init signal; a failed run cannot say whether the harness came up":` — init signal: ${audit.initSignal}`}`),write(` resume ${audit.resume}`);const attested=one.attestation;attested!==void 0&&write(` attested ${attested.floor} up to (not including) ${attested.ceiling}, fixtures at ${attested.fixturesAt} — ${attested.installedInRange?"the installed version is inside the range":"the INSTALLED VERSION IS OUTSIDE THE RANGE; dispatch will refuse until re-attestation"}`),write(` isolation ${audit.isolation.flag===null?"no hermetic flag":audit.isolation.enforced?`builds run in their own setup (${audit.isolation.flag}) — none of your own hooks, plugins or MCP servers; reviews keep theirs`:`${audit.isolation.flag} exists, not passed${audit.isolation.resumeSafe===!1?" — it would break session resume":audit.isolation.resumeSafe===null?" — its effect on resume is unvalidated":""}`}`),write(` ${audit.isolation.enforced?"builds get ":"config surface"} ${audit.configSurface.join("; ")}`),write("")}return write(" → toolroll config show which provider each phase actually resolves to"),EXIT.ok}async function agentsCommand(positional,flags,context){const{store,write,json,clock}=context,[action="list",provider,...rest]=positional,runners=store.listRunners().filter(one=>one.retiredAt===null).map(one=>one.name),runner=text(flags,"runner")??(runners.length===1?runners[0]:void 0);if(action==="list"){const rows=ACP_PROVIDER_IDS.map(id2=>{const seen=inspectAcpAgent(id2),checked=runners.flatMap(name2=>{const one=store.acpAttestationFor(id2,name2);return one===null?[]:[{runner:name2,agent:one.agent,models:one.models,at:one.recordedAt}]}),latest=store.acpChecksFor(id2,1)[0]??null;return{provider:id2,name:ACP_AGENTS[id2].name,installed:seen.found?seen.realpath:null,checked,latestCheck:latest===null?null:{id:latest.id,state:latest.state,model:latest.model,result:latest.result}}}),{detectAgents,detectionReport}=await import("./agent-detect.js"),{agentsReadOf}=await import("./engine-reads.js"),{acpCheckedHere,firstTaskRouted}=await import("./welcome-facts.js"),detection=await detectAgents({routed:firstTaskRouted(store),acpChecked:acpCheckedHere(store),store,...context.easySeams?.check===void 0?{}:{check:context.easySeams.check}}),{openRouterChatModels}=await import("./agent-thread/openrouter-chat.js"),{version:_version,...detected}=agentsReadOf(detection,"full",null,null,{piChatModels:()=>readPiConfiguredModels(),openRouterChatModels:()=>openRouterChatModels(store)});if(json)return write(envelopeJson({ok:!0,command:"agents",detected:{...detected,tookMs:detection.tookMs},agents:rows})),EXIT.ok;for(const line of detectionReport(detection))write(line);write(""),write("Agent checks");for(const row of rows){write(` ${row.name.padEnd(10)} ${row.installed===null?"not installed":row.installed}`);for(const one of row.checked)write(` checked on ${one.runner}: ${one.agent.name} ${one.agent.version}, ${one.models.length} models (${one.at.slice(0,10)})`);row.latestCheck!==null&&row.latestCheck.state!=="passed"&&write(` check #${row.latestCheck.id} (${row.latestCheck.model}): ${row.latestCheck.state}${row.latestCheck.result===null?"":` — ${row.latestCheck.result}`}`)}return write(" → `agents check <agent> --model <id>` asks this runner's watch to check one; it runs on the watch's next pass"),EXIT.ok}if(!["check","revoke","billing"].includes(action))return fail(write,json,"agents","usage","`toolroll agents [check|revoke|billing]`",EXIT.usage);if(provider===void 0||!isAcpProvider(provider))return fail(write,json,`agents ${action}`,"usage",`which agent? ${ACP_PROVIDER_IDS.join(", ")}`,EXIT.usage);if(runner===void 0||!runners.includes(runner))return fail(write,json,`agents ${action}`,"usage",`which runner? --runner ${runners.join(" | ")||"<name>"}`,EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`agents ${action}`,"usage","this takes your name and password — `--as <you>` and the hidden prompt",EXIT.usage);const verified=verifyApproverByPassword(store,acting.name,acting.token,store.knownRepos().filter(repo=>store.accountCanAccess(acting.name,repo)));if(!verified.ok)return fail(write,json,`agents ${action}`,"unauthenticated","that is not an approver, or the password does not match",EXIT.refused);if(!store.isInstanceOperator(verified.who.name))return fail(write,json,`agents ${action}`,"forbidden","only an installation operator can check, revoke or set billing for a runner's agents",EXIT.refused);const name=ACP_AGENTS[provider].name,now=clock();if(action==="revoke"){const revoked=store.revokeAcpAttestation(provider,runner,verified.who.name,now);return succeed(write,json,"agents revoke",{provider,runner,revoked},()=>[revoked?`${name} no longer runs on ${runner}; check it again to bring it back.`:`${name} wasn't checked on ${runner}.`])}if(action==="billing"){const[model2,kind]=rest;if(model2===void 0||!validModelId(model2)||kind!=="plan"&&kind!=="metered")return fail(write,json,"agents billing","usage","`agents billing <agent> <model> plan|metered`",EXIT.usage);const revision=store.declareAcpBilling({provider,runner,model:model2,kind,by:verified.who.name},now);return succeed(write,json,"agents billing",{provider,runner,model:model2,kind,revision},()=>[kind==="plan"?`${name} on ${model2} (${runner}) is billed by ${name}'s own plan: its runs count as $0, unmeasured, and monthly budgets don't hold them. Runs already started keep the terms they started with.`:`${name} on ${model2} (${runner}) is metered: its cost is unknown, so capped work and hard budgets hold it.`])}const model=text(flags,"model");if(model===void 0||!validModelId(model))return fail(write,json,"agents check","usage","`agents check <agent> --model <id>` — a model the agent offers (its own list shows after the check)",EXIT.usage);const id=store.requestAcpCheck({provider,runner,model,by:verified.who.name},now);return succeed(write,json,"agents check",{provider,runner,model,request:id},()=>[`Check #${id} asked for: ${name} on ${model}, on ${runner}. Its watch runs it on its next pass (two short runs, in the fence; the model's own spend).`,"→ `toolroll agents` shows how it went."])}async function keysCommand(positional,flags,context){const{write,json}=context,[action,provider,...rest]=positional;if(action===void 0||!KEYS_ACTIONS.includes(action))return fail(write,json,"keys","usage",`unknown \`keys ${action??""}\` — try ${KEYS_ACTIONS.join(", ")}`,EXIT.usage);if(action==="status"){const rows=PROVIDER_IDS.filter(isKeyedProvider).map(one=>({provider:one,envName:PROVIDER_KEY_ENV[one],...keyStatus(one),ambient:(process.env[PROVIDER_KEY_ENV[one]]??"")!==""}));if(json)return write(envelopeJson({ok:!0,command:"keys status",keys:rows})),EXIT.ok;for(const row of rows){const mode=readAuthMode(row.provider),state=row.set?`stored${row.updatedAt===null?"":` (${row.updatedAt.slice(0,10)})`}`:row.ambient?"environment only":"not set";write(` ${row.provider.padEnd(12)} ${row.envName.padEnd(22)} ${mode.padEnd(13)} ${state}`)}return write(" → subscription-mode providers use their own login; api-key mode hands over the stored (or ambient) key"),write(" → `keys auth <provider> subscription|api-key` switches; stored keys are kept either way"),EXIT.ok}if(provider===void 0||!isProviderId(provider))return fail(write,json,`keys ${action}`,"usage",`which provider? ${PROVIDER_IDS.filter(isKeyedProvider).join(", ")}`,EXIT.usage);if(!isKeyedProvider(provider))return fail(write,json,`keys ${action}`,"refused",`${ownSignInOf(provider).name} signs in its own way (\`${ownSignInOf(provider).signIn}\`) — Toolroll keeps no key for it`,EXIT.refused);if(action==="clear"){const forgotten=provider==="openrouter"?forgetOpenRouterKey({configDir:dirname(context.databaseFile)}):null,cleared=forgotten?.removed??clearProviderKey(provider),mode=readAuthMode(provider);return succeed(write,json,"keys clear",{provider,cleared,mode,warning:forgotten?.warning??null},()=>[forgotten?.warning??(cleared?mode==="subscription"?`The ${provider} key is removed. ${provider} uses its own login (subscription mode), so builds are unaffected.`:`The ${provider} key is removed — an environment variable, if one exists, takes over.`:"No stored key to remove.")])}if(action==="verify"){const stored=readProviderKey(provider);if(stored===null)return fail(write,json,"keys verify","refused",`no stored ${provider} key to verify`,EXIT.refused);const verdict2=await verifyProviderKey(provider,stored);return succeed(write,json,"keys verify",{provider,verdict:verdict2},()=>[verdictWords(provider,verdict2)])}if(action==="auth"){const[wanted]=rest;return wanted!=="subscription"&&wanted!=="api-key"?fail(write,json,"keys auth","usage",`\`toolroll keys auth ${provider} subscription|api-key\``,EXIT.usage):setAuthMode(provider,wanted).ok?succeed(write,json,"keys auth",{provider,mode:wanted},()=>[wanted==="subscription"?`${provider} now uses its own login; its stored key is kept as the fallback you can switch to.`:`${provider} now uses its API key; switch back with \`keys auth ${provider} subscription\`.`]):fail(write,json,"keys auth","refused",`${provider} has no subscription login — it is api-key only`,EXIT.refused)}const file=text(flags,"key-file");let value;if(file!==void 0)try{value=readFileSync(file,"utf8")}catch{return fail(write,json,"keys set","usage",`cannot read \`${file}\``,EXIT.usage)}else{if(process.stdin.isTTY)return fail(write,json,"keys set","usage","pipe the key in (`toolroll keys set gemini < key.txt` or via --key-file) — a key on an argv is visible to every process list",EXIT.usage);const chunks=[];for await(const chunk of process.stdin)chunks.push(chunk);value=Buffer.concat(chunks).toString("utf8")}if(!(provider==="openrouter"?saveOpenRouterKey(value,{configDir:dirname(context.databaseFile)}):saveProviderKey(provider,value)).ok)return fail(write,json,"keys set","implausible","that does not look like an API key — check the paste",EXIT.refused);const verdict=flag(flags,"no-verify")?null:await verifyProviderKey(provider,value);return succeed(write,json,"keys set",{provider,...verdict===null?{}:{verdict}},()=>[`The ${provider} key is stored (a private file, handed only to ${provider}'s own process at spawn).`,...verdict===null?[]:[verdictWords(provider,verdict)]])}async function peopleCommand(positional,flags,context){const{store,write,json,clock}=context,[action,...rest]=positional;if(action===void 0||!PEOPLE_ACTIONS.includes(action))return fail(write,json,"people","usage",`unknown \`people ${action??""}\` — try ${PEOPLE_ACTIONS.join(", ")}`,EXIT.usage);if(action==="list"){const accounts=store.accountFacts(),invites=store.openInvites(clock());if(json)return write(envelopeJson({ok:!0,command:"people list",accounts,invites})),EXIT.ok;if(accounts.length===0)return write("Nobody yet — `toolroll approver add <name>` bootstraps the first."),EXIT.ok;for(const one of accounts){const standing=one.revokedAt!==null?`revoked ${one.revokedAt.slice(0,10)} by ${one.revokedBy??"?"}`:one.role==="approver"?"approves":"watches";write(` ${one.name.padEnd(20)} ${standing.padEnd(28)} joined ${one.addedAt.slice(0,10)} · ${one.projects===null?"all projects":one.projects.length===0?"no projects":one.projects.join(", ")}`)}for(const one of invites)write(` (invite) ${one.role} invite from ${one.mintedBy}, expires ${one.expiresAt.slice(0,16).replace("T"," ")}`);return EXIT.ok}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`people ${action}`,"usage",`\`toolroll people ${action} … --as <you> --token <t>\``,EXIT.usage);const authenticated=action==="revoke"?authenticateApprover(store,acting.name,acting.token):credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,`people ${action}`,authenticated.reason,describeApproveFailure(authenticated.reason,acting.name),EXIT.refused);const repoGiven=text(flags,"repo"),allProjects=flags.has("all-projects"),noProjects=flags.has("no-projects");if([repoGiven!==void 0,allProjects,noProjects].filter(Boolean).length>1)return fail(write,json,`people ${action}`,"usage","Choose --repo <path>, --all-projects, or --no-projects.",EXIT.usage);const repo=repoGiven===void 0?null:canonicalProject(repoGiven);if(repoGiven!==void 0&&repo===null)return fail(write,json,`people ${action}`,"usage","The project folder must exist.",EXIT.usage);const projects=repo!==null?[repo]:noProjects?[]:null;if(action==="projects"){const name2=rest[0]?.trim();if(!name2||repoGiven===void 0&&!allProjects&&!noProjects)return fail(write,json,"people projects","usage","people projects <name> --repo <path> | --all-projects | --no-projects --as <you> --token <t>",EXIT.usage);const changed=store.setAccountProjects(name2,projects,acting.name,clock());return changed.ok?succeed(write,json,"people projects",{name:name2,projects},()=>[`${name2}: ${projects===null?"all projects":projects.length===0?"no project access":projects.join(", ")}. Access changes end existing sign-in sessions and derived authority.`]):fail(write,json,"people projects",changed.reason,"Project access was not changed: "+changed.reason,EXIT.refused)}if(action==="invite"){const roleFlag=text(flags,"role")??"viewer";if(roleFlag!=="viewer"&&roleFlag!=="approver")return fail(write,json,"people invite","usage","--role viewer|approver (viewer is the default)",EXIT.usage);if(noProjects)return fail(write,json,"people invite","usage","An invitation needs --repo <path> or all-project access.",EXIT.usage);const minted=store.mintInvite(roleFlag,acting.name,clock(),void 0,projects);return succeed(write,json,"people invite",{role:roleFlag,projects,path:`/join/${minted.token}`,expiresAt:minted.expiresAt},()=>[`The invite link's path — shown once, single-use, ${roleFlag==="approver"?"they can approve and act":"they can read work"} in ${projects===null?"all projects":projects.join(", ")}:`,` /join/${minted.token}`,`Open it on this console's address. It dies ${minted.expiresAt.slice(0,16).replace("T"," ")} UTC, or when you cancel it on the people screen.`])}const[name]=rest;if(name===void 0||name.trim()==="")return fail(write,json,"people revoke","usage","`toolroll people revoke <name> --as <you> --token <t>`",EXIT.usage);const severed=store.revokeAccount(name.trim(),acting.name,clock());if(!severed.ok){const words=severed.reason==="last-approver"?"that is the last account that can approve — add another approver first":severed.reason==="already-revoked"?`${name} is already removed`:`no account \`${name}\``;return fail(write,json,"people revoke",severed.reason,words,EXIT.refused)}return succeed(write,json,"people revoke",{name:name.trim(),...severed},()=>[`${name.trim()} can no longer sign in. Their open sessions, invites, and the ${severed.modesRevoked} mode(s) they signed ended with them.`,"Everything they ever approved or decided stays in the ledger, under their name."])}const MODE_ACTIONS=["set","show","revoke"];async function chatApprovalCommand(positional,flags,context){const{store,write,json,clock}=context,action=positional[0]??"show",command=`chat-approval ${action}`;if(!["show","on","off"].includes(action))return fail(write,json,"chat-approval","usage","Use chat-approval show | on | off [--repo <path>] [--full-access] [--cap-usd <n>] [--yes].",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"unauthenticated","Approving from chat is your own setting: pass --as <you> --token <your password> (or sign in once with toolroll up).",EXIT.refused);if(!(action==="on"?credentialApprover(store,acting.name,acting.token):authenticateApprover(store,acting.name,acting.token)).ok)return fail(write,json,command,"unauthenticated","That name and password aren't an approver's. Nothing was changed.",EXIT.refused);const given=text(flags,"repo"),scope=given===void 0?ALL_PROJECTS:canonicalProject(given)??resolve(given);if(scope!==ALL_PROJECTS&&!store.accountCanAccess(acting.name,scope))return fail(write,json,command,"unknown-project","That isn't one of your projects.",EXIT.refused);const where=scope===ALL_PROJECTS?"all your projects":projectName(scope);if(action==="show"){const rows=chatApprovalSettings(store,acting.name).map(one=>({scope:one.scope===ALL_PROJECTS?"all":one.scope,enabled:one.enabled,fullAccess:one.fullAccess,capMicrousd:one.capMicrousd,updatedAt:one.updatedAt}));return succeed(write,json,command,{settings:rows},()=>rows.length===0?["Approving from chat is off everywhere. Turn it on: toolroll chat-approval on [--repo <path>]"]:rows.map(one=>`${one.scope==="all"?"All projects":projectName(one.scope)}: ${one.enabled?`on · ${chatApprovalWords(one)}`:"off"}`))}const now=clock();if(action==="off"){const saved2=setChatApproval(store,{approver:acting.name,scope,enabled:!1,via:"the command line"},now);return saved2.ok?succeed(write,json,command,{applied:!0,scope:scope===ALL_PROJECTS?"all":scope},()=>[saved2.said]):fail(write,json,command,"refused",saved2.message,EXIT.refused)}const usd=text(flags,"cap-usd"),cap=usd===void 0?null:Number(usd);if(cap!==null&&!(Number.isFinite(cap)&&cap>=0&&cap<=1e4))return fail(write,json,command,"usage","Give --cap-usd in dollars, like 5.",EXIT.usage);const limits={fullAccess:flag(flags,"full-access"),capMicrousd:cap===null?null:Math.round(cap*1e6)},terms=[`Your own taps in your paired chat approve plans and merges in ${where}, until you turn it off: it doesn't expire.`,`Limits: ${chatApprovalWords(limits)}.`,"Plans written for you, protected paths, two-person rules and your organisation's policy still open in Toolroll."];if(!flag(flags,"yes"))return succeed(write,json,command,{applied:!1,scope:scope===ALL_PROJECTS?"all":scope,terms},()=>[`Turn on approving from chat for ${where}`,...terms.map(one=>` ${one}`),"","Nothing has changed. Add --yes to make this change."]);const saved=setChatApproval(store,{approver:acting.name,scope,enabled:!0,limits,via:"the command line"},now);return saved.ok?succeed(write,json,command,{applied:!0,scope:scope===ALL_PROJECTS?"all":scope,terms},()=>[saved.said]):fail(write,json,command,"refused",saved.message,EXIT.refused)}async function modeCommand(positional,flags,context){const{store,write,json,clock}=context,[action]=positional;if(action===void 0||!MODE_ACTIONS.includes(action))return fail(write,json,"mode","usage",`unknown \`mode ${action??""}\` — try ${MODE_ACTIONS.join(", ")}`,EXIT.usage);const repoGiven=text(flags,"repo"),repo=repoGiven===void 0?void 0:canonicalProject(repoGiven)??resolve(repoGiven);if(repo===void 0)return fail(write,json,"mode","usage","`mode` needs --repo <canonical path> — a mode is per-repository",EXIT.usage);const now=clock();if(action==="show"){const mode=store.activeMode(repo,now);if(mode===null)return succeed(write,json,"mode show",{repo,active:null},()=>[`${repo}: locked — every act keeps its own ceremony (the default).`]);const terms2=modeTermsFromJson(mode.termsJson);return succeed(write,json,"mode show",{repo,active:{name:mode.name,signedBy:mode.signedBy,expiry:mode.absoluteExpiry,digest:mode.digest}},()=>[`${repo}: ${mode.name}, signed by ${mode.signedBy}`,...terms2===null?[]:modeWords(terms2).map(w=>` ${w}`),` → mode revoke --repo ${repo} --as ${mode.signedBy} --token <t> (or any approver; one click)`])}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"mode","usage","signing or revoking a mode takes `--as <you> --token <t>`",EXIT.usage);const authed=flag(flags,"chat-approve")||flag(flags,"repair-auto")?credentialApprover(store,acting.name,acting.token):authenticateApprover(store,acting.name,acting.token);if(!authed.ok)return fail(write,json,"mode",authed.reason,"that is not an active approver, or the token does not match",EXIT.refused);if(action==="revoke")return store.revokeMode(repo,acting.name,"operator",now)?succeed(write,json,"mode revoke",{repo},()=>[`${repo}: mode revoked. Every act it covered falls back to its own ceremony; running work is untouched.`]):fail(write,json,"mode revoke","no-mode",`${repo} has no active mode`,EXIT.refused);const nameGiven=text(flags,"name")??"standard";if(nameGiven!=="standard"&&nameGiven!=="hands-off")return fail(write,json,"mode set","usage","--name is standard or hands-off",EXIT.usage);const daysGiven=Number(text(flags,"days")??"1");if(!Number.isInteger(daysGiven)||daysGiven<1||daysGiven>MODE_MAX_DAYS)return fail(write,json,"mode set","usage",`--days is 1 to ${MODE_MAX_DAYS} (a mode always expires)`,EXIT.usage);const expiry=new Date(now.getTime()+daysGiven*24*60*6e4).toISOString(),terms=presetTerms(nameGiven,expiry);if(text(flags,"publication")==="automerge"&&(terms.publication="automerge"),text(flags,"publication")==="notify"&&(terms.publication="notify"),flag(flags,"auto-approve")&&(terms.autoApproveFiling=!0),flag(flags,"plan-auto")&&(terms.planAuto=!0),["review-auto","review-retry-auto"].some(name=>flags.has(name)))return fail(write,json,"mode set","invalid","Separate model review has been removed; finished work goes to the lead or user.",EXIT.refused);if(flags.has("repair-max-attempts")&&!flag(flags,"repair-auto"))return fail(write,json,"mode set","invalid","--repair-max-attempts needs --repair-auto",EXIT.refused);if(flag(flags,"repair-auto")){const limit=Number(text(flags,"repair-max-attempts")??2);if(!Number.isInteger(limit)||limit<1||limit>3)return fail(write,json,"mode set","invalid","--repair-max-attempts is 1, 2 or 3",EXIT.refused);terms.repairAuto=!0,terms.repairMaxAttempts=limit}if(terms.planAuto&&!terms.autoApproveFiling)return fail(write,json,"mode set","invalid","--plan-auto requires automatic filing approval",EXIT.refused);if(flag(flags,"chat-approve")&&(terms.chatApprove=!0,terms.chatApproveChats=CHAT_APPROVE_ALL),terms.publication==="automerge"&&!store.hasMergeCapableGrant(repo,now))return fail(write,json,"mode set","no-grant","automerge needs a merge-capable publication grant on this repo — file one first",EXIT.refused);const digest=modeDigestOf(terms),id=store.signMode({repo,name:nameGiven,termsJson:modeTermsJson(terms),digest,signedBy:acting.name,absoluteExpiry:expiry,publication:terms.publication},now);return succeed(write,json,"mode set",{repo,id,digest,terms},()=>[`${repo}: ${nameGiven} mode signed by ${acting.name}, until ${expiry.slice(0,16).replace("T"," ")}.`,...modeWords(terms).map(w=>` ${w}`)])}async function configCommand(positional,flags,context){const{store,write,json,clock}=context,[action,phase]=positional;if(action!==void 0&&!CONFIG_ACTIONS.includes(action))return fail(write,json,"config","usage",`unknown \`config ${action}\` — try ${CONFIG_ACTIONS.join(", ")}`,EXIT.usage);const repoGiven=text(flags,"repo"),scope=repoGiven===void 0?INSTALLATION_SCOPE:canonicalProject(repoGiven)??resolve(repoGiven);if(phase==="quick-answers")return quickAnswersConfig(action??"show",repoGiven!==void 0,flags,context);if(phase==="task-sizing")return taskSizingConfig(action??"show",positional[2],repoGiven!==void 0,flags,context);if(phase==="flexible")return flexibleConfig(action??"show",positional[2],repoGiven!==void 0,flags,context);if(phase==="flexible-sign-in")return flexibleSignInConfig(action??"show",positional.slice(2),repoGiven!==void 0,flags,context);if(action===void 0||action==="show"){const installation=store.listPhaseConfig(INSTALLATION_SCOPE),project=scope===INSTALLATION_SCOPE?[]:store.listPhaseConfig(scope),resolved=["plan","build","repair","review"].map(one=>{const answer=resolvePhaseAgent(store,one,scope===INSTALLATION_SCOPE?null:scope,{});return{phase:one,...answer.ok?{provider:answer.spec.provider,model:answer.spec.model,source:answer.source}:{problem:answer.problem}}}),candidates=resolveRouteCandidates(store,scope===INSTALLATION_SCOPE?null:scope),strong=["plan","build","repair","review"].map(one=>({phase:one,strong:candidates.ok?candidates.candidates[one].strong:null})),alsoRows=[...store.listPhaseTierAlternates(INSTALLATION_SCOPE),...scope===INSTALLATION_SCOPE?[]:store.listPhaseTierAlternates(scope)],unusedLight=[INSTALLATION_SCOPE,...scope===INSTALLATION_SCOPE?[]:[scope]].filter(one=>store.phaseTierConfig(one,"plan","light")!==null);if(json)return write(envelopeJson({ok:!0,command:"config show",installation,project,resolved,strong,installationStrong:store.listPhaseTierConfig(INSTALLATION_SCOPE),projectStrong:scope===INSTALLATION_SCOPE?[]:store.listPhaseTierConfig(scope),installationAlso:store.listPhaseTierAlternates(INSTALLATION_SCOPE),projectAlso:scope===INSTALLATION_SCOPE?[]:store.listPhaseTierAlternates(scope)})),EXIT.ok;write(`Effective phase agents${scope===INSTALLATION_SCOPE?"":` for ${scope}`}:`);for(const one of resolved)"problem"in one?write(` ${one.phase.padEnd(8)} MISCONFIGURED — ${one.problem}`):write(` ${one.phase.padEnd(8)} ${one.provider}${one.model===null?" (harness default model)":` · ${one.model}`} [${one.source}]`);write(""),write(" strong tier (large or risky, strict, screenshot-proof, and automerge routes reach for these):");for(const one of strong)write(` ${one.phase.padEnd(8)} ${one.strong===null?"none configured — such routes keep the default above and say so":`${one.strong.provider}${one.strong.model===null?" (harness default model)":` · ${one.strong.model}`} [${one.strong.source}]`}`);write(" set one with: toolroll config set <phase> --tier strong --provider <p> --model <m> --as <you> --token <t>"),write(""),write(" light tier (small changes build on this, with no plan):");const light=candidates.ok?candidates.candidates.build.light??null:null;write(` ${"build".padEnd(8)} ${light===null?"none configured — small changes keep the default above and say so":`${light.provider} · ${light.model} [${light.source}]`}`);for(const one of unusedLight)write(` ${"plan".padEnd(8)} not used — a small change makes no plan; \`config clear plan --tier light${one===INSTALLATION_SCOPE?"":` --repo ${one}`}\` removes it`);if(write(" set one with: toolroll config set build --tier light --provider <p> --model <m> --as <you> --token <t>"),write(""),candidates.ok){const also=["plan","build"].flatMap(one=>Object.entries(candidates.candidates[one].alternates??{}).flatMap(([tier,list])=>(list??[]).map(spec=>` ${one.padEnd(8)} ${tier.padEnd(8)} also ${spec.provider} · ${spec.model} [${spec.source}]`)));if(also.length>0||alsoRows.length>0){write(" other providers on a tier (each task runs the one whose plan has more room):");for(const line of also)write(line);write("")}}return write(" repair note: the repair PROVIDER always inherits the build it mends — only its model is configurable."),installation.length===0&&project.length===0&&(write(" nothing configured — every phase runs the default (claude)."),write(" toolroll config set build --provider claude --model sonnet --as <you> --token <t>")),EXIT.ok}if(action!=="set"&&action!=="clear")return fail(write,json,"config","usage","`toolroll config [show|set <phase> --provider <p> [--model <m>]|clear <phase>] [--repo <path>] --as <you> --token <t>`",EXIT.usage);if((phase==="budgets"||phase==="chat")&&currentLocalOwner()!==null)return fail(write,json,`config ${action}`,"refused","Spend settings need your password: change them in Settings → Spend (or Settings → Lead), or pass `--as <you> --token <t>`.",EXIT.refused);if(phase==="budgets"){const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,`config ${action}`,"usage","changing spend defaults takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting2.name,acting2.token).ok)return fail(write,json,`config ${action}`,"unauthenticated","that is not an approver, or the token does not match",EXIT.refused);if(action==="clear")return store.setSpendDefaults({buildPerRunMicrousd:null},acting2.name,clock()),succeed(write,json,"config clear",{budgets:null},()=>["Spend defaults cleared — filings state their own numbers again."]);const build2=(flag2=>{const given=text(flags,flag2);if(given===void 0)return null;const value=Number(given);return Number.isFinite(value)&&value>0?Math.round(value*1e6):!1})("build-usd");return build2===!1?fail(write,json,"config set","usage","--build-usd is a positive dollar amount",EXIT.usage):(store.setSpendDefaults({buildPerRunMicrousd:build2},acting2.name,clock()),succeed(write,json,"config set",{budgets:store.getSpendDefaults()},()=>["Spend defaults set. New filings pre-fill from these; every approval still restates its own numbers:",...build2===null?[]:[` each ordinary build attempt: $${(build2/1e6).toFixed(2)} (also the installation backstop)`]]))}if(phase==="chat"){if(repoGiven!==void 0)return fail(write,json,`config ${action}`,"usage","chat is installation-scoped — no --repo",EXIT.usage);const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,`config ${action}`,"usage","changing chat spend takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting2.name,acting2.token).ok)return fail(write,json,`config ${action}`,"unauthenticated","that is not an approver, or the token does not match",EXIT.refused);if(action==="clear")return store.clearChatConfig(),succeed(write,json,"config clear",{chat:null},()=>["Chat is off — the config row is gone."]);const provider=text(flags,"provider"),requestedModel=text(flags,"model"),weeklyUsd=text(flags,"weekly-usd"),dailyGiven=text(flags,"daily-turns");if(provider!=="anthropic-api"&&provider!=="openrouter-api"&&provider!=="claude-subscription"&&provider!=="codex-subscription"&&provider!=="gemini-subscription"&&provider!=="grok-subscription")return fail(write,json,"config set","usage","chat provider is one of claude-subscription, codex-subscription, gemini-subscription, grok-subscription, anthropic-api, openrouter-api",EXIT.usage);const model=requestedModel??(isSubscriptionChatProvider(provider)?"default":"");if(!validModelId(model))return fail(write,json,"config set","usage","--model must be 1–128 letters, digits, dots, slashes, colons, underscores, or dashes",EXIT.usage);const priced=isDirectChatProvider(provider)?livePin(store,provider,model)??priceOf(model):null;if(isDirectChatProvider(provider)&&priced===null)return fail(write,json,"config set","unpriced-model",`chat reserves worst-case spend up front, so the model needs a price — run "toolroll models check" to load live prices, or pick one priced today: ${PRICED_MODELS.join(", ")}`,EXIT.refused);const weekly=Number(weeklyUsd);if(isDirectChatProvider(provider)&&(weeklyUsd===void 0||!Number.isFinite(weekly)||weekly<=0))return fail(write,json,"config set","usage","--weekly-usd <dollars> is required — chat without a ceiling is not configured, it is unbounded",EXIT.usage);const daily=dailyGiven===void 0?50:Number(dailyGiven);if(!Number.isInteger(daily)||daily<=0||daily>1e3)return fail(write,json,"config set","usage","--daily-turns is a whole number between 1 and 1000",EXIT.usage);const pinned=isDirectChatProvider(provider)?priced:{inMicrousd:0,outMicrousd:0};return pinned===null?fail(write,json,"config set","unpriced-model",`no compiled price for ${model}`,EXIT.refused):(store.setChatConfig({provider,model,dailyTurns:daily,weeklyCeilingMicrousd:isDirectChatProvider(provider)?Math.round(weekly*1e6):0,priceInMicrousd:pinned.inMicrousd,priceOutMicrousd:pinned.outMicrousd},acting2.name,clock()),succeed(write,json,"config set",{chat:store.getChatConfig()},()=>[isDirectChatProvider(provider)?`Chat answers with ${provider} · ${model}, at most ${daily} turns/day, at most $${weekly.toFixed(2)} per rolling week.`:`Chat answers through the logged-in ${provider==="codex-subscription"?"Codex":"Claude"} harness${model==="default"?" using its default model":` · ${model}`}, at most ${daily} turns/day, with no dollar ceiling.`,isDirectChatProvider(provider)?`The key rides the serve environment (${provider==="anthropic-api"?"ANTHROPIC_API_KEY":"OPENROUTER_API_KEY"}) — never this database.`:`The harness reuses its cached membership login; authenticate first with ${provider==="codex-subscription"?"`codex login`":"the `claude` CLI"}.`,...isSubscriptionChatProvider(provider)&&weeklyUsd!==void 0?["The supplied --weekly-usd value was ignored because membership usage has no dollar meter."]:[]]))}if(phase===void 0||!["plan","build","repair","review"].includes(phase))return fail(write,json,`config ${action}`,"usage","which phase? plan, build, repair, review — or chat",EXIT.usage);const owner=currentLocalOwner(),acting=owner!==null?{name:owner.account,token:""}:await askCredentials(flags,context),provedGeneration=acting===null?-1:store.accountOf(acting.name)?.generation??-1,verified=owner!==null?{ok:!0,method:"local-owner"}:acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||verified===null||!verified.ok)return refuseApprover(context,`config ${action}`,verified,"changing spend routing takes `--as <you> --token <t>`",phase);const tierGiven=text(flags,"tier");if(tierGiven!==void 0&&tierGiven!=="strong"&&tierGiven!=="light")return fail(write,json,`config ${action}`,"usage","--tier is `light` or `strong` — the routine tier is the plain phase row",EXIT.usage);if(tierGiven==="light"&&phase!=="build"&&!(action==="clear"&&phase==="plan"&&!flag(flags,"also")))return fail(write,json,`config ${action}`,"usage","--tier light is for build only — a small change makes no plan, and repairs resume the builder's session",EXIT.usage);const projectKnown=repoGiven===void 0||await knownProject(context,repoGiven,{listed:!0,canonical:!0})!==void 0,proof={actor:acting.name,generation:provedGeneration,method:verified.method},written=(slot,to,extra=[])=>writeModelRow(store,proof,scope,()=>projectKnown,slot,to,clock(),extra),said=(command,result,payload,lines)=>{const incomplete=result.ok?result.unresolved:null;return succeed(write,json,command,{...payload,...incomplete===null?{}:{incomplete}},()=>[...lines(),...incomplete===null?[]:[` ! new tasks can't be filed here yet: ${incomplete}`]])};if(flag(flags,"also")){if(phase!=="plan"&&phase!=="build")return fail(write,json,`config ${action}`,"usage","--also is for plan or build — repairs follow the build's provider",EXIT.usage);const tier=tierGiven??"routine",alsoProvider=text(flags,"provider");if(alsoProvider!==void 0&&!isProviderId(alsoProvider))return fail(write,json,`config ${action}`,"usage",`--provider is one of ${PROVIDER_IDS.join(", ")}`,EXIT.usage);if(action==="clear"){const alsoClear=written(null,null,[{kind:"also-clear",phase,tier,provider:alsoProvider??null}]);if(!alsoClear.ok)return fail(write,json,"config clear",alsoClear.reason,alsoClear.problem,EXIT.refused);const removed=alsoClear.extra;return said("config clear",alsoClear,{scope,phase,tier,also:!0,provider:alsoProvider??null,cleared:removed},()=>[removed>0?`Removed ${removed} other-provider ${tier} ${phase} agent${removed===1?"":"s"} at ${scope}; sealed routes are untouched.`:`No other-provider ${tier} ${phase} agent${alsoProvider===void 0?"":` on ${alsoProvider}`} was configured at ${scope}.`])}const alsoModel=text(flags,"model");if(alsoProvider===void 0||alsoModel===void 0)return fail(write,json,"config set","usage","--also names an exact --provider and --model — approvals bind exact routing",EXIT.usage);const alsoValid=validateSpec({provider:alsoProvider,model:alsoModel});if(!alsoValid.ok)return fail(write,json,"config set","invalid",alsoValid.problem,EXIT.usage);const alsoSet=written(null,null,[{kind:"also-set",phase,tier,provider:alsoProvider,model:alsoModel}]);if(!alsoSet.ok)return fail(write,json,"config set",alsoSet.reason,alsoSet.problem,EXIT.refused);const resolvedNow=resolveRouteCandidates(store,scope===INSTALLATION_SCOPE?null:scope),own=resolvedNow.ok?tier==="routine"?resolvedNow.candidates[phase].routine:tier==="light"?resolvedNow.candidates[phase].light??null:resolvedNow.candidates[phase].strong:null;return said("config set",alsoSet,{scope,phase,tier,also:!0,provider:alsoProvider,model:alsoModel},()=>[`${tier} ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} can also run ${alsoProvider} · ${alsoModel}, set by ${acting.name}.`,own!==null&&own.provider===alsoProvider&&!own.source.includes("also")?` ! the ${tier} ${phase} agent already runs ${alsoProvider} (${own.model}) — this one is not used while it does.`:" tasks filed from now on run on whichever provider's plan has more room; sealed routes are untouched."])}if(action==="clear"){if(tierGiven==="light"&&phase==="build"){const lightWrite=written({phase,tier:"light"},null);if(!lightWrite.ok)return fail(write,json,"config clear",lightWrite.reason,lightWrite.problem,EXIT.refused);const clearedLight=lightWrite.diff.length>0;return said("config clear",lightWrite,{scope,phase,tier:"light",cleared:clearedLight},()=>[clearedLight?`Cleared the light ${phase} agent at ${scope} — small changes keep the default and say so; sealed routes are untouched.`:`No light ${phase} agent was configured at ${scope}.`])}if(tierGiven==="light"){const legacyClear=written(null,null,[{kind:"legacy-light-clear",phase}]);if(!legacyClear.ok)return fail(write,json,"config clear",legacyClear.reason,legacyClear.problem,EXIT.refused);const clearedLight=legacyClear.extra>0;return said("config clear",legacyClear,{scope,phase,tier:"light",cleared:clearedLight},()=>[clearedLight?`Cleared the light ${phase} agent at ${scope} — small changes keep the default and say so; sealed routes are untouched.`:`No light ${phase} agent was configured at ${scope}.`])}if(tierGiven==="strong"){const strongWrite=written({phase,tier:"strong"},null);if(!strongWrite.ok)return fail(write,json,"config clear",strongWrite.reason,strongWrite.problem,EXIT.refused);const clearedStrong=strongWrite.diff.length>0;return said("config clear",strongWrite,{scope,phase,tier:"strong",cleared:clearedStrong},()=>[clearedStrong?`Cleared the strong ${phase} agent at ${scope} — demanding routes keep the default and say so; sealed routes are untouched.`:`No strong ${phase} agent was configured at ${scope}.`])}const routineWrite=written({phase,tier:"routine"},null);if(!routineWrite.ok)return fail(write,json,"config clear",routineWrite.reason,routineWrite.problem,EXIT.refused);const cleared=routineWrite.diff.length>0;return said("config clear",routineWrite,{scope,phase,cleared},()=>[cleared?`Cleared ${phase} at ${scope} — it resolves one layer down now.`:`Nothing was configured for ${phase} at ${scope}.`])}const providerGiven=text(flags,"provider");if(providerGiven===void 0||!isProviderId(providerGiven))return fail(write,json,"config set","usage",`--provider is one of ${PROVIDER_IDS.join(", ")}`,EXIT.usage);const modelGiven=text(flags,"model")??null,valid=validateSpec({provider:providerGiven,model:modelGiven});if(!valid.ok)return fail(write,json,"config set","invalid",valid.problem,EXIT.usage);if(tierGiven==="light"){if(modelGiven===null)return fail(write,json,"config set","usage",`a light ${phase} agent names an exact --model — approvals bind exact routing`,EXIT.usage);const lightSet=written({phase,tier:"light"},{provider:providerGiven,model:modelGiven});return lightSet.ok?said("config set",lightSet,{scope,phase,tier:"light",provider:providerGiven,model:modelGiven},()=>[`light ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} is ${providerGiven} · ${modelGiven}, set by ${acting.name}.`," small changes filed from now on build on it with no plan; sealed routes are untouched."]):fail(write,json,"config set",lightSet.reason,lightSet.problem,EXIT.refused)}if(tierGiven==="strong"){if(phase==="review"&&providerGiven==="gemini")return fail(write,json,"config set","invalid","gemini has no isolation posture for the review phase yet — name claude or codex as the strong reviewer",EXIT.usage);if(modelGiven===null)return fail(write,json,"config set","usage",`a strong ${phase} agent names an exact --model — approvals bind exact routing`,EXIT.usage);const strongSet=written({phase,tier:"strong"},{provider:providerGiven,model:modelGiven});return strongSet.ok?said("config set",strongSet,{scope,phase,tier:"strong",provider:providerGiven,model:modelGiven},()=>[`strong ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} is ${providerGiven}${modelGiven===null?"":` · ${modelGiven}`}, set by ${acting.name}.`," large or risky, strict, screenshot-proof, and automerge routes filed from now on reach for it; sealed routes are untouched.",...phase==="repair"?[" a strong repair agent applies only when its provider is the build's — cross-provider repair does not exist."]:[]]):fail(write,json,"config set",strongSet.reason,strongSet.problem,EXIT.refused)}const routineSet=written({phase,tier:"routine"},{provider:providerGiven,model:modelGiven});if(!routineSet.ok)return fail(write,json,"config set",routineSet.reason,routineSet.problem,EXIT.refused);const warnings=[];return modelGiven===null&&warnings.push(`no --model named: approvals bind exact routing, so scopes cannot file until ${phase} has an exact model — \`config set ${phase} --provider ${providerGiven} --model <model>\``),providerGiven==="openrouter"&&(process.env.OPENROUTER_API_KEY??"")===""&&warnings.push("OPENROUTER_API_KEY is not present in this environment — runs will fail until the runner exports it."),providerGiven!=="claude"&&warnings.push(`${providerGiven} does not report dollar cost: its runs land as UNMEASURED, and any schedule with a weekly limit fails closed on them by design.`),said("config set",routineSet,{scope,phase,provider:providerGiven,model:modelGiven,warnings},()=>[`${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} now runs ${providerGiven}${modelGiven===null?"":` · ${modelGiven}`}, set by ${acting.name}.`,...warnings.map(one=>` ! ${one}`)])}async function setupCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),action=positional[0]??"show",repo=text(flags,"repo");if(action==="show"){if(repo===void 0)return fail(write,json,"setup show","usage","which repo? --repo <path>",EXIT.usage);const live=store.liveWorktreeSetup(repo);return json?(write(envelopeJson({ok:!0,command:"setup show",repo,setup:live})),EXIT.ok):(write(live===null?`No worktree setup for ${repo}. Fresh checkouts run nothing before the agent.`:`${repo} runs before every agent:
482
+ `)[0]??"",attestationOf(id))}}})}let recorded=null;if(flags.has("report")){const runnerName=text(flags,"runner"),runnerToken=text(flags,"token");if(runnerName===void 0||runnerToken===void 0)return fail(write,json,"providers","usage","`toolroll providers --report --runner <name> --token <t>` records readiness under that runner",EXIT.usage);const observed=await observeProviderReadiness((file,args,options)=>probe(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)),reported=reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},context.clock());if(!reported.ok)return fail(write,json,"providers",reported.reason,describeAuth(reported.reason,runnerName),EXIT.refused);recorded=observed}if(json)return write(envelopeJson({ok:!0,command:"providers",providers:report,...recorded===null?{}:{readiness:recorded}})),EXIT.ok;if(recorded!==null){write(`readiness recorded for ${text(flags,"runner")??""}:`);for(const one of recorded)write(` ${one.provider.padEnd(11)}${one.state.toUpperCase()} — ${one.reason} [${one.probe}]`);write("")}for(const one of report){const name=String(one.provider);write(`${name}`),write(` installed ${one.installed===!0?`yes — ${String(one.version)}`:`no — \`${String(one.binary)}\` did not answer`}`),one.identity!==null&&one.identity!==void 0?write(` authenticated ${String(one.identity)} (probed just now, without spending)`):name==="claude"&&write(" authenticated not probed — no non-spending check exists; a real run is the proof"),write(` last success ${one.lastSuccessfulRun===null?"never on this installation":`${String(one.lastSuccessfulRun)} — login was valid then`}`),one.keyEnv!==void 0&&write(` ${String(one.keyEnv)} ${one.keyPresent===!0?"present (not validated — presence is not authorization)":"ABSENT — runs will fail until the runner exports it"}`),write(` cost ${one.measuresCost===!0?"measured in dollars per run":"tokens only — runs land as UNMEASURED; schedules with a weekly limit fail closed on them"}`);const phases=one.configuredPhases;phases.length>0&&write(` configured ${phases.join(", ")} (installation)`);const audit=one.audit;write(` transport ${audit.transport}${audit.initSignal==="none"?" — no init signal; a failed run cannot say whether the harness came up":` — init signal: ${audit.initSignal}`}`),write(` resume ${audit.resume}`);const attested=one.attestation;attested!==void 0&&write(` attested ${attested.floor} up to (not including) ${attested.ceiling}, fixtures at ${attested.fixturesAt} — ${attested.installedInRange?"the installed version is inside the range":"the INSTALLED VERSION IS OUTSIDE THE RANGE; dispatch will refuse until re-attestation"}`),write(` isolation ${audit.isolation.flag===null?"no hermetic flag":audit.isolation.enforced?`builds run in their own setup (${audit.isolation.flag}) — none of your own hooks, plugins or MCP servers; reviews keep theirs`:`${audit.isolation.flag} exists, not passed${audit.isolation.resumeSafe===!1?" — it would break session resume":audit.isolation.resumeSafe===null?" — its effect on resume is unvalidated":""}`}`),write(` ${audit.isolation.enforced?"builds get ":"config surface"} ${audit.configSurface.join("; ")}`),write("")}return write(" → toolroll config show which provider each phase actually resolves to"),EXIT.ok}async function agentsCommand(positional,flags,context){const{store,write,json,clock}=context,[action="list",provider,...rest]=positional,runners=store.listRunners().filter(one=>one.retiredAt===null).map(one=>one.name),runner=text(flags,"runner")??(runners.length===1?runners[0]:void 0);if(action==="list"){const runnerPath=runnerPathOf(),rows=ACP_PROVIDER_IDS.map(id2=>{const seen=resolveAcpAgentForRunner(id2),checked=runners.flatMap(name2=>{const one=store.acpAttestationFor(id2,name2);return one===null?[]:[{runner:name2,agent:one.agent,models:one.models,at:one.recordedAt}]}),latest=store.acpChecksFor(id2,1)[0]??null;return{provider:id2,name:ACP_AGENTS[id2].name,installed:seen.found?seen.realpath:null,checked,latestCheck:latest===null?null:{id:latest.id,state:latest.state,model:latest.model,repo:latest.repo,result:latest.result}}}),{detectAgents,detectionReport}=await import("./agent-detect.js"),{agentsReadOf}=await import("./engine-reads.js"),{acpCheckedHere,acpCheckEvidenceHere,firstTaskRouted}=await import("./welcome-facts.js"),agentEnv={...process.env,PATH:runnerPath},detection=await detectAgents({env:agentEnv,routed:firstTaskRouted(store),acpChecked:acpCheckedHere(store,{env:agentEnv}),acpCheckEvidence:acpCheckEvidenceHere(store),store,...context.easySeams?.check===void 0?{}:{check:context.easySeams.check}}),{openRouterChatModels}=await import("./agent-thread/openrouter-chat.js"),{version:_version,...detected}=agentsReadOf(detection,"full",null,null,{piChatModels:()=>readPiConfiguredModels(),openRouterChatModels:()=>openRouterChatModels(store)});if(json)return write(envelopeJson({ok:!0,command:"agents",detected:{...detected,tookMs:detection.tookMs},agents:rows})),EXIT.ok;for(const line of detectionReport(detection))write(line);write(""),write("Agent checks");for(const row of rows){write(` ${row.name.padEnd(10)} ${row.installed===null?"not installed":row.installed}`);for(const one of row.checked)write(` checked on ${one.runner}: ${one.agent.name} ${one.agent.version}, ${one.models.length} models (${one.at.slice(0,10)})`);row.latestCheck!==null&&row.latestCheck.state!=="passed"&&write(` check #${row.latestCheck.id} (${row.latestCheck.model}): ${row.latestCheck.state}${row.latestCheck.result===null?"":` — ${row.latestCheck.result}`}`)}return write(" → `agents check <agent> --model <id>` asks this runner's watch to check one; it runs on the watch's next pass"),EXIT.ok}if(!["check","revoke","billing"].includes(action))return fail(write,json,"agents","usage","`toolroll agents [check|revoke|billing]`",EXIT.usage);if(provider===void 0||!isAcpProvider(provider))return fail(write,json,`agents ${action}`,"usage",`which agent? ${ACP_PROVIDER_IDS.join(", ")}`,EXIT.usage);if(runner===void 0||!runners.includes(runner))return fail(write,json,`agents ${action}`,"usage",`which runner? --runner ${runners.join(" | ")||"<name>"}`,EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`agents ${action}`,"usage","this takes your name and password — `--as <you>` and the hidden prompt",EXIT.usage);const verified=verifyApproverByPassword(store,acting.name,acting.token,store.knownRepos().filter(repo2=>store.accountCanAccess(acting.name,repo2)));if(!verified.ok)return fail(write,json,`agents ${action}`,"unauthenticated","that is not an approver, or the password does not match",EXIT.refused);if(!store.isInstanceOperator(verified.who.name))return fail(write,json,`agents ${action}`,"forbidden","only an installation operator can check, revoke or set billing for a runner's agents",EXIT.refused);const name=ACP_AGENTS[provider].name,now=clock();if(action==="revoke"){const revoked=store.revokeAcpAttestation(provider,runner,verified.who.name,now);return succeed(write,json,"agents revoke",{provider,runner,revoked},()=>[revoked?`${name} no longer runs on ${runner}; check it again to bring it back.`:`${name} wasn't checked on ${runner}.`])}if(action==="billing"){const[model2,kind]=rest;if(model2===void 0||!validModelId(model2)||kind!=="plan"&&kind!=="metered")return fail(write,json,"agents billing","usage","`agents billing <agent> <model> plan|metered`",EXIT.usage);const revision=store.declareAcpBilling({provider,runner,model:model2,kind,by:verified.who.name},now);return succeed(write,json,"agents billing",{provider,runner,model:model2,kind,revision},()=>[kind==="plan"?`${name} on ${model2} (${runner}) is billed by ${name}'s own plan: its runs count as $0, unmeasured, and monthly budgets don't hold them. Runs already started keep the terms they started with.`:`${name} on ${model2} (${runner}) is metered: its cost is unknown, so capped work and hard budgets hold it.`])}const model=text(flags,"model");if(model===void 0||!validModelId(model))return fail(write,json,"agents check","usage","`agents check <agent> --model <id>` — a model the agent offers (its own list shows after the check)",EXIT.usage);const repoGiven=text(flags,"repo"),repo=repoGiven===void 0?null:canonicalProject(repoGiven)??resolve(repoGiven);if(repo!==null){const runnerRow=store.getRunner(runner);if(runnerRow!==null&&runnerRow.runner.repos.length>0&&!runnerRow.runner.repos.includes(repo))return fail(write,json,"agents check","unauthorized-repo",`${runner} is not bound to ${repo}`,EXIT.refused)}const id=store.requestAcpCheck({provider,runner,model,repo,by:verified.who.name},now);return succeed(write,json,"agents check",{provider,runner,model,repo,request:id},()=>[`Check #${id} asked for: ${name} on ${model}, on ${runner}${repo===null?"":` for ${projectName(repo)}`}. Its watch runs it on its next pass (two short runs, in the fence; the model's own spend).`,"→ `toolroll agents` shows how it went."])}async function keysCommand(positional,flags,context){const{write,json}=context,[action,provider,...rest]=positional;if(action===void 0||!KEYS_ACTIONS.includes(action))return fail(write,json,"keys","usage",`unknown \`keys ${action??""}\` — try ${KEYS_ACTIONS.join(", ")}`,EXIT.usage);if(action==="status"){const rows=PROVIDER_IDS.filter(isKeyedProvider).map(one=>({provider:one,envName:PROVIDER_KEY_ENV[one],...keyStatus(one),ambient:(process.env[PROVIDER_KEY_ENV[one]]??"")!==""}));if(json)return write(envelopeJson({ok:!0,command:"keys status",keys:rows})),EXIT.ok;for(const row of rows){const mode=readAuthMode(row.provider),state=row.set?`stored${row.updatedAt===null?"":` (${row.updatedAt.slice(0,10)})`}`:row.ambient?"environment only":"not set";write(` ${row.provider.padEnd(12)} ${row.envName.padEnd(22)} ${mode.padEnd(13)} ${state}`)}return write(" → subscription-mode providers use their own login; api-key mode hands over the stored (or ambient) key"),write(" → `keys auth <provider> subscription|api-key` switches; stored keys are kept either way"),EXIT.ok}if(provider===void 0||!isProviderId(provider))return fail(write,json,`keys ${action}`,"usage",`which provider? ${PROVIDER_IDS.filter(isKeyedProvider).join(", ")}`,EXIT.usage);if(!isKeyedProvider(provider))return fail(write,json,`keys ${action}`,"refused",`${ownSignInOf(provider).name} signs in its own way (\`${ownSignInOf(provider).signIn}\`) — Toolroll keeps no key for it`,EXIT.refused);if(action==="clear"){const forgotten=provider==="openrouter"?forgetOpenRouterKey({configDir:dirname(context.databaseFile)}):null,cleared=forgotten?.removed??clearProviderKey(provider),mode=readAuthMode(provider);return succeed(write,json,"keys clear",{provider,cleared,mode,warning:forgotten?.warning??null},()=>[forgotten?.warning??(cleared?mode==="subscription"?`The ${provider} key is removed. ${provider} uses its own login (subscription mode), so builds are unaffected.`:`The ${provider} key is removed — an environment variable, if one exists, takes over.`:"No stored key to remove.")])}if(action==="verify"){const stored=readProviderKey(provider);if(stored===null)return fail(write,json,"keys verify","refused",`no stored ${provider} key to verify`,EXIT.refused);const verdict2=await verifyProviderKey(provider,stored);return succeed(write,json,"keys verify",{provider,verdict:verdict2},()=>[verdictWords(provider,verdict2)])}if(action==="auth"){const[wanted]=rest;return wanted!=="subscription"&&wanted!=="api-key"?fail(write,json,"keys auth","usage",`\`toolroll keys auth ${provider} subscription|api-key\``,EXIT.usage):setAuthMode(provider,wanted).ok?succeed(write,json,"keys auth",{provider,mode:wanted},()=>[wanted==="subscription"?`${provider} now uses its own login; its stored key is kept as the fallback you can switch to.`:`${provider} now uses its API key; switch back with \`keys auth ${provider} subscription\`.`]):fail(write,json,"keys auth","refused",`${provider} has no subscription login — it is api-key only`,EXIT.refused)}const file=text(flags,"key-file");let value;if(file!==void 0)try{value=readFileSync(file,"utf8")}catch{return fail(write,json,"keys set","usage",`cannot read \`${file}\``,EXIT.usage)}else{if(process.stdin.isTTY)return fail(write,json,"keys set","usage","pipe the key in (`toolroll keys set gemini < key.txt` or via --key-file) — a key on an argv is visible to every process list",EXIT.usage);const chunks=[];for await(const chunk of process.stdin)chunks.push(chunk);value=Buffer.concat(chunks).toString("utf8")}if(!(provider==="openrouter"?saveOpenRouterKey(value,{configDir:dirname(context.databaseFile)}):saveProviderKey(provider,value)).ok)return fail(write,json,"keys set","implausible","that does not look like an API key — check the paste",EXIT.refused);const verdict=flag(flags,"no-verify")?null:await verifyProviderKey(provider,value);return succeed(write,json,"keys set",{provider,...verdict===null?{}:{verdict}},()=>[`The ${provider} key is stored (a private file, handed only to ${provider}'s own process at spawn).`,...verdict===null?[]:[verdictWords(provider,verdict)]])}async function peopleCommand(positional,flags,context){const{store,write,json,clock}=context,[action,...rest]=positional;if(action===void 0||!PEOPLE_ACTIONS.includes(action))return fail(write,json,"people","usage",`unknown \`people ${action??""}\` — try ${PEOPLE_ACTIONS.join(", ")}`,EXIT.usage);if(action==="list"){const accounts=store.accountFacts(),invites=store.openInvites(clock());if(json)return write(envelopeJson({ok:!0,command:"people list",accounts,invites})),EXIT.ok;if(accounts.length===0)return write("Nobody yet — `toolroll approver add <name>` bootstraps the first."),EXIT.ok;for(const one of accounts){const standing=one.revokedAt!==null?`revoked ${one.revokedAt.slice(0,10)} by ${one.revokedBy??"?"}`:one.role==="approver"?"approves":"watches";write(` ${one.name.padEnd(20)} ${standing.padEnd(28)} joined ${one.addedAt.slice(0,10)} · ${one.projects===null?"all projects":one.projects.length===0?"no projects":one.projects.join(", ")}`)}for(const one of invites)write(` (invite) ${one.role} invite from ${one.mintedBy}, expires ${one.expiresAt.slice(0,16).replace("T"," ")}`);return EXIT.ok}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`people ${action}`,"usage",`\`toolroll people ${action} … --as <you> --token <t>\``,EXIT.usage);const authenticated=action==="revoke"?authenticateApprover(store,acting.name,acting.token):credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,`people ${action}`,authenticated.reason,describeApproveFailure(authenticated.reason,acting.name),EXIT.refused);const repoGiven=text(flags,"repo"),allProjects=flags.has("all-projects"),noProjects=flags.has("no-projects");if([repoGiven!==void 0,allProjects,noProjects].filter(Boolean).length>1)return fail(write,json,`people ${action}`,"usage","Choose --repo <path>, --all-projects, or --no-projects.",EXIT.usage);const repo=repoGiven===void 0?null:canonicalProject(repoGiven);if(repoGiven!==void 0&&repo===null)return fail(write,json,`people ${action}`,"usage","The project folder must exist.",EXIT.usage);const projects=repo!==null?[repo]:noProjects?[]:null;if(action==="projects"){const name2=rest[0]?.trim();if(!name2||repoGiven===void 0&&!allProjects&&!noProjects)return fail(write,json,"people projects","usage","people projects <name> --repo <path> | --all-projects | --no-projects --as <you> --token <t>",EXIT.usage);const changed=store.setAccountProjects(name2,projects,acting.name,clock());return changed.ok?succeed(write,json,"people projects",{name:name2,projects},()=>[`${name2}: ${projects===null?"all projects":projects.length===0?"no project access":projects.join(", ")}. Access changes end existing sign-in sessions and derived authority.`]):fail(write,json,"people projects",changed.reason,"Project access was not changed: "+changed.reason,EXIT.refused)}if(action==="invite"){const roleFlag=text(flags,"role")??"viewer";if(roleFlag!=="viewer"&&roleFlag!=="approver")return fail(write,json,"people invite","usage","--role viewer|approver (viewer is the default)",EXIT.usage);if(noProjects)return fail(write,json,"people invite","usage","An invitation needs --repo <path> or all-project access.",EXIT.usage);const minted=store.mintInvite(roleFlag,acting.name,clock(),void 0,projects);return succeed(write,json,"people invite",{role:roleFlag,projects,path:`/join/${minted.token}`,expiresAt:minted.expiresAt},()=>[`The invite link's path — shown once, single-use, ${roleFlag==="approver"?"they can approve and act":"they can read work"} in ${projects===null?"all projects":projects.join(", ")}:`,` /join/${minted.token}`,`Open it on this console's address. It dies ${minted.expiresAt.slice(0,16).replace("T"," ")} UTC, or when you cancel it on the people screen.`])}const[name]=rest;if(name===void 0||name.trim()==="")return fail(write,json,"people revoke","usage","`toolroll people revoke <name> --as <you> --token <t>`",EXIT.usage);const severed=store.revokeAccount(name.trim(),acting.name,clock());if(!severed.ok){const words=severed.reason==="last-approver"?"that is the last account that can approve — add another approver first":severed.reason==="already-revoked"?`${name} is already removed`:`no account \`${name}\``;return fail(write,json,"people revoke",severed.reason,words,EXIT.refused)}return succeed(write,json,"people revoke",{name:name.trim(),...severed},()=>[`${name.trim()} can no longer sign in. Their open sessions, invites, and the ${severed.modesRevoked} mode(s) they signed ended with them.`,"Everything they ever approved or decided stays in the ledger, under their name."])}const MODE_ACTIONS=["set","show","revoke"];async function chatApprovalCommand(positional,flags,context){const{store,write,json,clock}=context,action=positional[0]??"show",command=`chat-approval ${action}`;if(!["show","on","off"].includes(action))return fail(write,json,"chat-approval","usage","Use chat-approval show | on | off [--repo <path>] [--full-access] [--cap-usd <n>] [--yes].",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"unauthenticated","Approving from chat is your own setting: pass --as <you> --token <your password> (or sign in once with toolroll up).",EXIT.refused);if(!(action==="on"?credentialApprover(store,acting.name,acting.token):authenticateApprover(store,acting.name,acting.token)).ok)return fail(write,json,command,"unauthenticated","That name and password aren't an approver's. Nothing was changed.",EXIT.refused);const given=text(flags,"repo"),scope=given===void 0?ALL_PROJECTS:canonicalProject(given)??resolve(given);if(scope!==ALL_PROJECTS&&!store.accountCanAccess(acting.name,scope))return fail(write,json,command,"unknown-project","That isn't one of your projects.",EXIT.refused);const where=scope===ALL_PROJECTS?"all your projects":projectName(scope);if(action==="show"){const rows=chatApprovalSettings(store,acting.name).map(one=>({scope:one.scope===ALL_PROJECTS?"all":one.scope,enabled:one.enabled,fullAccess:one.fullAccess,capMicrousd:one.capMicrousd,updatedAt:one.updatedAt}));return succeed(write,json,command,{settings:rows},()=>rows.length===0?["Approving from chat is off everywhere. Turn it on: toolroll chat-approval on [--repo <path>]"]:rows.map(one=>`${one.scope==="all"?"All projects":projectName(one.scope)}: ${one.enabled?`on · ${chatApprovalWords(one)}`:"off"}`))}const now=clock();if(action==="off"){const saved2=setChatApproval(store,{approver:acting.name,scope,enabled:!1,via:"the command line"},now);return saved2.ok?succeed(write,json,command,{applied:!0,scope:scope===ALL_PROJECTS?"all":scope},()=>[saved2.said]):fail(write,json,command,"refused",saved2.message,EXIT.refused)}const usd=text(flags,"cap-usd"),cap=usd===void 0?null:Number(usd);if(cap!==null&&!(Number.isFinite(cap)&&cap>=0&&cap<=1e4))return fail(write,json,command,"usage","Give --cap-usd in dollars, like 5.",EXIT.usage);const limits={fullAccess:flag(flags,"full-access"),capMicrousd:cap===null?null:Math.round(cap*1e6)},terms=[`Your own taps in your paired chat approve plans and merges in ${where}, until you turn it off: it doesn't expire.`,`Limits: ${chatApprovalWords(limits)}.`,"Plans written for you, protected paths, two-person rules and your organisation's policy still open in Toolroll."];if(!flag(flags,"yes"))return succeed(write,json,command,{applied:!1,scope:scope===ALL_PROJECTS?"all":scope,terms},()=>[`Turn on approving from chat for ${where}`,...terms.map(one=>` ${one}`),"","Nothing has changed. Add --yes to make this change."]);const saved=setChatApproval(store,{approver:acting.name,scope,enabled:!0,limits,via:"the command line"},now);return saved.ok?succeed(write,json,command,{applied:!0,scope:scope===ALL_PROJECTS?"all":scope,terms},()=>[saved.said]):fail(write,json,command,"refused",saved.message,EXIT.refused)}async function modeCommand(positional,flags,context){const{store,write,json,clock}=context,[action]=positional;if(action===void 0||!MODE_ACTIONS.includes(action))return fail(write,json,"mode","usage",`unknown \`mode ${action??""}\` — try ${MODE_ACTIONS.join(", ")}`,EXIT.usage);const repoGiven=text(flags,"repo"),repo=repoGiven===void 0?void 0:canonicalProject(repoGiven)??resolve(repoGiven);if(repo===void 0)return fail(write,json,"mode","usage","`mode` needs --repo <canonical path> — a mode is per-repository",EXIT.usage);const now=clock();if(action==="show"){const mode=store.activeMode(repo,now);if(mode===null)return succeed(write,json,"mode show",{repo,active:null},()=>[`${repo}: locked — every act keeps its own ceremony (the default).`]);const terms2=modeTermsFromJson(mode.termsJson);return succeed(write,json,"mode show",{repo,active:{name:mode.name,signedBy:mode.signedBy,expiry:mode.absoluteExpiry,digest:mode.digest}},()=>[`${repo}: ${mode.name}, signed by ${mode.signedBy}`,...terms2===null?[]:modeWords(terms2).map(w=>` ${w}`),` → mode revoke --repo ${repo} --as ${mode.signedBy} --token <t> (or any approver; one click)`])}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"mode","usage","signing or revoking a mode takes `--as <you> --token <t>`",EXIT.usage);const authed=flag(flags,"chat-approve")||flag(flags,"repair-auto")?credentialApprover(store,acting.name,acting.token):authenticateApprover(store,acting.name,acting.token);if(!authed.ok)return fail(write,json,"mode",authed.reason,"that is not an active approver, or the token does not match",EXIT.refused);if(action==="revoke")return store.revokeMode(repo,acting.name,"operator",now)?succeed(write,json,"mode revoke",{repo},()=>[`${repo}: mode revoked. Every act it covered falls back to its own ceremony; running work is untouched.`]):fail(write,json,"mode revoke","no-mode",`${repo} has no active mode`,EXIT.refused);const nameGiven=text(flags,"name")??"standard";if(nameGiven!=="standard"&&nameGiven!=="hands-off")return fail(write,json,"mode set","usage","--name is standard or hands-off",EXIT.usage);const daysGiven=Number(text(flags,"days")??"1");if(!Number.isInteger(daysGiven)||daysGiven<1||daysGiven>MODE_MAX_DAYS)return fail(write,json,"mode set","usage",`--days is 1 to ${MODE_MAX_DAYS} (a mode always expires)`,EXIT.usage);const expiry=new Date(now.getTime()+daysGiven*24*60*6e4).toISOString(),terms=presetTerms(nameGiven,expiry);if(text(flags,"publication")==="automerge"&&(terms.publication="automerge"),text(flags,"publication")==="notify"&&(terms.publication="notify"),flag(flags,"auto-approve")&&(terms.autoApproveFiling=!0),flag(flags,"plan-auto")&&(terms.planAuto=!0),["review-auto","review-retry-auto"].some(name=>flags.has(name)))return fail(write,json,"mode set","invalid","Separate model review has been removed; finished work goes to the lead or user.",EXIT.refused);if(flags.has("repair-max-attempts")&&!flag(flags,"repair-auto"))return fail(write,json,"mode set","invalid","--repair-max-attempts needs --repair-auto",EXIT.refused);if(flag(flags,"repair-auto")){const limit=Number(text(flags,"repair-max-attempts")??2);if(!Number.isInteger(limit)||limit<1||limit>3)return fail(write,json,"mode set","invalid","--repair-max-attempts is 1, 2 or 3",EXIT.refused);terms.repairAuto=!0,terms.repairMaxAttempts=limit}if(terms.planAuto&&!terms.autoApproveFiling)return fail(write,json,"mode set","invalid","--plan-auto requires automatic filing approval",EXIT.refused);if(flag(flags,"chat-approve")&&(terms.chatApprove=!0,terms.chatApproveChats=CHAT_APPROVE_ALL),terms.publication==="automerge"&&!store.hasMergeCapableGrant(repo,now))return fail(write,json,"mode set","no-grant","automerge needs a merge-capable publication grant on this repo — file one first",EXIT.refused);const digest=modeDigestOf(terms),id=store.signMode({repo,name:nameGiven,termsJson:modeTermsJson(terms),digest,signedBy:acting.name,absoluteExpiry:expiry,publication:terms.publication},now);return succeed(write,json,"mode set",{repo,id,digest,terms},()=>[`${repo}: ${nameGiven} mode signed by ${acting.name}, until ${expiry.slice(0,16).replace("T"," ")}.`,...modeWords(terms).map(w=>` ${w}`)])}async function configCommand(positional,flags,context){const{store,write,json,clock}=context,[action,phase]=positional;if(action!==void 0&&!CONFIG_ACTIONS.includes(action))return fail(write,json,"config","usage",`unknown \`config ${action}\` — try ${CONFIG_ACTIONS.join(", ")}`,EXIT.usage);const repoGiven=text(flags,"repo"),scope=repoGiven===void 0?INSTALLATION_SCOPE:canonicalProject(repoGiven)??resolve(repoGiven);if(phase==="quick-answers")return quickAnswersConfig(action??"show",repoGiven!==void 0,flags,context);if(phase==="task-sizing")return taskSizingConfig(action??"show",positional[2],repoGiven!==void 0,flags,context);if(phase==="flexible")return flexibleConfig(action??"show",positional[2],repoGiven!==void 0,flags,context);if(phase==="flexible-sign-in")return flexibleSignInConfig(action??"show",positional.slice(2),repoGiven!==void 0,flags,context);if(action===void 0||action==="show"){const installation=store.listPhaseConfig(INSTALLATION_SCOPE),project=scope===INSTALLATION_SCOPE?[]:store.listPhaseConfig(scope),resolved=["plan","build","repair","review"].map(one=>{const answer=resolvePhaseAgent(store,one,scope===INSTALLATION_SCOPE?null:scope,{});return{phase:one,...answer.ok?{provider:answer.spec.provider,model:answer.spec.model,source:answer.source}:{problem:answer.problem}}}),candidates=resolveRouteCandidates(store,scope===INSTALLATION_SCOPE?null:scope),strong=["plan","build","repair","review"].map(one=>({phase:one,strong:candidates.ok?candidates.candidates[one].strong:null})),alsoRows=[...store.listPhaseTierAlternates(INSTALLATION_SCOPE),...scope===INSTALLATION_SCOPE?[]:store.listPhaseTierAlternates(scope)],unusedLight=[INSTALLATION_SCOPE,...scope===INSTALLATION_SCOPE?[]:[scope]].filter(one=>store.phaseTierConfig(one,"plan","light")!==null);if(json)return write(envelopeJson({ok:!0,command:"config show",installation,project,resolved,strong,installationStrong:store.listPhaseTierConfig(INSTALLATION_SCOPE),projectStrong:scope===INSTALLATION_SCOPE?[]:store.listPhaseTierConfig(scope),installationAlso:store.listPhaseTierAlternates(INSTALLATION_SCOPE),projectAlso:scope===INSTALLATION_SCOPE?[]:store.listPhaseTierAlternates(scope)})),EXIT.ok;write(`Effective phase agents${scope===INSTALLATION_SCOPE?"":` for ${scope}`}:`);for(const one of resolved)"problem"in one?write(` ${one.phase.padEnd(8)} MISCONFIGURED — ${one.problem}`):write(` ${one.phase.padEnd(8)} ${one.provider}${one.model===null?" (harness default model)":` · ${one.model}`} [${one.source}]`);write(""),write(" strong tier (large or risky, strict, screenshot-proof, and automerge routes reach for these):");for(const one of strong)write(` ${one.phase.padEnd(8)} ${one.strong===null?"none configured — such routes keep the default above and say so":`${one.strong.provider}${one.strong.model===null?" (harness default model)":` · ${one.strong.model}`} [${one.strong.source}]`}`);write(" set one with: toolroll config set <phase> --tier strong --provider <p> --model <m> --as <you> --token <t>"),write(""),write(" light tier (small changes build on this, with no plan):");const light=candidates.ok?candidates.candidates.build.light??null:null;write(` ${"build".padEnd(8)} ${light===null?"none configured — small changes keep the default above and say so":`${light.provider} · ${light.model} [${light.source}]`}`);for(const one of unusedLight)write(` ${"plan".padEnd(8)} not used — a small change makes no plan; \`config clear plan --tier light${one===INSTALLATION_SCOPE?"":` --repo ${one}`}\` removes it`);if(write(" set one with: toolroll config set build --tier light --provider <p> --model <m> --as <you> --token <t>"),write(""),candidates.ok){const also=["plan","build"].flatMap(one=>Object.entries(candidates.candidates[one].alternates??{}).flatMap(([tier,list])=>(list??[]).map(spec=>` ${one.padEnd(8)} ${tier.padEnd(8)} also ${spec.provider} · ${spec.model} [${spec.source}]`)));if(also.length>0||alsoRows.length>0){write(" other providers on a tier (each task runs the one whose plan has more room):");for(const line of also)write(line);write("")}}return write(" repair note: the repair PROVIDER always inherits the build it mends — only its model is configurable."),installation.length===0&&project.length===0&&(write(" nothing configured — every phase runs the default (claude)."),write(" toolroll config set build --provider claude --model sonnet --as <you> --token <t>")),EXIT.ok}if(action!=="set"&&action!=="clear")return fail(write,json,"config","usage","`toolroll config [show|set <phase> --provider <p> [--model <m>]|clear <phase>] [--repo <path>] --as <you> --token <t>`",EXIT.usage);if((phase==="budgets"||phase==="chat")&&currentLocalOwner()!==null)return fail(write,json,`config ${action}`,"refused","Spend settings need your password: change them in Settings → Spend (or Settings → Lead), or pass `--as <you> --token <t>`.",EXIT.refused);if(phase==="budgets"){const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,`config ${action}`,"usage","changing spend defaults takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting2.name,acting2.token).ok)return fail(write,json,`config ${action}`,"unauthenticated","that is not an approver, or the token does not match",EXIT.refused);if(action==="clear")return store.setSpendDefaults({buildPerRunMicrousd:null},acting2.name,clock()),succeed(write,json,"config clear",{budgets:null},()=>["Spend defaults cleared — filings state their own numbers again."]);const build2=(flag2=>{const given=text(flags,flag2);if(given===void 0)return null;const value=Number(given);return Number.isFinite(value)&&value>0?Math.round(value*1e6):!1})("build-usd");return build2===!1?fail(write,json,"config set","usage","--build-usd is a positive dollar amount",EXIT.usage):(store.setSpendDefaults({buildPerRunMicrousd:build2},acting2.name,clock()),succeed(write,json,"config set",{budgets:store.getSpendDefaults()},()=>["Spend defaults set. New filings pre-fill from these; every approval still restates its own numbers:",...build2===null?[]:[` each ordinary build attempt: $${(build2/1e6).toFixed(2)} (also the installation backstop)`]]))}if(phase==="chat"){if(repoGiven!==void 0)return fail(write,json,`config ${action}`,"usage","chat is installation-scoped — no --repo",EXIT.usage);const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,`config ${action}`,"usage","changing chat spend takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting2.name,acting2.token).ok)return fail(write,json,`config ${action}`,"unauthenticated","that is not an approver, or the token does not match",EXIT.refused);if(action==="clear")return store.clearChatConfig(),succeed(write,json,"config clear",{chat:null},()=>["Chat is off — the config row is gone."]);const provider=text(flags,"provider"),requestedModel=text(flags,"model"),weeklyUsd=text(flags,"weekly-usd"),dailyGiven=text(flags,"daily-turns");if(provider!=="anthropic-api"&&provider!=="openrouter-api"&&provider!=="claude-subscription"&&provider!=="codex-subscription"&&provider!=="gemini-subscription"&&provider!=="grok-subscription")return fail(write,json,"config set","usage","chat provider is one of claude-subscription, codex-subscription, gemini-subscription, grok-subscription, anthropic-api, openrouter-api",EXIT.usage);const model=requestedModel??(isSubscriptionChatProvider(provider)?"default":"");if(!validModelId(model))return fail(write,json,"config set","usage","--model must be 1–128 letters, digits, dots, slashes, colons, underscores, or dashes",EXIT.usage);const priced=isDirectChatProvider(provider)?livePin(store,provider,model)??priceOf(model):null;if(isDirectChatProvider(provider)&&priced===null)return fail(write,json,"config set","unpriced-model",`chat reserves worst-case spend up front, so the model needs a price — run "toolroll models check" to load live prices, or pick one priced today: ${PRICED_MODELS.join(", ")}`,EXIT.refused);const weekly=Number(weeklyUsd);if(isDirectChatProvider(provider)&&(weeklyUsd===void 0||!Number.isFinite(weekly)||weekly<=0))return fail(write,json,"config set","usage","--weekly-usd <dollars> is required — chat without a ceiling is not configured, it is unbounded",EXIT.usage);const daily=dailyGiven===void 0?50:Number(dailyGiven);if(!Number.isInteger(daily)||daily<=0||daily>1e3)return fail(write,json,"config set","usage","--daily-turns is a whole number between 1 and 1000",EXIT.usage);const pinned=isDirectChatProvider(provider)?priced:{inMicrousd:0,outMicrousd:0};return pinned===null?fail(write,json,"config set","unpriced-model",`no compiled price for ${model}`,EXIT.refused):(store.setChatConfig({provider,model,dailyTurns:daily,weeklyCeilingMicrousd:isDirectChatProvider(provider)?Math.round(weekly*1e6):0,priceInMicrousd:pinned.inMicrousd,priceOutMicrousd:pinned.outMicrousd},acting2.name,clock()),succeed(write,json,"config set",{chat:store.getChatConfig()},()=>[isDirectChatProvider(provider)?`Chat answers with ${provider} · ${model}, at most ${daily} turns/day, at most $${weekly.toFixed(2)} per rolling week.`:`Chat answers through the logged-in ${provider==="codex-subscription"?"Codex":"Claude"} harness${model==="default"?" using its default model":` · ${model}`}, at most ${daily} turns/day, with no dollar ceiling.`,isDirectChatProvider(provider)?`The key rides the serve environment (${provider==="anthropic-api"?"ANTHROPIC_API_KEY":"OPENROUTER_API_KEY"}) — never this database.`:`The harness reuses its cached membership login; authenticate first with ${provider==="codex-subscription"?"`codex login`":"the `claude` CLI"}.`,...isSubscriptionChatProvider(provider)&&weeklyUsd!==void 0?["The supplied --weekly-usd value was ignored because membership usage has no dollar meter."]:[]]))}if(phase===void 0||!["plan","build","repair","review"].includes(phase))return fail(write,json,`config ${action}`,"usage","which phase? plan, build, repair, review — or chat",EXIT.usage);const owner=currentLocalOwner(),acting=owner!==null?{name:owner.account,token:""}:await askCredentials(flags,context),provedGeneration=acting===null?-1:store.accountOf(acting.name)?.generation??-1,verified=owner!==null?{ok:!0,method:"local-owner"}:acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||verified===null||!verified.ok)return refuseApprover(context,`config ${action}`,verified,"changing spend routing takes `--as <you> --token <t>`",phase);const tierGiven=text(flags,"tier");if(tierGiven!==void 0&&tierGiven!=="strong"&&tierGiven!=="light")return fail(write,json,`config ${action}`,"usage","--tier is `light` or `strong` — the routine tier is the plain phase row",EXIT.usage);if(tierGiven==="light"&&phase!=="build"&&!(action==="clear"&&phase==="plan"&&!flag(flags,"also")))return fail(write,json,`config ${action}`,"usage","--tier light is for build only — a small change makes no plan, and repairs resume the builder's session",EXIT.usage);const projectKnown=repoGiven===void 0||await knownProject(context,repoGiven,{listed:!0,canonical:!0})!==void 0,proof={actor:acting.name,generation:provedGeneration,method:verified.method},written=(slot,to,extra=[])=>writeModelRow(store,proof,scope,()=>projectKnown,slot,to,clock(),extra),fast=ownerMode(store,clock())==="fast",askReroute=flag(flags,"reroute"),said=(command,result,payload,lines)=>{const incomplete=result.ok?result.unresolved:null,changedSlots=result.ok&&result.diff.length>0?result.diff.map(one=>one.slot):void 0,changed=result.ok&&(result.diff.length>0||result.extra>0);let reroutePayload={};const rerouteLines=[];if(result.ok&&(fast&&changed||askReroute)){const moved=rerouteWaitingTasks(store,scope,clock(),changedSlots===void 0?{}:{changedSlots}),words=rerouteReplyWords(moved);words!==null?(reroutePayload={rerouted:{count:moved.moved.length,tasks:moved.moved.map(one=>one.taskId),replanned:moved.replanned,agent:moved.agentLabel}},rerouteLines.push(` ${words}`)):askReroute&&(reroutePayload={rerouted:{count:0,tasks:[],replanned:0,agent:moved.agentLabel}},rerouteLines.push(" No waiting tasks needed re-routing."))}else if(result.ok&&!fast&&!askReroute&&changed){const eligible=eligibleModelChangeTasks(store,scope,clock(),changedSlots===void 0?{}:{changedSlots});eligible.length>0&&(reroutePayload={reroutable:{count:eligible.length,tasks:eligible.map(one=>one.taskId)}},rerouteLines.push(` Re-route ${eligible.length} task${eligible.length===1?"":"s"} to match: re-run with --reroute (or use Settings → Models).`))}return succeed(write,json,command,{...payload,...reroutePayload,...incomplete===null?{}:{incomplete}},()=>[...lines(),...rerouteLines,...incomplete===null?[]:[` ! new tasks can't be filed here yet: ${incomplete}`]])};if(flag(flags,"also")){if(phase!=="plan"&&phase!=="build")return fail(write,json,`config ${action}`,"usage","--also is for plan or build — repairs follow the build's provider",EXIT.usage);const tier=tierGiven??"routine",alsoProvider=text(flags,"provider");if(alsoProvider!==void 0&&!isProviderId(alsoProvider))return fail(write,json,`config ${action}`,"usage",`--provider is one of ${PROVIDER_IDS.join(", ")}`,EXIT.usage);if(action==="clear"){const alsoClear=written(null,null,[{kind:"also-clear",phase,tier,provider:alsoProvider??null}]);if(!alsoClear.ok)return fail(write,json,"config clear",alsoClear.reason,alsoClear.problem,EXIT.refused);const removed=alsoClear.extra;return said("config clear",alsoClear,{scope,phase,tier,also:!0,provider:alsoProvider??null,cleared:removed},()=>[removed>0?`Removed ${removed} other-provider ${tier} ${phase} agent${removed===1?"":"s"} at ${scope}; sealed routes are untouched.`:`No other-provider ${tier} ${phase} agent${alsoProvider===void 0?"":` on ${alsoProvider}`} was configured at ${scope}.`])}const alsoModel=text(flags,"model");if(alsoProvider===void 0||alsoModel===void 0)return fail(write,json,"config set","usage","--also names an exact --provider and --model — approvals bind exact routing",EXIT.usage);const alsoValid=validateSpec({provider:alsoProvider,model:alsoModel});if(!alsoValid.ok)return fail(write,json,"config set","invalid",alsoValid.problem,EXIT.usage);const alsoSet=written(null,null,[{kind:"also-set",phase,tier,provider:alsoProvider,model:alsoModel}]);if(!alsoSet.ok)return fail(write,json,"config set",alsoSet.reason,alsoSet.problem,EXIT.refused);const resolvedNow=resolveRouteCandidates(store,scope===INSTALLATION_SCOPE?null:scope),own=resolvedNow.ok?tier==="routine"?resolvedNow.candidates[phase].routine:tier==="light"?resolvedNow.candidates[phase].light??null:resolvedNow.candidates[phase].strong:null;return said("config set",alsoSet,{scope,phase,tier,also:!0,provider:alsoProvider,model:alsoModel},()=>[`${tier} ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} can also run ${alsoProvider} · ${alsoModel}, set by ${acting.name}.`,own!==null&&own.provider===alsoProvider&&!own.source.includes("also")?` ! the ${tier} ${phase} agent already runs ${alsoProvider} (${own.model}) — this one is not used while it does.`:" tasks filed from now on run on whichever provider's plan has more room; sealed routes are untouched."])}if(action==="clear"){if(tierGiven==="light"&&phase==="build"){const lightWrite=written({phase,tier:"light"},null);if(!lightWrite.ok)return fail(write,json,"config clear",lightWrite.reason,lightWrite.problem,EXIT.refused);const clearedLight=lightWrite.diff.length>0;return said("config clear",lightWrite,{scope,phase,tier:"light",cleared:clearedLight},()=>[clearedLight?`Cleared the light ${phase} agent at ${scope} — small changes keep the default and say so; sealed routes are untouched.`:`No light ${phase} agent was configured at ${scope}.`])}if(tierGiven==="light"){const legacyClear=written(null,null,[{kind:"legacy-light-clear",phase}]);if(!legacyClear.ok)return fail(write,json,"config clear",legacyClear.reason,legacyClear.problem,EXIT.refused);const clearedLight=legacyClear.extra>0;return said("config clear",legacyClear,{scope,phase,tier:"light",cleared:clearedLight},()=>[clearedLight?`Cleared the light ${phase} agent at ${scope} — small changes keep the default and say so; sealed routes are untouched.`:`No light ${phase} agent was configured at ${scope}.`])}if(tierGiven==="strong"){const strongWrite=written({phase,tier:"strong"},null);if(!strongWrite.ok)return fail(write,json,"config clear",strongWrite.reason,strongWrite.problem,EXIT.refused);const clearedStrong=strongWrite.diff.length>0;return said("config clear",strongWrite,{scope,phase,tier:"strong",cleared:clearedStrong},()=>[clearedStrong?`Cleared the strong ${phase} agent at ${scope} — demanding routes keep the default and say so; sealed routes are untouched.`:`No strong ${phase} agent was configured at ${scope}.`])}const routineWrite=written({phase,tier:"routine"},null);if(!routineWrite.ok)return fail(write,json,"config clear",routineWrite.reason,routineWrite.problem,EXIT.refused);const cleared=routineWrite.diff.length>0;return said("config clear",routineWrite,{scope,phase,cleared},()=>[cleared?`Cleared ${phase} at ${scope} — it resolves one layer down now.`:`Nothing was configured for ${phase} at ${scope}.`])}const providerGiven=text(flags,"provider");if(providerGiven===void 0||!isProviderId(providerGiven))return fail(write,json,"config set","usage",`--provider is one of ${PROVIDER_IDS.join(", ")}`,EXIT.usage);const modelGiven=text(flags,"model")??null,valid=validateSpec({provider:providerGiven,model:modelGiven});if(!valid.ok)return fail(write,json,"config set","invalid",valid.problem,EXIT.usage);if(tierGiven==="light"){if(modelGiven===null)return fail(write,json,"config set","usage",`a light ${phase} agent names an exact --model — approvals bind exact routing`,EXIT.usage);const lightSet=written({phase,tier:"light"},{provider:providerGiven,model:modelGiven});return lightSet.ok?said("config set",lightSet,{scope,phase,tier:"light",provider:providerGiven,model:modelGiven},()=>[`light ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} is ${providerGiven} · ${modelGiven}, set by ${acting.name}.`," small changes filed from now on build on it with no plan; sealed routes are untouched."]):fail(write,json,"config set",lightSet.reason,lightSet.problem,EXIT.refused)}if(tierGiven==="strong"){if(phase==="review"&&providerGiven==="gemini")return fail(write,json,"config set","invalid","gemini has no isolation posture for the review phase yet — name claude or codex as the strong reviewer",EXIT.usage);if(modelGiven===null)return fail(write,json,"config set","usage",`a strong ${phase} agent names an exact --model — approvals bind exact routing`,EXIT.usage);const strongSet=written({phase,tier:"strong"},{provider:providerGiven,model:modelGiven});if(!strongSet.ok)return fail(write,json,"config set",strongSet.reason,strongSet.problem,EXIT.refused);const followed2=(strongSet.repairFollowed??[]).map(one=>({slot:one.slot.tier==="routine"?one.slot.phase:`${one.slot.phase}-${one.slot.tier}`,provider:one.effective.provider,model:one.effective.model})),followedLines2=(strongSet.repairFollowed??[]).map(one=>{const name=one.slot.tier==="strong"?"strong repair":"repair",target=`${one.effective.provider}${one.effective.model===null?"":` · ${one.effective.model}`}`;return` ${name} moved with it to ${target}.`});return said("config set",strongSet,{scope,phase,tier:"strong",provider:providerGiven,model:modelGiven,...followed2.length>0?{repairFollowed:followed2}:{}},()=>[`strong ${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} is ${providerGiven}${modelGiven===null?"":` · ${modelGiven}`}, set by ${acting.name}.`,...followedLines2," large or risky, strict, screenshot-proof, and automerge routes filed from now on reach for it; sealed routes are untouched.",...phase==="repair"?[" a strong repair agent applies only when its provider is the build's — cross-provider repair does not exist."]:[]])}const routineSet=written({phase,tier:"routine"},{provider:providerGiven,model:modelGiven});if(!routineSet.ok)return fail(write,json,"config set",routineSet.reason,routineSet.problem,EXIT.refused);const followed=(routineSet.repairFollowed??[]).map(one=>({slot:one.slot.tier==="routine"?one.slot.phase:`${one.slot.phase}-${one.slot.tier}`,provider:one.effective.provider,model:one.effective.model})),followedLines=(routineSet.repairFollowed??[]).map(one=>{const name=one.slot.tier==="strong"?"strong repair":"repair",target=`${one.effective.provider}${one.effective.model===null?"":` · ${one.effective.model}`}`;return` ${name} moved with it to ${target}.`}),warnings=[];return modelGiven===null&&warnings.push(`no --model named: approvals bind exact routing, so scopes cannot file until ${phase} has an exact model — \`config set ${phase} --provider ${providerGiven} --model <model>\``),providerGiven==="openrouter"&&(process.env.OPENROUTER_API_KEY??"")===""&&warnings.push("OPENROUTER_API_KEY is not present in this environment — runs will fail until the runner exports it."),providerGiven!=="claude"&&warnings.push(`${providerGiven} does not report dollar cost: its runs land as UNMEASURED, and any schedule with a weekly limit fails closed on them by design.`),said("config set",routineSet,{scope,phase,provider:providerGiven,model:modelGiven,warnings,...followed.length>0?{repairFollowed:followed}:{}},()=>[`${phase} at ${scope===INSTALLATION_SCOPE?"the installation":scope} now runs ${providerGiven}${modelGiven===null?"":` · ${modelGiven}`}, set by ${acting.name}.`,...followedLines,...warnings.map(one=>` ! ${one}`)])}async function setupCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),action=positional[0]??"show",repo=text(flags,"repo");if(action==="show"){if(repo===void 0)return fail(write,json,"setup show","usage","which repo? --repo <path>",EXIT.usage);const live=store.liveWorktreeSetup(repo);return json?(write(envelopeJson({ok:!0,command:"setup show",repo,setup:live})),EXIT.ok):(write(live===null?`No worktree setup for ${repo}. Fresh checkouts run nothing before the agent.`:`${repo} runs before every agent:
466
483
  ${live.command}
467
484
  timeout ${Math.round(live.timeoutMs/1e3)}s · digest ${live.digest} · approved by ${live.approvedBy} at ${live.approvedAt}`),EXIT.ok)}if(action!=="set"&&action!=="clear")return fail(write,json,"setup","usage","`toolroll setup [show|set --command <cmd> [--timeout-seconds <n>] [--yes|--request <why>]|clear] --repo <path> --as <you> --token <t>`",EXIT.usage);if(repo===void 0)return fail(write,json,`setup ${action}`,"usage","which repo? --repo <path>",EXIT.usage);if(action==="set"&&flags.has("request")){const reqCmd=text(flags,"command");if(reqCmd===void 0||reqCmd.trim()==="")return fail(write,json,"setup set","usage","--command <cmd> is what every fresh checkout will run",EXIT.usage);if(reqCmd.length>2e3||hasDisguisedText(reqCmd))return fail(write,json,"setup set","invalid","the command must be under 2000 characters with no control or bidi characters",EXIT.usage);if(/([A-Za-z0-9_-]*(?:token|secret|password|passwd|apikey|api_key|authorization|bearer|credential)[A-Za-z0-9_-]*\s*[=:]\s*)(?![$"']?\$)\S+/i.test(reqCmd)||/\/\/[^\s/@]+:[^\s/@]+@/.test(reqCmd))return fail(write,json,"setup set","credential-shaped","the command appears to embed a credential — reference an environment variable the runner exports (e.g. $NPM_TOKEN) instead of a literal value",EXIT.usage);const reqTimeoutSeconds=Number(text(flags,"timeout-seconds")??"300");if(!Number.isInteger(reqTimeoutSeconds)||reqTimeoutSeconds<1||reqTimeoutSeconds>3600)return fail(write,json,"setup set","invalid","--timeout-seconds is 1..3600",EXIT.usage);const resolvedRepo=await knownProject(context,repo,{listed:!0,canonical:!0})??resolve(repo),req=fileAgentRequest(context.databaseFile,{kind:"worktree-setup",repo:resolvedRepo,...text(flags,"by")===void 0?{}:{requester:text(flags,"by")},summary:`Set worktree setup: ${reqCmd}`,why:text(flags,"why")??text(flags,"request")??"",params:{command:reqCmd,timeoutSeconds:reqTimeoutSeconds}},clock());return finishFiledRequest("setup set",req,flags,context)}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`setup ${action}`,verified,"an approved setup runs unattended in every future worktree — changing it takes `--as <you> --token <t>`",repo);if(action==="clear"){const cleared=store.clearWorktreeSetup(repo,acting.name,clock());return succeed(write,json,"setup clear",{repo,cleared},()=>[cleared?`Cleared — fresh checkouts of ${repo} run nothing now.`:`Nothing was set for ${repo}.`])}const command=text(flags,"command");if(command===void 0||command.trim()==="")return fail(write,json,"setup set","usage","--command <cmd> is what every fresh checkout will run",EXIT.usage);if(command.length>2e3||hasDisguisedText(command))return fail(write,json,"setup set","invalid","the command must be under 2000 characters with no control or bidi characters",EXIT.usage);if(/([A-Za-z0-9_-]*(?:token|secret|password|passwd|apikey|api_key|authorization|bearer|credential)[A-Za-z0-9_-]*\s*[=:]\s*)(?![$"']?\$)\S+/i.test(command)||/\/\/[^\s/@]+:[^\s/@]+@/.test(command))return fail(write,json,"setup set","credential-shaped","the command appears to embed a credential — reference an environment variable the runner exports (e.g. $NPM_TOKEN) instead of a literal value",EXIT.usage);const timeoutSeconds=Number(text(flags,"timeout-seconds")??"300");if(!Number.isInteger(timeoutSeconds)||timeoutSeconds<1||timeoutSeconds>3600)return fail(write,json,"setup set","invalid","--timeout-seconds is 1..3600",EXIT.usage);if(flags.get("yes")!==!0){if(json)return write(envelopeJson({ok:!1,command:"setup set",reason:"unconfirmed",repo,setupCommand:command,timeoutSeconds})),EXIT.refused;for(const line of["The terms, exactly:",` repo ${repo}`,` command ${command}`,` timeout ${timeoutSeconds}s`,"","Every FUTURE worktree of this repo runs this command unattended,","before any agent spawns in it, under an ALLOWLISTED environment","(PATH, HOME, locale, temp — no credentials). A failed setup blocks","the build as an environment problem. Re-run with --yes to approve."])write(line);return EXIT.refused}const saved=store.setWorktreeSetup({repo,command,timeoutMs:timeoutSeconds*1e3,approvedBy:acting.name},clock());return succeed(write,json,"setup set",{repo,digest:saved.digest,timeoutSeconds},()=>[`Approved: fresh checkouts of ${repo} run \`${command}\` (digest ${saved.digest}, ${timeoutSeconds}s) before any agent.`])}async function verifyCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),action=positional[0]??"show",raw=text(flags,"repo");if(raw!==void 0&&activeRemote()!==null&&!isAbsolute(raw))return fail(write,json,`verify ${action}`,"usage","name the project's full path: --repo <path>",EXIT.usage);const repo=raw===void 0?void 0:verifyRepoOf(store,raw),legacy=raw!==void 0&&raw!==repo&&!isAbsolute(raw)&&store.liveVerifyCommand(raw)!==null?raw:null,legacyNote=legacy===null?[]:[`An older check command saved under the name "${legacy}" applies to no project. Set the command for ${repo} again; \`toolroll verify clear --repo ${legacy}\` removes the old one.`];if(action==="show"){if(repo===void 0)return fail(write,json,"verify show","usage","which repo? --repo <path>",EXIT.usage);for(const line of json?[]:legacyNote)write(line);const live=store.liveVerifyCommand(repo),quick=liveQuickCommand(store,repo),level=projectCheckLevel(store,repo),suggestion=quick===null?suggestQuickCommand(repo):null;return json?(write(envelopeJson({ok:!0,command:"verify show",repo,verify:live,quick,level:level.level,...suggestion===null?{}:{suggestedQuick:suggestion}})),EXIT.ok):(write(live===null?`No verification command for ${repo}. A build's proof lands "attested" at best — nothing re-runs it.`:`${repo} re-runs after every commit:
468
485
  ${live.command}
@@ -471,25 +488,25 @@ Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:comman
471
488
  ${quick.command}
472
489
  timeout ${Math.round(quick.timeoutMs/1e3)}s · digest ${quick.digest} · approved by ${quick.approvedBy}`):level.level==="quick"&&write(`No quick command yet, so Quick runs the full check.${suggestion===null?"":` Suggested from the project's scripts:
473
490
  toolroll verify set --repo ${repo} --quick "${suggestion}"`}`),EXIT.ok)}if(action==="level"){if(repo===void 0)return fail(write,json,"verify level","usage","which repo? --repo <path>",EXIT.usage);const wanted=positional[1];if(!isCheckLevel(wanted))return fail(write,json,"verify level","usage","`toolroll verify level quick|full|off --repo <path> --as <you> --token <t>`",EXIT.usage);if(passwordFreeInstall(store,flags,context.principal!==void 0))return fail(write,json,"verify level","local-owner","Changing a check needs a password. Run `toolroll password set` first.",EXIT.refused);const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,"verify level","usage","changing a project's checks takes `--as <you> --token <t>`",EXIT.usage);const authenticated=authenticateApprover(store,acting2.name,acting2.token,repo);if(!authenticated.ok)return fail(write,json,"verify level",authenticated.reason,describeApproveFailure(authenticated.reason,repo),EXIT.refused);const changed=setProjectCheckLevel(store,repo,wanted,acting2.name,clock()),runsFull=wanted==="quick"&&liveQuickCommand(store,repo)===null;return succeed(write,json,"verify level",{repo,level:wanted,before:changed.before,changed:changed.changed},()=>[`${repo}: checks are ${CHECK_LEVEL_WORDS[wanted]}${changed.changed?` (was ${CHECK_LEVEL_WORDS[changed.before]})`:""}. ${CHECK_LEVEL_HINTS[wanted]}`,...runsFull?[`No quick command is approved yet, so builds run the full check. Approve one with \`toolroll verify set --repo ${repo} --quick "<cmd>"\`.`]:[],...wanted!=="full"?["The full check still runs when a pull request opens, and Merge waits for it unless a person merges anyway."]:[]])}if(action!=="set"&&action!=="clear")return fail(write,json,"verify","usage","`toolroll verify [show|level quick|full|off|set --command <cmd>|--quick <cmd> [--timeout-seconds <n>] [--self-heal --setup-digest <shown>] --yes|clear [--level quick]] --repo <path> --as <you> --token <t>`",EXIT.usage);const quickValue=text(flags,"quick"),quickClear=action==="clear"&&text(flags,"level")==="quick",grantKey=repo===void 0?void 0:quickValue!==void 0||quickClear?quickVerifyKey(repo):repo;if(repo===void 0)return fail(write,json,`verify ${action}`,"usage","which repo? --repo <path>",EXIT.usage);if(passwordFreeInstall(store,flags,context.principal!==void 0))return fail(write,json,`verify ${action}`,"local-owner",`${action==="set"?"Setting":"Clearing"} a check needs a password. Run \`toolroll password set\` first.`,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`verify ${action}`,verified,"an approved verification command runs unattended after every future build — changing it takes `--as <you> --token <t>`",repo);if(action==="clear"){legacy!==null&&!quickClear&&store.clearVerifyCommand(legacy,acting.name,clock());const cleared=store.clearVerifyCommand(grantKey,acting.name,clock())||legacy!==null&&!quickClear;return quickClear?succeed(write,json,"verify clear",{repo,cleared,level:"quick"},()=>[cleared?`Cleared the quick command — Quick builds of ${repo} run the full check now.`:`No quick command was set for ${repo}.`]):succeed(write,json,"verify clear",{repo,cleared},()=>[cleared?`Cleared — builds of ${repo} land "attested" at best now; nothing re-runs.`:`Nothing was set for ${repo}.`])}const command=quickValue??text(flags,"command");if(quickValue!==void 0&&text(flags,"command")!==void 0)return fail(write,json,"verify set","usage",'give the quick command with --quick "<cmd>" or the full one with --command, not both',EXIT.usage);if(quickValue!==void 0&&flags.get("self-heal")===!0)return fail(write,json,"verify set","usage","--self-heal applies to the full command only",EXIT.usage);if(command===void 0||command.trim()==="")return fail(write,json,"verify set","usage","--command <cmd> is what the plane re-runs after every commit",EXIT.usage);if(command.length>2e3||hasDisguisedText(command))return fail(write,json,"verify set","invalid","the command must be under 2000 characters with no control or bidi characters",EXIT.usage);if(/([A-Za-z0-9_-]*(?:token|secret|password|passwd|apikey|api_key|authorization|bearer|credential)[A-Za-z0-9_-]*\s*[=:]\s*)(?![$"']?\$)\S+/i.test(command)||/\/\/[^\s/@]+:[^\s/@]+@/.test(command))return fail(write,json,"verify set","credential-shaped","the command appears to embed a credential — reference an environment variable the runner exports (e.g. $NPM_TOKEN) instead of a literal value",EXIT.usage);const timeoutSeconds=Number(text(flags,"timeout-seconds")??"300");if(!Number.isInteger(timeoutSeconds)||timeoutSeconds<1||timeoutSeconds>3600)return fail(write,json,"verify set","invalid","--timeout-seconds is 1..3600",EXIT.usage);const selfHeal=flags.get("self-heal")===!0,expectedSetupDigest=text(flags,"setup-digest");if(!selfHeal&&expectedSetupDigest!==void 0)return fail(write,json,"verify set","usage","--setup-digest is only valid with --self-heal",EXIT.usage);const recoverySetup=selfHeal?store.liveWorktreeSetup(repo):null;if(selfHeal&&recoverySetup===null)return fail(write,json,"verify set","setup-required","self-healing needs an approved project setup first — set the exact preparation command, then approve verification again with --self-heal",EXIT.refused);if(flags.get("yes")!==!0){if(json)return write(envelopeJson({ok:!1,command:"verify set",reason:"unconfirmed",repo,...quickValue===void 0?{}:{level:"quick"},verifyCommand:command,timeoutSeconds,selfHeal,recoverySetup:recoverySetup===null?null:{command:recoverySetup.command,digest:recoverySetup.digest}})),EXIT.refused;for(const line of["The terms, exactly:",` repo ${repo}`,` command ${command}`,` timeout ${timeoutSeconds}s`,"",quickValue===void 0?"Every FUTURE build of this repo re-runs this command unattended,":"Every FUTURE Quick build of this repo runs this command unattended,","once, right after it commits — under an ALLOWLISTED environment","(PATH, HOME, locale, temp — no credentials). A pass lands the",'build "verified"; a failure lands it "refuted", never blocked.',...recoverySetup===null?[]:["","Self-healing, exactly: if this check cannot start because a","required project executable is unavailable, Toolroll may replay",`the approved setup \`${recoverySetup.command}\` (digest ${recoverySetup.digest}) once,`,"then retry this exact check once. It stops if custody changes,","setup fails, or setup changes tracked files after the commit."],recoverySetup===null?"Re-run with --yes to approve.":`Re-run with --setup-digest ${recoverySetup.digest} --yes to approve.`])write(line);return EXIT.refused}if(selfHeal&&expectedSetupDigest===void 0)return fail(write,json,"verify set","setup-digest-required",`confirm self-healing with --setup-digest ${recoverySetup?.digest} exactly as previewed`,EXIT.refused);if(selfHeal&&expectedSetupDigest!==recoverySetup?.digest)return fail(write,json,"verify set","stale-approval",`the approved setup changed after preview — expected ${expectedSetupDigest}, current ${recoverySetup?.digest}; preview verification again before approving`,EXIT.refused);const saved=store.setVerifyCommand({repo:grantKey,command,timeoutMs:timeoutSeconds*1e3,approvedBy:acting.name,recoverySetupDigest:recoverySetup?.digest??null},clock());return quickValue!==void 0?succeed(write,json,"verify set",{repo,level:"quick",digest:saved.digest,timeoutSeconds},()=>[`Approved the quick check: Quick builds of ${repo} run \`${command}\` (digest ${saved.digest}, ${timeoutSeconds}s) right after commit.`]):succeed(write,json,"verify set",{repo,digest:saved.digest,timeoutSeconds,selfHeal},()=>[`Approved: builds of ${repo} re-run \`${command}\` (digest ${saved.digest}, ${timeoutSeconds}s) right after commit${selfHeal?"; a missing required project executable gets one bounded approved-setup recovery":""}.`])}const GITHUB_REPO_SHAPE=/^[A-Za-z0-9_.-]{1,80}\/[A-Za-z0-9_.-]{1,100}$/,LABEL_SHAPE=/^[A-Za-z0-9][A-Za-z0-9:_. -]{0,49}$/;function intakeTaskId(github,issueNumber){const suffix=`-${issueNumber}`;return`ghi-${github.replace(/[^A-Za-z0-9._-]+/g,"-")}`.slice(0,64-suffix.length)+suffix}async function intakeCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),gh=context.gitRunner??run,action=positional[0]??"show",repo=repoFrom(flags);if(action==="pr-comments"||action==="preview"||action==="run"){const demoFence=refuseDemo(context,`intake ${action}`);if(demoFence!==null)return demoFence}if(action==="show"){const grant2=store.liveIntakeGrant(repo);return json?(write(envelopeJson({ok:!0,command:"intake show",repo,grant:grant2})),EXIT.ok):(write(grant2===null?`No intake grant for ${repo}. Nothing on GitHub becomes a proposal here.`:`${repo} intakes GitHub issues from ${grant2.github} labeled "${grant2.label}"${grant2.reviewers===null?"":`; PR comments from: ${grant2.reviewers.join(", ")}`} — granted by ${grant2.approvedBy} at ${grant2.approvedAt}.`),EXIT.ok)}if(action==="grant"||action==="clear"){const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`intake ${action}`,verified,"an intake grant is standing authority — it takes `--as <you> --token <t>`",repo);if(action==="clear"){const cleared=store.clearIntakeGrant(repo,acting.name,clock());return succeed(write,json,"intake clear",{repo,cleared},()=>[cleared?`Revoked — nothing on GitHub becomes a proposal for ${repo} now.`:`Nothing was granted for ${repo}.`])}const github=text(flags,"github"),label=text(flags,"label");if(github===void 0||!GITHUB_REPO_SHAPE.test(github))return fail(write,json,"intake grant","usage","--github <owner/name> names the repository on GitHub",EXIT.usage);if(label===void 0||!LABEL_SHAPE.test(label))return fail(write,json,"intake grant","usage","--label <label> names the exact label that nominates an issue",EXIT.usage);const reviewersRaw=text(flags,"reviewers"),reviewers=reviewersRaw===void 0?null:reviewersRaw.split(",").map(one=>one.trim()).filter(one=>/^[A-Za-z0-9-]{1,39}$/.test(one));if(flags.get("yes")!==!0){if(json)return write(envelopeJson({ok:!1,command:"intake grant",reason:"unconfirmed",repo,github,label,reviewers})),EXIT.refused;for(const line of["The terms, exactly:",` local repo ${repo}`,` github ${github}`,` label ${label}`,` pr comments ${reviewers===null||reviewers.length===0?"nobody's — PR-comment intake stays off":`from ${reviewers.join(", ")} only`}`,"","Open issues carrying exactly this label become LOCAL, UNAPPROVED task","proposals when `toolroll intake run` passes. Nothing builds","without a scope you approve; nothing on GitHub is ever written to.","Re-run with --yes to grant."])write(line);return EXIT.refused}const granted=store.setIntakeGrant({repo,github,label,reviewers,approvedBy:acting.name},clock());return succeed(write,json,"intake grant",{repo,github,label,reviewers:granted.reviewers},()=>[`Granted: issues in ${github} labeled "${label}" become unapproved proposals for ${repo}.`])}if(action!=="preview"&&action!=="run"&&action!=="pr-comments")return fail(write,json,"intake","usage","`toolroll intake [show|grant|clear|preview|run|pr-comments] --repo <path> …`",EXIT.usage);const grant=store.liveIntakeGrant(repo);if(grant===null)return fail(write,json,`intake ${action}`,"no-grant",`no intake grant for ${repo} — \`toolroll intake grant\` states the terms`,EXIT.refused);if(action==="pr-comments"){if(grant.reviewers===null||grant.reviewers.length===0)return fail(write,json,"intake pr-comments","no-reviewers","the grant names no reviewers — `intake grant --reviewers <logins>` is the authority for this",EXIT.refused);const publications=store.openedPublications().filter(one=>one.prNumber!==null&&store.refForId(one.taskRef)?.repo===repo&&one.githubRepo===grant.github);let ingested=0,duplicates=0,refused=0;const skippedPrs=[];for(const publication of publications){const pr=publication.prNumber,terminal=store.artifactsFor(publication.run).find(one=>one.kind==="terminal-diff");if(terminal===void 0){skippedPrs.push({pr,reason:"no terminal diff to bind comments to"});continue}const proven=readVerifiedArtifact(context.evidenceRoot,terminal);if(!proven.ok){skippedPrs.push({pr,reason:`the terminal diff no longer verifies — ${proven.problem}`});continue}const asked2=await gh("gh",["api","--paginate",`repos/${grant.github}/pulls/${pr}/comments`],{timeoutMs:6e4});if(asked2.code!==0){skippedPrs.push({pr,reason:"github unreachable"});continue}let remote;try{remote=JSON.parse(asked2.stdout)}catch{skippedPrs.push({pr,reason:"github answered without its promised JSON"});continue}if(!Array.isArray(remote)){skippedPrs.push({pr,reason:"github answered with JSON that is not the promised array"});continue}for(const comment of remote){const login=String(comment.user?.login??"");if(!grant.reviewers.some(one=>one.toLowerCase()===login.toLowerCase()))continue;const id=Number(comment.id);if(!Number.isInteger(id)||id<=0)continue;const body=validateNote(String(comment.body??""));if(!body.ok){refused+=1;continue}const rawPath=String(comment.path??""),lineRaw=comment.line??comment.original_line,line=typeof lineRaw=="number"&&Number.isInteger(lineRaw)&&lineRaw>0?lineRaw:null;store.addDiffComment({artifactId:terminal.id,runId:publication.run,path:rawPath!==""&&rawPath.length<=300&&!hasDisguisedText(rawPath)?rawPath:null,line,note:body.note,author:`github:${login}`,sourceKey:`gh:${grant.github}:${id}`},clock())===null?duplicates+=1:ingested+=1}}return succeed(write,json,"intake pr-comments",{repo,prs:publications.length,ingested,duplicates,refused,skippedPrs},()=>[`${ingested} comment(s) ingested across ${publications.length} PR(s)${duplicates>0?`, ${duplicates} already known`:""}${refused>0?`, ${refused} refused by the validator`:""}.`,...skippedPrs.map(one=>` PR #${one.pr} skipped: ${one.reason}`),ingested>0?"Seal them into revision tasks from each build's page — every revision takes its own approval.":""])}const limit=Math.min(Math.max(Number(text(flags,"limit")??"50"),1),200),asked=await gh("gh",["issue","list","--repo",grant.github,"--label",grant.label,"--state","open","--limit",String(limit),"--json","number,title,updatedAt"],{timeoutMs:2e4});if(asked.code!==0)return fail(write,json,`intake ${action}`,"github-unreachable",`gh could not list ${grant.github}: ${(asked.stderr.split(`
474
- `)[0]??"").slice(0,200)}`,EXIT.failed);let issues;try{issues=JSON.parse(asked.stdout)}catch{return fail(write,json,`intake ${action}`,"github-unreadable","gh answered, but not with the JSON it promised",EXIT.failed)}const candidates=issues.filter(issue=>Number.isInteger(issue.number)&&issue.number>0).map(issue=>{const id=intakeTaskId(grant.github,issue.number),title=String(issue.title??""),clean=title.length>0&&title.length<=180&&!hasDisguisedText(title);return{id,number:issue.number,title,clean,exists:store.getTask(id)!==null}});if(action==="preview"){if(json)return write(envelopeJson({ok:!0,command:"intake preview",repo,github:grant.github,label:grant.label,candidates})),EXIT.ok;if(candidates.length===0)return write(`Nothing open in ${grant.github} carries "${grant.label}".`),EXIT.ok;write(`Would intake from ${grant.github} ("${grant.label}"):`);for(const one of candidates)write(` #${one.number} ${one.exists?"already here as":one.clean?"→":"REFUSED (title carries control characters)"} ${one.id}${one.clean?` — ${one.title}`:""}`);return write("Nothing was created. `toolroll intake run` makes the proposals."),EXIT.ok}const created=[],skipped=[];for(const one of candidates){if(one.exists)continue;if(!one.clean){skipped.push({id:one.id,reason:"title-refused"});continue}const made=store.transact(()=>{const filed=fileTaskProposal(store,{id:one.id,title:`GH#${one.number}: ${one.title}`,repo,goal:`Imported from GitHub issue #${one.number} in ${grant.github} (label "${grant.label}"). Only the title was imported — read the issue at https://github.com/${grant.github}/issues/${one.number} for full context, then edit and approve this scope before anything builds.`,acceptance:[{id:"c1",statement:"The linked GitHub issue's request is read and addressed.",how:null,evidence:["manual-review"]}],filedVia:"intake"},clock());if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:"github-issues",remoteRepo:grant.github,remoteId:String(one.number),provenance:"intake",intakeGrant:grant.id,establishedBy:"intake"},clock());if(!established.ok&&established.reason!=="duplicate")throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok?created.push(made.id):skipped.push({id:one.id,reason:made.reason})}return succeed(write,json,"intake run",{repo,github:grant.github,label:grant.label,created,skipped},()=>[`${created.length} proposal(s) created${skipped.length>0?`, ${skipped.length} skipped`:""} — each awaits its own scope approval.`,...created.map(one=>` ${one}`),...skipped.map(one=>` skipped ${one.id}: ${one.reason}`)])}function templateCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional;if(action===void 0||action==="list"){if(json)return write(envelopeJson({ok:!0,command:"template list",templates:TEMPLATES.map(one=>({name:one.name,kind:one.kind,purpose:one.purpose}))})),EXIT.ok;write("Templates — common work you edit to fit. Nothing a template"),write("files is approved; recipes only show existing ceremonies."),write("");for(const one of TEMPLATES)write(` ${one.name.padEnd(16)} ${one.kind.padEnd(9)} ${one.purpose}`);return write(""),write("`toolroll template show <name>` · `template apply <name> --repo <path>`"),EXIT.ok}if(action!=="show"&&action!=="apply")return fail(write,json,`template ${action}`,"usage","`toolroll template list | show <name> | apply <name> --repo <path> [--file]`",EXIT.usage);if(name===void 0)return fail(write,json,`template ${action}`,"usage","which template? `toolroll template list` names them",EXIT.usage);const template=templateByName(name);if(template===null)return fail(write,json,`template ${action}`,"unknown",`no template named ${name} — \`toolroll template list\``,EXIT.refused);if(action==="show"){if(json)return write(envelopeJson({ok:!0,command:"template show",template})),EXIT.ok;if(write(`${template.name} — ${template.purpose}`),template.kind==="recipe"){write(""),write(`This one is a recipe, not an application: ${template.why}`);for(const step of template.steps)write(""),write(` ${step.say}`),write(` ${step.run}`);return EXIT.ok}write(""),template.kind==="task"?(write(" files one task (unapproved until you approve its scope)"),write(` title ${template.title}`)):(write(" makes a scheduled flow (nothing repeats until you turn the schedule on)"),write(` name ${template.title}`),write(` schedule ${template.schedule}`)),write(` goal ${template.goal}`),template.outOfScope!==null&&write(` not ${template.outOfScope}`),template.touches.length>0&&write(` touches ${template.touches.join(", ")}`),write(""),write("You will probably edit:");for(const hint of template.edit)write(` - ${hint}`);return write(""),write(`\`toolroll template apply ${template.name} --repo <path>\` previews the exact filing.`),EXIT.ok}if(template.kind==="recipe")return fail(write,json,"template apply","recipe",`${template.name} cannot be applied: ${template.why} \`toolroll template show ${template.name}\` walks the ceremonies.`,EXIT.refused);const repoGiven=text(flags,"repo");if(repoGiven===void 0)return fail(write,json,"template apply","usage","which repository? --repo <path> — a template never guesses where work lands",EXIT.usage);const goal=text(flags,"goal")??template.goal,outOfScope=text(flags,"not")??template.outOfScope,touches=text(flags,"touches")===void 0?template.touches:(text(flags,"touches")??"").split(",").map(one=>one.trim()).filter(one=>one!=="");if(template.kind==="task"){const title=text(flags,"title")??template.title,draft={kind:"task",title,repo:canonicalProject(repoGiven)??resolve(repoGiven),goal,outOfScope,touches,filedVia:`template:${template.name}`};if(!flags.has("file"))return json?(write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3):(write("Would file, exactly (edit with --title/--goal/--not/--touches):"),write(""),write(` task ${draft.title}`),write(` repo ${draft.repo}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),write(""),write("Nothing was filed. Re-run with --file to file it — UNAPPROVED either way."),3);const made2=fileTaskProposal(store,{title,repo:repoGiven,goal,outOfScope,touches,acceptance:template.acceptance,filedVia:`template:${template.name}`},clock());if(!made2.ok)return fail(write,json,"template apply",made2.reason,made2.message,made2.reason==="duplicate"?EXIT.refused:EXIT.usage);const filedLink=consoleLinkFor(context,`/t/${encodeURIComponent(made2.id)}`);return succeed(write,json,"template apply",{filed:"task",id:made2.id,approved:!1,...filedLink===null?{}:{links:{task:filedLink}}},()=>[`Filed ${made2.id} from template ${template.name}.`,"","UNAPPROVED — NO AUTHORITY GRANTED. It builds only after you approve its scope:",` toolroll task show ${made2.id}`,...filedLink===null?[]:[` ${filedLink}`]])}const flowName=text(flags,"name")??template.title,scheduleGiven=text(flags,"schedule")??template.schedule,schedule=parseSchedule(scheduleGiven)!==null?scheduleGiven:scheduleFromWords(scheduleGiven)??scheduleGiven,ceilingGiven=text(flags,"ceiling"),costCeilingUsd=ceilingGiven===void 0?template.costCeilingUsd:Number(ceilingGiven),repo=canonicalProject(repoGiven)??resolve(repoGiven),terms={goal,outOfScope,touches,requirements:template.requirements,acceptance:template.acceptance,budgetPerRunMicrousd:null,costCeilingUsd};if(!flags.has("file")){const draft={kind:"scheduled flow",name:flowName,repo,schedule,...terms,filedVia:`template:${template.name}`};if(json)return write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3;const readable=parseSchedule(schedule);return write("Would make this scheduled flow (edit with --name/--goal/--not/--touches/--schedule/--ceiling):"),write(""),write(` flow ${draft.name}`),write(` repo ${draft.repo}`),write(` schedule ${readable===null?schedule:describeSchedule(readable)}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),draft.costCeilingUsd!==null&&write(` ceiling $${draft.costCeilingUsd} every 7 days`),write(""),write("Nothing was made. Re-run with --file to make it. Nothing repeats until you turn the schedule on."),3}const made=createScheduledFlow(store,{repo,name:flowName,stem:template.name,schedule,terms,by:context.principal?.account??"toolroll",filedBy:context.principal?.account??null},clock());if(!made.ok)return fail(write,json,"template apply","bad-terms",made.message,EXIT.usage);const flowLink=consoleLinkFor(context,`/flows/${made.flow}`);return succeed(write,json,"template apply",{filed:"scheduled flow",flow:made.flow,trigger:made.trigger,on:!1,...flowLink===null?{}:{links:{flow:flowLink}}},()=>[`Made ${flowName}, flow #${made.flow}, from template ${template.name}.`,"","Nothing repeats until you turn the schedule on; each run then waits for approval under the project's rules:",` toolroll flows trigger resume ${made.flow} ${made.trigger}`,...flowLink===null?[]:[` ${flowLink}`]])}function readTokenFile(path){if(path!==void 0)try{const raw=readFileSync(path,"utf8").trim();return raw===""?void 0:raw}catch{return}}async function daemonCommand(positional,flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"daemon");if(demoFence!==null)return demoFence;const[action="status"]=positional,repo=repoFrom(flags),configDir=dirname(context.telegramTokenFile),supervise=context.gitRunner??run,binFlag=text(flags,"bin"),resolveBin=async()=>{const direct=daemonLaunchCommand({execPath:process.execPath,...process.argv[1]===void 0?{}:{entry:resolve(process.argv[1])},...binFlag===void 0?{}:{explicitBin:resolve(binFlag)}});if(direct!==null)return direct;const found=await supervise("sh",["-lc","command -v toolroll || command -v standing-orders"]);return found.code===0&&found.stdout.trim()!==""?{bin:process.execPath,binArgs:[found.stdout.trim()]}:null};if(action==="install"){const runnerName=text(flags,"runner"),inlineToken=text(flags,"token"),tokenPath=text(flags,"token-file");if(inlineToken!==void 0&&tokenPath!==void 0)return fail(write,json,"daemon install","usage","choose one credential source: --token or --token-file",EXIT.usage);const token=inlineToken??readTokenFile(tokenPath);if(runnerName===void 0||token===void 0)return fail(write,json,"daemon install","usage","`toolroll daemon install --runner <name> (--token <t> | --token-file <path>) --repo <path>` (plus any watch flags to bake in)",EXIT.usage);const auth=authenticate(store,runnerName,token);if(!auth.ok)return fail(write,json,"daemon install",auth.reason,describeAuth(auth.reason,runnerName),EXIT.refused);const heartbeatBefore=store.getRunner(runnerName)?.runner.heartbeatAt??null,located=await resolveBin();if(located===null)return fail(write,json,"daemon install","no-bin","`toolroll` is not on the PATH the service would use — run `toolroll link` first, or pass --bin <absolute path>",EXIT.refused);const watchFlags=[];for(const name of["pool","model","repair-model","provider","plan-model","plan-provider","max","turns","tick-every","bridge-every","reconcile-every","containment"]){const value=text(flags,name);value!==void 0&&watchFlags.push(`--${name}`,value)}watchFlags.includes("--containment")||watchFlags.push("--containment",currentContainment().policy);const plan2=planDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if("error"in plan2)return fail(write,json,"daemon install","unsupported",plan2.error,EXIT.refused);const legacy2=installedLegacyDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if(flags.has("dry-run"))return json?(write(envelopeJson({ok:!0,command:"daemon install",dryRun:!0,plan:plan2,replaces:legacy2?.label??null})),EXIT.ok):(write(`Would write ${plan2.unitPath}:`),write(""),write(plan2.unitContent),write(`Token (0600): ${plan2.tokenFile} · logs: ${plan2.logPath}`),legacy2!==null&&write(`Would stop and remove ${legacy2.label} (${legacy2.unitPath}), the same watch under its older name.`),write("Nothing was written. Re-run without --dry-run to install."),EXIT.ok);const installed=await installReplacingLegacy(plan2,token,legacy2,supervise);if(!installed.ok)return fail(write,json,"daemon install","supervisor",installed.message,EXIT.failed);const readySince=legacy2===null?heartbeatBefore:store.getRunner(runnerName)?.runner.heartbeatAt??null,started=await daemonStatus(plan2,supervise);if(started.state!=="running")return fail(write,json,"daemon install","not-running",`the service was installed but did not stay running (${started.detail}) — read ${plan2.logPath}; no work will be claimed until this is fixed`,EXIT.failed);const liveRunner=(await awaitFreshHeartbeat(store,runnerName,installed.action==="running"&&legacy2===null?null:readySince)).ok?store.getRunner(runnerName)?.runner??null:null;if(liveRunner===null){const macHint=process.platform==="darwin"&&repo.startsWith(join(homedir(),"Documents"))?" macOS may be blocking background access to Documents; grant the Node executable Full Disk Access, move the repository outside a protected folder, or keep `toolroll up` running from your terminal.":"";return fail(write,json,"daemon install","not-ready",`the supervisor has a process, but ${runnerName} never reached its worker heartbeat.${macHint} Read ${plan2.logPath}; no work will be claimed until the heartbeat appears`,EXIT.failed)}return succeed(write,json,"daemon install",{label:plan2.label,unit:plan2.unitPath,logs:plan2.logPath,state:started.state,pid:started.pid,heartbeatAt:liveRunner.heartbeatAt,action:installed.action,changed:installed.changed,replaced:legacy2?.label??null,containment:containmentStatus(currentContainment())},()=>[installed.action==="running"?`${plan2.label} was already running under this exact definition; left alone.`:installed.action==="reloaded"?`Reloaded ${plan2.label} under its changed definition.`:`Installed and started ${plan2.label}.`,...legacy2===null?[]:[` replaced ${legacy2.label} (stopped and removed)`],` verified ${started.detail}`,` worker ${runnerName} answered at ${liveRunner.heartbeatAt}`,` unit ${plan2.unitPath}`,` token ${plan2.tokenFile} (0600 — the unit never carries it)`,` logs ${plan2.logPath}`,"","It survives reboots and restarts itself after crashes; watch's","incarnation recovery makes those restarts safe. `toolroll daemon","status` to check on it, `daemon uninstall` to take it back off."])}const planArgs={platform:process.platform,bin:binFlag??"toolroll",binArgs:[],runner:text(flags,"runner")??"runner",repo,configDir,watchFlags:[]},current=planDaemon(planArgs);if("error"in current)return fail(write,json,`daemon ${action}`,"unsupported",current.error,EXIT.refused);const legacy=installedLegacyDaemon(planArgs),plan=legacy!==null&&!existsSync(current.unitPath)?legacy:current;if(action==="status"){const state=await daemonStatus(plan,supervise),containment=currentContainment();return json?(write(envelopeJson({ok:!0,command:"daemon status",...state,label:plan.label,logs:plan.logPath,containment:containmentStatus(containment)})),state.state==="running"?EXIT.ok:EXIT.refused):(write(`${plan.label}: ${state.detail}`),write(` logs ${plan.logPath}`),write(` ${describeContainment(containment)}`),state.state==="not-installed"&&write(" → toolroll daemon install --runner <name> --token <t> --repo <path>"),state.state==="disabled"&&write(" → the service is disabled: `toolroll daemon install` re-enables and loads it"),state.state==="running"?EXIT.ok:EXIT.refused)}if(action==="uninstall"){const gone=await uninstallDaemon(current,supervise),legacyGone=legacy===null?null:await uninstallDaemon(legacy,supervise);return succeed(write,json,"daemon uninstall",{removed:gone.existed||legacyGone?.existed===!0},()=>[...gone.existed||legacyGone===null?[gone.existed?`Stopped and removed ${current.label}.`:`${current.label} was not installed; nothing to remove.`]:[],...legacyGone===null?[]:[`Stopped and removed ${legacy.label}.`]])}return action==="logs"?succeed(write,json,"daemon logs",{logs:plan.logPath},()=>[plan.logPath,` → tail -f ${plan.logPath}`]):fail(write,json,"daemon","usage","`toolroll daemon [install|status|uninstall|logs]`",EXIT.usage)}const WATCH_LEASE_MS=MAX_WATCH_LEASE_MS,WATCH_HEARTBEAT_MS=RUNNER_HEARTBEAT_MS;function startTelegramFollower(args){const{context,progress,label}=args,source=loadBotToken(process.env,context.telegramTokenFile);if(source===null)return null;const fence=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fence!==null)return progress(networkFenceLine(fence)),null;const transport=context.telegramTransport??createTransport(source.token),pushUrl=telegramPushUrl(readHooksBase(dirname(context.databaseFile)));return followBridge(context.store,{push:pushUrl===null?null:{url:pushUrl,secret:telegramHookSecret(dirname(context.databaseFile),!0)},readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context,args.publicUrl===void 0?{}:{serverOrigin:args.publicUrl}),botId:source.botId,transport,signal:args.signal,...args.owner===void 0?{}:{owner:args.owner},onCycle:cycle=>{progress(`${label} sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+((cycle.chatQueued??0)>0?`, chat received ${cycle.chatQueued}`:"")+((cycle.chatAnswered??0)>0?`, chat replied ${cycle.chatAnswered}`:"")+((cycle.chatConfirmed??0)>0?`, chat confirmed ${cycle.chatConfirmed}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}}).catch(error=>(progress(`${args.died.prefix}the telegram follower died — ${describe(error)}; ${args.died.next}`),null))}const TELEGRAM_STOP_WAIT_MS=5e3,CLEANUP_SLOW_MS=3e4,SHUTDOWN_DEADLINE_MS=6e4,WORKER_ALIVE_EVERY_MS=5e3,WORKER_SILENCE_MS=6e4;let staleStatusesRepaired=!1;async function runWatchLoop(args){const{context,flags,runner,token,repo,progress}=args,{store}=context;noticeGitIncidents(store,context.clock);const tickEveryMs=Number(text(flags,"tick-every")??6e4),bridgeEveryMs=Number(text(flags,"bridge-every")??45e3),reconcileEveryMs=Number(text(flags,"reconcile-every")??5*6e4),runFor=text(flags,"for")===void 0?null:Number(text(flags,"for"));if(!Number.isSafeInteger(reconcileEveryMs)||reconcileEveryMs<1||reconcileEveryMs>2147483647)throw new Error("--reconcile-every must be an integer from 1 to 2147483647 milliseconds");const incarnation=`${runFor===null?"toolroll-service:":""}${randomUUID()}`;let lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);const waitUntil=Date.now()+(args.leaseWaitMs??0);let saidWaiting=!1;const waitStopping=args.leaseWaitStopping??args.isStopping;for(;!lease.ok&&lease.reason==="watch-busy"&&Date.now()<waitUntil&&!waitStopping();)saidWaiting||progress(`watch: ${repo} is still held by the previous worker until ${lease.until??"its lease lapses"}; taking it over then`),saidWaiting=!0,await new Promise(resolve2=>setTimeout(resolve2,1e3)),lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);if(!lease.ok)return{ok:!1,reason:"watch-busy",detail:lease.reason==="watch-busy"?`another watch holds ${runner} on ${repo} until ${lease.until} — one watch per runner and repo; cron ticks may coexist, watches may not`:describeAuth(lease.reason,runner),ticks:0,built:0,broke:0};lease.superseded!==null&&lease.recovered>0&&progress(`Recovered ${lease.recovered} claim(s) from the previous watch (${lease.superseded.slice(0,8)}…) before dispatching anything.`);for(const line of args.containmentLines?.(currentContainment())??[`watch: ${describeContainment(currentContainment())}`])progress(line);store.startWatchEpisode({repo,runner,incarnation},new Date);try{notifyVersionLive(store,dirname(context.databaseFile),PACKAGE_VERSION,new Date)}catch{}if(recordRunnerVersion(dirname(context.databaseFile),runner,PACKAGE_VERSION,new Date),args.onReady?.(),!staleStatusesRepaired){staleStatusesRepaired=!0;const repaired=repairStaleStatuses(store,new Date);repaired.exitsRecorded>0&&progress(`watch: recorded ${repaired.exitsRecorded} finished process exit(s) left open by an earlier version`)}let leaseLost=!1,leaseLostReason=null,custodyUnknown=!1;const followController=new AbortController,hub=wakeHubFor(store,read=>briefly(store,read)),wakes=new WakePoker;args.onFollowController?.(followController);let failed=!1,failure;const fail2=error=>{failed||(failure=error),failed=!0,wakes.poke()},stopping=()=>args.isStopping()||leaseLost||failed,heartbeatEveryMs=context.watchHeartbeatMs??WATCH_HEARTBEAT_MS;let heartbeatTimer=null,heartbeatStopped=!1,busyBeats=0;const scheduleBeat=ms=>{heartbeatStopped||(heartbeatTimer=setTimeout(beat,ms),heartbeatTimer.unref?.())};function beat(){if(heartbeatTimer=null,heartbeatStopped||leaseLost)return;let answer=null,problem=null;try{answer=briefly(store,()=>renewWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date))}catch(error){if(isDatabaseBusy(error)){busyBeats++,custodyUnknown||progress(`watch: ${runner} on ${repo}: the database is busy, so this worker can't prove it still holds the project yet — no new work starts until it can`),custodyUnknown=!0,scheduleBeat(Math.min(heartbeatEveryMs,1e3*2**Math.min(busyBeats-1,4)));return}problem=`renewal could not be proved: ${describe(error)}`}if(answer!==null&&answer.ok){busyBeats=0,answer.lateMs>0&&progress(`watch: renewal late by ${Math.max(1,Math.round(answer.lateMs/1e3))}s — this worker still holds ${repo}; carrying on`),custodyUnknown&&(custodyUnknown=!1,progress(`watch: ${runner} on ${repo}: proved it still holds the project — new work may start again`),wakes.poke()),scheduleBeat(heartbeatEveryMs);return}leaseLostReason=answer===null?"error":answer.reason,leaseLost=!0,followController.abort(),wakes.poke(),progress(`watch: ${runner} on ${repo}: ${problem??renewalRefusedWords(answer.reason)} — stopping without admitting more work`)}scheduleBeat(heartbeatEveryMs);const stopHeartbeat=()=>{heartbeatStopped=!0,heartbeatTimer!==null&&clearTimeout(heartbeatTimer),heartbeatTimer=null};let cleanupStage=null,lastPassAt=null;args.health?.(()=>({repo,leaseLive:!leaseLost&&!custodyUnknown&&cleanupStage===null,lastPassAt,stopping:stopping(),cleanup:cleanupStage}));const serviceBridge=args.serviceBridge===!0,follower=serviceBridge?null:startTelegramFollower({context,publicUrl:text(flags,"public-url"),signal:followController.signal,progress,label:"watch: bridge",died:{prefix:"watch: ",next:"taps wait for the next watch"}}),slackFollower=superviseChatFollower("Slack",followController.signal,progress,()=>followSlack({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="slack"})),teamsFollower=superviseChatFollower("Teams",followController.signal,progress,()=>followTeams({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="teams"})),discordFollower=superviseChatFollower("Discord",followController.signal,progress,()=>followDiscord({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="discord"})),quiet=[],sink=line=>quiet.push(line),passFlags=(extra={})=>{const copy=new Map(flags);copy.set("json",!0),copy.set("incarnation",incarnation);for(const[key,value]of Object.entries(extra))copy.set(key,value);return copy};let reconciliationReady=!1,reconciliationFailure=null,reconciliationBusy=!1;const paused=()=>custodyUnknown||!reconciliationReady||updateAdmissionPaused(store.raw())||context.shouldPauseAdmission?.()===!0,admissionStopped=()=>stopping()||paused(),quietContext={...context,write:sink,json:!0,shouldStop:stopping,shouldPauseAdmission:paused},startedAt=Date.now(),deadline=runFor===null?null:startedAt+runFor;let lastTick=0,lastBridge=0,ticks=0,built=0,brokeCount=0;const sweepOwner={},maintenance=startMaintenance({intervalMs:reconcileEveryMs,onStop:()=>storageSweepSupervisor(context.databaseFile).stop(sweepOwner),shouldStop:stopping,onError:error=>{reconciliationReady=!1;const detail=describe(error);detail!==reconciliationFailure&&progress(`watch: reconciliation failed — ${detail}; new work is paused until a recovery pass succeeds`),reconciliationFailure=detail,reconciliationBusy=busyFailure(error)},retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{const maintenanceLines=[],maintenanceContext={...quietContext,...runFor===null?{sweepOwner}:{},write:line=>maintenanceLines.push(line)};if(runFor!==null&&delete maintenanceContext.sweepOwner,await reconcileCommand(passFlags(),maintenanceContext)!==EXIT.ok)throw new Error(maintenanceLines.join(" "));reconciliationFailure!==null&&progress("watch: reconciliation recovered — new work may resume");const recovered=!reconciliationReady;if(reconciliationFailure=null,reconciliationReady=!0,recovered&&wakes.poke(),!stopping()){try{const shipped=await flexibleArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});shipped.ok&&shipped.merged>0&&progress(`watch: merged ${shipped.merged} Flexible result(s) whose checks passed`),shipped.ok&&shipped.cancelled>0&&progress(`watch: stopped ${shipped.cancelled} Flexible merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Flexible ship pass failed — ${describe(error)}; retrying on its next interval`)}try{const dcShipped=await directChatArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});dcShipped.merged>0&&progress(`watch: merged ${dcShipped.merged} Direct Chat result(s) whose checks passed`),dcShipped.cancelled>0&&progress(`watch: stopped ${dcShipped.cancelled} Direct Chat merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Direct Chat ship pass failed — ${describe(error)}; retrying on its next interval`)}}if(!stopping()&&store.openedPublications().length>0)try{const checks=await observeChecks(store,context.publishExec===void 0?{}:{exec:context.publishExec});checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}catch(error){progress(`watch: CI observation failed — ${describe(error)}; retrying on its next interval`)}}}),followUpChecks=startMaintenance({intervalMs:5e3,shouldStop:stopping,onError:error=>progress(`watch: a follow-up check failed to run — ${describe(error)}; it is recorded on the result`),run:async()=>{if(store.isDemo())return;const batched=await runBatchChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});batched>0&&progress(`watch: settled ${batched} batch-checked result(s)`),context.agentRunner===void 0&&resumeHeldReleases(store,dirname(context.databaseFile),context.clock()),context.agentRunner===void 0&&context.databaseFile!==":memory:"&&sweepOrphanedReleases(store,context.databaseFile,dirname(context.databaseFile),context.clock()).then(resumed=>{for(const one of resumed)progress(`watch: ${basename(one.file,".json")}: continued the release by itself — ${one.why}`)}),requestMissingRechecks(store,context.evidenceRoot,context.clock()),resumeParkedRepairs(store,context.evidenceRoot,context.clock());const ran=await runWaitingChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});ran>0&&progress(`watch: ran ${ran} follow-up check(s)`),await refreshTrustedMains(store,context.evidenceRoot,context.clock(),context.gitRunner);const settledChecks=settleReleaseChecks(store,context.evidenceRoot,context.clock());settledChecks>0&&progress(`watch: settled ${settledChecks} release check(s)`),context.agentRunner===void 0&&await refreshGithubNightlies(store,context.clock),context.agentRunner===void 0&&await refreshLearning(store,context.clock),ran+batched>0&&moveCards(store,repo,context.clock(),context.evidenceRoot)}}),codeMapChecks=startMaintenance({intervalMs:6e4,shouldStop:stopping,onError:error=>progress(`watch: a code map check failed — ${describe(error)}; it tries again`),run:async()=>{store.isDemo()||context.agentRunner!==void 0||(await refreshCodeMaps(store,{scratch:join(context.evidenceRoot,".code-map"),clock:context.clock}),sweepDeliveries(store))}}),flowEveryMs=context.flowEveryMs??FLOW_EVERY_MS,flowPool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),flowGit=context.gitRunner??run,flowsDid=(moved,filed,did)=>{moved+filed!==0&&(store.bumpWake(),progress(`watch: ${did}`))},flowMoves=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: flow cards couldn't move — ${describe(error)}; they try again shortly`),run:async()=>{if(paused())return;const moved=moveCards(store,repo,context.clock(),context.evidenceRoot);flowsDid(moved.moved,moved.filed.length,`moved ${moved.moved} flow card(s), filed ${moved.filed.length} task(s)`)}}),flowSteps=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: a flow pass failed — ${describe(error)}; it runs again shortly`),run:async()=>{if(paused())return;let base=text(flags,"base");if(base===void 0){const head=await flowGit("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return;base=head.stdout.trim()}const pass=await flowHousekeeping(store,repo,context.clock,flowIoOf(context,flowPool,flowGit,base),admissionStopped);flowsDid(pass.flows.moved+pass.triggers.added+pass.steps.ran+pass.replies.taken,pass.flows.filed.length+pass.youiyoux.filed,`flow pass — ${pass.triggers.added} card(s) added, ${pass.youiyoux.filed} youiyoux request(s) filed, ${pass.replies.taken} reply(ies) taken, ${pass.steps.ran} step(s) run, ${pass.flows.moved} moved`)}}),modelWatch=startMaintenance({intervalMs:15*6e4,shouldStop:stopping,onError:error=>progress(`watch: the model check failed — ${describe(error)}; it retries later`),run:async()=>{await modelWatchPass(store,context.clock())&&progress("watch: checked models and CLI versions")}}),leaveServiceBeats=joinServiceBeats({context,progress,ciReady:()=>!admissionStopped(),stopping}),passes=args.passes??new ProjectPasses,slotFacts=yieldingSince=>{const now=new Date,found=store.getRunner(runner),bound=new Set(found?.runner.repos??[repo]),saved=savedProjectConcurrency(context.databaseFile);return{repo,capacity:found?.runner.capacity??1,running:store.liveClaimCountsByRepo(runner,now),limitOf:one=>saved.get(one)??PROJECT_CONCURRENCY_DEFAULT,waiting:new Set(store.listReady(now,runner).map(one=>one.repo).filter(one=>one!==null&&bound.has(one))),yieldingSince,passes}},lanes=[],buildLane=async index=>{const laneLines=[],laneContext={...quietContext,write:line=>laneLines.push(line)};let yieldingSince=null,yieldingTo=null;for(;!stopping()&&(deadline===null||Date.now()<deadline);){const seqBefore=store.wakeSeq();let broke=!1;if(!paused()){const facts=slotFacts(yieldingSince),answer=index<effectiveConcurrency(facts.limitOf(repo),facts.capacity)?maySlotTake(facts):null;if(answer!==null&&answer.take){yieldingSince=null,yieldingTo=null,laneLines.length=0;let code=EXIT.failed;try{code=await tickCommand(passFlags({"builds-only":"1"}),laneContext)}catch(error){laneLines.push(JSON.stringify({dispatched:[{id:"?",outcome:"failed",reason:"lane",detail:describe(error)}]}))}if(passes.passed(repo),code===EXIT.ok){built++,progress(`watch: build ${index+1} did work (${new Date().toISOString()})`);continue}code===EXIT.failed&&(brokeCount++,broke=!0,progress(`watch: build ${index+1} — ${brokenWords(laneLines)}`))}else answer!==null&&!answer.take&&answer.why==="fair-share"?(yieldingSince===null&&(yieldingSince=passes.stamp(),store.bumpWake()),yieldingTo=answer.to??null):(yieldingSince=null,yieldingTo=null)}if(!broke&&store.wakeSeq()!==seqBefore)continue;const seqIdle=store.wakeSeq(),dozeUntil=Math.min(Date.now()+tickEveryMs,deadline??Number.MAX_SAFE_INTEGER),theirTurnEnded=()=>yieldingTo!==null&&yieldingSince!==null&&passes.lastPass(yieldingTo)>yieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}},ensureLanes=()=>{const facts=slotFacts(null),wanted=effectiveConcurrency(facts.limitOf(repo),facts.capacity);for(;lanes.length+1<wanted&&!stopping();)lanes.push(buildLane(lanes.length+1).catch(fail2))};let firstLaneYieldingSince=null,firstLaneYieldingTo=null;try{for(await maintenance.runNow();!stopping()&&(deadline===null||Date.now()<deadline);){if(paused()){await hub.changed({baseline:store.wakeSeq(),deadline:Date.now()+1e3,until:stopping,poker:wakes});continue}ensureLanes();const share=maySlotTake(slotFacts(firstLaneYieldingSince)),yieldBuilds=!share.take&&share.why!=="capacity";!share.take&&share.why==="fair-share"?(firstLaneYieldingSince===null&&(firstLaneYieldingSince=passes.stamp(),store.bumpWake()),firstLaneYieldingTo=share.to??null):(firstLaneYieldingSince=null,firstLaneYieldingTo=null);const seqBefore=store.wakeSeq(),now=Date.now();let tickDidWork=!1,tickBroke=!1;{lastTick=now,quiet.length=0,store.expireOverdueDecisions(new Date);const code=await tickCommand(passFlags(yieldBuilds?{"yield-builds":"1"}:{}),quietContext);passes.passed(repo),ticks++,lastPassAt=new Date().toISOString(),code===EXIT.ok?(tickDidWork=!0,built++,progress(`watch: pass ${ticks} did work (${new Date().toISOString()})`)):code===EXIT.failed&&(brokeCount++,tickBroke=!0,progress(`watch: pass ${ticks} — ${brokenWords(quiet)}`))}try{store.sealLedger()}catch(error){progress(`watch: the ledger chain could not be sealed this pass (${error instanceof Error?error.message:String(error)})`)}if(!admissionStopped()&&store.pendingPublications().length>0){const published=await publishPass(store,{repo,evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});published.pushed+published.opened+published.adopted+published.failed>0&&progress(`watch: published — pushed ${published.pushed}, opened ${published.opened}, adopted ${published.adopted}`+(published.failed>0?`, gave up on ${published.failed}`:""))}if(follower===null&&now-lastBridge>=bridgeEveryMs){lastBridge=now;const source=serviceBridge?null:loadBotToken(process.env,context.telegramTokenFile),dir=dirname(context.databaseFile),primary=effectivePrimary(process.env,dir,source!==null);source!==null&&(quiet.length=0,await bridgeCommand(["telegram"],passFlags(primary.channel==="telegram"?{}:{"inbound-only":"1"}),quietContext))}if(tickDidWork||!tickBroke&&store.wakeSeq()!==seqBefore)continue;const idleUntil=Math.min(lastTick+tickEveryMs,lastBridge+bridgeEveryMs,deadline??Number.MAX_SAFE_INTEGER)-Date.now(),seqIdle=store.wakeSeq(),dozeUntil=Date.now()+Math.max(idleUntil,0),theirTurnEnded=()=>firstLaneYieldingTo!==null&&firstLaneYieldingSince!==null&&passes.lastPass(firstLaneYieldingTo)>firstLaneYieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}}catch(error){fail2(error)}finally{const step=async(name,work)=>{cleanupStage=name;const slow=setTimeout(()=>progress(`watch: stopping is still waiting on ${name}`),CLEANUP_SLOW_MS);slow.unref?.();try{await work()}finally{clearTimeout(slow)}};await step("its builds",()=>Promise.all(lanes)),await step("reconciliation",()=>maintenance.stop()),await step("follow-up checks",()=>followUpChecks.stop()),await step("the code map check",()=>codeMapChecks.stop()),await step("flow moves",()=>flowMoves.stop()),await step("flow steps",()=>flowSteps.stop()),await step("the model check",()=>modelWatch.stop()),await step("deliveries and fast CI",()=>leaveServiceBeats()),stopHeartbeat(),followController.abort(),follower!==null&&await step("the Telegram follower",()=>follower),await step("the Slack follower",()=>slackFollower),await step("the Teams follower",()=>teamsFollower),await step("the Discord follower",()=>discordFollower),cleanupStage="releasing the project",store.endWatchEpisode(incarnation,{ticks,built,broke:brokeCount},new Date),store.releaseWatchLease(runner,repo,incarnation,new Date),cleanupStage=null}if(failed)throw failure;return leaseLost?{ok:!1,reason:"lease-lost",lost:leaseLostReason??"error",detail:`the watch lease for ${runner} on ${repo} stopped renewing — ${renewalRefusedWords(leaseLostReason??"error")}`,ticks,built,broke:brokeCount}:reconciliationFailure!==null?{ok:!1,reason:"reconciliation-failed",detail:reconciliationFailure,ticks,built,broke:brokeCount,busy:reconciliationBusy}:{ok:!0,ticks,built,broke:brokeCount,incarnation}}function brokenWords(lines){try{const failed=(JSON.parse(lines[lines.length-1]??"").dispatched??[]).filter(one=>one.outcome==="failed");return failed.length===0?"a pass broke something — the run records have it":`${failed.slice(0,3).map(one=>`${one.id} failed (${one.reason??"?"}${one.detail===void 0?"":`: ${one.detail}`})`).join("; ")}${failed.length>3?`; and ${failed.length-3} more`:""}`}catch{return"a pass broke something — the run records have it"}}async function watchCommand(flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"watch");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token")??readTokenFile(text(flags,"token-file"));if(runner===void 0||token===void 0)return fail(write,json,"watch","usage","`toolroll watch --runner <name> --token <t>|--token-file <path> --repo <path> [--for <ms>]`",EXIT.usage);flags.set("token",token);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"watch",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags),progress=longCommandProgress(write,json);let stopping=!1,graceTimer,followAbort=null;const stopGraceMs=Number(text(flags,"stop-grace")??3e4),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Hard stop: ${terminated} provider process group(s) terminated. Their work is saved and kept in each checkout, and each task continues from it; fences keep late output out of every commit. Run \`toolroll\` again to continue.`)},dropSignals=onStopSignals(()=>{if(stopping){hardStop();return}stopping=!0,followAbort?.abort(),wakeHubFor(context.store,read=>briefly(context.store,read)).poke(),graceTimer=setTimeout(hardStop,stopGraceMs)}),startedAt=Date.now();let result;try{result=await runWatchLoop({flags,context,runner,token,repo,progress,isStopping:()=>stopping||context.shouldStop?.()===!0,onFollowController:controller=>{followAbort=controller}})}finally{graceTimer!==void 0&&clearTimeout(graceTimer),dropSignals()}return result.ok?succeed(write,json,"watch",{ticks:result.ticks,built:result.built,broke:result.broke,incarnation:result.incarnation},()=>[`Watched ${repo} for ${Math.round((Date.now()-startedAt)/1e3)}s: ${result.ticks} pass(es), ${result.built} with work, ${result.broke} broke.`,"The lease is handed back; cron or the next watch may take it."]):fail(write,json,"watch",result.reason,result.detail,result.reason==="reconciliation-failed"||result.reason==="loop-failed"?EXIT.failed:EXIT.refused,{ticks:result.ticks,built:result.built,broke:result.broke})}const UP_LOGIN_FILE="up-login.txt";export function writeLoginFileDurably(path,name,password){const fd=openSync(path,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL,384);try{writeSync(fd,`${name} ${password}
491
+ `)[0]??"").slice(0,200)}`,EXIT.failed);let issues;try{issues=JSON.parse(asked.stdout)}catch{return fail(write,json,`intake ${action}`,"github-unreadable","gh answered, but not with the JSON it promised",EXIT.failed)}const candidates=issues.filter(issue=>Number.isInteger(issue.number)&&issue.number>0).map(issue=>{const id=intakeTaskId(grant.github,issue.number),title=String(issue.title??""),clean=title.length>0&&title.length<=180&&!hasDisguisedText(title);return{id,number:issue.number,title,clean,exists:store.getTask(id)!==null}});if(action==="preview"){if(json)return write(envelopeJson({ok:!0,command:"intake preview",repo,github:grant.github,label:grant.label,candidates})),EXIT.ok;if(candidates.length===0)return write(`Nothing open in ${grant.github} carries "${grant.label}".`),EXIT.ok;write(`Would intake from ${grant.github} ("${grant.label}"):`);for(const one of candidates)write(` #${one.number} ${one.exists?"already here as":one.clean?"→":"REFUSED (title carries control characters)"} ${one.id}${one.clean?` — ${one.title}`:""}`);return write("Nothing was created. `toolroll intake run` makes the proposals."),EXIT.ok}const created=[],skipped=[];for(const one of candidates){if(one.exists)continue;if(!one.clean){skipped.push({id:one.id,reason:"title-refused"});continue}const made=store.transact(()=>{const filed=fileTaskProposal(store,{id:one.id,title:`GH#${one.number}: ${one.title}`,repo,goal:`Imported from GitHub issue #${one.number} in ${grant.github} (label "${grant.label}"). Only the title was imported — read the issue at https://github.com/${grant.github}/issues/${one.number} for full context, then edit and approve this scope before anything builds.`,acceptance:[{id:"c1",statement:"The linked GitHub issue's request is read and addressed.",how:null,evidence:["manual-review"]}],filedVia:"intake"},clock());if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:"github-issues",remoteRepo:grant.github,remoteId:String(one.number),provenance:"intake",intakeGrant:grant.id,establishedBy:"intake"},clock());if(!established.ok&&established.reason!=="duplicate")throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok?created.push(made.id):skipped.push({id:one.id,reason:made.reason})}return succeed(write,json,"intake run",{repo,github:grant.github,label:grant.label,created,skipped},()=>[`${created.length} proposal(s) created${skipped.length>0?`, ${skipped.length} skipped`:""} — each awaits its own scope approval.`,...created.map(one=>` ${one}`),...skipped.map(one=>` skipped ${one.id}: ${one.reason}`)])}function templateCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional;if(action===void 0||action==="list"){if(json)return write(envelopeJson({ok:!0,command:"template list",templates:TEMPLATES.map(one=>({name:one.name,kind:one.kind,purpose:one.purpose}))})),EXIT.ok;write("Templates — common work you edit to fit. Nothing a template"),write("files is approved; recipes only show existing ceremonies."),write("");for(const one of TEMPLATES)write(` ${one.name.padEnd(16)} ${one.kind.padEnd(9)} ${one.purpose}`);return write(""),write("`toolroll template show <name>` · `template apply <name> --repo <path>`"),EXIT.ok}if(action!=="show"&&action!=="apply")return fail(write,json,`template ${action}`,"usage","`toolroll template list | show <name> | apply <name> --repo <path> [--file]`",EXIT.usage);if(name===void 0)return fail(write,json,`template ${action}`,"usage","which template? `toolroll template list` names them",EXIT.usage);const template=templateByName(name);if(template===null)return fail(write,json,`template ${action}`,"unknown",`no template named ${name} — \`toolroll template list\``,EXIT.refused);if(action==="show"){if(json)return write(envelopeJson({ok:!0,command:"template show",template})),EXIT.ok;if(write(`${template.name} — ${template.purpose}`),template.kind==="recipe"){write(""),write(`This one is a recipe, not an application: ${template.why}`);for(const step of template.steps)write(""),write(` ${step.say}`),write(` ${step.run}`);return EXIT.ok}write(""),template.kind==="task"?(write(" files one task (unapproved until you approve its scope)"),write(` title ${template.title}`)):(write(" makes a scheduled flow (nothing repeats until you turn the schedule on)"),write(` name ${template.title}`),write(` schedule ${template.schedule}`)),write(` goal ${template.goal}`),template.outOfScope!==null&&write(` not ${template.outOfScope}`),template.touches.length>0&&write(` touches ${template.touches.join(", ")}`),write(""),write("You will probably edit:");for(const hint of template.edit)write(` - ${hint}`);return write(""),write(`\`toolroll template apply ${template.name} --repo <path>\` previews the exact filing.`),EXIT.ok}if(template.kind==="recipe")return fail(write,json,"template apply","recipe",`${template.name} cannot be applied: ${template.why} \`toolroll template show ${template.name}\` walks the ceremonies.`,EXIT.refused);const repoGiven=text(flags,"repo");if(repoGiven===void 0)return fail(write,json,"template apply","usage","which repository? --repo <path> — a template never guesses where work lands",EXIT.usage);const goal=text(flags,"goal")??template.goal,outOfScope=text(flags,"not")??template.outOfScope,touches=text(flags,"touches")===void 0?template.touches:(text(flags,"touches")??"").split(",").map(one=>one.trim()).filter(one=>one!=="");if(template.kind==="task"){const title=text(flags,"title")??template.title,draft={kind:"task",title,repo:canonicalProject(repoGiven)??resolve(repoGiven),goal,outOfScope,touches,filedVia:`template:${template.name}`};if(!flags.has("file"))return json?(write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3):(write("Would file, exactly (edit with --title/--goal/--not/--touches):"),write(""),write(` task ${draft.title}`),write(` repo ${draft.repo}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),write(""),write("Nothing was filed. Re-run with --file to file it — UNAPPROVED either way."),3);const made2=fileTaskProposal(store,{title,repo:repoGiven,goal,outOfScope,touches,acceptance:template.acceptance,filedVia:`template:${template.name}`},clock());if(!made2.ok)return fail(write,json,"template apply",made2.reason,made2.message,made2.reason==="duplicate"?EXIT.refused:EXIT.usage);const filedLink=consoleLinkFor(context,`/t/${encodeURIComponent(made2.id)}`);return succeed(write,json,"template apply",{filed:"task",id:made2.id,approved:!1,...filedLink===null?{}:{links:{task:filedLink}}},()=>[`Filed ${made2.id} from template ${template.name}.`,"","UNAPPROVED — NO AUTHORITY GRANTED. It builds only after you approve its scope:",` toolroll task show ${made2.id}`,...filedLink===null?[]:[` ${filedLink}`]])}const flowName=text(flags,"name")??template.title,scheduleGiven=text(flags,"schedule")??template.schedule,schedule=parseSchedule(scheduleGiven)!==null?scheduleGiven:scheduleFromWords(scheduleGiven)??scheduleGiven,ceilingGiven=text(flags,"ceiling"),costCeilingUsd=ceilingGiven===void 0?template.costCeilingUsd:Number(ceilingGiven),repo=canonicalProject(repoGiven)??resolve(repoGiven),terms={goal,outOfScope,touches,requirements:template.requirements,acceptance:template.acceptance,budgetPerRunMicrousd:null,costCeilingUsd};if(!flags.has("file")){const draft={kind:"scheduled flow",name:flowName,repo,schedule,...terms,filedVia:`template:${template.name}`};if(json)return write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3;const readable=parseSchedule(schedule);return write("Would make this scheduled flow (edit with --name/--goal/--not/--touches/--schedule/--ceiling):"),write(""),write(` flow ${draft.name}`),write(` repo ${draft.repo}`),write(` schedule ${readable===null?schedule:describeSchedule(readable)}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),draft.costCeilingUsd!==null&&write(` ceiling $${draft.costCeilingUsd} every 7 days`),write(""),write("Nothing was made. Re-run with --file to make it. Nothing repeats until you turn the schedule on."),3}const made=createScheduledFlow(store,{repo,name:flowName,stem:template.name,schedule,terms,by:context.principal?.account??"toolroll",filedBy:context.principal?.account??null},clock());if(!made.ok)return fail(write,json,"template apply","bad-terms",made.message,EXIT.usage);const flowLink=consoleLinkFor(context,`/flows/${made.flow}`);return succeed(write,json,"template apply",{filed:"scheduled flow",flow:made.flow,trigger:made.trigger,on:!1,...flowLink===null?{}:{links:{flow:flowLink}}},()=>[`Made ${flowName}, flow #${made.flow}, from template ${template.name}.`,"","Nothing repeats until you turn the schedule on; each run then waits for approval under the project's rules:",` toolroll flows trigger resume ${made.flow} ${made.trigger}`,...flowLink===null?[]:[` ${flowLink}`]])}function readTokenFile(path){if(path!==void 0)try{const raw=readFileSync(path,"utf8").trim();return raw===""?void 0:raw}catch{return}}async function daemonCommand(positional,flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"daemon");if(demoFence!==null)return demoFence;const[action="status"]=positional,repo=repoFrom(flags),configDir=dirname(context.telegramTokenFile),supervise=context.gitRunner??run,binFlag=text(flags,"bin"),resolveBin=async()=>{const direct=daemonLaunchCommand({execPath:process.execPath,...process.argv[1]===void 0?{}:{entry:resolve(process.argv[1])},...binFlag===void 0?{}:{explicitBin:resolve(binFlag)}});if(direct!==null)return direct;const found=await supervise("sh",["-lc","command -v toolroll || command -v standing-orders"]);return found.code===0&&found.stdout.trim()!==""?{bin:process.execPath,binArgs:[found.stdout.trim()]}:null};if(action==="install"){const runnerName=text(flags,"runner"),inlineToken=text(flags,"token"),tokenPath=text(flags,"token-file");if(inlineToken!==void 0&&tokenPath!==void 0)return fail(write,json,"daemon install","usage","choose one credential source: --token or --token-file",EXIT.usage);const token=inlineToken??readTokenFile(tokenPath);if(runnerName===void 0||token===void 0)return fail(write,json,"daemon install","usage","`toolroll daemon install --runner <name> (--token <t> | --token-file <path>) --repo <path>` (plus any watch flags to bake in)",EXIT.usage);const auth=authenticate(store,runnerName,token);if(!auth.ok)return fail(write,json,"daemon install",auth.reason,describeAuth(auth.reason,runnerName),EXIT.refused);const heartbeatBefore=store.getRunner(runnerName)?.runner.heartbeatAt??null,located=await resolveBin();if(located===null)return fail(write,json,"daemon install","no-bin","`toolroll` is not on the PATH the service would use — run `toolroll link` first, or pass --bin <absolute path>",EXIT.refused);const watchFlags=[];for(const name of["pool","model","repair-model","provider","plan-model","plan-provider","max","turns","tick-every","bridge-every","reconcile-every","containment"]){const value=text(flags,name);value!==void 0&&watchFlags.push(`--${name}`,value)}watchFlags.includes("--containment")||watchFlags.push("--containment",currentContainment().policy);const plan2=planDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if("error"in plan2)return fail(write,json,"daemon install","unsupported",plan2.error,EXIT.refused);const legacy2=installedLegacyDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if(flags.has("dry-run"))return json?(write(envelopeJson({ok:!0,command:"daemon install",dryRun:!0,plan:plan2,replaces:legacy2?.label??null})),EXIT.ok):(write(`Would write ${plan2.unitPath}:`),write(""),write(plan2.unitContent),write(`Token (0600): ${plan2.tokenFile} · logs: ${plan2.logPath}`),legacy2!==null&&write(`Would stop and remove ${legacy2.label} (${legacy2.unitPath}), the same watch under its older name.`),write("Nothing was written. Re-run without --dry-run to install."),EXIT.ok);const installed=await installReplacingLegacy(plan2,token,legacy2,supervise);if(!installed.ok)return fail(write,json,"daemon install","supervisor",installed.message,EXIT.failed);const readySince=legacy2===null?heartbeatBefore:store.getRunner(runnerName)?.runner.heartbeatAt??null,started=await daemonStatus(plan2,supervise);if(started.state!=="running")return fail(write,json,"daemon install","not-running",`the service was installed but did not stay running (${started.detail}) — read ${plan2.logPath}; no work will be claimed until this is fixed`,EXIT.failed);const liveRunner=(await awaitFreshHeartbeat(store,runnerName,installed.action==="running"&&legacy2===null?null:readySince)).ok?store.getRunner(runnerName)?.runner??null:null;if(liveRunner===null){const macHint=process.platform==="darwin"&&repo.startsWith(join(homedir(),"Documents"))?" macOS may be blocking background access to Documents; grant the Node executable Full Disk Access, move the repository outside a protected folder, or keep `toolroll up` running from your terminal.":"";return fail(write,json,"daemon install","not-ready",`the supervisor has a process, but ${runnerName} never reached its worker heartbeat.${macHint} Read ${plan2.logPath}; no work will be claimed until the heartbeat appears`,EXIT.failed)}return succeed(write,json,"daemon install",{label:plan2.label,unit:plan2.unitPath,logs:plan2.logPath,state:started.state,pid:started.pid,heartbeatAt:liveRunner.heartbeatAt,action:installed.action,changed:installed.changed,replaced:legacy2?.label??null,containment:containmentStatus(currentContainment())},()=>[installed.action==="running"?`${plan2.label} was already running under this exact definition; left alone.`:installed.action==="reloaded"?`Reloaded ${plan2.label} under its changed definition.`:`Installed and started ${plan2.label}.`,...legacy2===null?[]:[` replaced ${legacy2.label} (stopped and removed)`],` verified ${started.detail}`,` worker ${runnerName} answered at ${liveRunner.heartbeatAt}`,` unit ${plan2.unitPath}`,` token ${plan2.tokenFile} (0600 — the unit never carries it)`,` logs ${plan2.logPath}`,"","It survives reboots and restarts itself after crashes; watch's","incarnation recovery makes those restarts safe. `toolroll daemon","status` to check on it, `daemon uninstall` to take it back off."])}const planArgs={platform:process.platform,bin:binFlag??"toolroll",binArgs:[],runner:text(flags,"runner")??"runner",repo,configDir,watchFlags:[]},current=planDaemon(planArgs);if("error"in current)return fail(write,json,`daemon ${action}`,"unsupported",current.error,EXIT.refused);const legacy=installedLegacyDaemon(planArgs),plan=legacy!==null&&!existsSync(current.unitPath)?legacy:current;if(action==="status"){const state=await daemonStatus(plan,supervise),containment=currentContainment();return json?(write(envelopeJson({ok:!0,command:"daemon status",...state,label:plan.label,logs:plan.logPath,containment:containmentStatus(containment)})),state.state==="running"?EXIT.ok:EXIT.refused):(write(`${plan.label}: ${state.detail}`),write(` logs ${plan.logPath}`),write(` ${describeContainment(containment)}`),state.state==="not-installed"&&write(" → toolroll daemon install --runner <name> --token <t> --repo <path>"),state.state==="disabled"&&write(" → the service is disabled: `toolroll daemon install` re-enables and loads it"),state.state==="running"?EXIT.ok:EXIT.refused)}if(action==="uninstall"){const gone=await uninstallDaemon(current,supervise),legacyGone=legacy===null?null:await uninstallDaemon(legacy,supervise);return succeed(write,json,"daemon uninstall",{removed:gone.existed||legacyGone?.existed===!0},()=>[...gone.existed||legacyGone===null?[gone.existed?`Stopped and removed ${current.label}.`:`${current.label} was not installed; nothing to remove.`]:[],...legacyGone===null?[]:[`Stopped and removed ${legacy.label}.`]])}return action==="logs"?succeed(write,json,"daemon logs",{logs:plan.logPath},()=>[plan.logPath,` → tail -f ${plan.logPath}`]):fail(write,json,"daemon","usage","`toolroll daemon [install|status|uninstall|logs]`",EXIT.usage)}const WATCH_LEASE_MS=MAX_WATCH_LEASE_MS,WATCH_HEARTBEAT_MS=RUNNER_HEARTBEAT_MS;function startTelegramFollower(args){const{context,progress,label}=args,source=loadBotToken(process.env,context.telegramTokenFile);if(source===null)return null;const fence=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fence!==null)return progress(networkFenceLine(fence)),null;const transport=context.telegramTransport??createTransport(source.token),pushUrl=telegramPushUrl(readHooksBase(dirname(context.databaseFile)));return followBridge(context.store,{push:pushUrl===null?null:{url:pushUrl,secret:telegramHookSecret(dirname(context.databaseFile),!0)},readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context,args.publicUrl===void 0?{}:{serverOrigin:args.publicUrl}),botId:source.botId,transport,signal:args.signal,...args.owner===void 0?{}:{owner:args.owner},onCycle:cycle=>{progress(`${label} sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+((cycle.chatQueued??0)>0?`, chat received ${cycle.chatQueued}`:"")+((cycle.chatAnswered??0)>0?`, chat replied ${cycle.chatAnswered}`:"")+((cycle.chatConfirmed??0)>0?`, chat confirmed ${cycle.chatConfirmed}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}}).catch(error=>(progress(`${args.died.prefix}the telegram follower died — ${describe(error)}; ${args.died.next}`),null))}const TELEGRAM_STOP_WAIT_MS=5e3,CLEANUP_SLOW_MS=3e4,SHUTDOWN_DEADLINE_MS=6e4,WORKER_ALIVE_EVERY_MS=5e3,WORKER_SILENCE_MS=6e4;let staleStatusesRepaired=!1;async function runWatchLoop(args){const{context,flags,runner,token,repo,progress}=args,{store}=context;noticeGitIncidents(store,context.clock);const tickEveryMs=Number(text(flags,"tick-every")??6e4),bridgeEveryMs=Number(text(flags,"bridge-every")??45e3),reconcileEveryMs=Number(text(flags,"reconcile-every")??5*6e4),runFor=text(flags,"for")===void 0?null:Number(text(flags,"for"));if(!Number.isSafeInteger(reconcileEveryMs)||reconcileEveryMs<1||reconcileEveryMs>2147483647)throw new Error("--reconcile-every must be an integer from 1 to 2147483647 milliseconds");const incarnation=`${runFor===null?"toolroll-service:":""}${randomUUID()}`;let lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);const waitUntil=Date.now()+(args.leaseWaitMs??0);let saidWaiting=!1;const waitStopping=args.leaseWaitStopping??args.isStopping;for(;!lease.ok&&lease.reason==="watch-busy"&&Date.now()<waitUntil&&!waitStopping();)saidWaiting||progress(`watch: ${repo} is still held by the previous worker until ${lease.until??"its lease lapses"}; taking it over then`),saidWaiting=!0,await new Promise(resolve2=>setTimeout(resolve2,1e3)),lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);if(!lease.ok)return{ok:!1,reason:"watch-busy",detail:lease.reason==="watch-busy"?`another watch holds ${runner} on ${repo} until ${lease.until} — one watch per runner and repo; cron ticks may coexist, watches may not`:describeAuth(lease.reason,runner),ticks:0,built:0,broke:0};lease.superseded!==null&&lease.recovered>0&&progress(`Recovered ${lease.recovered} claim(s) from the previous watch (${lease.superseded.slice(0,8)}…) before dispatching anything.`);for(const line of args.containmentLines?.(currentContainment())??[`watch: ${describeContainment(currentContainment())}`])progress(line);store.startWatchEpisode({repo,runner,incarnation},new Date);try{notifyVersionLive(store,dirname(context.databaseFile),PACKAGE_VERSION,new Date)}catch{}if(recordRunnerVersion(dirname(context.databaseFile),runner,PACKAGE_VERSION,new Date),args.onReady?.(),!staleStatusesRepaired){staleStatusesRepaired=!0;const repaired=repairStaleStatuses(store,new Date);repaired.exitsRecorded>0&&progress(`watch: recorded ${repaired.exitsRecorded} finished process exit(s) left open by an earlier version`)}let leaseLost=!1,leaseLostReason=null,custodyUnknown=!1;const followController=new AbortController,hub=wakeHubFor(store,read=>briefly(store,read)),wakes=new WakePoker;args.onFollowController?.(followController);let failed=!1,failure;const fail2=error=>{failed||(failure=error),failed=!0,wakes.poke()},stopping=()=>args.isStopping()||leaseLost||failed,heartbeatEveryMs=context.watchHeartbeatMs??WATCH_HEARTBEAT_MS;let heartbeatTimer=null,heartbeatStopped=!1,busyBeats=0;const scheduleBeat=ms=>{heartbeatStopped||(heartbeatTimer=setTimeout(beat,ms),heartbeatTimer.unref?.())};function beat(){if(heartbeatTimer=null,heartbeatStopped||leaseLost)return;let answer=null,problem=null;try{answer=briefly(store,()=>renewWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date))}catch(error){if(isDatabaseBusy(error)){busyBeats++,custodyUnknown||progress(`watch: ${runner} on ${repo}: the database is busy, so this worker can't prove it still holds the project yet — no new work starts until it can`),custodyUnknown=!0,scheduleBeat(Math.min(heartbeatEveryMs,1e3*2**Math.min(busyBeats-1,4)));return}problem=`renewal could not be proved: ${describe(error)}`}if(answer!==null&&answer.ok){busyBeats=0,answer.lateMs>0&&progress(`watch: renewal late by ${Math.max(1,Math.round(answer.lateMs/1e3))}s — this worker still holds ${repo}; carrying on`),custodyUnknown&&(custodyUnknown=!1,progress(`watch: ${runner} on ${repo}: proved it still holds the project — new work may start again`),wakes.poke()),scheduleBeat(heartbeatEveryMs);return}leaseLostReason=answer===null?"error":answer.reason,leaseLost=!0,followController.abort(),wakes.poke(),progress(`watch: ${runner} on ${repo}: ${problem??renewalRefusedWords(answer.reason)} — stopping without admitting more work`)}scheduleBeat(heartbeatEveryMs);const stopHeartbeat=()=>{heartbeatStopped=!0,heartbeatTimer!==null&&clearTimeout(heartbeatTimer),heartbeatTimer=null};let cleanupStage=null,lastPassAt=null;args.health?.(()=>({repo,leaseLive:!leaseLost&&!custodyUnknown&&cleanupStage===null,lastPassAt,stopping:stopping(),cleanup:cleanupStage}));const serviceBridge=args.serviceBridge===!0,follower=serviceBridge?null:startTelegramFollower({context,publicUrl:text(flags,"public-url"),signal:followController.signal,progress,label:"watch: bridge",died:{prefix:"watch: ",next:"taps wait for the next watch"}}),slackFollower=superviseChatFollower("Slack",followController.signal,progress,()=>followSlack({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="slack"})),teamsFollower=superviseChatFollower("Teams",followController.signal,progress,()=>followTeams({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="teams"})),discordFollower=superviseChatFollower("Discord",followController.signal,progress,()=>followDiscord({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="discord"})),quiet=[],sink=line=>quiet.push(line),passFlags=(extra={})=>{const copy=new Map(flags);copy.set("json",!0),copy.set("incarnation",incarnation);for(const[key,value]of Object.entries(extra))copy.set(key,value);return copy};let reconciliationReady=!1,reconciliationFailure=null,reconciliationBusy=!1;const paused=()=>custodyUnknown||!reconciliationReady||updateAdmissionPaused(store.raw())||context.shouldPauseAdmission?.()===!0,admissionStopped=()=>stopping()||paused(),quietContext={...context,write:sink,json:!0,shouldStop:stopping,shouldPauseAdmission:paused},startedAt=Date.now(),deadline=runFor===null?null:startedAt+runFor;let lastTick=0,lastBridge=0,ticks=0,built=0,brokeCount=0;const sweepOwner={},maintenance=startMaintenance({intervalMs:reconcileEveryMs,onStop:()=>storageSweepSupervisor(context.databaseFile).stop(sweepOwner),shouldStop:stopping,onError:error=>{reconciliationReady=!1;const detail=describe(error);detail!==reconciliationFailure&&progress(`watch: reconciliation failed — ${detail}; new work is paused until a recovery pass succeeds`),reconciliationFailure=detail,reconciliationBusy=busyFailure(error)},retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{const maintenanceLines=[],maintenanceContext={...quietContext,...runFor===null?{sweepOwner}:{},write:line=>maintenanceLines.push(line)};if(runFor!==null&&delete maintenanceContext.sweepOwner,await reconcileCommand(passFlags(),maintenanceContext)!==EXIT.ok)throw new Error(maintenanceLines.join(" "));reconciliationFailure!==null&&progress("watch: reconciliation recovered — new work may resume");const recovered=!reconciliationReady;if(reconciliationFailure=null,reconciliationReady=!0,recovered&&wakes.poke(),!stopping()){try{const shipped=await flexibleArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});shipped.ok&&shipped.merged>0&&progress(`watch: merged ${shipped.merged} Flexible result(s) whose checks passed`),shipped.ok&&shipped.cancelled>0&&progress(`watch: stopped ${shipped.cancelled} Flexible merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Flexible ship pass failed — ${describe(error)}; retrying on its next interval`)}try{const dcShipped=await directChatArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});dcShipped.merged>0&&progress(`watch: merged ${dcShipped.merged} Direct Chat result(s) whose checks passed`),dcShipped.cancelled>0&&progress(`watch: stopped ${dcShipped.cancelled} Direct Chat merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Direct Chat ship pass failed — ${describe(error)}; retrying on its next interval`)}}if(!stopping()&&store.openedPublications().length>0)try{const checks=await observeChecks(store,context.publishExec===void 0?{}:{exec:context.publishExec});checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}catch(error){progress(`watch: CI observation failed — ${describe(error)}; retrying on its next interval`)}}}),followUpChecks=startMaintenance({intervalMs:5e3,shouldStop:stopping,onError:error=>progress(`watch: a follow-up check failed to run — ${describe(error)}; it is recorded on the result`),run:async()=>{if(store.isDemo())return;const batched=await runBatchChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});batched>0&&progress(`watch: settled ${batched} batch-checked result(s)`),context.agentRunner===void 0&&resumeHeldReleases(store,dirname(context.databaseFile),context.clock()),context.agentRunner===void 0&&context.databaseFile!==":memory:"&&sweepOrphanedReleases(store,context.databaseFile,dirname(context.databaseFile),context.clock()).then(resumed=>{for(const one of resumed)progress(`watch: ${basename(one.file,".json")}: continued the release by itself — ${one.why}`)}),requestMissingRechecks(store,context.evidenceRoot,context.clock()),resumeParkedRepairs(store,context.evidenceRoot,context.clock());const ran=await runWaitingChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});ran>0&&progress(`watch: ran ${ran} follow-up check(s)`);const pendingLand=await runPendingLocalLands(store,context.clock(),{root:context.evidenceRoot,...context.gitRunner===void 0?{}:{git:context.gitRunner}});pendingLand.landed.length>0&&progress(`watch: landed ${pendingLand.landed.length} queued local task(s)`),await refreshTrustedMains(store,context.evidenceRoot,context.clock(),context.gitRunner);const settledChecks=settleReleaseChecks(store,context.evidenceRoot,context.clock());settledChecks>0&&progress(`watch: settled ${settledChecks} release check(s)`),context.agentRunner===void 0&&await refreshGithubNightlies(store,context.clock),context.agentRunner===void 0&&await refreshLearning(store,context.clock),ran+batched>0&&moveCards(store,repo,context.clock(),context.evidenceRoot)}}),codeMapChecks=startMaintenance({intervalMs:6e4,shouldStop:stopping,onError:error=>progress(`watch: a code map check failed — ${describe(error)}; it tries again`),run:async()=>{store.isDemo()||context.agentRunner!==void 0||(await refreshCodeMaps(store,{scratch:join(context.evidenceRoot,".code-map"),clock:context.clock}),sweepDeliveries(store))}}),flowEveryMs=context.flowEveryMs??FLOW_EVERY_MS,flowPool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),flowGit=context.gitRunner??run,flowsDid=(moved,filed,did)=>{moved+filed!==0&&(store.bumpWake(),progress(`watch: ${did}`))},flowMoves=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: flow cards couldn't move — ${describe(error)}; they try again shortly`),run:async()=>{if(paused())return;const moved=moveCards(store,repo,context.clock(),context.evidenceRoot);flowsDid(moved.moved,moved.filed.length,`moved ${moved.moved} flow card(s), filed ${moved.filed.length} task(s)`)}}),flowSteps=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: a flow pass failed — ${describe(error)}; it runs again shortly`),run:async()=>{if(paused())return;let base=text(flags,"base");if(base===void 0){const head=await flowGit("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return;base=head.stdout.trim()}const pass=await flowHousekeeping(store,repo,context.clock,flowIoOf(context,flowPool,flowGit,base),admissionStopped);flowsDid(pass.flows.moved+pass.triggers.added+pass.steps.ran+pass.replies.taken,pass.flows.filed.length+pass.youiyoux.filed,`flow pass — ${pass.triggers.added} card(s) added, ${pass.youiyoux.filed} youiyoux request(s) filed, ${pass.replies.taken} reply(ies) taken, ${pass.steps.ran} step(s) run, ${pass.flows.moved} moved`)}}),modelWatch=startMaintenance({intervalMs:15*6e4,shouldStop:stopping,onError:error=>progress(`watch: the model check failed — ${describe(error)}; it retries later`),run:async()=>{await modelWatchPass(store,context.clock())&&progress("watch: checked models and CLI versions")}}),leaveServiceBeats=joinServiceBeats({context,progress,ciReady:()=>!admissionStopped(),stopping}),passes=args.passes??new ProjectPasses,slotFacts=yieldingSince=>{const now=new Date,found=store.getRunner(runner),bound=new Set(found?.runner.repos??[repo]),saved=savedProjectConcurrency(context.databaseFile);return{repo,capacity:found?.runner.capacity??1,running:store.liveClaimCountsByRepo(runner,now),limitOf:one=>saved.get(one)??PROJECT_CONCURRENCY_DEFAULT,waiting:new Set(store.listReady(now,runner).map(one=>one.repo).filter(one=>one!==null&&bound.has(one))),yieldingSince,passes}},lanes=[],buildLane=async index=>{const laneLines=[],laneContext={...quietContext,write:line=>laneLines.push(line)};let yieldingSince=null,yieldingTo=null;for(;!stopping()&&(deadline===null||Date.now()<deadline);){const seqBefore=store.wakeSeq();let broke=!1;if(!paused()){const facts=slotFacts(yieldingSince),answer=index<effectiveConcurrency(facts.limitOf(repo),facts.capacity)?maySlotTake(facts):null;if(answer!==null&&answer.take){yieldingSince=null,yieldingTo=null,laneLines.length=0;let code=EXIT.failed;try{code=await tickCommand(passFlags({"builds-only":"1"}),laneContext)}catch(error){laneLines.push(JSON.stringify({dispatched:[{id:"?",outcome:"failed",reason:"lane",detail:describe(error)}]}))}if(passes.passed(repo),code===EXIT.ok){built++,progress(`watch: build ${index+1} did work (${new Date().toISOString()})`);continue}code===EXIT.failed&&(brokeCount++,broke=!0,progress(`watch: build ${index+1} — ${brokenWords(laneLines)}`))}else answer!==null&&!answer.take&&answer.why==="fair-share"?(yieldingSince===null&&(yieldingSince=passes.stamp(),store.bumpWake()),yieldingTo=answer.to??null):(yieldingSince=null,yieldingTo=null)}if(!broke&&store.wakeSeq()!==seqBefore)continue;const seqIdle=store.wakeSeq(),dozeUntil=Math.min(Date.now()+tickEveryMs,deadline??Number.MAX_SAFE_INTEGER),theirTurnEnded=()=>yieldingTo!==null&&yieldingSince!==null&&passes.lastPass(yieldingTo)>yieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}},ensureLanes=()=>{const facts=slotFacts(null),wanted=effectiveConcurrency(facts.limitOf(repo),facts.capacity);for(;lanes.length+1<wanted&&!stopping();)lanes.push(buildLane(lanes.length+1).catch(fail2))};let firstLaneYieldingSince=null,firstLaneYieldingTo=null;try{for(await maintenance.runNow();!stopping()&&(deadline===null||Date.now()<deadline);){if(paused()){await hub.changed({baseline:store.wakeSeq(),deadline:Date.now()+1e3,until:stopping,poker:wakes});continue}ensureLanes();const share=maySlotTake(slotFacts(firstLaneYieldingSince)),yieldBuilds=!share.take&&share.why!=="capacity";!share.take&&share.why==="fair-share"?(firstLaneYieldingSince===null&&(firstLaneYieldingSince=passes.stamp(),store.bumpWake()),firstLaneYieldingTo=share.to??null):(firstLaneYieldingSince=null,firstLaneYieldingTo=null);const seqBefore=store.wakeSeq(),now=Date.now();let tickDidWork=!1,tickBroke=!1;{lastTick=now,quiet.length=0,store.expireOverdueDecisions(new Date);const code=await tickCommand(passFlags(yieldBuilds?{"yield-builds":"1"}:{}),quietContext);passes.passed(repo),ticks++,lastPassAt=new Date().toISOString(),code===EXIT.ok?(tickDidWork=!0,built++,progress(`watch: pass ${ticks} did work (${new Date().toISOString()})`)):code===EXIT.failed&&(brokeCount++,tickBroke=!0,progress(`watch: pass ${ticks} — ${brokenWords(quiet)}`))}try{store.sealLedger()}catch(error){progress(`watch: the ledger chain could not be sealed this pass (${error instanceof Error?error.message:String(error)})`)}if(!admissionStopped()&&store.pendingPublications().length>0){const published=await publishPass(store,{repo,evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});published.pushed+published.opened+published.adopted+published.failed>0&&progress(`watch: published — pushed ${published.pushed}, opened ${published.opened}, adopted ${published.adopted}`+(published.failed>0?`, gave up on ${published.failed}`:""))}if(follower===null&&now-lastBridge>=bridgeEveryMs){lastBridge=now;const source=serviceBridge?null:loadBotToken(process.env,context.telegramTokenFile),dir=dirname(context.databaseFile),primary=effectivePrimary(process.env,dir,source!==null);source!==null&&(quiet.length=0,await bridgeCommand(["telegram"],passFlags(primary.channel==="telegram"?{}:{"inbound-only":"1"}),quietContext))}if(tickDidWork||!tickBroke&&store.wakeSeq()!==seqBefore)continue;const idleUntil=Math.min(lastTick+tickEveryMs,lastBridge+bridgeEveryMs,deadline??Number.MAX_SAFE_INTEGER)-Date.now(),seqIdle=store.wakeSeq(),dozeUntil=Date.now()+Math.max(idleUntil,0),theirTurnEnded=()=>firstLaneYieldingTo!==null&&firstLaneYieldingSince!==null&&passes.lastPass(firstLaneYieldingTo)>firstLaneYieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}}catch(error){fail2(error)}finally{const step=async(name,work)=>{cleanupStage=name;const slow=setTimeout(()=>progress(`watch: stopping is still waiting on ${name}`),CLEANUP_SLOW_MS);slow.unref?.();try{await work()}finally{clearTimeout(slow)}};await step("its builds",()=>Promise.all(lanes)),await step("reconciliation",()=>maintenance.stop()),await step("follow-up checks",()=>followUpChecks.stop()),await step("the code map check",()=>codeMapChecks.stop()),await step("flow moves",()=>flowMoves.stop()),await step("flow steps",()=>flowSteps.stop()),await step("the model check",()=>modelWatch.stop()),await step("deliveries and fast CI",()=>leaveServiceBeats()),stopHeartbeat(),followController.abort(),follower!==null&&await step("the Telegram follower",()=>follower),await step("the Slack follower",()=>slackFollower),await step("the Teams follower",()=>teamsFollower),await step("the Discord follower",()=>discordFollower),cleanupStage="releasing the project",store.endWatchEpisode(incarnation,{ticks,built,broke:brokeCount},new Date),store.releaseWatchLease(runner,repo,incarnation,new Date),cleanupStage=null}if(failed)throw failure;return leaseLost?{ok:!1,reason:"lease-lost",lost:leaseLostReason??"error",detail:`the watch lease for ${runner} on ${repo} stopped renewing — ${renewalRefusedWords(leaseLostReason??"error")}`,ticks,built,broke:brokeCount}:reconciliationFailure!==null?{ok:!1,reason:"reconciliation-failed",detail:reconciliationFailure,ticks,built,broke:brokeCount,busy:reconciliationBusy}:{ok:!0,ticks,built,broke:brokeCount,incarnation}}function brokenWords(lines){try{const failed=(JSON.parse(lines[lines.length-1]??"").dispatched??[]).filter(one=>one.outcome==="failed");return failed.length===0?"a pass broke something — the run records have it":`${failed.slice(0,3).map(one=>`${one.id} failed (${one.reason??"?"}${one.detail===void 0?"":`: ${one.detail}`})`).join("; ")}${failed.length>3?`; and ${failed.length-3} more`:""}`}catch{return"a pass broke something — the run records have it"}}async function watchCommand(flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"watch");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token")??readTokenFile(text(flags,"token-file"));if(runner===void 0||token===void 0)return fail(write,json,"watch","usage","`toolroll watch --runner <name> --token <t>|--token-file <path> --repo <path> [--for <ms>]`",EXIT.usage);flags.set("token",token);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"watch",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags),progress=longCommandProgress(write,json);let stopping=!1,graceTimer,followAbort=null;const stopGraceMs=Number(text(flags,"stop-grace")??3e4),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Hard stop: ${terminated} provider process group(s) terminated. Their work is saved and kept in each checkout, and each task continues from it; fences keep late output out of every commit. Run \`toolroll\` again to continue.`)},dropSignals=onStopSignals(()=>{if(stopping){hardStop();return}stopping=!0,followAbort?.abort(),wakeHubFor(context.store,read=>briefly(context.store,read)).poke(),graceTimer=setTimeout(hardStop,stopGraceMs)}),startedAt=Date.now();let result;try{result=await runWatchLoop({flags,context,runner,token,repo,progress,isStopping:()=>stopping||context.shouldStop?.()===!0,onFollowController:controller=>{followAbort=controller}})}finally{graceTimer!==void 0&&clearTimeout(graceTimer),dropSignals()}return result.ok?succeed(write,json,"watch",{ticks:result.ticks,built:result.built,broke:result.broke,incarnation:result.incarnation},()=>[`Watched ${repo} for ${Math.round((Date.now()-startedAt)/1e3)}s: ${result.ticks} pass(es), ${result.built} with work, ${result.broke} broke.`,"The lease is handed back; cron or the next watch may take it."]):fail(write,json,"watch",result.reason,result.detail,result.reason==="reconciliation-failed"||result.reason==="loop-failed"?EXIT.failed:EXIT.refused,{ticks:result.ticks,built:result.built,broke:result.broke})}const UP_LOGIN_FILE="up-login.txt";export function writeLoginFileDurably(path,name,password){const fd=openSync(path,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL,384);try{writeSync(fd,`${name} ${password}
475
492
  `),fsyncSync(fd)}finally{closeSync(fd)}const dir=openSync(dirname(path),fsConstants.O_RDONLY);try{fsyncSync(dir)}catch{}finally{closeSync(dir)}}function readLoginFile(path){if(activeRemote()!==null)throw new RemoteRefusal("unauthenticated",REMOTE_MESSAGES.credential);try{const raw=readFileSync(path,"utf8").trim(),cut=raw.indexOf(" ");if(cut<=0)return null;const name=raw.slice(0,cut),password=raw.slice(cut+1);return name===""||password===""?null:{name,password}}catch{return null}}async function resolveUpApprover(context,flags,canPrompt){const{store,clock}=context,stateDir=dirname(context.databaseFile),notes=[],local=localOwnerBinding(store);if(local!==null)return{approver:local.account,approvers:[local.account],verified:!1,passwordFile:null,mintedPassword:null,notes,startAuthority:"local"};const migration=migrateLegacyLogin(stateDir);migration.kind==="moved"?notes.push(`moved your saved login into ${migration.to} (owner-only, kept from agents)`):migration.kind==="both"?notes.push(`${migration.from} was left in place: ${migration.to} already holds a different login, and that one is used`):(migration.kind==="refused"||migration.kind==="failed")&&notes.push(`your saved login stays at ${migration.from} for now: ${migration.reason}`);let loginFile=savedLoginFile(stateDir);const asFlag=text(flags,"as");let names=store.listApprovers().map(one=>one.name);if(names.length===0){const orphan=readLoginFile(loginFile);if(orphan!==null){if(store.bootstrapApproverIfNone(orphan.name,hashApproverToken(orphan.password),clock()).ok)return notes.push(`adopted the login from ${UP_LOGIN_FILE} — a previous start was interrupted before it finished`),{approver:orphan.name,approvers:[orphan.name],verified:!0,passwordFile:loginFile,mintedPassword:null,notes,startAuthority:"full"};names=store.listApprovers().map(one=>one.name)}else{const name=asFlag??process.env.USER??process.env.USERNAME??"operator",password=mintSecret(12);try{loginFile=writableLoginFile(stateDir),writeLoginFileDurably(loginFile,name,password)}catch(error){return{refusal:`could not create ${loginFileOf(stateDir)} (${describe(error)}) — if a file is already there, another \`up\` may be starting; wait a moment, your login will be in it`}}if(store.bootstrapApproverIfNone(name,hashApproverToken(password),clock()).ok)return{approver:name,approvers:[name],verified:!0,passwordFile:loginFile,mintedPassword:password,notes,startAuthority:"full"};if(authenticateApprover(store,name,password).ok)return{approver:name,approvers:store.listApprovers().map(one=>one.name),verified:!0,passwordFile:loginFile,mintedPassword:null,notes,startAuthority:"full"};try{unlinkSync(loginFile)}catch{}names=store.listApprovers().map(one=>one.name)}}let fileLogin=null;const present=readLoginFile(loginFile);present!==null&&(authenticateApprover(store,present.name,present.password).ok?fileLogin=present:notes.push(`${UP_LOGIN_FILE} no longer matches any login — it is stale; your current password is the one you know`));let selected=null;if(asFlag!==void 0){if(!names.includes(asFlag))return{refusal:`no approver named \`${asFlag}\` — known: ${names.join(", ")}`};selected=asFlag}else names.length===1&&(selected=names[0]);let verified=!1,passwordFile=null;if(selected!==null&&fileLogin!==null&&fileLogin.name===selected)verified=!0,passwordFile=loginFile;else if(selected!==null&&canPrompt){const{askHidden:askHidden2}=await import("./prompt.js");let remembered=null;for(let attempt=1;attempt<=3&&!verified;attempt+=1){const typed=await askHidden2(`password for ${selected} (${attempt}/3): `);typed!==""&&authenticateApprover(store,selected,typed).ok&&(verified=!0,remembered=typed)}if(verified&&remembered!==null&&readLoginFile(loginFile)===null)try{loginFile=writableLoginFile(stateDir),writeLoginFileDurably(loginFile,selected,remembered),passwordFile=loginFile,notes.push(`remembered your login on this machine in ${loginFile} (owner-only) — the next \`up\` asks for nothing`)}catch{notes.push(`could not save your login in ${loginFileOf(stateDir)} — the next \`up\` will ask again`)}verified||notes.push(`could not verify ${selected}'s password — the console will still ask at login. If it is lost: another approver can add you (\`approver add\`), or restore the database/${UP_LOGIN_FILE}.`)}return{approver:selected,approvers:names,verified,passwordFile,mintedPassword:null,notes,startAuthority:verified?"full":"none"}}export function openBrowser(url){return openAddress(url)}function recordUpConsoleUrl(dir,url,now){try{const file=join(dir,UP_CONSOLE_FILE),temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${JSON.stringify({url,at:now.toISOString()})}
476
493
  `,{mode:384}),renameSync(temporary,file)}catch{}}function onboardLogin(store,loginFile){const names=store.listApprovers().map(one=>one.name),saved=readLoginFile(loginFile);return names.length===0?saved===null?null:{account:saved.name,file:loginFile}:saved!==null&&authenticateApprover(store,saved.name,saved.password).ok?{account:saved.name,file:loginFile}:{account:names.length===1?names[0]:null,file:null}}async function onboardCommand(flags,context){const{store,write,json,clock}=context,seams=context.onboardSeams??{},portGiven=text(flags,"port"),port=Number(portGiven??4180);if(portGiven!==void 0&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,"onboard","usage","--port is a whole number under 65536",EXIT.usage);const served=portGiven===void 0?readUpConsoleUrl(dirname(context.databaseFile)):null,home=seams.home??homedir(),env=seams.env??process.env,loginFile=savedLoginFile(dirname(context.databaseFile)),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),registryPath=registryPathOf(context),checker=createConnectionChecker({home,env,store:context.store}),code=await runOnboard({write,json,yes:flag(flags,"yes"),remove:flag(flags,"remove"),agentFlag:text(flags,"agent"),url:served??`http://127.0.0.1:${port}`,login:onboardLogin(store,loginFile),home,worktrees:join(dirname(context.databaseFile),"worktrees"),env,version:PACKAGE_VERSION,cwd:seams.cwd??process.cwd(),interactive:seams.interactive??(interactive()&&!underAgent(env)),confirm:seams.confirm??(async question=>/^y(es)?$/i.test(await ask(`${question} `))),findRepo:seams.findRepo??(async cwd=>{const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd}),topPath=top.code===0?canonicalProject(top.stdout.trim()):null;if(topPath===null)return null;const common=await gitRun("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd}),commonDir=common.code===0?common.stdout.trim():"",main=basename(commonDir)===".git"?canonicalProject(dirname(commonDir)):null;return{top:topPath,main:main??topPath}}),enrolled:async repo=>{const registry=await loadProjectRegistry(registryPath);return!("error"in registry)&&registry.repos.includes(repo)},enroll:async repo=>{const actor=commandLineActor(store,{databaseFile:context.databaseFile});if("ok"in actor)return{ok:!1,message:actor.message};const before=await loadProjectRegistry(registryPath),admitted=await admitProject(store,{registryFile:registryPath,path:repo,actor,now:clock()});return admitted.ok?{ok:!0,added:"error"in before||!before.repos.includes(admitted.repo)}:{ok:!1,message:admitted.message}},checkConnection:seams.checkConnection??(agent=>checker(agent)),pullRequests:seams.pullRequests??(async repo=>{const publishing=publishingOf(store,repo);if(publishing.on)return`on for ${publishing.githubRepo} into ${publishing.base}`;const checked=await checkPublishing(repo,context.publishExec===void 0?{}:{exec:context.publishExec});return checked.ok?`off: turn on with toolroll publish setup --repo ${repo} --yes (asks your password), or in Settings → Projects`:`off: ${checked.message}`}),youiyoux:seams.youiyoux??(async repo=>youiyouxOnboardLine(store,repo)),starterFlag:text(flags,"starter"),starters:{list:async repo=>{const views=startersFor(store,repo);return store.listApprovers().length>0?views:views.map(one=>({...one,blocked:one.blocked??"Needs your account first: run toolroll up, then onboard again."}))},switchOn:async(repo,id)=>{const owner=onboardLogin(store,loginFile)?.account??store.listApprovers()[0]?.name??null,starter=starterOf(id);return owner===null||starter===null?{ok:!1,said:"Needs your account first: run toolroll up, then onboard again."}:switchOnStarter(store,starter,repo,owner,clock(),dirname(context.databaseFile))}}});if(!json){const line=integrationsBrokenLine(await savedIntegrations(context).catch(()=>[]));line!==null&&write(line)}return code}async function upCommand(flags,context){const{store,write,json,clock}=context;if(context.upRole!==void 0)return upRoleCommand(context,context.upRole);const demoFence=refuseDemo(context,"up");if(demoFence!==null)return demoFence;const portGiven=text(flags,"port");let port=Number(portGiven??4180);if(portGiven!==void 0&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,"up","usage","--port is a whole number under 65536",EXIT.usage);const editorGiven=text(flags,"editor");if(editorGiven!==void 0&&editorGiven!=="vscode")return fail(write,json,"up","usage","--editor supports: vscode",EXIT.usage);const forGiven=text(flags,"for");if(forGiven!==void 0&&(!Number.isInteger(Number(forGiven))||Number(forGiven)<=0))return fail(write,json,"up","usage","--for takes a positive whole number of milliseconds",EXIT.usage);const capacityGiven=text(flags,"capacity"),capacityFlag=capacityGiven===void 0?null:parseRunnerCapacity(capacityGiven);if(capacityGiven!==void 0&&capacityFlag===null)return fail(write,json,"up","usage",`--capacity is a whole number of tasks, 1 to ${RUNNER_CAPACITY_MAX}`,EXIT.usage);const runnerFlag=text(flags,"runner");if(runnerFlag!==void 0&&!validRunnerName(runnerFlag))return fail(write,json,"up","usage",`a worker name is 1–${RUNNER_NAME_MAX} characters with no control characters`,EXIT.usage);const hostFlag=text(flags,"host")??"127.0.0.1";if(!/^[A-Za-z0-9.:-]{1,253}$/.test(hostFlag))return fail(write,json,"up","usage","--host is an address or a name",EXIT.usage);const allowFlag=text(flags,"allow-host"),publicUrlFlag=text(flags,"public-url"),laptop=flags.has("laptop");if(laptop&&(!["127.0.0.1","localhost","::1"].includes(hostFlag)||allowFlag!==void 0||publicUrlFlag!==void 0))return fail(write,json,"up","usage","--laptop serves this computer only: leave out --host, --allow-host and --public-url",EXIT.usage);const progress=longCommandProgress(write,json),registryPath=registryPathOf(context),removalsAtStart=registryRemovals(registryPath),loadedRegistry=await loadProjectRegistry(registryPath);if("error"in loadedRegistry)return fail(write,json,"up","registry",loadedRegistry.error,EXIT.refused);const gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),rootInputs=(text(flags,"project-root")??"").split(",").map(one=>one.trim()).filter(one=>one!==""),explicitRoots=[];for(const input of rootInputs){const canonical=canonicalProject(input);if(canonical===null)return fail(write,json,"up","project-root",`${input} is not a directory this machine can use`,EXIT.refused);explicitRoots.includes(canonical)||explicitRoots.push(canonical)}const projectRoots=[...resolveCeiling([],addRepos(loadedRegistry.roots,explicitRoots)).ceiling.roots],rootNotSaved=explicitRoots.length>0?". The projects folder wasn't saved, because this Toolroll didn't start: stop the one already running, then start it again with --project-root":"",repos=[],proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,deferredRepos=[],deferredGenerations={},repoLines={};for(const input of loadedRegistry.repos){const root=await proveRepo(input);root===null?(progress(`saved project unavailable — skipped ${input}; it connects when it's back`),deferredRepos.push(input),deferredGenerations[input]=removalsAtStart===null?-1:removalsAtStart[input]??0):(repos.includes(root)||repos.push(root),(repoLines[root]??=[]).push(input))}const explicitRepos=context.repoList??[],pinnedRepos=new Set;if(explicitRepos.length>0)for(const input of explicitRepos){const root=await proveRepo(input);if(root===null)return fail(write,json,"up","not-a-repository",`${input} is not inside a git repository — choose a repository, set a projects folder once with \`--project-root <dir>\`, or try the sandbox with \`toolroll demo\``,EXIT.refused);repos.includes(root)||repos.push(root),pinnedRepos.add(root)}else if(context.inferProjectFromCwd!==!1){const cwdRepo=await proveRepo(process.cwd());cwdRepo!==null&&!repos.includes(cwdRepo)&&repos.push(cwdRepo),cwdRepo!==null&&pinnedRepos.add(cwdRepo)}if(repos.length===0&&projectRoots.length===0&&deferredRepos.length===0){const fallback=laptop?upLaptopProjectsRoot(context.upSeams?.home??homedir()):null;if(fallback===null)return fail(write,json,"up","no-projects","choose where your projects live once: `toolroll up --project-root <dir>`",EXIT.refused);projectRoots.push(fallback)}if(!(!json&&!flags.has("verbose")&&(context.upSeams?.terminal??process.stdout.isTTY===!0)&&!underAgent(context.upSeams?.env??process.env))){for(const repo of repos)progress(`repository ${repo}`);for(const root of projectRoots)progress(`projects ${root}`)}const localCaller=upLocalInitCaller(context,flags),localInstall=laptop&&(localModeOf(store)?.enabled===!0||personMayInitLocalMode(localCaller)&&localModeCandidate(store)),candidates=laptop&&portGiven===void 0?upLaptopPortCandidates(store,context.upSeams?.laptopPorts,localInstall):[port];let probe=createNetServer(),reserved=!1;for(const candidate of candidates){if(candidate!==candidates[0]&&consoleRowForPort(store,candidate)!==null)break;if(candidate!==candidates[0]&&candidate===candidates[1]){let ours=null;try{ours=await proveLiveConsole(context.databaseFile,store,packageVersion())}catch{ours=null}if(ours?.ok===!0)return fail(write,json,"up","already-running",`Toolroll is already running at ${ours.url}${rootNotSaved}`,EXIT.refused);if(ours===null||ours.state!=="none")break;const serving=consoleServingNow(store,clock(),await consolesProvenDown(store,clock()));if(serving!==null)return fail(write,json,"up","already-running",`${serving.port===null?"Toolroll's console is already serving this database":`Toolroll is already running at http://127.0.0.1:${serving.port}`}${rootNotSaved}`,EXIT.refused)}if(probe=createNetServer(),port=candidate,reserved=await new Promise(resolveProbe=>{probe.once("error",()=>resolveProbe(!1)),probe.listen(candidate,"127.0.0.1",()=>resolveProbe(!0))}),reserved||consoleRowForPort(store,candidate)!==null)break}if(reserved&&laptop&&portGiven===void 0&&candidates.length>1&&(recordLaptopPort(store,port,new Date),port!==candidates[0]&&progress(`port ${candidates[0]} is in use by another program, so Toolroll uses ${port} on this computer`)),!reserved)return consoleRowForPort(store,port)?.state==="draining"?fail(write,json,"up","port-busy",`Toolroll is restarting (draining): the console on port ${port} is stopping — try again in a few seconds${rootNotSaved}`,EXIT.refused):fail(write,json,"up","port-busy",`port ${port} is taken — another \`up\` or \`serve\` may already be running; stop it, or pick a different --port${rootNotSaved}`,EXIT.refused);const agentRunning=underAgent(context.upSeams?.env??process.env),canPrompt=!json&&!agentRunning&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0;let runnerName="",runnerToken="",approver=null;try{flags.has("laptop")&&(await upLaptopLocalMode(context,text(flags,"as"),localCaller)).ok&&progress("local mode is on: this computer's browser signs in without a password");const approverPlan=await resolveUpApprover(context,flags,canPrompt);if("refusal"in approverPlan)return fail(write,json,"up","login",approverPlan.refusal,EXIT.refused);approver=approverPlan;for(const note of approverPlan.notes)progress(note);if(approverPlan.startAuthority==="none")return fail(write,json,"up","login",`${approverPlan.approver}'s password could not be verified — a runner only registers under a proven operator. Type it correctly, restore ${UP_LOGIN_FILE}, or have another approver re-add you.`,EXIT.refused);const base=runnerFlag??normalizeRunnerName(hostname());let doorAnswer=null;for(let attempt=1;attempt<=5;attempt+=1){const suffix=attempt===1?"":`-${attempt}`,name=attempt===1?base:`${base.slice(0,RUNNER_NAME_MAX-suffix.length)}${suffix}`,tryRegister=()=>registerRunnerIfIdle(store,{name,host:hostname(),repos,now:clock(),previousGone:holder=>recordedHolderProvedGone(runnerProcessFile(context.databaseFile,name),holder,hostname())});let answer=tryRegister();const drainWaitUntil=Date.now()+2*6e4;let saidDraining=!1;for(;!answer.ok&&answer.reason==="runner-draining"&&Date.now()<drainWaitUntil;)saidDraining||progress(`${answer.detail}; waiting for it to stop`),saidDraining=!0,await new Promise(resolveWait=>setTimeout(resolveWait,1e3)),answer=tryRegister();if(answer.ok){if(runnerName=name,runnerToken=answer.token,answer.signedOff!==null&&progress(`signed off the previous ${name}: its processes had already exited`),answer.recoveredRuns>0&&progress(`recovered ${answer.recoveredRuns} interrupted attempt(s) left by the previous ${name}`),!recordRunnerProcess(context.databaseFile,{runner:answer.runner,credentialHash:hashRunnerToken(answer.token)},"up",process.pid)){retireRunnerIfCurrent(store,runnerName,runnerToken,clock());const identity=processIdentityProblem();return fail(write,json,"up","runner-alive",`The worker process record could not be saved${identity===null?"":` (${identity})`}; nothing started`,EXIT.refused)}recordBuilderWish(store,"running","up",packageVersion(),clock()),doorAnswer=answer;break}if(doorAnswer=answer,runnerFlag!==void 0||answer.reason==="runner-draining")break}if(runnerName===""){const detail=doorAnswer!==null&&!doorAnswer.ok?doorAnswer.detail:"no worker name could be taken";return doorAnswer!==null&&!doorAnswer.ok&&doorAnswer.reason==="runner-draining"?fail(write,json,"up","runner-alive",`${detail}, and it hasn't yet — try again shortly`,EXIT.refused):fail(write,json,"up","runner-alive",`${detail} — that worker looks alive; stop the other \`up\` or watch, or name a different worker with --runner`,EXIT.refused)}{const enrolled=await updateProjectRegistry(registryPath,current=>({repos:addRepos(current.repos,repos),roots:addRepos(current.roots,projectRoots)}));if(!enrolled.ok)return retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),fail(write,json,"up","registry",`${enrolled.message} — nothing started`,EXIT.refused)}if(capacityFlag!==null){const changed=store.setRunnerCapacity(runnerName,capacityFlag,approverPlan.approver??"operator",clock());changed.ok&&changed.before!==changed.after&&progress(`${runnerName} now runs up to ${changed.after} task(s) at once (was ${changed.before})`)}}finally{await new Promise(done=>probe.close(()=>done()))}const pool=join(dirname(context.databaseFile),"worktrees"),split=!flags.has("single-process")&&context.upOneProcess!==!0,build2=upBuildIdentity(),containmentFlag=text(flags,"containment")??null,stopGraceMs=Number(text(flags,"stop-grace")??3e4);let stopping=!1,fatal=null,runTimer,resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);let currentRepos=[...repos],consoleRole=null,workerRole=null,resolveForced=()=>{};const forced=new Promise(resolveForce=>resolveForced=resolveForce);let forceTimer;const stopDeadlineMs=Math.max(1,stopGraceMs)+2e4,stop=()=>{if(stopping){workerRole?.hardStop();return}stopping=!0,resolveStopped();try{runnerName!==""&&drainRunnerIfCurrent(store,runnerName,runnerToken,clock(),new Date(clock().getTime()+stopDeadlineMs))}catch{}forceTimer=setTimeout(()=>{fatal??=`stopping took longer than ${Math.round(stopDeadlineMs/1e3)} s; its console and worker were stopped outright`,workerRole?.kill(),consoleRole?.kill(),resolveForced()},stopDeadlineMs),forceTimer.unref?.(),consoleRole?.send({type:"stopping"}),workerRole?.stop()},dropStopSignals=onStopSignals(stop);let parentGone=!1;const parentAtStart=process.ppid,parentWatch=context.upSeams===void 0&&parentAtStart>1?setInterval(()=>{process.ppid===parentAtStart||parentGone||(parentGone=!0,progress("the process that started Toolroll is gone; stopping"),stop())},1e3):void 0;parentWatch?.unref?.();const onDisconnect=()=>{parentGone||(parentGone=!0,progress("the process that started Toolroll closed its channel; stopping"),stop())};context.upSeams===void 0&&process.channel!==void 0&&process.channel!==null&&process.once("disconnect",onDisconnect);const labelled=split&&(json||flags.has("verbose")||!(context.upSeams?.terminal??process.stdout.isTTY===!0)),roleLine=role=>line=>progress(labelled?`[${role}] ${line}`:line),dropSignals=()=>{dropStopSignals(),process.removeListener("disconnect",onDisconnect),parentWatch!==void 0&&clearInterval(parentWatch)},consoleConfig={host:hostFlag,port,allowedHosts:allowFlag===void 0?null:allowFlag.split(",").map(one=>one.trim()).filter(one=>one!==""),publicUrl:publicUrlFlag??null,localRunner:runnerName,poolRoot:pool,repos:[...repos],projectRoots,registryPath,editor:editorGiven!==void 0,startAuthority:approver?.startAuthority??"none"},pendingLinks=new Map;let linkRequests=0;const roleSpawned=(role,pid)=>{const held=store.getRunner(runnerName);return held!==null&&held.credentialHash===hashRunnerToken(runnerToken)&&recordRunnerProcess(context.databaseFile,held,role,pid)};consoleRole=startUpRole({role:"console",split,context,build:build2,shutdownMs:15e3,onSpawned:pid=>roleSpawned("console",pid),start:()=>({type:"start",role:"console",databaseFile:context.databaseFile,containment:containmentFlag,build:build2,config:{...consoleConfig,repos:[...currentRepos]}}),onMessage:message=>{message.type==="log"?roleLine("console")(message.line):message.type==="sign-in-link"&&(pendingLinks.get(message.id)?.(message.link),pendingLinks.delete(message.id))},onReady:(_,again)=>{again&&(roleLine("console")("started again"),consoleRole?.send({type:"repos",repos:[...currentRepos]}))},onEnded:(detail,restarting)=>{restarting?roleLine("console")(`${detail}; starting it again`):stopping||(fatal=detail,stop())}});const consoleReady=await consoleRole.ready;if(!consoleReady.ok)return dropSignals(),retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),consoleReady.reason==="port-busy"?fail(write,json,"up","port-busy",`${consoleReady.detail} — the port was taken while starting; try again`,EXIT.refused):fail(write,json,"up","failed",`the console could not start (${consoleReady.detail}) — nothing was left running`,EXIT.failed);const url=consoleReady.url;if(!stopping){workerRole=startUpRole({role:"worker",split,context,build:build2,onSpawned:pid=>roleSpawned("worker",pid),shutdownMs:Math.max(1,stopGraceMs)+15e3,watchdog:{graceMs:stopGraceMs,say:line=>roleLine("worker")(line),...context.upSeams?.watchdogSilenceMs===void 0?{}:{silenceMs:context.upSeams.watchdogSilenceMs},paused:()=>briefly(store,()=>{if(updateAdmissionPaused(store.raw()))return!0;const own=store.getRunner(runnerName)?.runner;return own!==void 0&&drainOf(store,own,clock())!==null})},start:generation=>({type:"start",role:"worker",databaseFile:context.databaseFile,containment:containmentFlag,build:build2,config:{runner:runnerName,token:runnerToken,repos:generation===1?[...repos]:[...currentRepos],pinnedRepos:[...pinnedRepos],projectRoots,registryPath,pool,deferredRepos:[...deferredRepos],deferredGenerations:{...deferredGenerations},repoLines,forMs:forGiven===void 0?null:Number(forGiven),publicUrl:publicUrlFlag??null,stopGraceMs,verbose:flags.has("verbose"),terminal:context.upSeams?.terminal??process.stdout.isTTY===!0,leaseWaitMs:split?WATCH_LEASE_MS+15e3:0}}),onMessage:message=>{if(message.type==="log")roleLine("worker")(message.line);else if(message.type==="deferred"){const narrowed=upNarrowDeferred(deferredRepos,message.repos);deferredRepos.length=0,deferredRepos.push(...narrowed)}else if(message.type==="repos"){const bound=new Set(store.getRunner(runnerName)?.runner.repos??[]);currentRepos=message.repos.filter(repo=>bound.has(repo)),consoleRole?.send({type:"repos",repos:[...currentRepos]})}},onReady:(_,again)=>{again&&roleLine("worker")("started again: its builds and checks continue")},onEnded:(detail,restarting)=>{if(restarting&&authenticate(store,runnerName,runnerToken).ok){roleLine("worker")(`${detail}; starting it again — its interrupted builds are recovered first`);return}stopping||(fatal=restarting?`the builder identity changed (${detail})`:detail,stop())}});const workerReady=await workerRole.ready;!workerReady.ok&&fatal===null&&(fatal=workerReady.detail,stop())}const runnerHeartbeat=setInterval(()=>{let beat;try{beat=briefly(store,()=>heartbeatRunner(store,runnerName,runnerToken,clock()))}catch(error){if(isDatabaseBusy(error)||stopping)return;fatal=`the builder's heartbeat could not be recorded (${describe(error)})`,stop();return}!beat.ok&&!stopping&&(fatal=`the builder identity changed (${beat.reason})`,stop())},RUNNER_HEARTBEAT_MS);runnerHeartbeat.unref?.();let removeSignInPageNow=()=>{};const approverPlan2=approver,terminal=!agentRunning&&(context.upSeams?.terminal??process.stdout.isTTY===!0),upHandoff=buildHandoff({url,login:{account:approverPlan2.passwordFile===null?approverPlan2.approver:loginAccount(approverPlan2.passwordFile)??approverPlan2.approver,file:approverPlan2.passwordFile}});recordUpConsoleUrl(dirname(context.databaseFile),url,clock());let firstRunDetection=null;if(fatal===null&&!stopping&&store.firstSuccessAt(clock())===null&&!store.isDemo()&&(firstRunDetection=await(context.upSeams?.detectFirstRun??(()=>detectFirstRunAgents({env:context.upSeams?.env??process.env,home:context.upSeams?.home??homedir()})))().catch(()=>null),firstRunDetection!==null&&autoSelectFirstRunDefault(store,firstRunDetection,clock())),fatal===null&&!stopping)if(json)write(envelopeJson({ok:!0,command:"up",url,repos,runner:runnerName,approver:approverPlan2.approver,approvers:approverPlan2.approvers,approverVerified:approverPlan2.verified,...approverPlan2.passwordFile===null?{}:{passwordFile:approverPlan2.passwordFile},handoff:upHandoff,...firstRunDetection===null?{}:{detectedAgents:{recommendedDefault:firstRunDetection.recommendedDefault,readinessSummary:firstRunDetection.readinessSummary,ready:firstRunDetection.readyAgents.map(one=>one.id)}}}));else if(terminal){const account=approverPlan2.approver,localStart=approverPlan2.startAuthority==="local",request=upLinkRequest(approverPlan2.startAuthority,account),pageParent=instanceRunDir(context.databaseFile),hasOpener=platformOpener(context.upSeams?.signInPlatform)!==null,canOpen=hasOpener&&prepareRunDir(pageParent)===null,linkExpiresAt=Date.now()+SIGN_IN_LINK_MS,link=request===null||flags.has("no-open")||!canOpen?null:await new Promise(resolveLink=>{const id=++linkRequests,timer=setTimeout(()=>{pendingLinks.delete(id),resolveLink(null)},1e4);pendingLinks.set(id,value=>{clearTimeout(timer),resolveLink(value)}),consoleRole?.send({type:"sign-in-link",id,...request})}),saved=approverPlan2.passwordFile===null?null:resolve(approverPlan2.passwordFile),showCommand=saved===null?null:`cat -- '${saved.replaceAll("'","'\\''")}'`,signInWords2=account===null?`sign in as one of ${approverPlan2.approvers.join(", ")}`:showCommand===null?`sign in as ${account} with your password`:`sign in as ${account}`,opened=link===null?!1:await(async()=>{const outcome=localStart?"local link":"one-time link",page=await openSignInLink(new URL(link,url).toString(),{parent:pageParent,spent:ledgerSpent(store,outcome,localStart?null:account),expiresAt:linkExpiresAt,...context.upSeams?.signInOpener===void 0?{}:{opener:context.upSeams.signInOpener},...context.upSeams?.signInPlatform===void 0?{}:{platform:context.upSeams.signInPlatform}});return removeSignInPageNow=page.stop,page.opened})();if(write(""),write(`Toolroll is on ${url}`),localStart?opened?(write("Opening it in your browser now, already signed in."),write("If it doesn't open, stop it with Ctrl-C and run the same command again.")):flags.has("no-open")?write("To sign in from this computer's browser, run the same command again without --no-open."):write(hasOpener?"Your browser didn't open. Stop it with Ctrl-C and run the same command again.":`${NO_SAFE_OPENER.charAt(0).toUpperCase()}${NO_SAFE_OPENER.slice(1)}.`):opened?(write("Opening it in your browser now, already signed in."),write(`If it doesn't open, go to that address and ${signInWords2}.`)):write(`${signInWords2.charAt(0).toUpperCase()}${signInWords2.slice(1)}.`),showCommand!==null&&write(`Your password: run \`${showCommand}\``),opened||write("Ctrl-C stops it."),firstRunDetection!==null){write("");for(const line of formatFirstRunAgentsTable(firstRunDetection))write(line)}}else{write("");for(const line of handoffLines(upHandoff,{local:approverPlan2.startAuthority==="local"}))write(line);write("Run `toolroll onboard` inside a repository to add it and install the Toolroll skill for your agent.")}forGiven!==void 0&&!stopping&&(runTimer=setTimeout(stop,Number(forGiven)),runTimer.unref?.()),await stopped,removeSignInPageNow(),workerRole!==null&&await Promise.race([workerRole.done,forced]),clearInterval(runnerHeartbeat),runTimer!==void 0&&clearTimeout(runTimer),dropSignals(),retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),consoleRole.stop();const closed=await Promise.race([consoleRole.done,forced.then(()=>({problem:null}))]);return forceTimer!==void 0&&clearTimeout(forceTimer),parentGone&&setTimeout(()=>process.exit(fatal===null?EXIT.ok:EXIT.failed),1e3).unref?.(),closed.problem!==null&&fatal===null&&(fatal=closed.problem),fatal!==null?(process.stderr.write(`up: ${fatal}
477
494
  `),EXIT.failed):(progress(flags.has("laptop")?"Toolroll stopped. Run `toolroll` to start it again.":"Toolroll stopped. Run `toolroll up` anywhere on this machine to start it again with every saved project."),EXIT.ok)}function digestWords(everyMs){return everyMs%36e5===0?`${everyMs/36e5}h`:`${Math.round(everyMs/6e4)}m`}async function bridgeCommand(positional,flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"bridge");if(demoFence!==null)return demoFence;const[channel,action]=positional;if(channel!=="telegram")return fail(write,json,"bridge","usage","`toolroll bridge telegram [pair|unpair|token|status|digest|retry]`",EXIT.usage);if(action==="retry"){const retried=store.retryTelegramReplies(null,clock());return succeed(write,json,"bridge retry",{retried},()=>[retried===0?"No unsent Telegram replies.":`Sending ${retried} Telegram ${retried===1?"reply":"replies"} again on the next bridge pass.`])}if(action==="token"){const value=positional[2];if(flags.has("clear")){const removed=clearBotToken(context.telegramTokenFile);return succeed(write,json,"bridge token",{cleared:removed},()=>[removed?"Token file removed.":"There was no token file to remove."])}if(value===void 0)return fail(write,json,"bridge token","usage","`toolroll bridge telegram token <bot-token>` (from @BotFather), or --clear",EXIT.usage);const saved=saveBotToken(context.telegramTokenFile,value);return saved.ok?succeed(write,json,"bridge token",{saved:!0,file:context.telegramTokenFile},()=>[`Saved (owner-only) to ${context.telegramTokenFile}.`,`${TOKEN_ENV} in the environment would take precedence over it.`]):fail(write,json,"bridge token","bad-token",saved.message,EXIT.refused)}if(action==="digest"){const every=text(flags,"every");if(flags.has("off"))return store.setTelegramDigest(null,"cli",clock()),succeed(write,json,"bridge digest",{everyMs:null},()=>["Digest off — every fact pages as it lands."]);if(every===void 0){const current=store.telegramDigest(),held=store.countRoutinePending();return succeed(write,json,"bridge digest",{...current,held},()=>[current.everyMs===null?"Digest off — every fact pages as it lands. `bridge telegram digest --every 2h` turns it on.":`Digest every ${digestWords(current.everyMs)}; ${held} routine fact(s) held; next no earlier than ${current.lastSentAt===null?"the next bridge pass":new Date(new Date(current.lastSentAt).getTime()+current.everyMs).toISOString()}.`])}const parsed=/^([1-9][0-9]{0,3})(m|h)$/.exec(every);if(parsed===null)return fail(write,json,"bridge digest","usage","--every takes minutes or hours: 30m, 2h, 24h — or --off",EXIT.usage);const everyMs=Number(parsed[1])*(parsed[2]==="h"?36e5:6e4);return everyMs<5*6e4||everyMs>168*36e5?fail(write,json,"bridge digest","usage","the digest cadence is between 5 minutes and 7 days",EXIT.usage):(store.setTelegramDigest(everyMs,"cli",clock()),succeed(write,json,"bridge digest",{everyMs},()=>[`Digest every ${digestWords(everyMs)}. Routine facts are held and sent together; decisions and anything that needs you now still page at once.`]))}const source=loadBotToken(process.env,context.telegramTokenFile);if(action==="status"){const bindings=source===null?[]:store.liveTelegramBindings(source.botId),binding=bindings[0]??null,pending=store.listNotifications("pending").length,digest=store.telegramDigest();return json?(write(envelopeJson({ok:!0,command:"bridge status",token:source===null?null:{source:source.source,botId:source.botId,redacted:redactToken(source.token)},paired:binding!==null,approver:binding?.approver??null,people:bindings.map(one=>one.approver),outboxPending:pending,digest:{everyMs:digest.everyMs,lastSentAt:digest.lastSentAt,held:digest.everyMs===null?0:store.countRoutinePending()}})),EXIT.ok):(write(source===null?`No bot token. Set ${TOKEN_ENV}, run \`toolroll bridge telegram token <t>\`, or use the serve settings card.`:`Token ${redactToken(source.token)} (${source.source}), bot ${source.botId}.`),write(binding===null?"No chat is paired.":`Paired: ${bindings.length===1?`chat answers as ${binding.approver}`:`${bindings.length} chats answer as ${bindings.map(one=>one.approver).join(", ")}`}.`),write(`Outbox pending: ${pending}.`),write(digest.everyMs===null?"Digest off.":`Digest every ${digestWords(digest.everyMs)}; ${store.countRoutinePending()} routine fact(s) held.`),EXIT.ok)}if(action==="pair"||action==="unpair"){const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`bridge ${action}`,"usage","`--as <you> --token <your password>` — pairing hands your authority to a chat, so it takes your credential",EXIT.usage);const{name:asWho,token}=acting,authenticated=action==="pair"?credentialApprover(store,asWho,token):authenticateApprover(store,asWho,token);if(!authenticated.ok)return fail(write,json,`bridge ${action}`,authenticated.reason,describeApproveFailure(authenticated.reason,asWho),EXIT.refused);if(action==="unpair"){if(source===null)return fail(write,json,"bridge unpair","no-token","no bot token, so no bot to unpair",EXIT.refused);const revoked=store.unpairTelegram(source.botId,asWho,clock());return succeed(write,json,"bridge unpair",{revoked},()=>[revoked?"Unpaired. Every outstanding button from that chat is dead. Rotate the bot token with @BotFather if it may have leaked.":"Nothing was paired."])}const code=mintPairingCode();return store.createTelegramPairing({codeHash:hashPairingCode(code),approver:asWho,by:asWho,ttlMs:PAIRING_TTL_MS},clock()),succeed(write,json,"bridge pair",{code,expiresInMs:PAIRING_TTL_MS},()=>["From your phone, send your bot this message within 10 minutes:","",` /pair ${code}`,"","The next bridge pass completes it. The code works once, in a private","chat only, and the chat will answer as you — treat it accordingly."])}if(action!==void 0)return fail(write,json,"bridge","usage","`toolroll bridge telegram [pair|unpair|token|status]`",EXIT.usage);if(source===null)return fail(write,json,"bridge","no-token",`no bot token — set ${TOKEN_ENV}, run \`toolroll bridge telegram token <t>\`, or use the serve settings card`,EXIT.refused);const fenced=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fenced!==null)return fail(write,json,"bridge","network-fenced",networkFenceLine(fenced),EXIT.refused);const transport=context.telegramTransport??createTransport(source.token);if(flags.has("follow")){const controller=new AbortController,dropSignals=onStopSignals(()=>controller.abort()),runFor=text(flags,"for"),timer=runFor===void 0?null:setTimeout(()=>controller.abort(),Number(runFor));timer?.unref?.();const fence=context.shouldStop===void 0?null:setInterval(()=>{context.shouldStop?.()===!0&&controller.abort()},50);fence?.unref?.(),json||write(`Following bot ${source.botId} — taps apply as they arrive. Ctrl-C stops it.`);try{const report2=await followBridge(store,{readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context),...flags.has("inbound-only")?{deliver:!1}:{},botId:source.botId,transport,signal:controller.signal,clock,...text(flags,"poll")===void 0?{}:{pollSeconds:Number(text(flags,"poll"))},onCycle:cycle=>{json||write(`bridge: sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}});return succeed(write,json,"bridge follow",{report:report2},()=>[`Followed for ${report2.cycles} cycle(s): sent ${report2.sent}, answered ${report2.answered}, paired ${report2.paired}, ignored ${report2.ignored}, status replies ${report2.statusReplies??0}.`,...report2.problems.slice(-5).map(problem=>` problem: ${problem}`)])}finally{timer!==null&&clearTimeout(timer),fence!==null&&clearInterval(fence),dropSignals()}}const passed=await bridgePass(store,{readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context),botId:source.botId,transport,clock,...flags.has("inbound-only")?{deliver:!1}:{}});if(!passed.ok)return fail(write,json,"bridge",passed.reason,passed.message,EXIT.refused);const{report}=passed,broke=report.problems.length>0,idle=report.sent===0&&report.answered===0&&report.paired===0&&(report.statusReplies??0)===0&&(report.chatQueued??0)===0&&(report.chatAnswered??0)===0&&(report.chatRefused??0)===0&&(report.chatConfirmed??0)===0,lines=()=>[`Sent ${report.sent}, answered ${report.answered}, paired ${report.paired}, ignored ${report.ignored}, status replies ${report.statusReplies??0}, chat received ${report.chatQueued??0}, chat replied ${report.chatAnswered??0}, chat confirmed ${report.chatConfirmed??0}.`,...report.backlog?["Telegram still holds more updates than one pass's budget — run it again."]:[],...report.problems.map(problem=>` problem: ${problem}`)];return broke?fail(write,json,"bridge","telegram-transport",lines().join(`
478
495
  `),EXIT.failed,{report}):idle?fail(write,json,"bridge","idle","nothing to send, nothing arrived",EXIT.refused,{report}):succeed(write,json,"bridge",{report},lines)}async function publishCommand(positional,flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"publish");if(demoFence!==null)return demoFence;const repo=repoFrom(flags),[action]=positional;if(action!==void 0&&!PUBLISH_ACTIONS.includes(action))return fail(write,json,"publish","usage",`unknown \`publish ${action}\` — try ${PUBLISH_ACTIONS.join(", ")}, or bare \`publish\` for the publication pass`,EXIT.usage);if(action==="setup"){const mergeMethod=text(flags,"merge-method")??"squash";if(!["squash","merge","rebase"].includes(mergeMethod))return fail(write,json,"publish setup","usage","--merge-method is squash, merge or rebase",EXIT.usage);const checked=await checkPublishing(repo,context.publishExec===void 0?{}:{exec:context.publishExec});if(!checked.ok)return fail(write,json,"publish setup",checked.reason,checked.message,EXIT.refused);const settings={mergeMethod,mergeWhenGreen:flags.has("merge-when-green")},plan=checked.plan,terms=[`Pull requests for ${plan.githubRepo} into ${plan.base}${plan.account===null?"":`, as ${plan.account}`}.`,'Complete will offer "Complete and open a pull request"; the pull request opens from the exact completed commit.',`Merges ${settings.mergeMethod} and delete the branch${settings.mergeWhenGreen?", by themselves once checks pass":" when a person selects Merge"}.`];if(!flags.has("yes")){if(json)return write(envelopeJson({ok:!1,command:"publish setup",reason:"unconfirmed",proposed:{...plan,...settings}})),EXIT.refused;for(const line of terms)write(line);return write("Nothing is set up yet. Repeat with --yes --as <you> --token <password> to turn it on."),EXIT.refused}const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(store,acting.name,acting.token,repo);return acting===null||!verified?.ok?refuseApprover(context,"publish setup",verified,"turning on pull requests takes --as <you> --token <your password>",acting?.name):(savePublishing(store,plan,acting.name,settings,clock()),succeed(write,json,"publish setup",{publishing:publishingOf(store,repo)},()=>["Pull requests are on.",...terms]))}if(action==="grant"){const github=text(flags,"github");if(github===void 0||!/^[\w.-]+\/[\w.-]+$/.test(github))return fail(write,json,"publish grant","usage","`--github <owner/name>` is required, exactly",EXIT.usage);const wantsMerge=flags.has("allow-merge"),mergeMethod=text(flags,"merge-method");if(wantsMerge&&(mergeMethod===void 0||!["squash","merge","rebase"].includes(mergeMethod)))return fail(write,json,"publish grant","usage","--allow-merge names its method: --merge-method squash|merge|rebase",EXIT.usage);const spec={repo,githubRepo:github,remote:text(flags,"remote")??"origin",headPrefix:text(flags,"head-prefix")??BRANCH_PREFIX,base:text(flags,"base")??"main",capabilities:["push-branch","open-pr"],selector:flags.has("all-tasks")?"all":"ours",draft:!flags.has("ready"),merge:wantsMerge,mergeMethod:wantsMerge?mergeMethod:null,mergeDeleteBranch:wantsMerge&&flags.has("merge-delete-branch")},mergeTerms=[];if(wantsMerge){const whoAmI=await(context.publishExec??void 0)?.("gh",["api","user","--jq",".login"],{timeoutMs:1e4})??await(await import("./exec.js")).run("gh",["api","user","--jq",".login"],{timeoutMs:1e4}),account=whoAmI.code===0?whoAmI.stdout.trim():"(gh is not signed in — merges will refuse)";mergeTerms.push("","AND auto-merge: pull requests this plane opened or adopted, on "+github+" into "+spec.base+",","merge as "+mergeMethod+(spec.mergeDeleteBranch?" and delete the remote branch":"")+" — ONLY after CI was OBSERVED green on the exact","head commit (silence, running, or a moved head never merge; drafts never merge;","a base with a merge queue, or protection this plane cannot read, pauses with a page).","Merging acts as the GitHub account signed into gh on the machine that runs the","sweep — currently: "+account+" — and is NOT pinned; changing gh auth changes who merges.","CI can turn red on the same commit between the last look and the merge; the","exact-commit match cannot see that. An all-skipped check rollup reads as passing.")}if(!flags.has("yes")){if(json)return write(envelopeJson({ok:!1,command:"publish grant",reason:"unconfirmed",proposed:spec,granted:!1})),EXIT.refused;write("This grant would allow, unattended:");for(const line of describePublicationGrant(spec))write(line);for(const line of mergeTerms)write(line);return write(""),write("Nothing is granted yet. Repeat with --yes --as <you> --token <approver-token> to agree to exactly this."),EXIT.refused}const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"publish grant",verified,"granting takes --as <you> --token <your password> — pushing your repos is a person's yes",acting?.name);const{name:asWho}=acting;return store.savePublicationGrant({...spec,grantedBy:asWho},clock()),succeed(write,json,"publish grant",{granted:!0,grant:spec},()=>[`Granted by ${asWho}:`,...describePublicationGrant(spec),"Revoke any time: `toolroll publish revoke --as <you> --token <t>`."])}if(action==="revoke"){const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"publish revoke",verified,"`--as <you> --token <your password>`",acting?.name);const{name:asWho}=acting,revoked=store.revokePublicationGrant(repo,asWho,clock());return succeed(write,json,"publish revoke",{revoked},()=>[revoked?"Revoked. The next pass pushes nothing, whatever intents exist.":"There was no live grant to revoke."])}if(action==="status"){const grant=store.publicationGrantFor(repo),pending=store.pendingPublications();if(json)return write(envelopeJson({ok:!0,command:"publish status",grant,pending})),EXIT.ok;if(write(grant===null?"No live publication grant.":`Granted by ${grant.grantedBy} at ${grant.grantedAt}:`),grant!==null)for(const line of describePublicationGrant(grant))write(line);return write(pending.length===0?"Nothing owed.":`Owed: ${pending.length} publication(s) pending.`),EXIT.ok}if(action==="merge"||action==="refire"){const prGiven=positional[1],pr=Number(prGiven);if(prGiven===void 0||!Number.isInteger(pr)||pr<=0)return fail(write,json,`publish ${action}`,"usage",`\`toolroll publish ${action} <pr> --as <you> --token <t>\``,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`publish ${action}`,verified,"authorizing a merge takes `--as <you> --token <t>` — who said yes is recorded, not asserted",acting?.name);const publication=store.openedPublications().find(one=>one.prNumber===pr);if(publication===void 0)return fail(write,json,`publish ${action}`,"unknown",`no open publication holds PR #${pr}`,EXIT.refused);const flexibleHold=flexibleMergeRefusal(store,store.refForId(publication.taskRef)?.externalId??null,action==="merge"?"publish-merge":"publish-refire");if(flexibleHold!==null)return fail(write,json,`publish ${action}`,"flexible",flexibleHold,EXIT.refused);const intent=store.mergeIntentFor(publication.id);if(intent===null)return fail(write,json,`publish ${action}`,"no-intent",`PR #${pr} has no merge intent yet — the sweep writes one when a merge-capable grant covers it`,EXIT.refused);if(action==="merge"){const released=store.authorizeMergeIntent(intent.id,intent.headSha,acting.name,clock());return released.ok?(store.resolveEpisodes(`merge-attn:${publication.id}`,context.clock()),succeed(write,json,"publish merge",{pr,headSha:intent.headSha},()=>[`Your yes covers PR #${pr} at ${intent.headSha.slice(0,12)} — the next sweep merges it once CI is seen green on that exact commit.`])):released.reason==="recovery-held"?fail(write,json,"publish merge","recovery-held","Checks are on hold after recovery. Earlier execution is unverified.",EXIT.refused):fail(write,json,"publish merge",released.reason,released.reason==="not-waiting"?`PR #${pr} is not waiting for you (it is ${intent.state}) — only a waiting merge takes this yes`:`PR #${pr}'s commit moved since this intent was written — the sweep will re-prove and re-ask`,EXIT.refused)}const refired=store.refireMergeIntent(intent.id,acting.name,clock());return refired.ok?(store.resolveEpisodes(`merge-attn:${publication.id}`,context.clock()),succeed(write,json,"publish refire",{pr},()=>[`PR #${pr} re-enters the full merge road — claim, re-proof, and the firing gate, from the top.`])):refired.reason==="recovery-held"?fail(write,json,"publish refire","recovery-held","Checks are on hold after recovery. Earlier execution is unverified.",EXIT.refused):fail(write,json,"publish refire",refired.reason,refired.reason==="not-firing"?`PR #${pr} has no half-fired merge (it is ${intent.state})`:`PR #${pr}'s merge claim is still live — its owner may finish; refire only recovers one gone silent past its deadline`,EXIT.refused)}if(action==="unblock"||action==="rearm"){const prGiven=positional[1],pr=Number(prGiven);if(prGiven===void 0||!Number.isInteger(pr)||pr<=0)return fail(write,json,`publish ${action}`,"usage",`\`toolroll publish ${action} <pr> --as <you> --token <t>\``,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`publish ${action}`,verified,`${action==="unblock"?"lifting a repair hold":"re-arming a refused merge"} takes \`--as <you> --token <t>\` — who decided is recorded, not asserted`,acting?.name);const publication=store.openedPublications().find(one=>one.prNumber===pr);if(publication===void 0)return fail(write,json,`publish ${action}`,"unknown",`no open publication holds PR #${pr}`,EXIT.refused);if(action==="unblock"){const lifted=store.liftMergeBlocker(publication.id,acting.name,context.clock());return store.resolveEpisodes(`merge-attn:${publication.id}`,context.clock()),succeed(write,json,"publish unblock",{pr,lifted},()=>[lifted?`PR #${pr} no longer holds for its repair — the next sweep may merge it under the granted terms.`:`PR #${pr} was not held by a repair.`])}const rearmed=store.rearmMergeIntent(publication.id);return rearmed==="recovery-held"?fail(write,json,"publish rearm","recovery-held","Checks are on hold after recovery. Earlier execution is unverified.",EXIT.refused):(store.resolveEpisodes(`merge-attn:${publication.id}`,context.clock()),succeed(write,json,"publish rearm",{pr,rearmed},()=>[rearmed?`PR #${pr}'s merge is re-armed — the next sweep re-proves everything and tries again.`:`PR #${pr} had no refused merge to re-arm.`]))}if(action!==void 0)return fail(write,json,"publish","usage","`toolroll publish [grant|revoke|status|unblock|rearm]`",EXIT.usage);const report=await publishPass(store,{repo,clock,evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}}),merges=await sweepMerges(store,{repo,clock,...context.publishExec===void 0?{}:{exec:context.publishExec}}),idle=report.pushed===0&&report.opened===0&&report.adopted===0&&report.failed===0&&merges.merged===0&&merges.refused===0,lines=()=>[`Pushed ${report.pushed}, opened ${report.opened}, adopted ${report.adopted}, gave up on ${report.failed}.`+(merges.merged+merges.refused+merges.skipped>0?` Merged ${merges.merged}, refused ${merges.refused}, holding ${merges.skipped}.`:""),...report.problems.map(problem=>` problem: ${problem}`),...merges.problems.map(problem=>` merge: ${problem}`)];return report.problems.length>0?fail(write,json,"publish","publish-problems",lines().join(`
479
496
  `),EXIT.failed,{report}):idle?fail(write,json,"publish","idle","nothing owed — no pending publications",EXIT.refused,{report}):succeed(write,json,"publish",{report},lines)}async function peekCommand(positional,flags,context){const{store,write,json,clock}=context,[given]=positional;let runId;if(given!==void 0){if(!/^[1-9][0-9]{0,14}$/.test(given))return fail(write,json,"peek","usage","`toolroll peek [<run-id>] [--tmux]`",EXIT.usage);if(runId=Number(given),store.getRun(runId)===null)return fail(write,json,"peek","unknown-run",`no run #${runId}`,EXIT.refused)}const linesGiven=text(flags,"lines"),lines=linesGiven===void 0?12:Number(linesGiven);if(!Number.isInteger(lines)||lines<1||lines>PEEK_TAIL_LINES)return fail(write,json,"peek","usage",`--lines is a whole number from 1 to ${PEEK_TAIL_LINES}`,EXIT.usage);const interactive2=!json&&process.stdout.isTTY===!0&&process.stdin.isTTY===!0;if(flags.has("tmux")){if(!interactive2)return fail(write,json,"peek","usage","--tmux needs a terminal",EXIT.usage);const panes=snapshotLiveRuns(store,context.evidenceRoot,clock()),opened=await openInTmux(panes,[process.execPath,process.argv[1]??"toolroll",...text(flags,"db")===void 0?[]:["--db",text(flags,"db")]],async(file,args)=>{const answer=await execRun(file,args);return{code:answer.code,stderr:answer.stderr}});return opened.ok?attachTmux():fail(write,json,"peek","tmux",opened.message,EXIT.refused)}if(!interactive2){const body=snapshotLiveRuns(store,context.evidenceRoot,clock()).filter(one=>runId===void 0||one.runId===runId).map(one=>({...one,lines:one.lines.slice(-lines)}));return succeed(write,json,"peek",{runs:body},()=>body.length===0?["No agent is working right now."]:body.flatMap(one=>[`#${one.runId} ${one.title} — ${one.runner} · ${one.role} · ${one.phase} · ${elapsedWords(one.startedAt,clock())}`,...one.lines.length===0?[" (no transcript yet)"]:one.lines.map(line=>` ${line}`),""]))}return runPeek(store,context.evidenceRoot,{...runId===void 0?{}:{runId},io:{stdout:process.stdout,stdin:process.stdin},clock})}async function outboxCommand(positional,flags,context){const{store,write,json,clock}=context,[action]=positional;if(action==="list"||action===void 0){const wanted=flags.has("all")?"all":"pending",notifications=store.listNotifications(wanted);if(json)return write(envelopeJson({ok:!0,command:"outbox list",notifications})),EXIT.ok;if(notifications.length===0)return write(wanted==="pending"?"Nothing pending.":"The outbox is empty."),EXIT.ok;for(const one of notifications)write(` #${one.id} ${one.kind.padEnd(18)} ${one.subject}`),write(` ${one.resolvedAt===null?"pending":`resolved ${one.resolvedAt}`}`);return EXIT.ok}if(action==="deliver"){const demoFence=refuseDemo(context,"outbox deliver");if(demoFence!==null)return demoFence;const command=text(flags,"cmd");if(command===void 0)return fail(write,json,"outbox deliver","usage","--cmd says how: it runs once per notification, reading $TOOLROLL_KIND, $TOOLROLL_SUBJECT, $TOOLROLL_BODY",EXIT.usage);const owner=`outbox-${randomUUID()}`;let pushed=0;try{pushed=(await pushPass(store,{configDir:dirname(context.databaseFile),clock})).accepted}catch{}const pending=claimNotifications(store,notificationDestination("command",command),owner,clock());if(pending.length===0)return succeed(write,json,"outbox deliver",{delivered:0,failed:0,pushed},()=>[pushed>0?`Nothing for the shell command; ${pushed} push(es) accepted.`:"Nothing waiting to be delivered."]);let delivered=0,failed=0;for(const one of pending){if(!notificationClaimHeld(store,one,owner,clock())){failed++;continue}const sent=await run("sh",["-lc",command],{timeoutMs:3e4,env:notificationCommandEnv(one)});if(sent.code===0){const receipt=sent.stdout.split(`
480
497
  `)[0]?.trim()??"";finalizeNotification(store,one,owner,{ok:!0,receipt:receipt===""?null:receipt},clock())?delivered++:failed++}else{const error=sent.timedOut?"timed out":sent.stderr.split(`
481
- `)[0]?.trim()||`exit ${sent.code}`;finalizeNotification(store,one,owner,{ok:!1,error},clock()),failed++}}const code=failed>0?EXIT.failed:EXIT.ok;return json?(write(envelopeJson({ok:failed===0,command:"outbox deliver",delivered,failed})),code):(write(`Delivered ${delivered}, failed ${failed}.`),code)}return fail(write,json,"outbox","usage",`unknown \`outbox ${action}\` — try list, deliver`,EXIT.usage)}async function enrollCommand(positional,flags,context){const{store,write,json,now}=context,repo=positional[0]===void 0?process.cwd():resolve(positional[0]),backend=text(flags,"backend")??BUILT_IN,mutations=readMutations(flags);if(mutations===null)return fail(write,json,"enroll","usage",`--allow takes ${MUTATION_CLASSES.join(", ")}`,EXIT.usage);const selectorFlag=text(flags,"selector")??"ours";if(selectorFlag!=="ours"&&selectorFlag!=="all")return fail(write,json,"enroll","usage","--selector is `ours` or `all`",EXIT.usage);const paths=readPaths(flags,backend);if(paths.length===0)return fail(write,json,"enroll","usage",`--paths says what may be written for backend \`${backend}\``,EXIT.usage);const wantsDispatch=flags.has("allow-dispatch"),dispatchRepo=text(flags,"github");if(wantsDispatch&&backend!=="github-issues")return fail(write,json,"enroll","usage","--allow-dispatch is a github-issues authority in this release",EXIT.usage);if(wantsDispatch&&(dispatchRepo===void 0||!GITHUB_REPO_SHAPE.test(dispatchRepo)))return fail(write,json,"enroll","usage","--allow-dispatch binds exactly one tracker: name it with `--github <owner/name>`",EXIT.usage);const grant=await proposeGrant({repo,backend,paths,mutations,selector:selectorFlag,credentialScope:text(flags,"credentials")??null,now});if(wantsDispatch){const previous=store.grantFor(repo,backend);grant.dispatch=!0,grant.remoteRepo=dispatchRepo,grant.planeId=previous?.planeId??randomBytes(8).toString("hex"),grant.dispatchBlocked="pending-marker"}if(!flags.has("yes")){if(json)return write(envelopeJson({ok:!1,command:"enroll",reason:"unconfirmed",grant})),EXIT.refused;write("Would grant write access:"),write("");for(const line of describeGrant(grant))write(line);for(const line of describeWithheld(grant))write(line);return wantsDispatch&&(write(""),write(`AND external dispatch: this plane will BUILD what ${dispatchRepo} nominates,`),write("under scopes approved here, and spend accordingly. Write-back stays limited"),write("to the classes above. Enrolling writes a plane marker label to the repository"),write("(needs push permission there); a second plane's marker pauses building here.")),write(""),write("Nothing has been granted. Re-run with --yes to agree to this."),EXIT.refused}if(store.saveGrant(grant,mutationFrom(flags,now)),wantsDispatch){const wrote=await ghDispatchAdapter().writeMarker(dispatchRepo,grant.planeId);if(wrote.ok?store.setDispatchBlocked(repo,backend,null,now):store.setDispatchBlocked(repo,backend,"pending-marker",now,wrote.message),!wrote.ok)return succeed(write,json,"enroll",{grant,marker:"pending"},()=>[`Granted, but the plane marker could not be written (${wrote.message}).`,"Building stays paused until it is — re-run this enroll to retry."])}return succeed(write,json,"enroll",{grant},()=>[`Granted. Toolroll may now write to ${backend} in ${repo}.`,...describeGrant(grant),...describeWithheld(grant),...wantsDispatch?["",`External dispatch is ON for ${dispatchRepo} — \`toolroll sync\` pulls its nominated work.`]:[],"","Take it back with `toolroll revoke`."])}function grantsCommand(context){const{store,write,json}=context,grants=store.listGrants();if(json)return write(envelopeJson({ok:!0,command:"grants",count:grants.length,grants})),EXIT.ok;if(grants.length===0)return write("Nothing is enrolled. Discovery is read-only until something is."),write(" toolroll enroll <repo> --backend <name> --paths <path>"),EXIT.ok;for(const grant of grants){write(`${grant.repo} ${grant.backend}`);for(const line of describeGrant(grant).slice(2))write(line);write("")}return EXIT.ok}function checkProgressCommand(positional,context){if(positional.length!==1||!/^[1-9][0-9]{0,14}$/.test(positional[0]??""))return fail(context.write,context.json,"check-progress","usage","use check-progress <run>",EXIT.usage);const run2=Number(positional[0]);if(!Number.isSafeInteger(run2)||context.store.getRun(run2)===null)return fail(context.write,context.json,"check-progress","unknown-run","no such run",EXIT.refused);const progress=context.store.checkProgress(run2);return progress===null?fail(context.write,context.json,"check-progress","no-progress","this run has no saved check progress",EXIT.refused):succeed(context.write,context.json,"check-progress",{run:run2,progress},()=>[progress.line])}function revokeCommand(positional,flags,context){const{store,write,json,now}=context,repo=positional[0]===void 0?process.cwd():resolve(positional[0]),backend=text(flags,"backend")??BUILT_IN,outgoing=store.grantFor(repo,backend),revoked=store.revokeGrant(repo,backend,mutationFrom(flags,now));return revoked&&outgoing?.dispatch===!0&&outgoing.remoteRepo!=null&&ghDispatchAdapter().deleteMarker(outgoing.remoteRepo),revoked?succeed(write,json,"revoke",{repo,backend},()=>[`Revoked. ${backend} in ${repo} is read-only again.`]):fail(write,json,"revoke","no-grant",`${repo} was not enrolled for ${backend}`,EXIT.refused)}function readMutations(flags){const given=text(flags,"allow");if(given===void 0)return[...DEFAULT_MUTATIONS];const wanted=given.split(",").map(one=>one.trim()).filter(Boolean);return wanted.some(one=>!MUTATION_CLASSES.includes(one))?null:wanted}function readPaths(flags,backend){const given=text(flags,"paths");return given!==void 0?given.split(",").map(one=>one.trim()).filter(Boolean):backend===BUILT_IN?[BUILT_IN]:[]}async function statusCommand(positional,flags,context){const command="status",allowed=new Set(["db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a status option.`,EXIT.usage);if(positional.length>0)return fail(context.write,context.json,command,"usage","Use `toolroll status [--json]`.",EXIT.usage);const viewer=currentActor()?.account??readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null,lens=context.principal?.lens??null;if(lens!==null){const status2=installationStatus(context.store,context.clock(),viewer,lens,context.evidenceRoot);return succeed(context.write,context.json,command,{...status2,projects:[]},()=>renderInstallationStatus(status2,!0))}const status=installationStatus(context.store,context.clock(),viewer,null,context.evidenceRoot),current=PACKAGE_VERSION,method=installMethod(context.installBin),release2=newerRelease(await latestRelease(dirname(context.databaseFile),{now:context.clock,...context.releaseIo}),current);release2!==null&&notifySecurityRelease(context.store,release2,current,method.updateCommand,context.clock());const line=updateLine(release2,current,method.updateCommand),update=release2===null?{}:{update:{current,latest:release2.version,security:release2.security,updateCommand:method.updateCommand,url:release2.url}},savedList=await savedIntegrations(context).catch(()=>[]),brokenIntegrations=savedList.filter(one=>one.state==="broken"),brokenLine=integrationsBrokenLine(brokenIntegrations),signedOutLines=agentsSignedOutLines(savedList),signedOut=signedOutLines.length===0?{}:{agentsSignedOut:signedOutLines},integrations=brokenIntegrations.length===0?{}:{integrations:{broken:brokenIntegrations.map(one=>({key:one.key,name:one.name,fix:one.action.kind==="fix"?one.action.words:null}))}},waiting=waitingUpdate(context.databaseFile,run2=>context.store.stopQuiescenceProblem(run2)!==null,context.clock()),updateWaiting=waiting===null?{}:{updateWaiting:{app:waiting.app,version:waiting.version,stopped:waiting.stopped,run:waiting.run,on:waiting.on,action:waiting.action}},legacyWebhookWarning=loadWebhookTargets(process.env,dirname(context.databaseFile)).length>0?LEGACY_WEBHOOK_WARNING:null,drift=["source","npx","desktop"].includes(method.kind)?null:(()=>{try{return serviceDriftHere(context.databaseFile,{version:current,dist:context.laptopSeams?.dist??currentRuntime(current).dist},context.laptopSeams??{})}catch{return null}})(),driftLine=drift===null?null:driftWords(drift.service,drift.cli),runtimeDrift=drift===null?{}:{runtimeDrift:{service:drift.service.version,serviceRuntime:drift.service.dist,cli:current,words:driftLine,fix:"toolroll update --yes"}},projects=projectBuildsStatus(context),projectsLine=projects.length===0?null:`Builds by project: ${projects.slice(0,8).map(one=>`${one.name} ${one.running} of ${one.limit}${one.builder==="restarting"?" (builder restarting)":""}`).join(", ")}${projects.length>8?", …":""}`,unsent=context.store.unsentTelegramReplies(null,null,new Date(context.clock().getTime()-UNSENT_REPLY_MS)),unsentLine=unsentRepliesLine(unsent),unsentReplies=unsent.length===0?{}:{unsentReplies:unsent.map(one=>({...one,retry:"toolroll bridge telegram retry"}))},laptop={laptop:await laptopStatus(context.store,context.databaseFile,context.laptopSeams)};return!laptop.laptop.running&&laptop.laptop.background==="on"&&!machineActing()&&await restartOwnBuilder(context.store,context.databaseFile,context.laptopSeams,context.clock()).catch(()=>null),succeed(context.write,context.json,command,{...status,projects,...laptop,...update,...integrations,...signedOut,...updateWaiting,...runtimeDrift,...unsentReplies,...legacyWebhookWarning===null?{}:{legacyWebhookWarning}},()=>[...waiting===null?[]:[waiting.words],...unsentLine===null?[]:[unsentLine],...renderInstallationStatus(status),...projectsLine===null?[]:[projectsLine],...line===null?[]:[line],...driftLine===null?[]:[driftLine],...signedOutLines,...brokenLine===null?[]:[brokenLine],...legacyWebhookWarning===null?[]:[legacyWebhookWarning]])}function unsentRepliesLine(unsent){if(unsent.length===0)return null;const oldest=unsent[0];return`${unsent.length===1?"A Telegram reply hasn't":`${unsent.length} Telegram replies haven't`} been sent since ${oldest.since.slice(11,16)} UTC${oldest.error===null?"":` (${oldest.error})`}. Retry: toolroll bridge telegram retry`}function projectBuildsStatus(context){const now=context.clock(),running=context.store.runningBuildsByRepo(now),saved=savedProjectConcurrency(context.databaseFile),workers=context.store.listRunners().filter(one=>one.retiredAt===null);return[...new Set([...context.store.listProjects().map(one=>one.path),...context.store.knownRepos(),...running.keys()])].sort().map(repo=>{const capacities=workers.filter(one=>one.repos.includes(repo)).map(one=>one.capacity),setting=saved.get(repo)??PROJECT_CONCURRENCY_DEFAULT,builders=buildersFor(context.store,repo,now),restarting=builders.alive.length>0&&builders.watching.length===0;return{repo,name:projectName(repo),running:running.get(repo)??0,limit:capacities.length===0?setting:effectiveConcurrency(setting,Math.max(...capacities)),...restarting?{builder:"restarting"}:{}}})}async function integrationIoFor(context){const registered=await loadProjectRegistry(registryPathOf(context)).catch(()=>({error:"unreadable"})),repos=[...new Set([..."error"in registered?[]:registered.repos,...context.store.listProjects().map(one=>one.path)])],seams=context.integrationIo??{};return{store:context.store,dir:dirname(context.databaseFile),telegramTokenFile:context.telegramTokenFile,env:process.env,repos,gh:(file,args,options)=>run(file,[...args],options),checkConnection:createConnectionChecker({store:context.store}),clock:context.clock,...seams}}async function savedIntegrations(context){return integrationsNow(await integrationIoFor(context))}async function integrationsCommand(positional,flags,context){const command="integrations",allowed=new Set(["db","json","saved"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not an integrations option.`,EXIT.usage);if(positional.length>0)return fail(context.write,context.json,command,"usage","Use `toolroll integrations [--saved] [--json]`.",EXIT.usage);const io=await integrationIoFor(context),list=flag(flags,"saved")?integrationsNow(io):await checkIntegrations(io),counts={connected:0,"not-set-up":0,broken:0};for(const one of list)counts[one.state]+=1;const secrets=toolSecretStorage();return succeed(context.write,context.json,command,{integrations:list,counts,secrets:{kind:secrets.kind,words:secrets.words,...secrets.problem===void 0?{}:{problem:secrets.problem}}},()=>renderIntegrations(list,secrets))}async function waitTask(positional,flags,context){const command="task wait",allowed=new Set(["db","json","timeout"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a task wait option.`,EXIT.usage);if(positional.length!==1)return fail(context.write,context.json,command,"usage","Use `toolroll task wait <id> [--timeout <seconds>]`.",EXIT.usage);const givenTimeout=text(flags,"timeout"),timeoutSeconds=givenTimeout===void 0?null:Number(givenTimeout);if(timeoutSeconds!==null&&(!Number.isFinite(timeoutSeconds)||timeoutSeconds<0))return fail(context.write,context.json,command,"usage","--timeout must be zero or a positive number of seconds.",EXIT.usage);const task=positional[0],startedAt=Date.now(),timeoutMs=timeoutSeconds===null?null:timeoutSeconds*1e3,sleep=context.waitSleep??(milliseconds=>new Promise(resolve2=>setTimeout(resolve2,milliseconds)));let watchedRun;for(;;){const snapshot=taskWaitSnapshot(context.store,task,context.clock(),watchedRun);if(snapshot===null)return fail(context.write,context.json,command,"unknown-task",`No task named ${task}.`,EXIT.failed,{task});watchedRun===void 0&&snapshot.outcome==="Running"&&snapshot.run!==null&&(watchedRun=snapshot.run);const data={task:snapshot.task,outcome:snapshot.outcome,run:snapshot.run,replacedRun:snapshot.replacedRun,phase:snapshot.phase,check:snapshot.check,next:snapshot.next};if(snapshot.terminal){const line=renderTaskWait(snapshot);return snapshot.exitCode===EXIT.ok?succeed(context.write,context.json,command,data,()=>[line]):fail(context.write,context.json,command,snapshot.reason??"failed",line,EXIT.failed,data)}const elapsed=Date.now()-startedAt;if(timeoutMs!==null&&elapsed>=timeoutMs){const line=renderTaskWait(snapshot,"Timed out");return fail(context.write,context.json,command,"timeout",line,EXIT.usage,{...data,outcome:"Timed out"})}const remaining=timeoutMs===null?250:Math.max(1,Math.min(250,timeoutMs-elapsed));await sleep(remaining)}}function taskCommand(positional,flags,context){const[action,...rest]=positional;if(action===void 0)return context.write(TASK_HELP),EXIT.ok;const actor=currentActor();if(actor?.lead===!0&&rest[0]!==void 0&&LEAD_WORK_VERBS.has(action)){const noted=code=>(code===EXIT.ok&&noteLeadWork(context.store,actor,rest[0],action,context.clock()),code),done=taskAction(action,rest,flags,context);return typeof done=="number"?noted(done):done.then(noted)}return taskAction(action,rest,flags,context)}const LEAD_WORK_VERBS=new Set(["state","steer","pause","continue","reopen","requeue","regate","repair","resume","stop","scope","approve","plan","checks","revise","hold","unhold","route","require"]);function taskAction(action,rest,flags,context){switch(action){case"complete":case"revise":return action==="complete"&&currentLocalOwner()!==null?runLocalCompletion(rest,flags,context):action==="revise"&&currentLocalOwner()!==null?runLocalRevision(rest,flags,context):runTaskOutcomeCommand(action,rest,flags,{...context,operator:async()=>{const acting=await askCredentials(flags,context);if(acting===null)return null;const authenticated=verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo)));return authenticated.ok?authenticated.who:null},caller:()=>shellCallerFacts(context)});case"merge":return runTaskMergeCommand(rest,flags,{store:context.store,json:context.json,write:context.write,clock:context.clock,demo:context.store.isDemo(),credentials:()=>askCredentials(flags,context),...context.publishExec===void 0?{}:{exec:context.publishExec}});case"add":return addTask(rest,flags,context);case"new":return newTaskCommand(rest,flags,context);case"keep":return keepGrownCommand(rest,flags,context);case"checks":return runTaskChecks(rest,flags,context);case"ship":return taskShipCommand(rest,context);case"ready":return taskReadyCommand(rest,context);case"add-tests":return addTestsTask(rest,flags,context);case"list":return listTasks(flags,context);case"archive":return archiveTasksCommand(rest,flags,context);case"restore":return restoreTasksCommand(rest,flags,context);case"tidy":return tidyTasksCommand(rest,flags,context);case"show":return showTask(rest,context);case"log":return logTaskCommand(rest,flags,context);case"send":return sendTaskCommand(rest,flags,context);case"handoff":return handoffTaskCommand(rest,flags,context);case"attach":return attachTaskCommand(rest,flags,context);case"wait":return waitTask(rest,flags,context);case"evidence":return taskEvidenceCommand(rest,flags,context);case"state":return stateTask(rest,flags,context);case"ask":return askTask(rest,flags,context);case"block":return blockTask(rest,flags,context);case"unblock":return unblockTask(rest,flags,context);case"next":return nextTask(rest,flags,context);case"steer":return steerTask(rest,flags,context);case"pause":return pauseTask(rest,flags,context);case"continue":return continueTask(rest,flags,context);case"assign":return assignTask(rest,flags,context);case"reopen":return reopenTask(rest,flags,context);case"scope":return scopeTask(rest,flags,context);case"approve":return approveTask(rest,flags,context);case"hold":return holdTask(rest,flags,context);case"unhold":return unholdTask(rest,flags,context);case"stop":return stopTaskCommand(rest,flags,context);case"resume":return resumeTaskCommand(rest,flags,context);case"require":return requireTask(rest,flags,context);case"requeue":return currentLocalOwner()!==null?localRetryCommand(rest,flags,context):requeueTask(rest,flags,context);case"regate":return regateTaskCommand(rest,flags,context);case"handover":return handoverCommand(rest,followThroughContext(context,flags));case"before-after":return evidenceCommand(rest,flags,followThroughContext(context,flags));case"failing-first":return failingFirstCommand(rest,followThroughContext(context,flags));case"plan":return currentLocalOwner()!==null?localPlanCommand(rest,flags,context):planTaskCommand(rest,flags,context);case"review":return reviewTaskCommand(rest,flags,context);case"accept":return acceptTaskProof(rest,flags,context);case"land":return landTaskCommand(rest,flags,context);case"repair":return repairTaskCommand(rest,flags,context);case"route":return routeTaskCommand(rest,flags,context);default:return fail(context.write,context.json,"task","usage",`unknown \`task ${action??""}\` — try ${TASK_ACTIONS.join(", ")}`,EXIT.usage)}}async function addTask(positional,flags,context,fromNew=!1){const{store,write,json,now}=context,title=positional.join(" ").trim();if(title==="")return fail(write,json,"task add","usage","a task needs a title",EXIT.usage);const checks=text(flags,"checks");if(checks!==void 0&&!isCheckLevel(checks))return fail(write,json,"task add","usage","--checks is quick, full or off",EXIT.usage);const badText=validateTaskText({title});if(badText!==null)return fail(write,json,"task add",badText.reason,badText.message,EXIT.usage);const backendName=text(flags,"backend")??BUILT_IN;if(flags.has("report")&&backendName!==BUILT_IN)return fail(write,json,"task add","usage","--report files a scout task in the built-in backend only — drop --backend",EXIT.usage);if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"task add","usage",`no backend \`${backendName}\``,EXIT.usage);const created=await backend.create({title});if(!created.ok){const code=created.reason==="denied"?EXIT.refused:EXIT.failed;return fail(write,json,"task add",created.reason,created.message,code)}store.refFor(backendName,created.value,"ours");const dispatchGrant=store.grantFor(repoFrom(flags),backendName);let mirrored=null;if(backendName==="github-issues"&&dispatchGrant?.dispatch===!0&&dispatchGrant.remoteRepo!=null){const localId=mirrorTaskId(dispatchGrant.remoteRepo,created.value),made=store.transact(()=>{const filed=fileTaskProposal(store,{id:localId,title,repo:dispatchGrant.repo,filedVia:"cli"},now);if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:backendName,remoteRepo:dispatchGrant.remoteRepo,remoteId:created.value,provenance:"local-create",establishedBy:"cli"},now);if(!established.ok)throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok&&(mirrored=made.id)}return succeed(write,json,"task add",{id:created.value,backend:backendName,...mirrored===null?{}:{mirror:mirrored}},()=>[`Filed ${created.value} in ${backendName}.`,...mirrored===null?[]:[`Mirrored locally as ${mirrored} — scope and approve it, and this plane builds it.`]])}const id=text(flags,"id")??(activeRemote()===null?slug(title,now):`task-${randomBytes(16).toString("hex")}`),replaces=text(flags,"replaces");if(replaces!==void 0&&(replaces===id||store.getTask(replaces)===null))return fail(write,json,"task add","unknown-task",`no task \`${replaces}\` to replace`,EXIT.refused);if(replaces!==void 0&&builtinReplacementHeld(store,replaces,id))return fail(write,json,"task add","recovery-held","This task can't be replaced while earlier check execution is unverified after recovery.",EXIT.refused);noteActingPerson(flags,context);const outcome=store.replay(mutationFrom(flags,now),"task add",()=>store.getTask(id)!==null?{ok:!1}:replaces!==void 0?createBuiltinReplacement(store,{id,title,report:flags.has("report"),repo:text(flags,"repo")??null,replaces,now}):{ok:!0,task:store.createTask({id,title,...flags.has("report")?{deliverable:"report"}:{}},now)},result=>result.ok);if(!outcome.ok)return"reason"in outcome?fail(write,json,"task add",outcome.reason,outcome.reason==="recovery-held"?"This task can't be replaced while earlier check execution is unverified after recovery.":"The replacement couldn't be filed. Nothing was changed.",EXIT.refused):fail(write,json,"task add","exists",`\`${id}\` already exists`,EXIT.refused);const filedId=outcome.task.id,remote=activeRemote();if(remote!==null&&filedId!==id){const saved=store.lookupRef(filedId);if(saved===null||saved.repo!==text(flags,"repo")||!remote.allows(saved.repo))throw new RemoteRefusal("not-found","Not found.")}remote?.noteTask(filedId),replaces===void 0&&store.stampFiledVia(store.refFor(BUILT_IN,filedId).id,"cli");const placedIn=text(flags,"repo");if(placedIn!==void 0&&replaces===void 0){const placed=store.placeTask(store.refFor(BUILT_IN,filedId).id,canonicalProject(placedIn)??resolve(placedIn));if(typeof placed=="object"&&!placed.ok)return fail(write,json,"task add","scoped","this task already has a scope — placement is immutable once somebody could have approved it",EXIT.refused)}if(checks!==void 0){const chosen=setTaskCheckLevel(store,outcome.task.id,checks,"cli",now);if(!chosen.ok)return fail(write,json,"task add","checks-fixed",chosen.message,EXIT.refused)}const link=consoleLinkFor(context,`/t/${encodeURIComponent(outcome.task.id)}`);let noAgent=null;const filedRef=placedIn===void 0||remote!==null?null:store.lookupRef(outcome.task.id);if(filedRef!==null&&filedRef.repo!==null)try{const agentless=agentlessFirstRun(store,filedRef,!0,buildersFor(store,filedRef.repo,now).alive.map(one=>one.name));agentless!==null&&(noAgent=`${NO_AGENT_TITLE}. Run \`${agentless.command}\` so it can be planned.`)}catch{noAgent=null}const next=filedRef!==null&&filedRef.repo!==null&&filedRef.plan===null&&!flags.has("report")?`Next: run \`toolroll\`, select it and press p to ask for a plan.${fromNew?"":" To build without a plan, file it with `toolroll task new` instead."}`:null;return succeed(write,json,"task add",{task:outcome.task,...replaces===void 0?{}:{replaces},repo:placedIn===void 0?null:resolve(placedIn),...checks===void 0?{}:{checks},...link===null?{}:{links:{task:link}},...noAgent===null?{}:{waiting:noAgent},...next===null?{}:{next}},()=>[`Queued ${outcome.task.id} — ${outcome.task.title}${flags.has("report")?" (a scout task: it delivers a report)":""}${checks===void 0?"":` · checks: ${CHECK_LEVEL_WORDS[checks]}`}`,...replaces===void 0?[]:[` It replaces ${replaces}.`],...noAgent===null?[]:[` ${noAgent}`],...placedIn===void 0&&remote===null?[" It has no project yet: choose one on its page in Toolroll, or file it with `--repo <folder>`."]:[],...next===null?[]:[` ${next}`],...link===null?[]:[` ${link}`]])}function latestBuildResult(store,taskId){const family=store.taskFamilyOf(taskId,null,!0),versions=family===null?[taskId]:[family.current.id,...family.versions.map(one=>one.id).filter(id=>id!==family.current.id)];for(const id of versions){const ref=store.lookupRef(id),run2=ref===null?void 0:store.runsFor(ref.id).find(one=>one.role==="builder"&&one.finishedAt!==null&&one.headRevision!==null);if(run2!==void 0)return{runId:run2.id,head:run2.headRevision}}return null}async function runTaskChecks(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),taskId=positional[0];if(taskId===void 0)return fail(write,json,"task checks","usage","`toolroll task checks <task> [--level quick|full]`",EXIT.usage);const level=text(flags,"level")??"quick";if(level!=="quick"&&level!=="full")return fail(write,json,"task checks","usage","--level is quick or full",EXIT.usage);const demoFence=refuseDemo(context,"task checks");if(demoFence!==null)return demoFence;const result=latestBuildResult(store,taskId);if(result===null)return fail(write,json,"task checks","no-result",`${taskId} has no finished result to check`,EXIT.refused);const asked=requestFollowUpChecks(store,{runId:result.runId,level,actor:"cli"},clock());if(!asked.ok)return fail(write,json,"task checks",asked.reason,asked.message,EXIT.refused);const done=await runFollowUpCheck(store,context.evidenceRoot,asked.request,{now:clock});if(done?.state==="recovery-held")return fail(write,json,"task checks","recovery-held",done.note,EXIT.refused);const state=done?.state??"waiting",words=`${CHECK_LEVEL_WORDS[asked.level]} checks`,payload={task:taskId,run:result.runId,head:result.head,request:asked.request,level:asked.level,state,exitCode:done?.exitCode??null},complete=assignmentOf(store,taskId,clock(),{principal:"operator",repos:null,includeUnplaced:!0},context.evidenceRoot)?.state==="complete";return state==="failed"?json?(write(envelopeJson({ok:!1,command:"task checks",reason:"checks-failed",...payload})),EXIT.failed):(write(`${words} failed on ${result.head.slice(0,7)}${done?.exitCode==null?"":` (exit ${done.exitCode})`}. ${complete?"It stays Complete; it can't land until they pass on its exact commit.":"The result shows the failure."}`),EXIT.failed):succeed(write,json,"task checks",payload,()=>[state==="passed"?`${words} passed on ${result.head.slice(0,7)}.${complete?" It stays Complete.":""}`:state==="running"?`${words} are already running on ${result.head.slice(0,7)}.`:state==="not-run"?`${words} didn't run: ${done?.note??"see the result's log"}`:`${words} are queued on ${result.head.slice(0,7)}.`])}function addTestsTask(positional,_flags,context){const{store,write,json,now}=context,taskId=positional[0];if(taskId===void 0)return fail(write,json,"task add-tests","usage","`toolroll task add-tests <task>`",EXIT.usage);const result=latestBuildResult(store,taskId);if(result===null)return fail(write,json,"task add-tests","no-result",`${taskId} has no finished result to write tests for`,EXIT.refused);const filed=fileAddTestsTask(store,context.evidenceRoot,{runId:result.runId,actor:"cli",filedVia:"cli"},now);return filed.ok?succeed(write,json,"task add-tests",{task:taskId,filed:filed.id,existing:filed.existing},()=>[filed.existing?`Tests for ${taskId} are already filed as ${filed.id}.`:`Filed ${filed.id} to add tests for ${taskId}. Approve its scope to start.`]):fail(write,json,"task add-tests",filed.reason,filed.message,EXIT.refused)}function requireTask(positional,flags,context){const{store,write,json,now}=context,id=positional[0],given=text(flags,"cap");if(id===void 0||given===void 0)return fail(write,json,"task require","usage","`toolroll task require <id> --cap <kind:name>[,<kind:name>]` — or --cap none to clear",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task require","unknown-task",`no task \`${id}\``,EXIT.refused);const keys=given==="none"?[]:given.split(",").map(one=>one.trim()).filter(Boolean);for(const key of keys)if(parseCapabilityKey(key)===null)return fail(write,json,"task require","usage",`\`${key}\` is not a capability key — say kind:name, like env:SUPABASE_KEY or cli:gh`,EXIT.usage);return store.setRequirements(store.refFor(BUILT_IN,id).id,keys,mutationFrom(flags,now)),succeed(write,json,"task require",{id,requirements:keys},()=>[keys.length===0?`${id} requires nothing.`:`${id} now requires: ${keys.join(", ")}. Nothing dispatches it until every one is verified.`])}async function capCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional,repo=repoFrom(flags);if(action==="add"){if(name===void 0)return fail(write,json,"cap add","usage","`toolroll cap add <name> [--kind env|cli|mcp|ci|other] [--probe <cmd>] [--expires <iso>]`",EXIT.usage);const kind=text(flags,"kind")??"env";if(!["env","cli","mcp","ci","other"].includes(kind))return fail(write,json,"cap add","usage","--kind takes env, cli, mcp, ci or other",EXIT.usage);let probe=text(flags,"probe")??null;if(probe===null&&kind==="env"){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))return fail(write,json,"cap add","usage",`\`${name}\` is not an environment variable name — give --probe explicitly`,EXIT.usage);probe=`test -n "$${name}"`}const expires=text(flags,"expires")??null;return store.saveCapability({repo,kind,name,probe,status:"unprobed",addedBy:`operator@${hostname()}`,createdAt:clock().toISOString(),lastVerifiedAt:null,verifiedBy:null,lastResult:null,expiresAt:expires},mutationFrom(flags,clock())),succeed(write,json,"cap add",{repo,kind,name,probe},()=>[`Recorded ${kind}:${name} for ${repo}.`,probe===null?"No probe — nothing can verify it, so it will stand as a gap until it has one.":`Probe: ${probe}`,"Nothing is verified yet: `toolroll cap probe`."])}if(action==="list"||action===void 0){const capabilities=store.listCapabilities(repo);if(json)return write(envelopeJson({ok:!0,command:"cap list",repo,capabilities})),EXIT.ok;if(capabilities.length===0)return write(`No capabilities recorded for ${repo}. \`toolroll cap add\` or \`cap scan\`.`),EXIT.ok;for(const one of capabilities){const state=describeCapability(one,clock());write(` ${`${one.kind}:${one.name}`.padEnd(32)} ${state}`)}return EXIT.ok}if(action==="scan"){const report=scanRepo(repo);let recorded=0;for(const one of report.found)store.getCapability(repo,one.kind,one.name)===null&&(store.saveCapability({repo,kind:one.kind,name:one.name,probe:one.probe,status:"unprobed",addedBy:`scan:${one.source}`,createdAt:clock().toISOString(),lastVerifiedAt:null,verifiedBy:null,lastResult:null,expiresAt:null}),recorded++);if(json)return write(envelopeJson({ok:!0,command:"cap scan",repo,recorded,...report})),EXIT.ok;if(report.found.length===0)return write(`Nothing detected in ${repo}. Detection reads .env.example, .mcp.json, supabase/config.toml and workflow files.`),EXIT.ok;for(const one of report.found)write(` ${`${one.kind}:${one.name}`.padEnd(32)} ${one.source}${one.probe===null?" (no probe)":""}`);for(const bad of report.rejected)write(` rejected ${bad.name} from ${bad.source} — not a valid identifier`);return write(""),write(`${recorded} new, ${report.found.length-recorded} already recorded. Nothing is verified: \`toolroll cap probe\`.`),EXIT.ok}if(action==="probe"){const only=positional.slice(1);for(const key of only)if(parseCapabilityKey(key)===null)return fail(write,json,"cap probe","usage",`\`${key}\` is not a capability key — say kind:name`,EXIT.usage);const outcomes=await probeRepo(store,repo,`operator@${hostname()}`,clock(),only.length===0?{}:{only:new Set(only)});if(outcomes.length===0)return fail(write,json,"cap probe","empty",`nothing to probe for ${repo}`,EXIT.refused);const unverified=outcomes.filter(one=>one.status!=="verified");return write(json?envelopeJson({ok:!0,command:"cap probe",repo,outcomes}):outcomes.map(one=>` ${`${one.kind}:${one.name}`.padEnd(32)} ${one.status}${one.detail===void 0?"":` ${one.detail}`}`).join(`
498
+ `)[0]?.trim()||`exit ${sent.code}`;finalizeNotification(store,one,owner,{ok:!1,error},clock()),failed++}}const code=failed>0?EXIT.failed:EXIT.ok;return json?(write(envelopeJson({ok:failed===0,command:"outbox deliver",delivered,failed})),code):(write(`Delivered ${delivered}, failed ${failed}.`),code)}return fail(write,json,"outbox","usage",`unknown \`outbox ${action}\` — try list, deliver`,EXIT.usage)}async function enrollCommand(positional,flags,context){const{store,write,json,now}=context,repo=positional[0]===void 0?process.cwd():resolve(positional[0]),backend=text(flags,"backend")??BUILT_IN,mutations=readMutations(flags);if(mutations===null)return fail(write,json,"enroll","usage",`--allow takes ${MUTATION_CLASSES.join(", ")}`,EXIT.usage);const selectorFlag=text(flags,"selector")??"ours";if(selectorFlag!=="ours"&&selectorFlag!=="all")return fail(write,json,"enroll","usage","--selector is `ours` or `all`",EXIT.usage);const paths=readPaths(flags,backend);if(paths.length===0)return fail(write,json,"enroll","usage",`--paths says what may be written for backend \`${backend}\``,EXIT.usage);const wantsDispatch=flags.has("allow-dispatch"),dispatchRepo=text(flags,"github");if(wantsDispatch&&backend!=="github-issues")return fail(write,json,"enroll","usage","--allow-dispatch is a github-issues authority in this release",EXIT.usage);if(wantsDispatch&&(dispatchRepo===void 0||!GITHUB_REPO_SHAPE.test(dispatchRepo)))return fail(write,json,"enroll","usage","--allow-dispatch binds exactly one tracker: name it with `--github <owner/name>`",EXIT.usage);const grant=await proposeGrant({repo,backend,paths,mutations,selector:selectorFlag,credentialScope:text(flags,"credentials")??null,now});if(wantsDispatch){const previous=store.grantFor(repo,backend);grant.dispatch=!0,grant.remoteRepo=dispatchRepo,grant.planeId=previous?.planeId??randomBytes(8).toString("hex"),grant.dispatchBlocked="pending-marker"}if(!flags.has("yes")){if(json)return write(envelopeJson({ok:!1,command:"enroll",reason:"unconfirmed",grant})),EXIT.refused;write("Would grant write access:"),write("");for(const line of describeGrant(grant))write(line);for(const line of describeWithheld(grant))write(line);return wantsDispatch&&(write(""),write(`AND external dispatch: this plane will BUILD what ${dispatchRepo} nominates,`),write("under scopes approved here, and spend accordingly. Write-back stays limited"),write("to the classes above. Enrolling writes a plane marker label to the repository"),write("(needs push permission there); a second plane's marker pauses building here.")),write(""),write("Nothing has been granted. Re-run with --yes to agree to this."),EXIT.refused}if(store.saveGrant(grant,mutationFrom(flags,now)),wantsDispatch){const wrote=await ghDispatchAdapter().writeMarker(dispatchRepo,grant.planeId);if(wrote.ok?store.setDispatchBlocked(repo,backend,null,now):store.setDispatchBlocked(repo,backend,"pending-marker",now,wrote.message),!wrote.ok)return succeed(write,json,"enroll",{grant,marker:"pending"},()=>[`Granted, but the plane marker could not be written (${wrote.message}).`,"Building stays paused until it is — re-run this enroll to retry."])}return succeed(write,json,"enroll",{grant},()=>[`Granted. Toolroll may now write to ${backend} in ${repo}.`,...describeGrant(grant),...describeWithheld(grant),...wantsDispatch?["",`External dispatch is ON for ${dispatchRepo} — \`toolroll sync\` pulls its nominated work.`]:[],"","Take it back with `toolroll revoke`."])}function grantsCommand(context){const{store,write,json}=context,grants=store.listGrants();if(json)return write(envelopeJson({ok:!0,command:"grants",count:grants.length,grants})),EXIT.ok;if(grants.length===0)return write("Nothing is enrolled. Discovery is read-only until something is."),write(" toolroll enroll <repo> --backend <name> --paths <path>"),EXIT.ok;for(const grant of grants){write(`${grant.repo} ${grant.backend}`);for(const line of describeGrant(grant).slice(2))write(line);write("")}return EXIT.ok}function checkProgressCommand(positional,context){if(positional.length!==1||!/^[1-9][0-9]{0,14}$/.test(positional[0]??""))return fail(context.write,context.json,"check-progress","usage","use check-progress <run>",EXIT.usage);const run2=Number(positional[0]);if(!Number.isSafeInteger(run2)||context.store.getRun(run2)===null)return fail(context.write,context.json,"check-progress","unknown-run","no such run",EXIT.refused);const progress=context.store.checkProgress(run2);return progress===null?fail(context.write,context.json,"check-progress","no-progress","this run has no saved check progress",EXIT.refused):succeed(context.write,context.json,"check-progress",{run:run2,progress},()=>[progress.line])}function revokeCommand(positional,flags,context){const{store,write,json,now}=context,repo=positional[0]===void 0?process.cwd():resolve(positional[0]),backend=text(flags,"backend")??BUILT_IN,outgoing=store.grantFor(repo,backend),revoked=store.revokeGrant(repo,backend,mutationFrom(flags,now));return revoked&&outgoing?.dispatch===!0&&outgoing.remoteRepo!=null&&ghDispatchAdapter().deleteMarker(outgoing.remoteRepo),revoked?succeed(write,json,"revoke",{repo,backend},()=>[`Revoked. ${backend} in ${repo} is read-only again.`]):fail(write,json,"revoke","no-grant",`${repo} was not enrolled for ${backend}`,EXIT.refused)}function readMutations(flags){const given=text(flags,"allow");if(given===void 0)return[...DEFAULT_MUTATIONS];const wanted=given.split(",").map(one=>one.trim()).filter(Boolean);return wanted.some(one=>!MUTATION_CLASSES.includes(one))?null:wanted}function readPaths(flags,backend){const given=text(flags,"paths");return given!==void 0?given.split(",").map(one=>one.trim()).filter(Boolean):backend===BUILT_IN?[BUILT_IN]:[]}async function statusCommand(positional,flags,context){const command="status",allowed=new Set(["db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a status option.`,EXIT.usage);if(positional.length>0)return fail(context.write,context.json,command,"usage","Use `toolroll status [--json]`.",EXIT.usage);const viewer=currentActor()?.account??readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null,lens=context.principal?.lens??null;if(lens!==null){const status2=installationStatus(context.store,context.clock(),viewer,lens,context.evidenceRoot);return succeed(context.write,context.json,command,{...status2,projects:[]},()=>renderInstallationStatus(status2,!0))}const status=installationStatus(context.store,context.clock(),viewer,null,context.evidenceRoot),current=PACKAGE_VERSION,method=installMethod(context.installBin),release2=newerRelease(await latestRelease(dirname(context.databaseFile),{now:context.clock,...context.releaseIo}),current);release2!==null&&notifySecurityRelease(context.store,release2,current,method.updateCommand,context.clock());const line=updateLine(release2,current,method.updateCommand),update=release2===null?{}:{update:{current,latest:release2.version,security:release2.security,updateCommand:method.updateCommand,url:release2.url}},savedList=await savedIntegrations(context).catch(()=>[]),brokenIntegrations=savedList.filter(one=>one.state==="broken"),brokenLine=integrationsBrokenLine(brokenIntegrations),signedOutLines=agentsSignedOutLines(savedList),signedOut=signedOutLines.length===0?{}:{agentsSignedOut:signedOutLines},integrations=brokenIntegrations.length===0?{}:{integrations:{broken:brokenIntegrations.map(one=>({key:one.key,name:one.name,fix:one.action.kind==="fix"?one.action.words:null}))}},waiting=waitingUpdate(context.databaseFile,run2=>context.store.stopQuiescenceProblem(run2)!==null,context.clock()),updateWaiting=waiting===null?{}:{updateWaiting:{app:waiting.app,version:waiting.version,stopped:waiting.stopped,run:waiting.run,on:waiting.on,action:waiting.action}},legacyWebhookWarning=loadWebhookTargets(process.env,dirname(context.databaseFile)).length>0?LEGACY_WEBHOOK_WARNING:null,drift=["source","npx","desktop"].includes(method.kind)?null:(()=>{try{return serviceDriftHere(context.databaseFile,{version:current,dist:context.laptopSeams?.dist??currentRuntime(current).dist},context.laptopSeams??{})}catch{return null}})(),driftLine=drift===null?null:driftWords(drift.service,drift.cli),runtimeDrift=drift===null?{}:{runtimeDrift:{service:drift.service.version,serviceRuntime:drift.service.dist,cli:current,words:driftLine,fix:"toolroll update --yes"}},projects=projectBuildsStatus(context),projectsLine=projects.length===0?null:`Builds by project: ${projects.slice(0,8).map(one=>`${one.name} ${one.running} of ${one.limit}${one.builder==="restarting"?" (builder restarting)":""}`).join(", ")}${projects.length>8?", …":""}`,unsent=context.store.unsentTelegramReplies(null,null,new Date(context.clock().getTime()-UNSENT_REPLY_MS)),unsentLine=unsentRepliesLine(unsent),unsentReplies=unsent.length===0?{}:{unsentReplies:unsent.map(one=>({...one,retry:"toolroll bridge telegram retry"}))},laptop={laptop:await laptopStatus(context.store,context.databaseFile,context.laptopSeams)};return!laptop.laptop.running&&laptop.laptop.background==="on"&&!machineActing()&&await restartOwnBuilder(context.store,context.databaseFile,context.laptopSeams,context.clock()).catch(()=>null),succeed(context.write,context.json,command,{...status,projects,...laptop,...update,...integrations,...signedOut,...updateWaiting,...runtimeDrift,...unsentReplies,...legacyWebhookWarning===null?{}:{legacyWebhookWarning}},()=>[...waiting===null?[]:[waiting.words],...unsentLine===null?[]:[unsentLine],...renderInstallationStatus(status),...projectsLine===null?[]:[projectsLine],...line===null?[]:[line],...driftLine===null?[]:[driftLine],...signedOutLines,...brokenLine===null?[]:[brokenLine],...legacyWebhookWarning===null?[]:[legacyWebhookWarning]])}function unsentRepliesLine(unsent){if(unsent.length===0)return null;const oldest=unsent[0];return`${unsent.length===1?"A Telegram reply hasn't":`${unsent.length} Telegram replies haven't`} been sent since ${oldest.since.slice(11,16)} UTC${oldest.error===null?"":` (${oldest.error})`}. Retry: toolroll bridge telegram retry`}function projectBuildsStatus(context){const now=context.clock(),running=context.store.runningBuildsByRepo(now),saved=savedProjectConcurrency(context.databaseFile),workers=context.store.listRunners().filter(one=>one.retiredAt===null);return[...new Set([...context.store.listProjects().map(one=>one.path),...context.store.knownRepos(),...running.keys()])].sort().map(repo=>{const capacities=workers.filter(one=>one.repos.includes(repo)).map(one=>one.capacity),setting=saved.get(repo)??PROJECT_CONCURRENCY_DEFAULT,builders=buildersFor(context.store,repo,now),restarting=builders.alive.length>0&&builders.watching.length===0;return{repo,name:projectName(repo),running:running.get(repo)??0,limit:capacities.length===0?setting:effectiveConcurrency(setting,Math.max(...capacities)),...restarting?{builder:"restarting"}:{}}})}async function integrationIoFor(context){const registered=await loadProjectRegistry(registryPathOf(context)).catch(()=>({error:"unreadable"})),repos=[...new Set([..."error"in registered?[]:registered.repos,...context.store.listProjects().map(one=>one.path)])],seams=context.integrationIo??{};return{store:context.store,dir:dirname(context.databaseFile),telegramTokenFile:context.telegramTokenFile,env:process.env,repos,gh:(file,args,options)=>run(file,[...args],options),checkConnection:createConnectionChecker({store:context.store}),clock:context.clock,...seams}}async function savedIntegrations(context){return integrationsNow(await integrationIoFor(context))}async function integrationsCommand(positional,flags,context){const command="integrations",allowed=new Set(["db","json","saved"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not an integrations option.`,EXIT.usage);if(positional.length>0)return fail(context.write,context.json,command,"usage","Use `toolroll integrations [--saved] [--json]`.",EXIT.usage);const io=await integrationIoFor(context),list=flag(flags,"saved")?integrationsNow(io):await checkIntegrations(io),counts={connected:0,"not-set-up":0,broken:0};for(const one of list)counts[one.state]+=1;const secrets=toolSecretStorage();return succeed(context.write,context.json,command,{integrations:list,counts,secrets:{kind:secrets.kind,words:secrets.words,...secrets.problem===void 0?{}:{problem:secrets.problem}}},()=>renderIntegrations(list,secrets))}async function waitTask(positional,flags,context){const command="task wait",allowed=new Set(["db","json","timeout"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a task wait option.`,EXIT.usage);if(positional.length!==1)return fail(context.write,context.json,command,"usage","Use `toolroll task wait <id> [--timeout <seconds>]`.",EXIT.usage);const givenTimeout=text(flags,"timeout"),timeoutSeconds=givenTimeout===void 0?null:Number(givenTimeout);if(timeoutSeconds!==null&&(!Number.isFinite(timeoutSeconds)||timeoutSeconds<0))return fail(context.write,context.json,command,"usage","--timeout must be zero or a positive number of seconds.",EXIT.usage);const task=positional[0],startedAt=Date.now(),timeoutMs=timeoutSeconds===null?null:timeoutSeconds*1e3,sleep=context.waitSleep??(milliseconds=>new Promise(resolve2=>setTimeout(resolve2,milliseconds)));let watchedRun;for(;;){const snapshot=taskWaitSnapshot(context.store,task,context.clock(),watchedRun);if(snapshot===null)return fail(context.write,context.json,command,"unknown-task",`No task named ${task}.`,EXIT.failed,{task});watchedRun===void 0&&snapshot.outcome==="Running"&&snapshot.run!==null&&(watchedRun=snapshot.run);const data={task:snapshot.task,outcome:snapshot.outcome,run:snapshot.run,replacedRun:snapshot.replacedRun,phase:snapshot.phase,check:snapshot.check,next:snapshot.next};if(snapshot.terminal){const line=renderTaskWait(snapshot);return snapshot.exitCode===EXIT.ok?succeed(context.write,context.json,command,data,()=>[line]):fail(context.write,context.json,command,snapshot.reason??"failed",line,EXIT.failed,data)}const elapsed=Date.now()-startedAt;if(timeoutMs!==null&&elapsed>=timeoutMs){const line=renderTaskWait(snapshot,"Timed out");return fail(context.write,context.json,command,"timeout",line,EXIT.usage,{...data,outcome:"Timed out"})}const remaining=timeoutMs===null?250:Math.max(1,Math.min(250,timeoutMs-elapsed));await sleep(remaining)}}function taskCommand(positional,flags,context){const[action,...rest]=positional;if(action===void 0)return context.write(TASK_HELP),EXIT.ok;const actor=currentActor();if(actor?.lead===!0&&rest[0]!==void 0&&LEAD_WORK_VERBS.has(action)){const noted=code=>(code===EXIT.ok&&noteLeadWork(context.store,actor,rest[0],action,context.clock()),code),done=taskAction(action,rest,flags,context);return typeof done=="number"?noted(done):done.then(noted)}return taskAction(action,rest,flags,context)}const LEAD_WORK_VERBS=new Set(["state","steer","pause","continue","reopen","requeue","regate","repair","resume","stop","scope","approve","plan","checks","revise","hold","unhold","route","require"]);function taskAction(action,rest,flags,context){switch(action){case"complete":case"revise":return action==="complete"&&currentLocalOwner()!==null?runLocalCompletion(rest,flags,context):action==="revise"&&currentLocalOwner()!==null?runLocalRevision(rest,flags,context):runTaskOutcomeCommand(action,rest,flags,{...context,operator:async()=>{const acting=await askCredentials(flags,context);if(acting===null)return null;const authenticated=verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo)));return authenticated.ok?authenticated.who:null},caller:()=>shellCallerFacts(context)});case"merge":return runTaskMergeCommand(rest,flags,{store:context.store,json:context.json,write:context.write,clock:context.clock,demo:context.store.isDemo(),credentials:()=>askCredentials(flags,context),...context.publishExec===void 0?{}:{exec:context.publishExec}});case"add":return addTask(rest,flags,context);case"new":return newTaskCommand(rest,flags,context);case"keep":return keepGrownCommand(rest,flags,context);case"checks":return runTaskChecks(rest,flags,context);case"ship":return taskShipCommand(rest,context);case"ready":return taskReadyCommand(rest,context);case"add-tests":return addTestsTask(rest,flags,context);case"list":return listTasks(flags,context);case"archive":return archiveTasksCommand(rest,flags,context);case"restore":return restoreTasksCommand(rest,flags,context);case"tidy":return tidyTasksCommand(rest,flags,context);case"show":return showTask(rest,context);case"log":return logTaskCommand(rest,flags,context);case"send":return sendTaskCommand(rest,flags,context);case"handoff":return handoffTaskCommand(rest,flags,context);case"attach":return attachTaskCommand(rest,flags,context);case"wait":return waitTask(rest,flags,context);case"evidence":return taskEvidenceCommand(rest,flags,context);case"state":return stateTask(rest,flags,context);case"ask":return askTask(rest,flags,context);case"block":return blockTask(rest,flags,context);case"unblock":return unblockTask(rest,flags,context);case"next":return nextTask(rest,flags,context);case"steer":return steerTask(rest,flags,context);case"pause":return pauseTask(rest,flags,context);case"continue":return continueTask(rest,flags,context);case"assign":return assignTask(rest,flags,context);case"reopen":return reopenTask(rest,flags,context);case"scope":return scopeTask(rest,flags,context);case"approve":return approveTask(rest,flags,context);case"hold":return holdTask(rest,flags,context);case"unhold":return unholdTask(rest,flags,context);case"stop":return stopTaskCommand(rest,flags,context);case"resume":return resumeTaskCommand(rest,flags,context);case"require":return requireTask(rest,flags,context);case"requeue":return currentLocalOwner()!==null?localRetryCommand(rest,flags,context):requeueTask(rest,flags,context);case"regate":return regateTaskCommand(rest,flags,context);case"handover":return handoverCommand(rest,followThroughContext(context,flags));case"before-after":return evidenceCommand(rest,flags,followThroughContext(context,flags));case"failing-first":return failingFirstCommand(rest,followThroughContext(context,flags));case"plan":return currentLocalOwner()!==null?localPlanCommand(rest,flags,context):planTaskCommand(rest,flags,context);case"review":return reviewTaskCommand(rest,flags,context);case"accept":return acceptTaskProof(rest,flags,context);case"land":return landTaskCommand(rest,flags,context);case"repair":return repairTaskCommand(rest,flags,context);case"route":return routeTaskCommand(rest,flags,context);default:return fail(context.write,context.json,"task","usage",`unknown \`task ${action??""}\` — try ${TASK_ACTIONS.join(", ")}`,EXIT.usage)}}async function addTask(positional,flags,context,fromNew=!1){const{store,write,json,now}=context;if(!fromNew){const allowed=new Set(["goal","body","plan","just-code","repo","id","replaces","checks","report","backend","json","db","key","as","token"]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,"task add","usage",`--${name} is not a task add option.`,EXIT.usage)}const title=positional.join(" ").trim();if(title==="")return fail(write,json,"task add","usage","a task needs a title",EXIT.usage);if(flags.has("plan")&&flags.has("just-code"))return fail(write,json,"task add","usage","choose --plan or --just-code",EXIT.usage);if(flags.has("goal")&&flags.has("body"))return fail(write,json,"task add","usage","--body is an alias for --goal; use one",EXIT.usage);const goal=text(flags,"goal")??text(flags,"body"),proposal=goal!==void 0||flags.has("plan")||flags.has("just-code")?{...goal===void 0?{}:{goal,acceptance:fastAcceptance(goal)},planning:flags.has("plan")?"required":flags.has("just-code")?"skip":"auto"}:void 0,checks=text(flags,"checks");if(checks!==void 0&&!isCheckLevel(checks))return fail(write,json,"task add","usage","--checks is quick, full or off",EXIT.usage);const badText=validateTaskText({title,...goal===void 0?{}:{goal}});if(badText!==null)return fail(write,json,"task add",badText.reason,badText.message,EXIT.usage);const backendName=text(flags,"backend")??BUILT_IN;if(proposal!==void 0&&backendName!==BUILT_IN)return fail(write,json,"task add","usage","--goal, --body, --plan and --just-code require the built-in backend",EXIT.usage);if(flags.has("report")&&backendName!==BUILT_IN)return fail(write,json,"task add","usage","--report files a scout task in the built-in backend only — drop --backend",EXIT.usage);if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"task add","usage",`no backend \`${backendName}\``,EXIT.usage);const created=await backend.create({title});if(!created.ok){const code=created.reason==="denied"?EXIT.refused:EXIT.failed;return fail(write,json,"task add",created.reason,created.message,code)}store.refFor(backendName,created.value,"ours");const dispatchGrant=store.grantFor(repoFrom(flags),backendName);let mirrored=null;if(backendName==="github-issues"&&dispatchGrant?.dispatch===!0&&dispatchGrant.remoteRepo!=null){const localId=mirrorTaskId(dispatchGrant.remoteRepo,created.value),made=store.transact(()=>{const filed=fileTaskProposal(store,{id:localId,title,repo:dispatchGrant.repo,filedVia:"cli"},now);if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:backendName,remoteRepo:dispatchGrant.remoteRepo,remoteId:created.value,provenance:"local-create",establishedBy:"cli"},now);if(!established.ok)throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok&&(mirrored=made.id)}return succeed(write,json,"task add",{id:created.value,backend:backendName,...mirrored===null?{}:{mirror:mirrored}},()=>[`Filed ${created.value} in ${backendName}.`,...mirrored===null?[]:[`Mirrored locally as ${mirrored} — scope and approve it, and this plane builds it.`]])}const id=text(flags,"id")??(activeRemote()===null?slug(title,now):`task-${randomBytes(16).toString("hex")}`),replaces=text(flags,"replaces");if(replaces!==void 0&&(replaces===id||store.getTask(replaces)===null))return fail(write,json,"task add","unknown-task",`no task \`${replaces}\` to replace`,EXIT.refused);if(replaces!==void 0&&builtinReplacementHeld(store,replaces,id))return fail(write,json,"task add","recovery-held","This task can't be replaced while earlier check execution is unverified after recovery.",EXIT.refused);noteActingPerson(flags,context);const outcome=store.replay(mutationFrom(flags,now),"task add",()=>{if(store.getTask(id)!==null)return{ok:!1};if(replaces!==void 0)return createBuiltinReplacement(store,{id,title,report:flags.has("report"),repo:text(flags,"repo")??null,replaces,now,...proposal===void 0?{}:{proposal}});if(proposal!==void 0){const filed=fileTaskProposal(store,{id,title,...proposal,...text(flags,"repo")===void 0?{}:{repo:text(flags,"repo")},...flags.has("report")?{deliverable:"report"}:{},filedVia:"cli"},now);return filed.ok?{ok:!0,task:store.getTask(filed.id)}:filed}return{ok:!0,task:store.createTask({id,title,...flags.has("report")?{deliverable:"report"}:{}},now)}},result=>result.ok);if(!outcome.ok)return"reason"in outcome&&"message"in outcome&&typeof outcome.message=="string"?fail(write,json,"task add",outcome.reason,outcome.message,EXIT.usage):"reason"in outcome?fail(write,json,"task add",outcome.reason,outcome.reason==="recovery-held"?"This task can't be replaced while earlier check execution is unverified after recovery.":"The replacement couldn't be filed. Nothing was changed.",EXIT.refused):fail(write,json,"task add","exists",`\`${id}\` already exists`,EXIT.refused);const filedId=outcome.task.id,remote=activeRemote();if(remote!==null&&filedId!==id){const saved=store.lookupRef(filedId);if(saved===null||saved.repo!==text(flags,"repo")||!remote.allows(saved.repo))throw new RemoteRefusal("not-found","Not found.")}remote?.noteTask(filedId),replaces===void 0&&store.stampFiledVia(store.refFor(BUILT_IN,filedId).id,"cli");const placedIn=text(flags,"repo");if(placedIn!==void 0&&replaces===void 0&&proposal===void 0){const placed=store.placeTask(store.refFor(BUILT_IN,filedId).id,canonicalProject(placedIn)??resolve(placedIn));if(typeof placed=="object"&&!placed.ok)return fail(write,json,"task add","scoped","this task already has a scope — placement is immutable once somebody could have approved it",EXIT.refused)}if(checks!==void 0){const chosen=setTaskCheckLevel(store,outcome.task.id,checks,"cli",now);if(!chosen.ok)return fail(write,json,"task add","checks-fixed",chosen.message,EXIT.refused)}const link=consoleLinkFor(context,`/t/${encodeURIComponent(outcome.task.id)}`);let noAgent=null;const filedRef=placedIn===void 0||remote!==null?null:store.lookupRef(outcome.task.id);if(filedRef!==null&&filedRef.repo!==null)try{const agentless=agentlessFirstRun(store,filedRef,!0,buildersFor(store,filedRef.repo,now).alive.map(one=>one.name));agentless!==null&&(noAgent=`${NO_AGENT_TITLE}. Run \`${agentless.command}\` so it can be planned.`)}catch{noAgent=null}const next=proposal===void 0&&filedRef!==null&&filedRef.repo!==null&&filedRef.plan===null&&!flags.has("report")?`Next: run \`toolroll\`, select it and press p to ask for a plan.${fromNew?"":" To build without a plan, file it with `toolroll task new` instead."}`:null;return succeed(write,json,"task add",{task:outcome.task,...replaces===void 0?{}:{replaces},repo:placedIn===void 0?null:resolve(placedIn),...checks===void 0?{}:{checks},...link===null?{}:{links:{task:link}},...noAgent===null?{}:{waiting:noAgent},...next===null?{}:{next}},()=>[`Queued ${outcome.task.id} — ${outcome.task.title}${flags.has("report")?" (a scout task: it delivers a report)":""}${checks===void 0?"":` · checks: ${CHECK_LEVEL_WORDS[checks]}`}`,...replaces===void 0?[]:[` It replaces ${replaces}.`],...noAgent===null?[]:[` ${noAgent}`],...placedIn===void 0&&remote===null?[" It has no project yet: choose one on its page in Toolroll, or file it with `--repo <folder>`."]:[],...next===null?[]:[` ${next}`],...link===null?[]:[` ${link}`]])}function latestBuildResult(store,taskId){const family=store.taskFamilyOf(taskId,null,!0),versions=family===null?[taskId]:[family.current.id,...family.versions.map(one=>one.id).filter(id=>id!==family.current.id)];for(const id of versions){const ref=store.lookupRef(id),run2=ref===null?void 0:store.runsFor(ref.id).find(one=>one.role==="builder"&&one.finishedAt!==null&&one.headRevision!==null);if(run2!==void 0)return{runId:run2.id,head:run2.headRevision}}return null}async function runTaskChecks(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),taskId=positional[0];if(taskId===void 0)return fail(write,json,"task checks","usage","`toolroll task checks <task> [--level quick|full]`",EXIT.usage);const level=text(flags,"level")??"quick";if(level!=="quick"&&level!=="full")return fail(write,json,"task checks","usage","--level is quick or full",EXIT.usage);const demoFence=refuseDemo(context,"task checks");if(demoFence!==null)return demoFence;const result=latestBuildResult(store,taskId);if(result===null)return fail(write,json,"task checks","no-result",`${taskId} has no finished result to check`,EXIT.refused);const asked=requestFollowUpChecks(store,{runId:result.runId,level,actor:"cli"},clock());if(!asked.ok)return fail(write,json,"task checks",asked.reason,asked.message,EXIT.refused);const done=await runFollowUpCheck(store,context.evidenceRoot,asked.request,{now:clock});if(done?.state==="recovery-held")return fail(write,json,"task checks","recovery-held",done.note,EXIT.refused);const state=done?.state??"waiting",words=`${CHECK_LEVEL_WORDS[asked.level]} checks`,payload={task:taskId,run:result.runId,head:result.head,request:asked.request,level:asked.level,state,exitCode:done?.exitCode??null},complete=assignmentOf(store,taskId,clock(),{principal:"operator",repos:null,includeUnplaced:!0},context.evidenceRoot)?.state==="complete";return state==="failed"?json?(write(envelopeJson({ok:!1,command:"task checks",reason:"checks-failed",...payload})),EXIT.failed):(write(`${words} failed on ${result.head.slice(0,7)}${done?.exitCode==null?"":` (exit ${done.exitCode})`}. ${complete?"It stays Complete; it can't land until they pass on its exact commit.":"The result shows the failure."}`),EXIT.failed):succeed(write,json,"task checks",payload,()=>[state==="passed"?`${words} passed on ${result.head.slice(0,7)}.${complete?" It stays Complete.":""}`:state==="running"?`${words} are already running on ${result.head.slice(0,7)}.`:state==="not-run"?`${words} didn't run: ${done?.note??"see the result's log"}`:`${words} are queued on ${result.head.slice(0,7)}.`])}function addTestsTask(positional,_flags,context){const{store,write,json,now}=context,taskId=positional[0];if(taskId===void 0)return fail(write,json,"task add-tests","usage","`toolroll task add-tests <task>`",EXIT.usage);const result=latestBuildResult(store,taskId);if(result===null)return fail(write,json,"task add-tests","no-result",`${taskId} has no finished result to write tests for`,EXIT.refused);const filed=fileAddTestsTask(store,context.evidenceRoot,{runId:result.runId,actor:"cli",filedVia:"cli"},now);return filed.ok?succeed(write,json,"task add-tests",{task:taskId,filed:filed.id,existing:filed.existing},()=>[filed.existing?`Tests for ${taskId} are already filed as ${filed.id}.`:`Filed ${filed.id} to add tests for ${taskId}. Approve its scope to start.`]):fail(write,json,"task add-tests",filed.reason,filed.message,EXIT.refused)}function requireTask(positional,flags,context){const{store,write,json,now}=context,id=positional[0],given=text(flags,"cap");if(id===void 0||given===void 0)return fail(write,json,"task require","usage","`toolroll task require <id> --cap <kind:name>[,<kind:name>]` — or --cap none to clear",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task require","unknown-task",`no task \`${id}\``,EXIT.refused);const keys=given==="none"?[]:given.split(",").map(one=>one.trim()).filter(Boolean);for(const key of keys)if(parseCapabilityKey(key)===null)return fail(write,json,"task require","usage",`\`${key}\` is not a capability key — say kind:name, like env:SUPABASE_KEY or cli:gh`,EXIT.usage);return store.setRequirements(store.refFor(BUILT_IN,id).id,keys,mutationFrom(flags,now)),succeed(write,json,"task require",{id,requirements:keys},()=>[keys.length===0?`${id} requires nothing.`:`${id} now requires: ${keys.join(", ")}. Nothing dispatches it until every one is verified.`])}async function capCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional,repo=repoFrom(flags);if(action==="add"){if(name===void 0)return fail(write,json,"cap add","usage","`toolroll cap add <name> [--kind env|cli|mcp|ci|other] [--probe <cmd>] [--expires <iso>]`",EXIT.usage);const kind=text(flags,"kind")??"env";if(!["env","cli","mcp","ci","other"].includes(kind))return fail(write,json,"cap add","usage","--kind takes env, cli, mcp, ci or other",EXIT.usage);let probe=text(flags,"probe")??null;if(probe===null&&kind==="env"){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))return fail(write,json,"cap add","usage",`\`${name}\` is not an environment variable name — give --probe explicitly`,EXIT.usage);probe=`test -n "$${name}"`}const expires=text(flags,"expires")??null;return store.saveCapability({repo,kind,name,probe,status:"unprobed",addedBy:`operator@${hostname()}`,createdAt:clock().toISOString(),lastVerifiedAt:null,verifiedBy:null,lastResult:null,expiresAt:expires},mutationFrom(flags,clock())),succeed(write,json,"cap add",{repo,kind,name,probe},()=>[`Recorded ${kind}:${name} for ${repo}.`,probe===null?"No probe — nothing can verify it, so it will stand as a gap until it has one.":`Probe: ${probe}`,"Nothing is verified yet: `toolroll cap probe`."])}if(action==="list"||action===void 0){const capabilities=store.listCapabilities(repo);if(json)return write(envelopeJson({ok:!0,command:"cap list",repo,capabilities})),EXIT.ok;if(capabilities.length===0)return write(`No capabilities recorded for ${repo}. \`toolroll cap add\` or \`cap scan\`.`),EXIT.ok;for(const one of capabilities){const state=describeCapability(one,clock());write(` ${`${one.kind}:${one.name}`.padEnd(32)} ${state}`)}return EXIT.ok}if(action==="scan"){const report=scanRepo(repo);let recorded=0;for(const one of report.found)store.getCapability(repo,one.kind,one.name)===null&&(store.saveCapability({repo,kind:one.kind,name:one.name,probe:one.probe,status:"unprobed",addedBy:`scan:${one.source}`,createdAt:clock().toISOString(),lastVerifiedAt:null,verifiedBy:null,lastResult:null,expiresAt:null}),recorded++);if(json)return write(envelopeJson({ok:!0,command:"cap scan",repo,recorded,...report})),EXIT.ok;if(report.found.length===0)return write(`Nothing detected in ${repo}. Detection reads .env.example, .mcp.json, supabase/config.toml and workflow files.`),EXIT.ok;for(const one of report.found)write(` ${`${one.kind}:${one.name}`.padEnd(32)} ${one.source}${one.probe===null?" (no probe)":""}`);for(const bad of report.rejected)write(` rejected ${bad.name} from ${bad.source} — not a valid identifier`);return write(""),write(`${recorded} new, ${report.found.length-recorded} already recorded. Nothing is verified: \`toolroll cap probe\`.`),EXIT.ok}if(action==="probe"){const only=positional.slice(1);for(const key of only)if(parseCapabilityKey(key)===null)return fail(write,json,"cap probe","usage",`\`${key}\` is not a capability key — say kind:name`,EXIT.usage);const outcomes=await probeRepo(store,repo,`operator@${hostname()}`,clock(),only.length===0?{}:{only:new Set(only)});if(outcomes.length===0)return fail(write,json,"cap probe","empty",`nothing to probe for ${repo}`,EXIT.refused);const unverified=outcomes.filter(one=>one.status!=="verified");return write(json?envelopeJson({ok:!0,command:"cap probe",repo,outcomes}):outcomes.map(one=>` ${`${one.kind}:${one.name}`.padEnd(32)} ${one.status}${one.detail===void 0?"":` ${one.detail}`}`).join(`
482
499
  `)),unverified.length===0?EXIT.ok:EXIT.refused}return fail(write,json,"cap","usage",`unknown \`cap ${action}\` — try add, list, scan, probe`,EXIT.usage)}function listTasks(flags,context){const{store,write,json,now}=context,wanted=text(flags,"state"),rawView=text(flags,"view"),rawLimit=text(flags,"limit"),limit=rawLimit===void 0?40:Number(rawLimit);if(wanted!==void 0&&!STATES.includes(wanted))return fail(write,json,"task list","usage",`--state takes one of ${STATES.join(", ")}`,EXIT.usage);if(rawView!==void 0&&!["all","needs-you","running","queued","completed","archived"].includes(rawView)||!Number.isSafeInteger(limit)||limit<1||limit>100)return fail(write,json,"task list","usage","--view takes all, needs-you, running, queued, completed or archived; --limit takes 1–100",EXIT.usage);const lens=context.principal?.lens??null,access={principal:"operator",repos:lens,includeUnplaced:lens===null},options={view:parseWorkView(rawView??null),limit,cursor:text(flags,"cursor")??null,...wanted===void 0?{}:{state:wanted},...text(flags,"repo")===void 0?{}:{project:text(flags,"repo")},root:context.evidenceRoot},refused=error=>{if(!(error instanceof WorkIndexCursorError))throw error;return fail(write,json,"task list","usage","Invalid page cursor. Start again without --cursor.",EXIT.usage)},show=page2=>{const landed=landedRowsOf(store,page2.items),tasks=page2.items.map(item=>({...item,id:item.rootId,...landed.has(item.rootId)?{landed:landed.get(item.rootId)}:{}}));if(json)return write(envelopeJson({ok:!0,command:"task list",count:tasks.length,tasks,totals:page2.totals,nextCursor:page2.nextCursor,limit:page2.limit,view:page2.view,evidence:"recorded"})),EXIT.ok;tasks.length===0&&write(wanted===void 0?"The task list is empty.":`Nothing is ${wanted}.`);const width=Math.max(0,...tasks.map(task=>task.id.length)),AFTER={failed:"checks failed after acceptance",stale:"checks out of date",unreadable:"checks couldn't be read"},marks=task=>{const said=[..."landed"in task?[`${task.landed.charAt(0).toLowerCase()}${task.landed.slice(1)}`]:[],...task.check===void 0?[]:[AFTER[task.check]]];return said.length===0?"":` · ${said.join(" · ")}`};for(const task of tasks)write(task.archived===void 0?` ${task.id.padEnd(width)} ${task.status.label.padEnd(16)} ${task.title}${marks(task)}`:` ${task.id.padEnd(width)} ${"Archived".padEnd(16)} ${task.title} — by ${task.archived.byKind==="tidy"?"tidy":task.archived.by}: ${task.archived.reason}`);return page2.nextCursor!==null&&write(`Next page: --cursor ${page2.nextCursor}`),EXIT.ok},executor=readExecutorOf(store);if(executor!==null)return executor.workIndexPage(now,access,options).then(show,refused);let page;try{page=workIndexPage(store,now,access,options)}catch(error){return refused(error)}return show(page)}function showTask(positional,context){const{store,write,json,now}=context,id=positional[0]===void 0?void 0:resolveTaskId(store,positional[0]);if(id===void 0)return fail(write,json,"task show","usage","which task?",EXIT.usage);const task=store.getTask(id);if(task===null)return fail(write,json,"task show","unknown-task",`no task \`${id}\``,EXIT.refused);const ref=store.refFor(BUILT_IN,id),scope=store.getScope(id),runs=store.runsFor(ref.id),latestFinished=runs.find(one=>one.finishedAt!==null&&(one.role==="builder"||one.role==="scout"))??null,proofVerdict=latestFinished===null?null:store.proofVerdictFor(latestFinished.id),proofAccepted=latestFinished!==null&&store.proofAcceptance(latestFinished.id)!==null,routed=routeOfTask(store,id,ref,now),readiness=store.readinessLookupFor(ref.repo,ref.assignedRunner,now),lens=context.principal?.lens??null,access={principal:"operator",repos:lens,includeUnplaced:lens===null,dependencyRepos:lens},blockers=store.blockers(id),visibleBlockers=lens===null?blockers:blockers.filter(blocker=>{const repo=store.lookupRef(blocker)?.repo;return repo!=null&&lens.includes(repo)}),work=taskWorkSummaryOf(store,id,now,access),current=assignmentOf(store,id,now,access,context.evidenceRoot),listed=workIndexTask(store,id,now,access,context.evidenceRoot),shared=listed===null?null:{headline:listed.status.label,sentence:listed.status.detail},primaryAction=listed===null?work?.primaryAction??null:listed.primaryAction,steeringLive=store.steeringLiveBuild(ref.id,now)!==null,base=taskBaseOf(store,id),landedNow=current===null?null:landedNowOf(store,current)?.words??null,detail={task,work:work===null||listed===null?work:{...work,status:{...work.status,label:listed.status.label,detail:listed.status.detail,tone:listed.status.tone},primaryAction},status:shared===null?null:{headline:shared.headline,sentence:shared.sentence},assignment:assignmentBrief(current),ref:ref.id,blockedBy:visibleBlockers.length===blockers.length?visibleBlockers:[...visibleBlockers,"a task in another project"],position:lens===null?store.queuePosition(id):null,reservedFor:ref.assignedRunner,hold:store.activeHold(ref.id,now),claim:currentClaim(store,ref.id,now),scope,approval:approvalOf(scope),personApproval:personApprovalOf(store,id),route:taskRouteView(routed,readiness),base,landing:landedNow,runs:runs.map(one=>({...one,route:store.runRoute(one.id)})),deliverable:ref.deliverable,report:readVerifiedReport(store,context.evidenceRoot,ref.id),proofVerdict:proofVerdict?.verdict??null,proofReasons:proofVerdict?.reasons??[],proofMatrix:proofVerdict?.matrix??[],proofAccepted,semanticCoverage:latestFinished===null?null:semanticCoverage(proofVerdict?.matrix??[],latestFinished.qualityMode??"default"),review:latestFinished===null?null:store.reviewRetryStateOf(latestFinished.id),automaticReview:latestFinished===null?null:buildReviewOf(store,latestFinished.id),dispatch:diagnoseTaskDispatch(store,id,now,lens),control:taskControlOf(store,ref.id,now),stops:store.stopsForTask(ref.id),pullRequest:newestPullRequestOf(store,store.taskFamilyOf(id,null,!0)?.versions.map(one=>one.id)??[id]),steering:store.listSteerNotes(ref.id).map(one=>({id:one.id,author:one.author,createdAt:one.createdAt,note:one.note,standing:steerStandingOf(one,steeringLive),words:steerStandingWords(one,steeringLive,utcMinute)})),approvalTerms:scope===null?null:approvalSummaryOf(scope,summaryContextOf(store,id,scope,now)).key},checkedByPerson=detail.proofAccepted||shared?.headline==="Complete",shownReasons=checkedByPerson?detail.proofReasons.filter(reason=>manualReviewCriterionOf(reason)===null):detail.proofReasons,shownMatrix=checkedByPerson?detail.proofMatrix.map(row=>({...row,detail:row.detail.filter(line=>manualReviewCriterionOf(line)===null)})):detail.proofMatrix;return succeed(write,json,"task show",detail,()=>[`${task.id} ${shared?.headline??detail.work?.status.label??task.state}${ref.deliverable==="report"?" (scout — delivers a report)":""}`,` ${task.title}`,...landedNow===null?[]:[` landing: ${landedNow}`],...detail.work===null?[]:[` status: ${shared?.headline??detail.work.status.label}${shared===null?"":`${shared.headline==="On hold"?" · ":" — "}${shared.sentence}`}`,...primaryAction===null||checkedByPerson&&(primaryAction.code==="open-result"||primaryAction.code==="inspect-run")?[]:[` next: ${primaryAction.label}${primaryAction.target.decisionId===null?"":` — decision #${primaryAction.target.decisionId}`}`]],...task.state!=="done"||detail.proofVerdict===null?[]:shared?.headline==="Complete"&&current?.completion?.person!==void 0?[` checked: ${acceptedWords(current?.completion??null)}`,...matrixWords(shownMatrix),...detail.semanticCoverage===null?[]:coverageWords(detail.semanticCoverage).map(line=>` ${line}`)]:[` checked: ${proofVerdictWords(current?.receipt?.runId===latestFinished?.id?current?.readiness?.verdict??detail.proofVerdict:detail.proofVerdict,detail.proofReasons).word}${detail.proofAccepted?" (accepted)":""}`,...shownReasons.length>0?[` ${shownReasons.map(plainReasonWords).join(" ")}`]:[],...matrixWords(shownMatrix),...detail.semanticCoverage===null?[]:coverageWords(detail.semanticCoverage).map(line=>` ${line}`)],...detail.report===null?[]:detail.report.ok?[` report: ${detail.report.report.title} (build #${detail.report.run})`,` ${detail.report.report.summary}`,...detail.report.report.followUps.map((one,index)=>` follow-up ${index+1}: ${one.title}`)]:[` report: ${detail.report.problem} (build #${detail.report.run})`],...pullRequestLines(detail.pullRequest),...base===null?[]:[` base: ${baseStandingWords(base,landedNow!==null)}`],...detail.blockedBy.length>0?[` waits for ${detail.blockedBy.join(", ")}`]:[],...detail.position===null?[]:[` position ${detail.position.position} of ${detail.position.total}${detail.position.column===null?" in the shared queue":` in ${detail.position.column}'s queue`}`],...detail.hold===null?[]:[` held: ${detail.hold.reason}`],...detail.steering.slice(-5).map(one=>` note #${one.id} to the agent: ${one.words}`),...detail.claim===null?[]:[` claimed by ${detail.claim.runner} until ${detail.claim.expiresAt}`],...detail.dispatch===null||shared?.headline==="Complete"?[]:[` dispatch: ${detail.dispatch.detail.startsWith(detail.dispatch.summary)?detail.dispatch.detail:`${detail.dispatch.summary} — ${detail.dispatch.detail}`}`],...detail.control.kind==="none"?[]:detail.control.kind==="stop"?[` control: run #${detail.control.run} is live — \`task stop ${task.id} --run ${detail.control.run} --as <you> --token <t>\``]:detail.control.kind==="stopping"?[` control: run #${detail.control.run} is stopping (asked by ${detail.control.stop.requestedBy} at ${detail.control.stop.requestedAt})${detail.control.unsettledRun?" — its processes are not yet established gone":" — the run ended but the stop is unsettled; needs attention"}`]:detail.control.kind==="paused"?[` control: paused — run #${detail.control.run} was stopped by ${detail.control.stop.requestedBy} (${detail.control.stop.settlement??"?"})${detail.control.committed?"; its commit is on the branch":""}; work preserved${detail.control.worktree===null?"":` in ${detail.control.worktree}`} — \`task resume ${task.id} --run ${detail.control.run} --as <you> --token <t>\``]:[` control: review #${detail.control.run} was stopped by ${detail.control.stop.requestedBy} — inspect its saved result and give feedback; separate model review has been removed`],...detail.automaticReview===null?reviewStatusLines(detail.review,latestFinished?.id??null):buildReviewLines(detail.automaticReview),...scope===null?[" no plan yet — nothing is built until one is written and approved"]:describeScope(scope,readiness,taskEvidenceWords(store,task.id,now),summaryContextOf(store,task.id,scope,now)),...planContractLines(store,context.evidenceRoot,id),...taskRouteStandingLines(id,routed,detail.dispatch?.summary===NO_AGENT_TITLE),...detail.runs.filter(one=>one.route!==null).slice(0,8).map(one=>` ${runWords(detail.runs,one.id)} ${one.role.padEnd(8)} ${one.route.provider}${one.route.model===null?"":` · ${one.route.model}`} [${one.route.chosen}]`)])}function reviewStatusLines(review,sourceRun){if(review===null||sourceRun===null||review.state==="unrequested")return[];const word={unrequested:"not requested",queued:"legacy request retained; the worker will close it without running a model review",running:`running — attempt ${review.live?.attempt??review.attempts.length} of ${review.cap}`,succeeded:`succeeded on attempt ${review.succeeded?.attempt??1} of ${review.cap}`,retryable:`${review.latest!==null&&wasInterrupted(review.latest)?"interrupted":"failed"} on attempt ${review.latest?.attempt??review.attempts.length} of ${review.cap} — inspect the saved result; model reviews no longer retry`,exhausted:`exhausted — all ${review.cap} attempts ended without a review; nothing retries a fourth time`};return[` review: ${review.state==="queued"&&review.attempts.length===0?"queued — waiting for a worker":word[review.state]}`,...review.attempts.map(one=>` attempt ${one.attempt}: run #${one.runId} ${one.outcome===null?"open":one.outcome==="no-change"?"reviewed":`${one.outcome}${one.reason===null?"":` (${one.reason})`}`}`)]}function taskRouteView(routed,readiness){return routed===null?null:routed.kind==="route"?{kind:"route",source:routed.source,...projectRoute(routed.route,readiness)}:routed.kind==="legacy"?{kind:"legacy",source:"legacy",approved:routed.approved,profile:{provider:routed.profile.provider,model:routed.profile.model,repairModel:routed.profile.repairModel==="inherit"?routed.profile.model:routed.profile.repairModel}}:{kind:"unreadable",source:null,problem:routed.problem}}function taskRouteStandingLines(id,routed,agentless=!1){return routed===null?[]:agentless&&routed.kind==="unreadable"&&routed.problem.includes("has no exact model")?[" agents not chosen yet: sign in a coding agent first"]:routed.kind==="route"?[` agents ${routed.source==="approved"?"approved with the plan — a configuration change never moves them":routed.source==="proposed"?"proposed — approving the plan approves them":"recommended now — no plan filed yet"}`]:routed.kind==="legacy"?[` agents approved before agent routing existed — ${routed.profile.provider} · ${routed.profile.model} builds and repairs (repair model ${routed.profile.repairModel==="inherit"?routed.profile.model:routed.profile.repairModel}); the planner and reviewer resolve from configuration at run time`]:[` agents UNREADABLE — ${routed.problem}`,` nothing runs for ${id} until its plan is saved again and approved`]}async function acceptTaskProof(positional,flags,context){const{store,write,json,now}=context,finishing=flags.has("finish")||flags.has("digest"),despiteFlag=flags.has("despite")?flags.get("despite"):flags.get("note"),despiting=flags.has("despite")||flags.has("note");if(flags.has("despite")&&flags.has("note"))return fail(write,json,"task accept","usage",'Use --despite "<reason>" once (--note is the same flag).',EXIT.usage);if(finishing&&despiting)return fail(write,json,"task accept","usage","--despite accepts a result with a reason and never finishes the task; --finish and --digest finish it. Use one: first accept with --despite, then finish with --finish.",EXIT.usage);if(!finishing&&!despiting)return fail(write,json,"task accept","usage",'Say what accepting means: `toolroll task accept <id> --finish` accepts the result and finishes the task, or `--despite "<reason>"` accepts it with a reason without finishing.',EXIT.usage);if(finishing){if(flags.get("finish")!==void 0&&flags.get("finish")!==!0)return fail(write,json,"task accept","usage","--finish takes no value.",EXIT.usage);const rest=new Map(flags);return rest.delete("finish"),currentLocalOwner()!==null?runLocalCompletion(positional,rest,{...context,command:"task accept"}):runTaskOutcomeCommand("complete",positional,rest,{...context,command:"task accept",operator:async()=>{const acting2=await askCredentials(flags,context);if(acting2===null)return null;const authenticated=verifyApproverByPassword(context.store,acting2.name,acting2.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting2.name,repo)));return authenticated.ok?authenticated.who:null},caller:()=>shellCallerFacts(context)})}const id=positional[0];if(id===void 0)return fail(write,json,"task accept","usage",'`toolroll task accept <id> --despite "<reason>" --as <you> --token <t>`',EXIT.usage);if(typeof despiteFlag!="string"||despiteFlag.trim()==="")return fail(write,json,"task accept","usage",'--despite needs the reason you accept it anyway: `--despite "<reason>"`.',EXIT.usage);const validated=validateNote(despiteFlag);if(!validated.ok)return fail(write,json,"task accept","invalid",validated.problem,EXIT.usage);const task=store.getTask(id);if(task===null)return fail(write,json,"task accept","unknown-task",`no task \`${id}\``,EXIT.refused);if(currentLocalOwner()!==null)return store.transact(()=>{const owner=localActNow(store,"complete-task");if(owner===null)return fail(write,json,"task accept","local-owner",LOCAL_OWNER_LAPSED,EXIT.refused);const ref2=store.lookupRef(id);if(ref2?.repo==null||!store.accountCanAccess(owner.account,ref2.repo))return fail(write,json,"task accept","unknown-task","That task is unavailable in your projects.",EXIT.refused);if(!verifyApproverStanding(store,owner.account,owner.accountGeneration,[ref2.repo]).ok)return fail(write,json,"task accept","local-owner",LOCAL_OWNER_LAPSED,EXIT.refused);const latest2=store.runsFor(ref2.id).find(one=>one.finishedAt!==null&&(one.role==="builder"||one.role==="scout"));if(latest2===void 0)return fail(write,json,"task accept","no-run",`${id} has no finished attempt to accept`,EXIT.refused);const local=localCompletionRefusal(store,`operator:${owner.account}`,[task.id,store.taskFamilyOf(task.id,null,!0)?.root.id??task.id],latest2.id,context.evidenceRoot);return local!==null?fail(write,json,"task accept",local.reason,local.message,EXIT.refused):(store.acceptProof(latest2.id,owner.account,validated.note,now),succeed(write,json,"task accept",{id,run:latest2.id,acceptedBy:owner.account},()=>[`Accepted ${id}'s build #${latest2.id} with your reason. It isn't finished: \`toolroll task accept ${id} --finish\` finishes it.`]))});const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task accept",verified,"accepting a result with a reason is a person's act — it takes `--as <you> --token <t>`",id);const ref=store.refFor(BUILT_IN,id),latest=store.runsFor(ref.id).find(one=>one.finishedAt!==null&&(one.role==="builder"||one.role==="scout"));return latest===void 0?fail(write,json,"task accept","no-run",`${id} has no finished attempt to accept`,EXIT.refused):(store.acceptProof(latest.id,acting.name,validated.note,now),succeed(write,json,"task accept",{id,run:latest.id,acceptedBy:acting.name},()=>[`Accepted ${id}'s build #${latest.id} with your reason, ${acting.name}. It isn't finished: \`toolroll task accept ${id} --finish\` finishes it.`]))}async function repairTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[runText]=positional,runId=Number(runText??"");if(runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task repair","usage","`toolroll task repair <run-id> [--yes] --as <you> --token <t>`",EXIT.usage);let chain=store.repairChainFor(runId);if(chain===null&&flags.get("yes")===!0){const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,"task repair","usage","Evidence collection requires --as and --token.",EXIT.usage);const failed=checkRepairOfRun(store,runId),authenticated=authenticateApprover(store,acting2.name,acting2.token,failed?.repo);if(!authenticated.ok)return fail(write,json,"task repair",authenticated.reason,describeApproveFailure(authenticated.reason,String(runId)),EXIT.refused);if(failed!==null){const started=startCheckRepair(store,context.evidenceRoot,runId,clock());if(!started.ok)return fail(write,json,"task repair","refused",started.message,EXIT.refused);chain=store.repairChainFor(runId)}const run2=store.getRun(runId),proof=store.proofVerdictFor(runId),repo=run2&&store.refById(run2.taskRef)?.repo;repo&&repo===repoFrom(flags)&&proof?.matrix.some(row=>row.assessment&&row.review?.judgement==="cannot-tell")&&!proof.matrix.some(row=>row.review?.judgement==="contradicts")&&(maybeTriggerRepair(store,repo,context.evidenceRoot,runId,proof.verdict,clock()),chain=store.repairChainFor(runId))}if(chain===null)return fail(write,json,"task repair","unknown-task",`run ${runId} has no drafted repair — a repair is only drafted after a review names unmet criteria`,EXIT.refused);if(chain.draftTask===null)return fail(write,json,"task repair","refused",`no draft was ever made for run ${runId} — the chain stopped at ${chain.outcome} before drafting one`,EXIT.refused);const draftId=chain.draftTask;if(!(flags.get("yes")===!0)){const draftScope2=store.getScope(draftId);return succeed(write,json,"task repair",{run:runId,draft:draftId,attempt:chain.attempt,unresolved:chain.unresolved,basis:chain.basis,outcome:chain.outcome,approved:draftScope2?.approvedAt!==null&&draftScope2?.approvedAt!==void 0},()=>[`${draftId} — attempt ${chain.attempt}, drafted by ${chain.basis==="mode"?"a signed mode":"the review pass"}, repairing: ${chain.unresolved.join(", ")}.`,draftScope2?.approvedAt!=null?"Already approved — it builds on the next dispatch.":"Unapproved. Add --yes --as <you> --token <t> to approve it now."])}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task repair",verified,"approving a repair draft is a person's act — it takes `--as <you> --token <t>`",draftId);const draftScope=store.getScope(draftId);if(draftScope===null)return fail(write,json,"task repair","no-scope",`${draftId} has no scope to approve`,EXIT.refused);const approved=approve(store,draftId,acting.name,clock(),draftScope.digest,acting.token);return approved.ok?succeed(write,json,"task repair",{run:runId,draft:draftId,approvedBy:acting.name},()=>[`Approved: ${draftId} (attempt ${chain.attempt}) will build on the next dispatch.`]):fail(write,json,"task repair",approved.reason,approved.reason==="policy"?`${draftId}: ${approved.message}`:describeApproveFailure(approved.reason,draftId),EXIT.refused)}async function stateTask(positional,flags,context){const{store,write,json,now}=context,[id,state]=positional;if(id===void 0||state===void 0)return fail(write,json,"task state","usage","`toolroll task state <id> <state>`",EXIT.usage);if(!STATES.includes(state))return fail(write,json,"task state","usage",`state is one of ${STATES.join(", ")}`,EXIT.usage);const backendName=text(flags,"backend")??BUILT_IN;if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"task state","usage",`no backend \`${backendName}\``,EXIT.usage);const moved2=await backend.setState(id,state);if(!moved2.ok){const code=moved2.reason==="denied"||moved2.reason==="unsupported"?EXIT.refused:EXIT.failed;return fail(write,json,"task state",moved2.reason,moved2.message,code)}return succeed(write,json,"task state",{id,state,backend:backendName},()=>[`${id} is now ${state} in ${backendName}.`])}const replacedBy=text(flags,"replaced-by");if(replacedBy!==void 0){if(state!=="cancelled")return fail(write,json,"task state","usage","--replaced-by goes with cancelled: `task state <id> cancelled --replaced-by <id>`",EXIT.usage);if(replacedBy===id||store.getTask(replacedBy)===null)return fail(write,json,"task state","unknown-task",`no task \`${replacedBy}\` to replace it`,EXIT.refused)}noteActingPerson(flags,context);const moved=store.setTaskState(id,state,now,mutationFrom(flags,now),text(flags,"reason"),replacedBy);return moved.ok?succeed(write,json,"task state",{id,state,...replacedBy===void 0?{}:{replacedBy}},()=>[replacedBy===void 0?`${id} is now ${state}.`:`${id} is replaced by ${replacedBy}.`]):moved.reason==="recovery-held"?fail(write,json,"task state","recovery-held","This task can't be replaced while earlier check execution is unverified after recovery.",EXIT.refused):moved.reason==="reason-required"||moved.reason==="bad-reason"?fail(write,json,"task state",moved.reason,moved.reason==="reason-required"?"a coordinator filed this task — add --reason with why you are cancelling it":"--reason must be at most 500 plain characters, without hidden or control characters",EXIT.refused):moved.reason==="external-closed"?fail(write,json,"task state","external-closed","the tracker closed this — reopen it first, or leave it cancelled",EXIT.refused):fail(write,json,"task state","unknown-task",`no task \`${id}\``,EXIT.refused)}function noteActingPerson(flags,context){if(currentActor()!==null)return;const name=text(flags,"as"),token=text(flags,"token");if(token!==void 0){name!==void 0&&name!==""&&token!==""&&authenticateAccount(context.store,name,token);return}const remembered=readLoginFile(savedLoginFile(dirname(context.databaseFile)));remembered!==null&&(name===void 0||name===remembered.name)&&claimActor(remembered.name)}function askTask(positional,flags,context){const{store,write,json,now}=context,[id,...extra]=positional,person=text(flags,"person"),why=text(flags,"why")?.trim();if(id===void 0||extra.length>0||person===void 0||why===void 0||why==="")return fail(write,json,"task ask","usage",'`toolroll task ask <id> --person <name> --why "what they need to do"`',EXIT.usage);if(why.length>500||/[\u0000-\u001f\u007f]/.test(why))return fail(write,json,"task ask","usage","--why is at most 500 plain characters on one line",EXIT.usage);if(noteActingPerson(flags,context),currentActor()===null)return fail(write,json,"task ask","unauthenticated","Hand a task on as the lead (its lead token) or with your sign-in (--as and --token, or the remembered login).",EXIT.refused);const asked=store.askPerson(id,person,why,now);return asked.ok?succeed(write,json,"task ask",{id,person,why},()=>[`Asked ${person} about ${id}. It is theirs now, and its updates reach them.`]):fail(write,json,"task ask",asked.reason,asked.reason==="unknown-task"?`no task \`${id}\``:asked.reason==="unplaced"?`${id} has no project yet, so nobody can be asked about it`:`${person} is not someone who can see this task's project`,EXIT.refused)}async function leadCommand(positional,flags,context){const{store,write,json}=context,[action,...extra]=positional;if(action==="say")return leadSayCommand(extra,flags,context);const command="lead token";if(action!=="token"||extra.length>0)return fail(write,json,`lead ${action??""}`.trim(),"usage",'`toolroll lead token [--revoke] --as <you> --token <password>` · `toolroll lead say "<text>" [--task <id>]` with the lead token',EXIT.usage);for(const name of flags.keys())if(!["as","token","revoke","db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a lead token option.`,EXIT.usage);if(currentActor()?.lead===!0)return fail(write,json,command,"refused","A lead cannot mint lead tokens. The person it acts for runs this with their password.",EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:flags.has("revoke")?authenticateApprover(store,acting.name,acting.token):credentialApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return fail(write,json,command,"unauthenticated","A lead token is minted behind your password: pass --as and --token (or use the remembered login).",EXIT.refused);const now=context.clock();if(flags.has("revoke")){const ended=store.revokeLeadCredentials(acting.name,acting.name,now);return succeed(write,json,command,{owner:acting.name,revoked:ended},()=>[ended===0?"You had no lead token.":"Your lead token no longer works."])}const minted=store.mintLeadCredential(acting.name,acting.name,now);return succeed(write,json,command,{owner:acting.name,id:minted.id,token:minted.token,actor:`lead for ${acting.name}`},()=>[minted.token,`Lead for ${acting.name}. Shown once; it replaces any earlier lead token.`,"Your lead passes it as --token <it> (or TOOLROLL_LEAD_TOKEN) on task and assignment commands. Its own work pings nobody;","it reaches you when the lead asks you (task ask), when it fails with nothing left to try, or for a security alert."])}function leadSayCommand(positional,flags,context){const{store,write,json}=context,command="lead say";for(const name of flags.keys())if(!["task","db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a lead say option.`,EXIT.usage);const task=flags.get("task");if(positional.length===0||task===!0)return fail(write,json,command,"usage",'`toolroll lead say "<what you\'re doing>" [--task <id>]` with the lead token',EXIT.usage);const actor=currentActor();if(actor?.lead!==!0)return fail(write,json,command,"unauthenticated","Only the lead speaks as the lead: pass its lead token (--token or TOOLROLL_LEAD_TOKEN).",EXIT.refused);const said=leadSay(store,actor,positional.join(" "),task??null,context.clock());return said.ok?succeed(write,json,command,{owner:actor.account,task:task??null,joined:said.joined,notification:said.notification},()=>[said.joined?`Added to your last message to ${actor.account}.`:`Told ${actor.account}.`]):fail(write,json,command,said.reason,said.message,said.reason==="usage"?EXIT.usage:EXIT.refused)}function leadClaimCommand(positional,flags,context){const{store,write,json}=context,command="assignment claim";for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not an assignment claim option.`,EXIT.usage);const id=positional[1];if(id===void 0||positional.length!==2)return fail(write,json,command,"usage","assignment claim takes exactly one task id.",EXIT.usage);const actor=currentActor(),claimed=leadClaim(store,actor,id,context.clock());return claimed.ok?succeed(write,json,command,{task:id,root:claimed.root,lead:claimed.claim},()=>[`${id} is yours: it reads "${leadNameOf(store,actor.account)} is on it" until you complete it, hand it on with task ask, or go two hours without acting on it.`]):fail(write,json,command,claimed.reason,claimed.message,claimed.reason==="usage"?EXIT.usage:EXIT.refused)}function blockTask(positional,flags,context){const{store,write,json}=context,id=positional[0],on=text(flags,"on");if(id===void 0||on===void 0)return fail(write,json,"task block","usage","`toolroll task block <id> --on <id>`",EXIT.usage);for(const each of[id,on])if(store.getTask(each)===null)return fail(write,json,"task block","unknown-task",`no task \`${each}\``,EXIT.refused);const result=store.addEdge(id,on,mutationFrom(flags,context.now));return result.ok?succeed(write,json,"task block",{blocked:id,blocker:on},()=>[`${id} now waits for ${on}.`]):fail(write,json,"task block","rejected",result.reason,EXIT.refused)}async function steerTask(positional,flags,context){const{store,write,json}=context,id=positional[0],note=text(flags,"note");if(id===void 0||note===void 0)return fail(write,json,"task steer","usage","`toolroll task steer <id> --note \"...\" --as <you> --token <t>` — steering speaks with the operator's voice, so it takes your credential; a running build's agent reads the note when it next checks for notes, otherwise the next attempt's brief quotes it, fenced, inside the approved scope",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"task steer","usage","steering takes `--as <you> --token <t>` — anonymous notes never reach an agent's brief",EXIT.usage);if(!authenticateApprover(store,acting.name,acting.token).ok)return fail(write,json,"task steer","not-an-approver","that is not an approver, or the token does not match",EXIT.refused);if(flags.get("now")===!0)return pauseRunningBuild("task steer",id,note,verifiedAuthor(acting.name),flags,context);const filed=store.fileSteerNote(id,verifiedAuthor(acting.name),note,context.now,mutationFrom(flags,context.now));if(!filed.ok){const detail=filed.reason==="unknown-task"?`no task \`${id}\``:filed.reason==="task-finished"?`${id} is finished — a note has no next attempt to reach`:filed.problem??"that note will not store";return fail(write,json,"task steer",filed.reason,detail,EXIT.refused)}const steered=store.lookupRef(id),live=steered!==null&&store.steeringLiveBuild(steered.id,context.now)!==null,liveInput=steered!==null&&store.liveInputRun(steered.id,context.now)!==null;return succeed(write,json,"task steer",{task:id,note:filed.id,standing:live?"waiting":"next-attempt"},()=>[`Noted. ${steerDestinationWords(live,liveInput)} \`task show ${id}\` says when it has been read.`])}async function pauseTask(positional,flags,context){const{store,write,json}=context,id=positional[0];if(id===void 0)return fail(write,json,"task pause","usage","`toolroll task pause <id> [--run <run-id>] --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context);return acting===null?fail(write,json,"task pause","usage","pausing takes `--as <you> --token <t>` — it is an approver's act and is recorded against your name",EXIT.usage):authenticateApprover(store,acting.name,acting.token).ok?pauseRunningBuild("task pause",id,void 0,verifiedAuthor(acting.name),flags,context):fail(write,json,"task pause","not-an-approver","that is not an approver, or the token does not match",EXIT.refused)}async function continueTask(positional,flags,context){const{store,write,json}=context,id=positional[0];if(id===void 0)return fail(write,json,"task continue","usage","`toolroll task continue <id> [--run <run-id>] --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"task continue","usage","resuming takes `--as <you> --token <t>` — it is an approver's act and is recorded against your name",EXIT.usage);if(!authenticateApprover(store,acting.name,acting.token).ok)return fail(write,json,"task continue","not-an-approver","that is not an approver, or the token does not match",EXIT.refused);const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null)return fail(write,json,"task continue","unknown-task",`no task \`${id}\``,EXIT.refused);const runText=text(flags,"run"),named=runText===void 0?store.liveInputRun(ref.id,context.now):Number(runText);if(named===null)return fail(write,json,"task continue","not-live",`${id} has no running Claude build to resume`,EXIT.refused);if(!Number.isInteger(named)||named<1)return fail(write,json,"task continue","usage","--run names one exact attempt by its number",EXIT.usage);const requestId=text(flags,"request")??text(flags,"key")??`cli-${randomUUID()}`,asked=store.requestResume({taskId:id,runId:named,by:verifiedAuthor(acting.name),via:"cli",requestId},context.now);return asked.ok?succeed(write,json,"task continue",{task:id,run:named,resume:asked.resume,repeated:asked.duplicate},()=>[asked.duplicate?`Build #${named} of ${id} was already asked to resume with that request; nothing changed.`:`Resuming build #${named} of ${id} where it stopped.`]):fail(write,json,"task continue",asked.reason,asked.detail,EXIT.refused,{run:named})}function pauseRunningBuild(command,id,note,by,flags,context){const{store,write,json}=context,ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null)return fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused);const runText=text(flags,"run"),named=runText===void 0?store.liveInputRun(ref.id,context.now):Number(runText);if(named===null)return fail(write,json,command,"not-live",note===void 0?`${id} has no running Claude build to pause`:`${id} has no running Claude build to pause; send the note without --now`,EXIT.refused);if(!Number.isInteger(named)||named<1)return fail(write,json,command,"usage","--run names one exact attempt by its number",EXIT.usage);const requestId=text(flags,"request")??text(flags,"key")??`cli-${randomUUID()}`,asked=store.requestPause({taskId:id,runId:named,by,via:"cli",requestId,...note===void 0?{}:{note}},context.now);return asked.ok?succeed(write,json,command,{task:id,run:named,pause:asked.pause,note:asked.note,repeated:asked.duplicate},()=>[asked.duplicate?`Build #${named} of ${id} was already asked to pause with that request; nothing changed.`:note===void 0?`Pausing build #${named} of ${id}. Its next note continues it; \`task stop\` ends it.`:`Pausing build #${named} of ${id}, then sending your note. \`task show ${id}\` says when it has been read.`]):fail(write,json,command,asked.reason,asked.detail,EXIT.refused,{run:named})}function unblockTask(positional,flags,context){const{store,write,json}=context,id=positional[0],on=text(flags,"on");return id===void 0||on===void 0?fail(write,json,"task unblock","usage","`toolroll task unblock <id> --on <id>`",EXIT.usage):store.getTask(id)===null?fail(write,json,"task unblock","unknown-task",`no task \`${id}\``,EXIT.refused):store.removeEdge(id,on,mutationFrom(flags,context.now)).ok?succeed(write,json,"task unblock",{blocked:id,blocker:on},()=>[`${id} no longer waits for ${on}.`]):fail(write,json,"task unblock","not-waiting",`${id} was not waiting on ${on}`,EXIT.refused)}function nextTask(positional,flags,context){const{store,write,json}=context,id=positional[0];if(id===void 0)return fail(write,json,"task next","usage","`toolroll task next <id> [--undo]`",EXIT.usage);if(flags.has("undo"))return store.clearTaskPriority(id,mutationFrom(flags,context.now)).ok?succeed(write,json,"task next",{task:id,priority:0},()=>[`${id} is back in filing order.`]):fail(write,json,"task next","unknown-task",`no task \`${id}\``,EXIT.refused);const moved=store.moveTaskNext(id,context.clock(),mutationFrom(flags,context.now));if(!moved.ok){const message=moved.reason==="unknown-task"?`no task \`${id}\``:moved.reason==="not-queued"?`${id} is not queued — only queued work can move up`:moved.reason==="claimed"?`${id} is being built right now — it needs no place in line`:"the queue rank could not be raised any further";return fail(write,json,"task next",moved.reason,message,EXIT.refused)}return succeed(write,json,"task next",{task:id,priority:moved.priority},()=>[`${id} moved to the front of its queue — a worker takes its own reserved work first, then the shared queue (approval still required).`])}function assignTask(positional,flags,context){const{store,write,json}=context,id=positional[0],runner=text(flags,"runner"),anyone=flags.has("anyone");if(id===void 0||runner===void 0&&!anyone||runner!==void 0&&anyone)return fail(write,json,"task assign","usage","`toolroll task assign <id> --runner <name> | --anyone`",EXIT.usage);const moved=store.moveTask({taskId:id,toRunner:runner??null,beforeTaskId:null},context.clock(),mutationFrom(flags,context.now));if(!moved.ok){const message=moved.reason==="unknown-task"?`no task \`${id}\``:moved.reason==="not-queued"?`${id} is not queued — only queued work can be reserved`:moved.reason==="claimed"?`${id} is being built right now — it needs no reservation`:moved.reason==="no-such-worker"?`no worker named \`${runner}\` — \`toolroll runner list\` names them`:moved.reason==="worker-retired"?`${runner} is retired — register the name again, or reserve for another worker`:"the queue did not accept the move";return fail(write,json,"task assign",moved.reason,message,EXIT.refused)}return succeed(write,json,"task assign",{task:id,reservedFor:runner??null},()=>[runner===void 0?`${id} is back in the shared queue — any free worker takes it.`:`${id} is reserved for ${runner}, at the back of that worker's queue — only that worker takes it.`])}async function reopenTask(positional,flags,context){const{store,write,json}=context,id=positional[0];if(id===void 0)return fail(write,json,"task reopen","usage","`toolroll task reopen <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"task reopen","usage","reopening takes `--as <you> --token <t>` — who resumed external work is recorded, not asserted",EXIT.usage);const reopened=store.reopenMirror(id,acting.name,context.clock());if(!reopened.ok){const said={"unknown-task":`no external task \`${id}\``,"not-latched":`${id} was never closed on its tracker — there is nothing to reopen`,"not-seen-open":"the tracker has not been SEEN open again since the close — reopen it there, then `toolroll sync`",claimed:`${id} is being built right now`,held:"a hold stands — lift it first (`task unhold`, or wait out the timer)","question-open":"an unanswered question stands — answer or close it first (it is on the task page)","incident-open":"an unresolved incident stands — resolve it first","bad-state":`${id} is not in a state reopen can take (it may already be done)`};return fail(write,json,"task reopen",reopened.reason,said[reopened.reason]??"the mirror could not be reopened",EXIT.refused)}return succeed(write,json,"task reopen",{task:id,by:acting.name},()=>[`${id} is queued again — the tracker was seen open, the approved scope stands, and the next pass may take it.`])}async function syncCommand(flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"sync");if(demoFence!==null)return demoFence;const only=text(flags,"repo"),grants=store.listGrants().filter(grant=>grant.dispatch===!0&&grant.remoteRepo!=null).filter(grant=>only===void 0||grant.repo===resolve(only));if(grants.length===0)return fail(write,json,"sync","no-grant","no tracker has a dispatch grant — `toolroll enroll <repo> --backend github-issues --github <owner/name> --allow-dispatch` states the terms",EXIT.refused);const adapter=ghDispatchAdapter(),reports=[];for(const grant of grants)reports.push(await syncPass(store,grant,adapter,context.clock));const failed=reports.filter(one=>one.outcome==="failed"||one.outcome==="blocked");if(json)return write(envelopeJson({ok:failed.length===0,command:"sync",...failed.length===0?{}:{reason:"sync-failed",message:failed[0]?.detail??"a pass failed"},reports})),failed.length===0?EXIT.ok:EXIT.failed;for(const report of reports)write(`${report.remoteRepo} ${report.outcome}${report.outcome==="complete"||report.outcome==="capped"?` — ${report.candidates} open, ${report.mirrored} newly mirrored, ${report.latched} closed there, ${report.delivered} write-back(s) delivered`:""}${report.detail===null?"":` (${report.detail})`}`);return failed.length>0?(write("A failed or blocked pass advances nothing — external work keeps its last verified state and will not dispatch past its freshness window."),EXIT.failed):EXIT.ok}async function scopeTask(positional,flags,context){const{store,write,json,now}=context,id=positional[0],goal=text(flags,"goal");if(id===void 0||goal===void 0)return fail(write,json,"task scope","usage","`toolroll task scope <id> --goal <what success is> --acceptance <rubric> [--not <text>] [--touches a,b] [--candidate <commit>] [--budget-usd <n>]`",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task scope","unknown-task",`no task \`${id}\``,EXIT.refused);if(store.filedViaOf(id)?.startsWith(FLEXIBLE_FILED_PREFIX)===!0)return fail(write,json,"task scope","flexible",FLEXIBLE_CANDIDATE_FIXED,EXIT.refused);const acceptanceGiven=text(flags,"acceptance");if(acceptanceGiven===void 0)return fail(write,json,"task scope","acceptance-required",'a scope needs at least one signed acceptance criterion — `--acceptance "<statement>|<evidence,kinds>"`, `;`-separated for more than one; evidence kinds are check, screenshot, changed-path, manual-review',EXIT.usage);const acceptanceParse=parseAcceptanceCriteria(acceptanceLinesToInput(splitAcceptanceRubric(acceptanceGiven)));if(acceptanceParse.problems.length>0)return fail(write,json,"task scope","bad-acceptance",`${acceptanceParse.problems.map(p=>p.message).join("; ")} — each criterion is \`<statement>|<evidence,kinds>\`, criteria are \`;\`-separated, and \`--acceptance plan\` asks the planner to write the rubric`,EXIT.usage);const candidateGiven=text(flags,"candidate");if(candidateGiven!==void 0&&!isCommitSha(candidateGiven))return fail(write,json,"task scope","usage","--candidate is the full 40-character commit hash the machine will check out",EXIT.usage);const releaseGiven=text(flags,"release");let releaseTerms,releaseCheck,releaseNote=null;const fromMain=flags.get("from-main")===!0;if((fromMain||flags.get("full-check")===!0)&&releaseGiven===void 0)return fail(write,json,"task scope","usage","--from-main and --full-check go with --release <version>:<pull request>:<branch>",EXIT.usage);if(flags.get("full-check")===!0&&!fromMain)return fail(write,json,"task scope","usage","--full-check goes with --from-main",EXIT.usage);if(releaseGiven!==void 0){const spec=/^(\d+\.\d+\.\d+):([1-9][0-9]*):([A-Za-z0-9._/-]+)$/.exec(releaseGiven);if(spec===null||candidateGiven===void 0)return fail(write,json,"task scope","usage","--release takes <version>:<pull request>:<branch>, with --candidate <commit>",EXIT.usage);const repo=store.lookupRef(id)?.repo??null;if(repo===null)return fail(write,json,"task scope","usage","a release scope's task has to be placed in its project first",EXIT.usage);if(fromMain){const purpose=releaseCheckPurposeFor(store,{repo,version:spec[1],pr:Number(spec[2]),branch:spec[3],candidate:candidateGiven,main:{check:flags.get("full-check")===!0?"full":"deploy"}});if(!purpose.ok)return fail(write,json,"task scope","refused",`This release from main can't be filed: ${purpose.why}.`,EXIT.refused);releaseCheck=purpose.purpose}}if(releaseGiven!==void 0&&candidateGiven!==void 0&&!fromMain){const spec=/^(\d+\.\d+\.\d+):([1-9][0-9]*):([A-Za-z0-9._/-]+)$/.exec(releaseGiven),repo=store.lookupRef(id).repo,made=releaseTermsFor(store,{repo,version:spec[1],pr:Number(spec[2]),branch:spec[3],candidate:candidateGiven,now,noCarry:flags.get("no-carry")===!0});if(made.ok)releaseTerms=made.terms;else{releaseNote=`Later commits on this release will each ask for approval: ${made.why}.`;const purpose=releaseCheckPurposeFor(store,{repo,version:spec[1],pr:Number(spec[2]),branch:spec[3],candidate:candidateGiven});purpose.ok&&(releaseCheck=purpose.purpose)}}if(acceptanceParse.criteria.length===0)return fail(write,json,"task scope","acceptance-required","--acceptance named no valid criteria",EXIT.usage);const touches=(text(flags,"touches")??"").split(",").map(one=>one.trim()).filter(Boolean),badText=validateScopeText({goal,outOfScope:text(flags,"not")??null,touches});if(badText!==null)return fail(write,json,"task scope",badText.reason,badText.message,EXIT.usage);const budgetGiven=text(flags,"budget-usd"),defaults=store.getSpendDefaults(),budgetUsd=budgetGiven!==void 0?Number(budgetGiven):defaults?.buildPerRunMicrousd!=null?defaults.buildPerRunMicrousd/1e6:null;if(budgetGiven!==void 0&&(!Number.isFinite(Number(budgetGiven))||Number(budgetGiven)<=0))return fail(write,json,"task scope","bad-budget","--budget-usd is a positive dollar amount",EXIT.usage);const routingAsked=text(flags,"provider")!==void 0||text(flags,"model")!==void 0||text(flags,"repair-model")!==void 0;let explicitProfile;if(routingAsked){const scopeRef=store.lookupRef(id),resolvedRouting=resolveScopeProfile(store,scopeRef?.repo??null,scopeRef===null?void 0:{agentProvider:scopeRef.agentProvider,agentModel:scopeRef.agentModel},{provider:text(flags,"provider"),model:text(flags,"model"),repairModel:text(flags,"repair-model")});if(!resolvedRouting.ok)return fail(write,json,"task scope",resolvedRouting.reason,resolvedRouting.problem,EXIT.usage);explicitProfile=resolvedRouting.profile}const{name:asGiven,token:tokenGiven}=credentialsFrom(flags,context),actor=asGiven!==void 0&&tokenGiven!==void 0&&authenticateApprover(store,asGiven,tokenGiven).ok?asGiven:null;let refinement=null;store.replay(mutationFrom(flags,now),"task-scope-filed",()=>{const ref=store.lookupRef(id),previous=store.getScope(id);if(ref===null||ref.deliverable==="report"||candidateGiven!==void 0||ref.sizing?.source==="person"||approvalOf(previous).approved||previous?.proposedVia==="coordinator"||store.filedViaOf(id)?.startsWith("mcp:"))return null;const input={title:store.getTask(id).title,goal,outOfScope:text(flags,"not")??null,touches};return store.applySizing(id,filingSizing(store,input),{followPlanning:!0},now).ok&&(refinement=refineFiledSizing(store,id,input,!0,context.clock)),null},()=>!1),await refinement;const generationBefore=store.lookupRef(id)?.planningGeneration??0,filed=store.replay(mutationFrom(flags,now),"task-scope-filed",()=>store.transact(()=>{const coverage=actor!==null?modeFilingCoverage(store,store.refFor(BUILT_IN,id).repo,actor,now):null,proposed=propose(store,{...candidateGiven===void 0?{}:{candidate:candidateGiven},...releaseTerms===void 0?{}:{releaseTerms,releaseCheck:null},...releaseCheck===void 0?{}:{releaseCheck,releaseTerms:null},taskId:id,goal,outOfScope:text(flags,"not")??null,touches,acceptance:acceptanceParse.criteria,...budgetUsd!==null?{budgetMicrousd:Math.round(budgetUsd*1e6)}:coverage?.defaultBudgetMicrousd!=null?{budgetMicrousd:coverage.defaultBudgetMicrousd}:{},...explicitProfile===void 0?{}:{profile:explicitProfile},...coverage?.escalated===!0?{posture:"escalated"}:{},now});let sealedUnderMode=!1,modeRefusedCoordinator=!1;if(coverage!==null&&rubricIsPlaceholder(proposed.acceptance)&&store.lookupRef(id)?.plan==null){const mode=store.activeMode(store.lookupRef(id)?.repo??"",now);(mode===null?null:modeTermsFromJson(mode.termsJson))?.planAuto===!0&&store.requestPlan(store.refFor(BUILT_IN,id).id,now)}return coverage!==null&&store.lookupRef(id)?.plan==="requested"?authorizePlanUnderMode(store,id,actor,now):coverage!==null&&proposed.profileState==="resolved"&&(sealedUnderMode=store.sealScopeApproval(id,actor,now,{},{kind:"mode",modeDigest:coverage.digest}),modeRefusedCoordinator=!sealedUnderMode),{ok:!0,scope:proposed,sealedUnderMode,modeRefusedCoordinator}}));if(!filed.ok)return fail(write,json,"task scope",filed.reason,filed.message,EXIT.refused);const scope=filed.scope;if(filed.modeRefusedCoordinator===!0)return succeed(write,json,"task scope",{scope,approvedUnderMode:!1,quarantined:!0},()=>[`Scope written for ${id} — but coordinator-filed: mode coverage cannot admit it; sign the scope.`,...describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now))]);if(filed.sealedUnderMode)return succeed(write,json,"task scope",{scope,approvedUnderMode:!0},()=>[`Scope written AND approved for ${id} — your operating mode covered it; it dispatches on the next pass.`,...describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now))]);const replanned=(store.lookupRef(id)?.planningGeneration??0)>generationBefore;return succeed(write,json,"task scope",{scope,...replanned?{planningRestarted:!0}:{},...releaseNote===null?{}:{releaseNote}},()=>[...releaseNote===null?[]:[releaseNote],replanned?`Scope written for ${id}. The scope changed, so planning starts again; nothing builds until somebody approves the new plan.`:`Scope written for ${id}. Nothing will build it until somebody approves it.`,...describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now)),"",` toolroll task approve ${id} --yes`])}async function routeTaskCommand(positional,flags,context){const{store,write,json,clock}=context,id=positional[0];if(id===void 0)return fail(write,json,"task route","usage","`toolroll task route <id> [--size <s>] [--risky yes|no] [--phase <p> --provider <p> --model <m> | --clear-phase <p>] [--digest <d>] --as <you> --token <t>`",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task route","unknown-task",`no task \`${id}\``,EXIT.refused);const ref=store.refFor(BUILT_IN,id),phaseGiven=text(flags,"phase"),clearGiven=text(flags,"clear-phase"),providerGiven=text(flags,"provider"),modelGiven=text(flags,"model"),digestGiven=text(flags,"digest"),sizeGiven=text(flags,"size"),riskyGiven=text(flags,"risky"),editing=phaseGiven!==void 0||clearGiven!==void 0||sizeGiven!==void 0||riskyGiven!==void 0,show=()=>{const scope=store.getScope(id),current=store.refFor(BUILT_IN,id),routed=routeOfTask(store,id,current,clock()),readiness=store.readinessLookupFor(ref.repo,ref.assignedRunner,clock()),view=taskRouteView(routed,readiness),projection=routed!==null&&routed.kind==="route"?projectRoute(routed.route,readiness):null;return succeed(write,json,"task route",{id,size:current.sizing??null,source:routed!==null&&routed.kind==="route"?routed.source:routed?.kind??null,route:view,overrides:current.routeOverrides??[],digest:scope?.digest??null,approval:approvalOf(scope)},()=>routed===null?[`${id}: no route can be recommended yet — ${scope===null?"place the task in a repository and file a scope":scope.unresolvedReason??"the phase configuration cannot resolve"}`]:[...projection===null?taskRouteStandingLines(id,routed):[`${id}: route ${routed.kind==="route"&&routed.source==="approved"?"SEALED by the approval":routed.kind==="route"&&routed.source==="proposed"?"proposed — the next approval seals it":"recommended live — no scope filed yet"}`,...routeWords(projection),...projection.legs.some(leg=>leg.reasons.some(reason=>reason.startsWith("no stronger")))?[" name a stronger agent once with `config set <phase> --tier strong --provider … --model …`"]:[]],...scope===null?[]:(()=>{const approval=approvalOf(scope);return[...scope.unresolvedReason===null||scope.unresolvedReason===void 0?[]:[` unresolved ${scope.unresolvedReason}`],` reference ${scope.digest}`,` approved ${approval.approved?`yes, by ${approval.by}`:approval.reason==="changed"?"no — approved once, then the terms changed; approve again":"no"}`]})()])};if(!editing)return show();const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"task route","usage","changing a route takes `--as <you> --token <t>` — it reroutes spend",EXIT.usage);if(sizeGiven!==void 0&&!isTaskSize(sizeGiven))return fail(write,json,"task route","usage",`--size is one of ${TASK_SIZES.join(", ")}`,EXIT.usage);if(riskyGiven!==void 0&&riskyGiven!=="yes"&&riskyGiven!=="no")return fail(write,json,"task route","usage","--risky is yes or no",EXIT.usage);const sizeEdit=sizeGiven===void 0&&riskyGiven===void 0?void 0:{size:sizeGiven??ref.sizing?.size??"medium",risky:riskyGiven===void 0?ref.sizing?.risky??!1:riskyGiven==="yes"};if(phaseGiven!==void 0&&clearGiven!==void 0)return fail(write,json,"task route","usage","say --phase … --provider … --model … OR --clear-phase …, not both",EXIT.usage);const phase=phaseGiven??clearGiven;if(phase!==void 0&&!ROUTE_PHASES.includes(phase))return fail(write,json,"task route","usage",`--${phaseGiven!==void 0?"phase":"clear-phase"} is one of ${ROUTE_PHASES.join(", ")}`,EXIT.usage);if(phaseGiven==="review")return fail(write,json,"task route","model-review-retired","Separate model review has been removed; no reviewer route is needed.",EXIT.refused);if(phaseGiven!==void 0){if(providerGiven===void 0||!isProviderId(providerGiven))return fail(write,json,"task route","usage",`--provider is one of ${PROVIDER_IDS.join(", ")}`,EXIT.usage);if(modelGiven===void 0||modelGiven==="")return fail(write,json,"task route","usage","an override names an exact --model — approvals bind exact routing",EXIT.usage);const valid=validateSpec({provider:providerGiven,model:modelGiven});if(!valid.ok)return fail(write,json,"task route","invalid",valid.problem,EXIT.usage)}const edited=store.editTaskRoute(ref.id,{by:acting.name,authenticate:()=>{const authenticated=authenticateApprover(store,acting.name,acting.token);return authenticated.ok?{ok:!0}:{ok:!1,reason:authenticated.reason}},...sizeEdit===void 0?{}:{size:sizeEdit},...phase===void 0?{}:{override:phaseGiven!==void 0?{phase,provider:providerGiven,model:modelGiven}:{phase,clear:!0}},...digestGiven===void 0?{}:{expectDigest:digestGiven==="none"?null:digestGiven}},clock());if(!edited.ok)return edited.reason==="unauthenticated"?fail(write,json,"task route",edited.detail,describeApproveFailure(edited.detail,id),EXIT.refused):fail(write,json,"task route",{"no-task":"unknown-task","live-claim":"claimed",changed:"changed",nothing:"usage","not-configured":"not-configured"}[edited.reason],`${id}: ${edited.detail}`,edited.reason==="nothing"?EXIT.usage:EXIT.refused);const code=show();return json||(edited.staled&&write(` ! the approval sealed under the previous route is now stale — approve ${id} again to seal this one`),edited.replanned&&write(" ! the planner changed after a draft landed — a new planner run was requested; approval waits for its draft")),code}async function approveTask(positional,flags,context){const{store,write,json,now}=context,id=positional[0];if(id===void 0)return fail(write,json,"task approve","usage","which task?",EXIT.usage);if(passwordFreeShell(store))return fail(write,json,"task approve","local-owner",passwordFreeShellWords("a",shellCallerFacts(context)),EXIT.refused);const scope=store.getScope(id);if(scope===null)return fail(write,json,"task approve","no-scope",`${id} has no scope to approve — write one first`,EXIT.refused);if(store.lookupRef(id)?.plan==="requested")return fail(write,json,"task approve","planning",`${id} is waiting on a planner — approval is blocked until the drafted plan lands`,EXIT.refused);let saw=text(flags,"digest");const summary=approvalSummaryOf(scope,summaryContextOf(store,id,scope,now));let shownTerms=text(flags,"terms"),{name:asWho,token}=credentialsFrom(flags,context),confirmedAloud=!1;if((!flags.has("yes")||saw===void 0||asWho===void 0||token===void 0)&&interactive()&&!json){write(`Approving lets a builder work on ${id}, within exactly this:`),write("");const changed=routeChangeOf(store,id);changed!==null&&(write(changed),write(""));for(const line of describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now)))write(line);for(const line of planContractLines(store,context.evidenceRoot,id))write(line);if(write(""),!await confirm("Approve exactly this?"))return write("Nothing approved."),EXIT.refused;saw??=scope.digest,shownTerms??=summary.key;const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"task approve","usage","approval needs who is agreeing",EXIT.usage);asWho=acting.name,token=acting.token,confirmedAloud=!0}if(!((flags.has("yes")||confirmedAloud)&&saw!==void 0&&asWho!==void 0&&token!==void 0)){if(json)return write(envelopeJson({ok:!1,command:"task approve",reason:"unconfirmed",scope,terms:summary.key})),EXIT.refused;write(`Would approve this, and let a builder work on ${id}:`),write("");const changed=routeChangeOf(store,id);changed!==null&&(write(changed),write(""));for(const line of describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now)))write(line);for(const line of planContractLines(store,context.evidenceRoot,id))write(line);return write(""),write("Nothing has been approved. Agree to this exact scope with:"),write(` toolroll task approve ${id} --yes --digest ${scope.digest} --terms ${summary.key} --as <you> --token <your password>`),EXIT.refused}if(saw===void 0||asWho===void 0||token===void 0)return fail(write,json,"task approve","usage","approving non-interactively takes --yes --digest <d> --terms <key> --as <you> --token <t>",EXIT.usage);if(shownTerms===void 0){if(json)return write(envelopeJson({ok:!1,command:"task approve",reason:"unconfirmed",message:"Name the terms you read: --terms <key>. Nothing was approved.",scope,terms:summary.key})),EXIT.refused;write(`Name the terms you read. Nothing was approved. ${id} would be approved on exactly this:`),write("");for(const line of describeScope(scope,void 0,null,summaryContextOf(store,id,scope,now)))write(line);return write(""),write(` toolroll task approve ${id} --yes --digest ${scope.digest} --terms ${summary.key} --as <you> --token <your password>`),EXIT.refused}const terms=shownTerms,approved=store.transact(()=>terms!==void 0&&approvalSummaryFor(store,id,now)?.key!==terms?{ok:!1,reason:"changed"}:approve(store,id,asWho,now,saw,token,mutationFrom(flags,now)));return approved.ok?succeed(write,json,"task approve",{scope:approved.scope},()=>[`Approved. A builder may now work on ${id}, within this scope:`,...describeScope(approved.scope,void 0,null,summaryContextOf(store,id,approved.scope,now))]):approved.reason==="policy"?fail(write,json,"task approve","policy",`${id}: ${approved.message}`,EXIT.refused):fail(write,json,"task approve",approved.reason,describeApproveFailure(approved.reason,id),EXIT.refused)}function describeApproveFailure(reason,id){return reason==="changed"?"the scope changed since you read it — look again before approving":reason==="requester"?`you filed ${id}, and this project needs someone else to approve it`:reason==="person-required"?`${id} is protected work: a person has to approve it, not an operating mode, a schedule or a subagent`:reason==="machine-proof"?"only a person can approve this — approve it on the task page or from your paired chat":reason==="archived"?`${id} is put away — restore it with \`toolroll task restore ${id}\` first`:reason==="cancelled"?`${id} was cancelled, so there is nothing to approve`:reason==="second-approver"?`your approval of ${id} is recorded; it is protected work, so a second person needs to approve it (toolroll task approve ${id} as them)`:reason==="no-approvers"?"nobody can approve anything yet — `toolroll approver add <you>` mints the credential that lets a person say yes":reason==="not-an-approver"?"that is not an approver, or the token does not match":reason==="unrouted"?`${id} was filed before agent routing and its old approval no longer stands — an approval now names exactly which agent plans, builds, repairs, and reviews: file the scope again (\`task scope ${id} …\`) so it is routed under today's agents, then approve it`:reason==="profile-unresolved"?`${id} cannot name an exact agent for every role — configure the project's agents (\`config set <phase> --provider … --model …\`), then file the scope again (\`task scope ${id} …\`) and approve it`:`${id} has no scope to approve`}export const PROPOSALS_ACTIONS=["list","confirm","dismiss"];async function proposalsCommand(positional,flags,context){const{store,write,json,now}=context,[action="list",idGiven]=positional;if(!PROPOSALS_ACTIONS.includes(action))return fail(write,json,"proposals","usage",`unknown \`proposals ${action}\` — try ${PROPOSALS_ACTIONS.join(", ")}`,EXIT.usage);store.sweepCoordinatorProposals(now);let repos;if(context.repoList!==void 0&&context.repoList.length>0)repos=context.repoList;else{const loaded=await loadRepos(join(dirname(context.databaseFile),"repos.json")).catch(()=>({error:"unreadable"}));if("error"in loaded)return fail(write,json,`proposals ${action}`,"registry","the enrolled-project registry could not be read — name projects with --repo",EXIT.refused);repos=loaded.repos}if(action==="list"){const rows=store.listCoordinatorProposals({repos,states:flags.has("all")?["pending","confirming","confirmed","refused","dismissed","expired"]:["pending"]});return succeed(write,json,"proposals list",{proposals:rows.map(one=>({id:one.id,kind:one.kind,by:one.name,repo:one.repo,state:one.state,payload:one.payload,outcome:one.outcome,createdAt:one.createdAt}))},()=>rows.length===0?["No coordinator proposals are pending."]:rows.map(one=>{const t=key=>typeof one.payload[key]=="string"?one.payload[key]:"",what=one.kind==="answer"?`answer decision #${String(one.payload.decision)} on ${t("task")} with "${t("optionLabel")}"${one.payload.reversible===!1?" (irreversible — confirm with --yes)":""}: ${t("rationale")}`:one.kind==="next"?`move ${t("task")} to the front`:one.kind==="reserve"?`${one.payload.worker===null?`release ${t("task")} to the shared queue`:`reserve ${t("task")} for ${t("worker")}`}`:one.kind==="hold"?`hold ${t("task")}: ${t("reason")}`:one.kind==="unhold"?`release ${t("task")} from its hold`:one.kind==="scope"?`rewrite the scope of ${t("task")}`:`cancel ${t("task")}: ${t("reason")} (arm it yourself: toolroll task cancel ${t("task")})`,head=` #${one.id} ${what} — by ${one.name} in ${projectName(one.repo)} [${one.state}]`;return one.kind==="answer"?[head,...answerContextLines(store,one.payload)].join(`
483
500
  `):head}))}const id=Number(idGiven);if(idGiven===void 0||!Number.isInteger(id)||id<1)return fail(write,json,`proposals ${action}`,"usage",`which proposal? toolroll proposals ${action} <id>`,EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`proposals ${action}`,"usage","confirming or dismissing takes your name and password — `--as <you>` and the hidden prompt",EXIT.usage);const admitted=repos.length===0?[]:repos,verified=verifyApproverByPassword(store,acting.name,acting.token,admitted);if(!verified.ok)return fail(write,json,`proposals ${action}`,"unauthenticated","that is not an approver, or the password does not match",EXIT.refused);if(action==="dismiss")return dismissCoordinatorProposal(store,verified.who,id,now)?succeed(write,json,"proposals dismiss",{proposal:id},()=>[`dismissed #${id}`]):fail(write,json,"proposals dismiss","not-pending","no pending proposal by that id in your projects",EXIT.refused);const row=store.getCoordinatorProposal(id);if(row!==null&&row.kind==="answer"&&!json)for(const line of answerContextLines(store,row.payload))write(line);const outcome=confirmCoordinatorProposal(store,verified.who,id,now,{authority:currentLocalOwner()===null?"full":"local-owner",confirm:flags.has("yes"),via:"cli"});return outcome.ok?succeed(write,json,"proposals confirm",{proposal:id,kind:outcome.kind,said:outcome.said,...outcome.taskId===null?{}:{task:outcome.taskId}},()=>[outcome.said,...outcome.kind==="scope"&&outcome.taskId!==null?[passwordFreeOwner(store)?`approve it in \`toolroll\`: press a on ${outcome.taskId}`:`approve it with your password: toolroll task approve ${outcome.taskId}`]:[]]):fail(write,json,"proposals confirm",outcome.reason,outcome.reason==="needs-confirm"?`${outcome.said} — read the consequences above, then pass --yes`:outcome.said,EXIT.refused)}async function chatCommand(flags,context){const{store,write,json}=context;if(flags.has("follow")&&flags.has("no-follow"))return fail(write,json,"chat","usage","Choose --follow or --no-follow.",EXIT.usage);const credentials=await askCredentials(flags,context);if(credentials===null)return fail(write,json,"chat","usage","the lead takes your name and password — `--as <you>` and the hidden prompt; `--token <t>` only where a script must (it lands in shell history)",EXIT.usage);const ceilingGiven=text(flags,"ceiling-usd");let repos;if(context.repoList!==void 0&&context.repoList.length>0)repos=context.repoList;else{const loaded=await loadRepos(join(dirname(context.databaseFile),"repos.json")).catch(()=>({error:"unreadable"}));if("error"in loaded)return fail(write,json,"chat","registry","the enrolled-project registry could not be read — name projects with --repo",EXIT.refused);repos=loaded.repos}return(await runLeadCli({store,databaseFile:context.databaseFile,write,json,credentials,repos,say:text(flags,"say"),end:flags.has("end"),...flags.has("follow")||flags.has("no-follow")?{follow:flags.has("follow")&&!flags.has("no-follow")}:{},ceilingUsd:ceilingGiven===void 0?void 0:Number(ceilingGiven),...context.leadSeams===void 0?{}:{seams:{...context.leadSeams,clock:context.leadSeams.clock??context.clock}},...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot},appOrigin:[loadConsoleUrl(process.env,dirname(context.databaseFile)),phoneOrigin(process.env,dirname(context.databaseFile))],...context.leadSeams===void 0&&liveTerminalWanted(json,process.env,process.stdout.isTTY===!0,()=>underAgent(process.env))?{liveTerminal:processTerminal()}:{}})).code}function credentialsFrom(flags,context,allowRemembered=!0){const remote=activeRemote();if(remote!==null)return{name:remote.account,token:remote.secret};const local=currentLocalOwner();if(local!==null)return{name:local.account,token:""};const lead=currentActor();if(context.leadToken!==void 0&&lead?.lead===!0)return{name:lead.account,token:context.leadToken};let name=text(flags,"as"),token=text(flags,"token");if(token===void 0&&allowRemembered){const remembered=readLoginFile(savedLoginFile(dirname(context.databaseFile)));if(remembered!==null&&(name===void 0||name===remembered.name)){name=remembered.name,token=remembered.password;const holder=rememberedLogin.getStore();holder!==void 0&&(holder.login={name,token})}}return{name,token}}async function askCredentials(flags,context,options={}){let{name,token}=credentialsFrom(flags,context,options.allowRemembered!==!1);const local=currentLocalOwner();if(local!==null)return{name:local.account,token:""};if(name===void 0&&token!==void 0&&activeRemote()===null&&(name=soloOperatorOf(context.store)??void 0),(name===void 0||token===void 0)&&interactive()&&!context.json){const usual=name===void 0?soloOperatorOf(context.store):null;if(name===void 0){const answered=await ask(usual===null?"username: ":`username [${usual}]: `);name=answered===""&&usual!==null?usual:answered}token??=await askHidden("password: ")}return name===void 0||token===void 0||name===""||token===""?null:{name,token}}function credentialApprover(store,by,token,repo){const proved=authenticateApprover(store,by,token,repo);return!proved.ok||credentialProof(proved.method)?proved:{ok:!1,reason:"not-an-approver"}}function authenticateApprover(store,by,token,repo){const remote=activeRemote();return remote!==null&&repo!==void 0&&!remote.allows(repo)?{ok:!1,reason:"not-an-approver"}:passwordApprover(store,by,token,repo)}function verifyApproverByPassword(store,name,token,repos){const remote=activeRemote();return approverByPassword(store,name,token,remote===null?repos:repos.filter(repo=>remote.allows(repo)))}async function readBoundedStdin(limit){if(refusePrompt(),process.stdin.isTTY)return null;const chunks=[];let size=0;for await(const chunk of process.stdin){const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(String(chunk));if(size+=bytes.length,size>limit)return process.stdin.pause(),null;chunks.push(bytes)}return Buffer.concat(chunks).toString("utf8")}function interactive(){return activeRemote()===null&&promptInteractive()}function refusePrompt(){if(activeRemote()!==null)throw new RemoteRefusal("unauthenticated",REMOTE_MESSAGES.credential)}async function ask(question){return refusePrompt(),promptAsk(question)}async function askHidden(question){return refusePrompt(),promptHidden(question)}async function confirm(question){return refusePrompt(),promptConfirm(question)}async function flowsCommand(positional,flags,context){const{store}=context,registered=await loadRepos(registryPathOf(context)).catch(()=>({error:"unreadable"})),remote=activeRemote(),projects=[...new Set([...store.knownRepos(),...store.listProjects().map(one=>one.path),..."error"in registered?[]:registered.repos])].filter(one=>remote===null||remote.allows(one)),acting=positional[0]!==void 0&&positional[0]!=="list"&&positional[0]!=="show"&&positional[0]!=="export"&&!flags.has("help")?await askCredentials(flags,context):null,dir=dirname(context.databaseFile);return runFlowsCommand(positional,flags,{store,write:context.write,json:context.json,clock:context.clock,credentials:acting,projects,configDir:dir,evidenceRoot:context.evidenceRoot,...remote===null?{}:{readInput:path=>remoteFile(remote,path)},...context.flowFetch===void 0?{}:{fetchFlow:context.flowFetch},triggerIo:{gh:context.flowTriggerIo?.gh??run,fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,shell:context.flowTriggerIo?.shell??context.flowStepIo?.shell??run,scratch:context.flowTriggerIo?.scratch??join(dir,"flow-scratch"),...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}}})}async function approverCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action!==void 0&&!APPROVER_ACTIONS.includes(action))return fail(write,json,"approver","usage",`unknown \`approver ${action}\` — try ${APPROVER_ACTIONS.join(", ")}`,EXIT.usage);if(action==="list"||action===void 0){const approvers=store.listApprovers();if(json)return write(envelopeJson({ok:!0,command:"approver list",approvers})),EXIT.ok;if(approvers.length===0)return write("Nobody can approve a scope yet, so nothing can be built."),write(" toolroll approver add <your name>"),EXIT.ok;for(const one of approvers)write(` ${one.name} since ${one.addedAt}`);return EXIT.ok}if(action==="add"){if(name===void 0)return fail(write,json,"approver add","usage","an approver needs a name",EXIT.usage);let password=text(flags,"password");const bootstrap=store.listApprovers().length===0;let by;if(!bootstrap){const vouched=await askCredentials(flags,context);vouched!==null&&(by=vouched)}if(password===void 0&&interactive()&&!json){const chosen=await askHidden(`password for ${name} (enter to auto-generate): `);if(chosen!==""){if(await askHidden("again: ")!==chosen)return fail(write,json,"approver add","mismatch","the two passwords did not match",EXIT.refused);password=chosen}}const added=addApprover(store,name,now,by,void 0,mutationFrom(flags,now),password);return added.ok?succeed(write,json,"approver add",{...added,...added.chosen?{token:"(chosen)"}:{}},()=>[`${added.name} may now sign in and approve scopes.`,"",...added.chosen?["Password set — stored salted and stretched, never readable again."]:[` password ${added.token}`,"","Shown once, stored only as a hash. Keep it somewhere an agent cannot read","(or choose your own next time: `approver add <name> --password <yours>`)."],...added.bootstrap?["","This was the first approver, so nothing had to vouch for it. Adding any","further approver now requires an existing one — do this before anything","else can reach this queue."]:[]]):fail(write,json,"approver add",added.reason,added.reason==="weak-password"?"a password needs at least 8 characters":"only an existing approver can add another — `--as <you> --token <your password>`",EXIT.refused)}return fail(write,json,"approver","usage",`unknown \`approver ${action}\` — try list or add`,EXIT.usage)}function holdTask(positional,flags,context){const{store,write,json,now}=context,id=positional[0],reason=text(flags,"reason");if(id===void 0||reason===void 0)return fail(write,json,"task hold","usage","`toolroll task hold <id> --reason <why>`",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task hold","unknown-task",`no task \`${id}\``,EXIT.refused);const untilText=text(flags,"until"),until=untilText===void 0?null:new Date(untilText);return until!==null&&Number.isNaN(until.getTime())?fail(write,json,"task hold","usage","--until takes a date, e.g. 2026-08-12T09:00:00Z",EXIT.usage):(store.hold(store.refFor(BUILT_IN,id).id,reason,until,now,mutationFrom(flags,now)),succeed(write,json,"task hold",{id,reason,until:until?.toISOString()??null},()=>[`${id} is on hold${until===null?"":` until ${until.toISOString()}`}: ${reason}`]))}function unholdTask(positional,flags,context){const{store,write,json}=context,id=positional[0];return id===void 0?fail(write,json,"task unhold","usage","which task?",EXIT.usage):store.getTask(id)===null?fail(write,json,"task unhold","unknown-task",`no task \`${id}\``,EXIT.refused):store.unhold(store.refFor(BUILT_IN,id).id,mutationFrom(flags,context.now))?succeed(write,json,"task unhold",{id},()=>[`${id} is off hold.`]):fail(write,json,"task unhold","not-held",`${id} was not on hold`,EXIT.refused)}async function stopTaskCommand(positional,flags,context){const{store,write,json,clock}=context,id=positional[0],runText=text(flags,"run"),runId=Number(runText??"");if(id===void 0||runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task stop","usage","`toolroll task stop <id> --run <run-id> --as <you> --token <t>` — the stop names one exact attempt",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task stop","unknown-task",`no task \`${id}\``,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task stop",verified,"stopping takes `--as <you> --token <t>` — it is an approver's act and is recorded against your name",id);const asked=requestTaskStop(store,{taskId:id,runId,by:acting.name,via:"cli"},clock());if(!asked.ok)return fail(write,json,"task stop",asked.reason,asked.detail,EXIT.refused,{run:runId});const control=taskControlOf(store,store.refFor(BUILT_IN,id).id,clock());return succeed(write,json,"task stop",{id,run:runId,requested:!asked.repeated,repeated:asked.repeated,terminated:asked.terminated,stop:asked.stop,control},()=>[asked.repeated?`Run #${runId} of ${id} was already asked to stop (by ${asked.stop.requestedBy} at ${asked.stop.requestedAt}); nothing changed.`:`Stop requested for run #${runId} of ${id}.`,asked.stop.settledAt===null?` It is stopping: its own processes are being ended${asked.terminated>0?` (${asked.terminated} process group${asked.terminated===1?"":"s"} signalled here)`:""}; \`task show ${id}\` reports when it has settled.`:` Settled (${asked.stop.settlement}).`," Its branch, uncommitted work, evidence, and decisions are preserved; the task stays paused until this exact attempt is resumed."])}async function resumeTaskCommand(positional,flags,context){const{store,write,json,clock}=context,id=positional[0],runText=text(flags,"run"),runId=Number(runText??"");if(id===void 0||runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task resume","usage","`toolroll task resume <id> --run <run-id> --as <you> --token <t>` — the resume names the exact stopped attempt",EXIT.usage);if(store.getTask(id)===null)return fail(write,json,"task resume","unknown-task",`no task \`${id}\``,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task resume",verified,"resuming takes `--as <you> --token <t>` — it lets the next pass spend again",id);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),worktrees=new WorktreePool(store,{root:pool}),resumed=resumeTaskStop(store,{taskId:id,runId,by:acting.name,via:"cli",occupied:path=>worktrees.inUse(path)},clock());if(!resumed.ok)return resumed.reason==="review"?fail(write,json,"task resume","review",`${resumed.detail} — separate model review has been removed; inspect the saved source result`,EXIT.refused,{run:runId}):fail(write,json,"task resume",resumed.reason,resumed.detail,EXIT.refused,{run:runId});const control=taskControlOf(store,store.refFor(BUILT_IN,id).id,clock());return succeed(write,json,"task resume",{id,run:runId,stop:resumed.stop,gate:resumed.gate,control},()=>[`Resumed ${id} from run #${runId}: the stop's hold is lifted; every other hold stands.`,resumed.gate===null?" The next pass takes a fresh claim, re-proves the signed scope, and inherits the preserved draft with fresh proof.":` Not starting yet — ${resumed.gate.summary}: ${resumed.gate.detail}`])}async function runCommand(positional,flags,context){const{store,write,json,clock}=context,[action,id,...extra]=positional,command="run settle",usage="`toolroll run settle <run-id>`";if(action!=="settle")return fail(write,json,"run","usage",usage,EXIT.usage);const runId=Number(id??"");if(id===void 0||extra.length>0||!/^[1-9]\d*$/.test(id)||!Number.isSafeInteger(runId))return fail(write,json,command,"usage",usage,EXIT.usage);const run2=store.getRun(runId);if(run2===null)return fail(write,json,command,"unknown-run",`no run #${runId}`,EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","checking a run again takes `--as <you> --token <t>` (or your sign-in from `toolroll up`)",EXIT.usage);const authenticated=authenticateApprover(store,acting.name,acting.token),repo=store.refById(run2.taskRef)?.repo??null;if(!authenticated.ok||!store.accountCanAccess(acting.name,repo))return fail(write,json,command,"not-an-approver","that is not an approver for this run's project, or the token does not match",EXIT.refused);if(run2.outcome===null)return fail(write,json,command,"still-running",`run #${runId} is still open`,EXIT.refused,{run:runId});const proved=await proveRunStopped(store,runId,clock),stopped=store.stopQuiescenceFact(runId);if(stopped===null)return succeed(write,json,command,{run:runId,outcome:proved.outcome==="skipped"?"already-stopped":"stopped",stoppedProcesses:proved.stopped??0},()=>[proved.outcome==="skipped"?`Run #${runId} had already stopped; nothing changed.`:`Run #${runId} stopped: Toolroll checked this computer's processes and none of them is the run's${proved.stopped?` (it stopped ${proved.stopped} the run left running)`:""}. The check is in the ledger.`]);const reason=proved.outcome==="blocked"?"unproven":stopped.kind==="alive"?"alive":"waiting",words=proved.outcome==="blocked"?`Run #${proved.run} ${proved.words}.`:stopped.kind==="alive"?`Something of run #${stopped.run} is still running; Toolroll stops what is proven the run's on its own.`:`Toolroll is still making sure run #${stopped.run} stopped. This clears on its own.`;return fail(write,json,command,reason,words,EXIT.refused,{run:runId})}async function projectRulesCommand(positional,flags,context){const command="project rules",repo=await projectAsked(context,flags,positional,command,{own:["not-requester","protect","protect-paths"],most:1,usage:'Use project rules --repo <project path> [--not-requester on|off] [--protect none|project] [--protect-paths "infra/**,migrations/**"].',match:{listed:!1,canonical:!1}});if(typeof repo=="number")return repo;const current=context.store.approvalRules(repo);if(!["not-requester","protect","protect-paths"].some(name=>flags.has(name)))return succeed(context.write,context.json,command,{repo,rules:current},()=>[`${repo}: ${rulesSummary(current)}`]);const onOff=text(flags,"not-requester");if(onOff!==void 0&&onOff!=="on"&&onOff!=="off")return fail(context.write,context.json,command,"usage","--not-requester takes on or off.",EXIT.usage);const protect=text(flags,"protect");if(protect!==void 0&&protect!=="none"&&protect!=="project")return fail(context.write,context.json,command,"usage","--protect takes none or project; list paths with --protect-paths.",EXIT.usage);const pathsFlag=text(flags,"protect-paths"),paths=pathsFlag===void 0?null:parseProtectedPaths(pathsFlag);if(paths!==null&&!paths.ok)return fail(context.write,context.json,command,"usage",paths.problem,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token);if(acting===null||!verified?.ok||!context.store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator changes approval rules: pass --as and --token (or use the remembered login).",EXIT.refused);const next={notRequester:onOff===void 0?current.notRequester:onOff==="on",protectProject:protect===void 0?paths!==null&&paths.ok?!1:current.protectProject:protect==="project",protectedPaths:protect!==void 0?[]:paths!==null&&paths.ok?paths.paths:current.protectedPaths};return context.store.setApprovalRules(repo,next,acting.name,context.clock()),succeed(context.write,context.json,command,{repo,rules:next},()=>[`${repo}: ${rulesSummary(next)}`])}async function projectNetworkCommand(positional,flags,context){const command="project network",local=flags.get("local"),repo=await projectAsked(context,flags,positional,command,{own:["allow","remove","open","allowlist","local","request","why","by","wait","timeout"],most:1,usage:"Use project network --repo <project path> [--allow host,…] [--remove host,…] [--open | --allowlist] [--local any|none] [--request <why>].",invalid:flags.has("open")&&flags.has("allowlist")||local!==void 0&&local!=="any"&&local!=="none",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const current=context.store.projectNetwork(repo),words=one=>[`${repo}: ${one.mode==="open"?"builds may reach any host":`builds reach their agent's provider, the package registries the project uses${one.hosts.length===0?"":`, and ${one.hosts.join(", ")}`}`}.`,one.loopback==="any"?"On a Mac, builds may reach this Mac's local services (never Toolroll's own).":"On a Mac, builds reach no local services but their own proxy and tools."],listOf=name=>{const given=text(flags,name);if(given===void 0)return[];const hosts=given.split(",").map(one=>one.trim()).filter(Boolean).map(normalizeHost);return hosts.some(one=>one===null)?null:hosts},add=listOf("allow"),remove=listOf("remove");if(add===null||remove===null)return fail(context.write,context.json,command,"usage","A host is a name like api.stripe.com or *.stripe.com: no address, port or path.",EXIT.usage);if(!(add.length>0||remove.length>0||flags.has("open")||flags.has("allowlist")||local!==void 0))return succeed(context.write,context.json,command,{repo,network:current},()=>words(current));const next={mode:flags.has("open")?"open":flags.has("allowlist")?"allowlist":current.mode,hosts:[...new Set([...current.hosts.filter(one=>!remove.includes(one)),...add])].sort(),loopback:local==="any"?"any":local==="none"?"proxy-only":current.loopback};if(next.hosts.length>MAX_NETWORK_HOSTS)return fail(context.write,context.json,command,"usage",`A project lists at most ${MAX_NETWORK_HOSTS} hosts.`,EXIT.usage);if(flags.has("request")){const parts=[];local==="any"&&parts.push("Allow this Mac's local services (localhost / ::1)"),local==="none"&&parts.push("Block local services (proxy-only)"),flags.has("open")&&parts.push("Switch build network to open (any host)"),flags.has("allowlist")&&parts.push("Switch build network to allowlist"),add.length>0&&parts.push(`Allow hosts: ${add.join(", ")}`),remove.length>0&&parts.push(`Remove hosts: ${remove.join(", ")}`);const req=fileAgentRequest(context.databaseFile,{kind:"network",repo,...text(flags,"by")===void 0?{}:{requester:text(flags,"by")},summary:parts.join(" · ")||"Update project network policy",why:text(flags,"why")??text(flags,"request")??"",params:{local:next.loopback,mode:next.mode,hosts:next.hosts,change:{add,remove,...flags.has("open")?{mode:"open"}:flags.has("allowlist")?{mode:"allowlist"}:{},...local==="any"?{local:"any"}:local==="none"?{local:"proxy-only"}:{}}}},context.clock());return finishFiledRequest(command,req,flags,context)}const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes what its builds may reach, with their password: pass --as and --token.",EXIT.refused);const{changed,waiting}=context.store.transact(()=>({changed:context.store.setProjectNetwork(repo,next,acting.name,context.clock()),waiting:proposeNetworkChanges(context.store,repo,context.clock())}));return succeed(context.write,context.json,command,{repo,before:changed.before,network:changed.after,waiting},()=>[...words(changed.after),waiting===0?"Scopes written from now on use this.":`${waiting===1?"1 task waits":`${waiting} tasks wait`} for your Approve to use it; a running task keeps the network it started with.`])}async function projectWritesCommand(positional,flags,context){const command="project writes",wanted=positional[1],repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project writes --repo <project path> [workspace | anywhere].",invalid:wanted!==void 0&&!isWritesMode(wanted),match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=one=>[`${repo}: builds write ${writesWords(one)}.`],current=context.store.projectWrites(repo);if(wanted===void 0)return succeed(context.write,context.json,command,{repo,writes:current},()=>words(current));const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes where its builds may write, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectWrites(repo,wanted,acting.name,context.clock());return succeed(context.write,context.json,command,{repo,before:changed.before,writes:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}async function unconfinedAgentsCommand(positional,flags,context){const command="config unconfined-agents",{store,write,json}=context,wanted=positional[1];if(positional.length>2||wanted!==void 0&&wanted!=="allow"&&wanted!=="refuse")return fail(write,json,command,"usage","Use config unconfined-agents [allow|refuse].",EXIT.usage);const words=allowed=>[allowed?`Builds run even where this machine can't confine them (each such run says "Not confined").`:"Builds this machine can't confine at the OS don't start."];if(wanted===void 0)return succeed(write,json,command,{allowed:store.unfencedAgentsAllowed()},()=>words(store.unfencedAgentsAllowed()));if(wanted==="allow"&&localModeOn(store))return fail(write,json,command,"refused",LOCAL_MODE_CONFINES,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(store,acting.name,acting.token);return acting===null||!verified?.ok||!store.isInstanceOperator(acting.name)?fail(write,json,command,"refused","An instance operator changes this, with their password: pass --as and --token.",EXIT.refused):(store.setUnfencedAgentsAllowed(wanted==="allow",acting.name,context.clock()),succeed(write,json,command,{allowed:wanted==="allow"},()=>words(wanted==="allow")))}async function projectConcurrencyCommand(positional,flags,context){const command="project concurrency",repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project concurrency [<n>] --repo <project path>.",match:{listed:!1,canonical:!0}});if(typeof repo=="number")return repo;const workers=context.store.listRunners().filter(one=>one.retiredAt===null&&one.repos.includes(repo)),capacity=workers.length===0?null:Math.max(...workers.map(one=>one.capacity)),words=n2=>`${repo}: builds up to ${n2} at once${capacity!==null&&capacity<n2?` (its worker runs ${capacity} at once, so ${capacity} for now)`:""}.`,given=positional[1];if(given===void 0){const current=projectConcurrency(context.databaseFile,repo);return succeed(context.write,context.json,command,{repo,concurrency:current,workerCapacity:capacity},()=>[words(current)])}const n=parseProjectConcurrency(given);if(n===null)return fail(context.write,context.json,command,"usage",`Builds at once is a whole number from 1 to ${RUNNER_CAPACITY_MAX}.`,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes how many tasks build at once: pass --as and --token (or use the remembered login).",EXIT.refused);const changed=saveProjectConcurrency(context.databaseFile,repo,n);return context.store.recordProjectConcurrency(acting.name,repo,changed.before,changed.after,context.clock()),context.store.bumpWake(),succeed(context.write,context.json,command,{repo,before:changed.before,concurrency:changed.after,workerCapacity:capacity},()=>[words(changed.after),...changed.before>changed.after?["Builds already running carry on; the new number applies to the next one."]:[]])}async function projectChecksCommand(positional,flags,context){const command="project checks",wanted=flags.get("batch"),repo=await projectAsked(context,flags,positional,command,{own:["batch"],most:1,usage:"Use project checks [--batch on|off] --repo <project path>.",invalid:wanted!==void 0&&wanted!=="on"&&wanted!=="off",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const level=projectCheckLevel(context.store,repo).level,words=on2=>[`${repo}: batch checks are ${on2?"on":"off"}. ${on2?BATCH_HINT:"Each result runs its own full check."}`,...on2&&level!=="full"?[`Checks are ${CHECK_LEVEL_WORDS[level]} for this project, so nothing is batched until they are Full.`]:[]];if(wanted===void 0){const current=projectBatchChecks(context.store,repo);return succeed(context.write,context.json,command,{repo,batch:current.on,windowMinutes:current.windowMs/6e4,level,setBy:current.setBy},()=>words(current.on))}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes batch checks: pass --as and --token (or use the remembered login).",EXIT.refused);const on=wanted==="on",changed=setProjectBatchChecks(context.store,repo,on,acting.name,context.clock());return succeed(context.write,context.json,command,{repo,batch:on,before:changed.before,changed:changed.changed,windowMinutes:BATCH_WINDOW_MS/6e4,level},()=>[...words(on),...changed.changed&&!on?["Results already waiting are checked now."]:[]])}async function projectDemoCommand(positional,flags,context){const command="project demo",repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project demo [<url>|off] --repo <project path>.",match:{listed:!1,canonical:!0}});if(typeof repo=="number")return repo;const words=url2=>url2===null?`${repo}: no demo; scouts screenshot public pages only.`:`${repo}: scouts may also screenshot ${url2}.`,given=positional[1];if(given===void 0){const current=projectDemoUrl(context.databaseFile,repo);return succeed(context.write,context.json,command,{repo,demoUrl:current},()=>[words(current)])}const url=given.trim().toLowerCase()==="off"?null:parseDemoUrl(given);if(url===null&&given.trim().toLowerCase()!=="off")return fail(context.write,context.json,command,"usage","The demo is an http or https address without a sign-in, or off.",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project sets its demo: pass --as and --token (or use the remembered login).",EXIT.refused);const changed=saveProjectDemo(context.databaseFile,repo,url);return context.store.recordProjectDemo(acting.name,repo,changed.before,changed.after,context.clock()),succeed(context.write,context.json,command,{repo,before:changed.before,demoUrl:changed.after},()=>[words(changed.after)])}function writeOut(context,command,out,content,summary,line,data){if(out===void 0)return context.write(context.json?envelopeJson({ok:!0,command,...summary,...data}):content.replace(/\n$/,"")),EXIT.ok;try{writeFileSync(resolve(out),content,{mode:384,flag:"wx"})}catch(error){const exists=error.code==="EEXIST";return fail(context.write,context.json,command,exists?"exists":"unwritable",exists?"That file exists already; choose another name.":"That file couldn't be written.",EXIT.failed)}return succeed(context.write,context.json,command,{...summary,out:resolve(out)},()=>[`${line} Saved to ${resolve(out)}.`])}async function projectDeleteCommand(positional,flags,context){const command="project delete",allowed=new Set(["repo","yes","as","token","token-file","token-env","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a project delete option.`,EXIT.usage);const repoFlag=text(flags,"repo");if(positional.length>1||repoFlag===void 0)return fail(context.write,context.json,command,"usage","Use project delete --repo <project path> [--yes].",EXIT.usage);const registryFile=registryPathOf(context),registered=await loadRepos(registryFile).catch(()=>({error:"unreadable"})),repo=[...new Set([...context.store.knownRepos(),...context.store.listProjects().map(one=>one.path),..."error"in registered?[]:registered.repos])].find(one=>one===repoFlag||one===resolve(repoFlag));if(repo===void 0)return fail(context.write,context.json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused);const store=context.store,acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator deletes projects: pass --as and --token (or use the remembered login).",EXIT.refused);const holdings=projectHoldings(store,repo),running=projectRunning(store,repo,context.clock());if(running.includes(PROJECT_RECOVERY_DELETE_MESSAGE))return fail(context.write,context.json,command,"recovery-held",PROJECT_RECOVERY_DELETE_MESSAGE,EXIT.refused);if(running.length>0)return fail(context.write,context.json,command,"running",`Nothing was deleted: ${running.join(", ")}. Stop it, then try again.`,EXIT.refused);if(!flags.has("yes"))return succeed(context.write,context.json,command,{repo,deleted:!1,holdings},()=>[`${repo}: Toolroll holds ${holdingsWords(holdings)} for it, and the checkouts and toolroll/ (or older standing-orders/) branches it made.`,"Deleting removes all of it; the repository and its own branches stay. There's no undo. Add --yes to delete."]);const done=await deleteProject(store,repo,{actor:acting.name,via:"command line",now:context.clock(),evidenceRoot:context.evidenceRoot??join(dirname(context.databaseFile),"evidence"),poolRoot:join(dirname(context.databaseFile),"worktrees")});return done.ok?(!("error"in registered)&&registered.repos.includes(repo)&&await updateRepos(registryFile,repos=>removeRepos(repos,[repo])).catch(()=>{}),succeed(context.write,context.json,command,{repo,deleted:!0,removed:done.removed,left:done.left,ledgerEntry:done.ledgerId},()=>[`Deleted ${repo}: ${holdingsWords(done.removed)}.`,...done.left.map(one=>`Git kept ${one}.`),`The ledger records it as entry #${done.ledgerId}.`])):fail(context.write,context.json,command,done.reason,done.said,done.reason==="running"||done.reason==="recovery-held"?EXIT.refused:EXIT.failed)}async function spendCommand(flags,context){const command="spend";for(const name of flags.keys())if(!["month","csv","live","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a spend option.`,EXIT.usage);const month=text(flags,"month")===void 0?monthOf(context.clock()):monthNamed(text(flags,"month")??null);if(month===null)return fail(context.write,context.json,command,"usage","Use spend --month YYYY-MM.",EXIT.usage);const gemini=(flags.has("live")?await refreshSubscriptions(context.store,context.databaseFile,{forceClaude:!0,forceGemini:!0,now:context.clock()}):null)?.gemini??readStoredGeminiStatus(context.databaseFile),items=spendItems(context.store.handle,month.from,month.to),names=subagentNames(context.store.handle);if(flags.has("csv"))return context.write(spendCsv(items,names).replace(/^\ufeff/,"").trimEnd()),EXIT.ok;const budgets=budgetStates(context.store.budgets(),items),total=items.reduce((sum,item)=>sum+(item.microusd??0),0),unpriced=items.filter(item=>item.microusd===null&&(item.tokensIn!==null||item.kind!=="run")).length,byProject=new Map;for(const item of items)item.project!==null&&byProject.set(item.project,(byProject.get(item.project)??0)+(item.microusd??0));const limits=context.store.providerLimits(),windows=limitsView(limits,[],{project:repo=>basename(repo),subagent:id=>String(id)},context.clock())?.tiles??[],tiers=tierReport(context.store.handle,month.from,month.to,items),suggestions=savingsReportOrError(context.store,context.store.knownRepos(),context.clock());return succeed(context.write,context.json,command,{month:month.name,totalMicrousd:total,unpriced,items:items.length,budgets,limits,...gemini!==null?{gemini}:{},tiers:{rows:tiers.rows,saved:tiers.saved},suggestions},()=>[`${month.name}: ${spendUsd(total)} (${items.length} pieces of work${unpriced>0?`, ${unpriced} unpriced`:""}; subscription work is $0)`,...windows.map(tile=>` ${`${tile.name} ${tile.window}`.padEnd(24)} ${tile.value}% · ${tile.detail}`),...[...byProject.entries()].sort((a,b)=>b[1]-a[1]).slice(0,10).map(([repo,microusd])=>` ${basename(repo).padEnd(24)} ${spendUsd(microusd)}`),...budgets.map(one=>` budget ${budgetLabel(one,names.get(Number(one.key))).replace(/'s$/,"").padEnd(24)} ${spendUsd(one.spentMicrousd)} of ${spendUsd(one.limitMicrousd)} (${one.percent}%)${one.hardStop?"":" alerts only"}`),...tierLines(tiers,spendUsd),...savingsLines(suggestions)])}async function backupCommand(positional,flags,context){const[action,...extra]=positional,command=`backup ${action??""}`.trim();for(const name of flags.keys())if(!["db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a backup option.`,EXIT.usage);if(extra.length>0||action!=="now"&&action!=="list")return fail(context.write,context.json,command,"usage","Use backup now or backup list.",EXIT.usage);const store=context.store;if(action==="now"){const made=await backupNow(store,context.databaseFile,"manual",context.clock);return made.ok?succeed(context.write,context.json,command,{backup:made},()=>[`Backed up to ${made.file} (${bytesWords(made.bytes)}).${made.removed===0?"":` Removed ${made.removed} older ${made.removed===1?"backup":"backups"}.`}`,...made.checkpoint!==null&&"problem"in made.checkpoint?[`The activity log failed its tamper check, so it was not anchored: ${made.checkpoint.problem}`]:[]]):fail(context.write,context.json,command,"failed",`The backup failed: ${made.error}`,EXIT.failed,{backup:made.id})}const settings=store.backupSettings(),folder=backupFolderOf(settings,context.databaseFile),files=backupFiles(folder,backupOwner(store,context.databaseFile)),runs=store.backupRuns(10),last=runs[0]??null;return succeed(context.write,context.json,command,{settings,folder,files,runs},()=>[settings.enabled?`Every ${settings.everyHours===1?"hour":`${settings.everyHours} hours`}, keeping the newest ${settings.keep}, in ${folder}.`:`Scheduled backups are off. Backups are kept in ${folder}.`,last===null?"No backup has run yet.":last.ok===!0?`Last backup ${last.startedAt.slice(0,16).replace("T"," ")} UTC: succeeded.`:last.ok===!1?`Last backup ${last.startedAt.slice(0,16).replace("T"," ")} UTC: FAILED (${last.error??"no reason recorded"}).`:`A backup started ${last.startedAt.slice(0,16).replace("T"," ")} UTC is still running.`,...files.length===0?["No backups of this database in the folder."]:files.map(one=>` ${one.name} ${bytesWords(one.bytes)}`)])}async function restoreCommand(file,positional,flags,write,json,now){const command="restore";for(const name of flags.keys())if(!["db","json","dry-run"].includes(name))return fail(write,json,command,"usage",`--${name} is not a restore option.`,EXIT.usage);const[backupFile,...extra]=positional;if(backupFile===void 0||extra.length>0)return fail(write,json,command,"usage","Use restore <backup file> [--dry-run].",EXIT.usage);const dryRun=flags.has("dry-run");let report;try{report=await restoreDatabase({databaseFile:file,file:backupFile,dryRun,now})}catch(error){return fail(write,json,command,"failed",`The restore failed: ${describe(error)}. The database is unchanged.`,EXIT.failed)}if(!report.ok)return fail(write,json,command,report.refusals[0]?.reason??"refused",["Nothing was restored.",...report.refusals.map(one=>` ${one.words}`)].join(`
484
- `),EXIT.refused,{report});const checked=`schema ${report.schemaVersion}, ledger chain verified (${report.ledger?.entries??0} entries)`;return succeed(write,json,command,{report},()=>dryRun?[`Dry run: ${report.file} can be restored (${checked}). Nothing was changed.`]:[`Restored ${report.file} (${checked}).`,`The database as it was is kept at ${report.savedAs}.`])}function exportCommand(positional,flags,context){const command="export";for(const name of flags.keys())if(!["out","zip","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not an export option.`,EXIT.usage);const out=text(flags,"out");if(positional.length>0||out===void 0||out==="")return fail(context.write,context.json,command,"usage","Use export --out <path> [--zip].",EXIT.usage);const target=resolve(out);if(existsSync(target))return fail(context.write,context.json,command,"exists","That path exists already; choose a new one.",EXIT.failed);const who="command line",now=context.clock(),zip=flags.has("zip");context.store.recordAction({at:now.toISOString(),actor:who,repo:null,taskId:null,runId:null,action:"everything exported",outcome:"exported",source:"access",detail:zip?"as a .zip":"as a folder"});const exported=buildExport(context.store,{who,now,evidenceRoot:context.evidenceRoot,configDir:dirname(context.databaseFile)});try{zip?writeFileSync(target,exportZip(exported),{mode:384,flag:"wx"}):writeExportFolder(target,exported)}catch{return fail(context.write,context.json,command,"unwritable","The export couldn't be written there.",EXIT.failed)}return succeed(context.write,context.json,command,{out:target,zip,files:exported.files.length,tables:exported.tables,packs:exported.packs},()=>[`Exported ${exportSummary(exported)} to ${target}.`,"manifest.json lists every file with its SHA-256; README.md explains the layout."])}async function budgetCommand(positional,flags,context){const[action]=positional,command=`budget ${action??""}`.trim(),store=context.store;if(action===void 0||action==="list"){const budgets=store.monthSpend(context.clock()).budgets;return succeed(context.write,context.json,command,{budgets},()=>budgets.length===0?["No budgets. `budget set --all|--project <path>|--person <name>|--subagent <id> --usd <n>` makes one."]:budgets.map(one=>`#${one.id} ${budgetLabel(one).replace(/'s$/,"")}: ${spendUsd(one.spentMicrousd)} of ${spendUsd(one.limitMicrousd)} this month (${one.percent}%)${one.hardStop?", stops API work at 100%":", alerts only"}`))}if(action!=="set"&&action!=="remove")return fail(context.write,context.json,command,"usage","Use budget list, budget set or budget remove.",EXIT.usage);const allowed=new Set(["all","project","person","subagent","teammate","usd","alerts-only","as","token","token-file","token-env","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a budget option.`,EXIT.usage);const chosen=[flags.has("all")?{scope:"installation",key:"*"}:null,text(flags,"project")===void 0?null:{scope:"project",key:resolve(text(flags,"project"))},text(flags,"person")===void 0?null:{scope:"person",key:text(flags,"person")},(text(flags,"subagent")??text(flags,"teammate"))===void 0?null:{scope:"subagent",key:text(flags,"subagent")??text(flags,"teammate")}].filter(one=>one!==null);if(chosen.length!==1)return fail(context.write,context.json,command,"usage","Name one of --all, --project <path>, --person <name> or --subagent <id>.",EXIT.usage);const target=chosen[0],acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets budgets: pass --as and --token (or use the remembered login).",EXIT.refused);if(!(target.scope==="installation"||(target.scope==="project"?store.knownRepos().includes(target.key):target.scope==="person"?store.accountFacts().some(one=>one.name===target.key&&one.revokedAt===null):store.handle.prepare("SELECT 1 FROM subagent WHERE id = ?").get(Number(target.key))!==void 0)))return fail(context.write,context.json,command,"not-found","That isn't a project, person or subagent here.",EXIT.refused);if(action==="remove"){const existing=store.budgets().find(one=>one.scope===target.scope&&one.key===target.key);return existing===void 0||!store.removeBudget(existing.id,acting.name,context.clock())?fail(context.write,context.json,command,"not-found","There's no such budget.",EXIT.refused):succeed(context.write,context.json,command,{removed:existing.id},()=>[`Removed the ${budgetLabel(existing).replace(/'s$/,"")} budget.`])}const dollars=Number(text(flags,"usd")??"");if(!Number.isFinite(dollars)||dollars<1||dollars>1e7)return fail(context.write,context.json,command,"usage","--usd is a whole number of dollars, at least 1.",EXIT.usage);const saved=store.setBudget({scope:target.scope,key:target.key,limitMicrousd:Math.round(dollars)*1e6,hardStop:!flags.has("alerts-only")},acting.name,context.clock());return succeed(context.write,context.json,command,{budget:saved},()=>[`${budgetLabel(saved).replace(/'s$/,"")}: ${spendUsd(saved.limitMicrousd)} a month${saved.hardStop?", API work stops at 100%":", alerts only"}.`])}async function notificationsCommand(positional,flags,context){const[action,value,...extra]=positional,command=`notifications${action===void 0?"":` ${action}`}`,store=context.store,muting=action==="mute"||action==="unmute";for(const name of flags.keys())if(!["as","token","token-file","token-env","db","json",...muting?["repo"]:[]].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a notifications option.`,EXIT.usage);const usage="Use notifications quiet, notifications all, notifications digest <HH:MM>|off, notifications screenshots off|first|all, or notifications mute|unmute --repo <project>.",valued=action==="digest"||action==="screenshots";if(extra.length>0||action!==void 0&&!["quiet","all","digest","screenshots","mute","unmute"].includes(action)||valued!==(value!==void 0)||muting&&(value!==void 0||text(flags,"repo")===void 0))return fail(context.write,context.json,command,"usage",usage,EXIT.usage);if(action==="screenshots"&&!RESULT_SCREENSHOTS.includes(value))return fail(context.write,context.json,command,"usage","Screenshots with results is off, first (the first one) or all (up to 4).",EXIT.usage);if(action==="digest"&&value!=="off"&&!isDigestTime(value))return fail(context.write,context.json,command,"usage","The digest time is HH:MM on a 24-hour clock, like 18:30, or off.",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return fail(context.write,context.json,command,"refused","Notifications are set per person: pass --as and --token (or use the remembered login).",EXIT.refused);const now=context.clock();if(muting){const typed=text(flags,"repo"),repo=canonicalProject(typed)??resolve(typed);if(!new Set([...store.knownRepos(),...store.listProjects().map(one=>one.path)]).has(repo)||!store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"unknown-project",`${typed} is not a project you can see.`,EXIT.refused);store.setProjectMuted(acting.name,repo,action==="mute",now);const muted2=store.mutedProjects(acting.name);return succeed(context.write,context.json,command,{repo,muted:action==="mute",mutedProjects:muted2},()=>[action==="mute"?`${basename(repo)} is muted: no pings for it. The console and your evening digest still show it.`:`${basename(repo)} pings you again.`])}const preference=action==="quiet"||action==="all"?store.setNotificationPreference(acting.name,{mode:action},acting.name,now):action==="digest"?store.setNotificationPreference(acting.name,{digestAt:value==="off"?null:value},acting.name,now):action==="screenshots"?store.setNotificationPreference(acting.name,{screenshots:value},acting.name,now):store.notificationPreference(acting.name),muted=store.mutedProjects(acting.name);return succeed(context.write,context.json,command,{mode:preference.mode,digestAt:preference.digestAt,screenshots:preference.screenshots,mutedProjects:muted},()=>[preference.mode==="quiet"?"Only when you're needed: one message per task, updated as it moves, and a new one when something needs you.":"Every step: a message for each update.",preference.digestAt===null?"No evening digest.":`Evening digest at ${preference.digestAt}: what finished, what waits and what failed.`,preference.screenshots==="off"?"Screenshots with results: off.":`Screenshots with results: ${preference.screenshots==="first"?"the first one":"up to 4"}.`,...muted.length===0?[]:[`Muted: ${muted.map(one=>basename(one)).join(", ")}.`]])}async function retentionCommand(positional,flags,context){const[action,...rest]=positional,command=`retention ${action??""}`.trim(),store=context.store,allowed=new Set(action==="set"?["as","token","token-file","token-env","db","json"]:["db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const label=kind2=>RETENTION_KINDS.find(one=>one.kind===kind2).label;if(action===void 0||action==="show"){const periods2=store.retentionPeriods(),chosen=store.retentionChosen(),defaulted=RETENTION_KINDS.map(one=>one.kind).filter(kind2=>!(kind2 in chosen)),last=lastSweepAt(store);return succeed(context.write,context.json,command,{periods:periods2,defaulted,lastSweep:last},()=>[...RETENTION_KINDS.map(one=>` ${one.kind.padEnd(14)} ${periodLabel(one.kind,periods2[one.kind],one.kind in chosen).toLowerCase().padEnd(18)} ${one.label}`),` ${NOTIFICATION_RETENTION_WORDS}`,last===null?"No sweep yet; the worker runs one a day.":`Last sweep ${last.slice(0,16).replace("T"," ")} UTC.`])}if(action==="preview"){const plan=retentionPlan(store,context.evidenceRoot,context.clock()),kept=plan.counts.filter(one=>one.days===null).map(one=>one.kind),fixed=notificationLifecyclePreview(store,context.clock());return succeed(context.write,context.json,command,{counts:plan.counts,lifecycle:fixed},()=>[...plan.counts.filter(one=>one.days!==null).map(one=>` ${label(one.kind).padEnd(26)} ${countWords(one)} older than ${periodWords(one.days)}, about ${bytesWords(one.bytes)}${one.more?" (more after this sweep)":""}`),` ${"Progress updates".padEnd(26)} ${fixed.pings} settled and older than ${LIFECYCLE_RETENTION_DAYS} days, task finished; ${fixed.legacy} undeliverable delivery records older than ${LIFECYCLE_RETENTION_DAYS} days`,kept.length===RETENTION_KINDS.length?"Everything else is kept forever.":`Nothing was removed.${kept.length===0?"":` Kept forever: ${kept.join(", ")}.`}`])}if(action!=="set")return fail(context.write,context.json,command,"usage","Use retention show, retention preview or retention set <kind> <period>.",EXIT.usage);const[kind,period,...extra]=rest;if(kind===void 0||!isRetentionKind(kind)||period===void 0||extra.length>0)return fail(context.write,context.json,command,"usage",`Use retention set <${RETENTION_KINDS.map(one=>one.kind).join("|")}> <days, like 1d, 90d or 1y, or forever>.`,EXIT.usage);const days=parsePeriod(period);if(days===void 0)return fail(context.write,context.json,command,"usage",`A period is forever, or ${MIN_DAYS} day to 10 years (1d, 90d, 12w, 1y).`,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets retention: pass --as and --token (or use the remembered login).",EXIT.refused);const periods=store.setRetentionPeriod(kind,days,acting.name,context.clock());return succeed(context.write,context.json,command,{periods},()=>[`${label(kind)}: kept ${days===null?"forever":`for ${periodWords(days)}`}.`])}async function storageCommand(positional,flags,context){const[action,...rest]=positional,command=`storage ${action??""}`.trim(),store=context.store,changes=action==="cleanup"&&rest.length>0||action==="clean"&&flags.has("yes")||action==="discard",allowed=new Set([...changes?["as","token","token-file","token-env"]:[],...action==="clean"||action==="discard"?["yes"]:[],...action==="clean"?["landed"]:[],"db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const pool=new WorktreePool(store,{root:join(dirname(context.databaseFile),"worktrees"),...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),operator=async()=>{const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);return acting!==null&&verified!==null&&verified.ok&&store.isInstanceOperator(acting.name)?acting.name:null},refused=what=>fail(context.write,context.json,command,"refused",`An instance operator ${what}: pass --as and --token (or use the remembered login).`,EXIT.refused),summary=plan=>[`Task folders: ${plan.count}, ${bytesWords(plan.totalBytes)}. ${plan.waitingReview} waiting for review, ${plan.withChanges} with uncommitted changes.`,plan.go.length===0?"A clean up now would free nothing.":`A clean up now would free about ${bytesWords(plan.freeBytes)} (${plan.go.length} task folder${plan.go.length===1?"":"s"}): toolroll storage clean`,`A finished task's clean folder is removed ${cleanupWords(plan.cleanup)}; its branch stays.`,idleCleanupWords(plan),...uncommittedLines(plan)],itemLine=one=>` ${bytesWords(one.bytes).padStart(8)} ${one.path}${one.why===null?"":` (${whyWords(one)})`}`,roots=context.tempRoots??tempRoots(),leftovers=measure=>{const found=testTempFolders(roots,context.clock()),sizes=measure?diskBytes(found.stale.map(one=>one.path)):new Map;return{count:found.all.length,stale:found.stale.length,staleBytes:[...sizes.values()].reduce((sum,one)=>sum+one,0)}},leftoverLine=temp=>temp.count===0?"Test temp folders: none.":`Test temp folders: ${temp.count}; ${temp.stale===0?"none older than a day.":`${temp.stale} older than a day: toolroll storage clean removes them.`}`,depsRoot=sharedDepsRoot(context.databaseFile),checkoutRows=()=>store.listWorktrees().map(row=>({path:row.path,repo:row.repo})),sharedFacts=copies=>{const sizes=diskBytes(copies.map(one=>one.dir));return copies.map(one=>({key:one.key,repo:one.repo,path:one.dir,bytes:sizes.get(one.dir)??0,checkouts:one.checkouts.length,usedBy:one.checkouts,retired:one.retired,node:one.node,createdAt:one.createdAt,usedAt:one.usedAt}))},sharedLine=one=>` ${bytesWords(one.bytes).padStart(8)} ${projectName(one.repo)} ${one.key.slice(0,8)}: ${one.checkouts===1?"1 checkout uses it":`${one.checkouts} checkouts use it`}${one.retired?" (changed after install; never linked again)":""}`,sweepFacts=()=>{const last=lastSweep(store),automatic=last?.source==="automatic"?last:lastSweep(store,"automatic");return{last,lastAutomatic:automatic,schedule:sweepSchedule(store,context.clock())}},sweepLines=facts=>{const when=at=>new Date(at).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),one=facts.last,head=one===null?"Not swept yet.":`Last swept ${when(one.at)}${one.source==="manual"?` by ${one.actor}`:" automatically"}: ${storageSweepWords(one.parts)}`,auto=one!==null&&one.source==="manual"&&facts.lastAutomatic!==null?[`Last automatic sweep ${when(facts.lastAutomatic.at)}: ${storageSweepWords(facts.lastAutomatic.parts)}`]:[];return[head,...auto,`Automatic sweep: ${sweepScheduleWords(facts.schedule,when)}`,...one===null?[]:sweepDetails(one.parts).slice(0,8).map(line=>` ${line}`)]};if(action===void 0){const plan=await checkoutPlan(store,pool,context.clock(),{manual:!0}),report=storageReport(store,context.databaseFile,plan.go.length===0?"nothing to clean up":`about ${bytesWords(plan.freeBytes)} to clean up`),{staleBytes:_,...temp}=leftovers(!1),shared=sharedFacts(sharedUse(depsRoot,checkoutRows())),sweep=sweepFacts();return succeed(context.write,context.json,"storage",{...report,checkouts:checkoutSummary(plan),testTemp:temp,shared,sweep},()=>[`${report.folder}: ${bytesWords(report.total)}`,...report.lines.map(one=>` ${one.what.padEnd(19)} ${bytesWords(one.bytes).padStart(8)}${one.count===void 0?"":` (${one.count})`}${one.note===void 0?"":` ${one.note}`}`),...shared.length===0?[]:["Shared dependencies:",...shared.map(sharedLine)],...summary(plan),leftoverLine({...temp,staleBytes:0}),...sweepLines(sweep)])}if(action==="cleanup"){if(rest.length===0){const cleanup2=store.checkoutCleanup(),idle=checkoutIdle(store);return succeed(context.write,context.json,command,{cleanup:cleanup2,idle},()=>[`A finished task's clean folder is removed ${cleanupWords(cleanup2)}; its branch stays.`,`A task's clean folder is removed ${idleWords(idle)}; its branch stays.`])}const usage=`Use storage cleanup <${CLEANUP_CHOICES.map(one=>one.value).join("|")}> or storage cleanup idle <7|14|30|never>.`;if(rest[0]==="idle"){const idle=rest.length===2?parseIdle(rest[1]):void 0;if(idle===void 0)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const actor2=await operator();if(actor2===null)return refused("sets idle cleanup");const saved2=setCheckoutIdle(store,idle,actor2,context.clock());return succeed(context.write,context.json,command,{idle:saved2},()=>[`Saved. A task's clean folder is removed ${idleWords(saved2)}; its branch stays.`])}const cleanup=rest.length===1?parseCleanup(rest[0]):void 0;if(cleanup===void 0)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const actor=await operator();if(actor===null)return refused("sets checkout cleanup");const saved=store.setCheckoutCleanup(cleanup,actor,context.clock());return succeed(context.write,context.json,command,{cleanup:saved},()=>[`Saved. A finished task's clean folder is removed ${cleanupWords(saved)}; its branch stays.`])}if(action==="clean"&&flags.has("landed"))return rest.length>0||flags.get("landed")!==!0?fail(context.write,context.json,"storage clean --landed","usage","Use storage clean --landed to preview, then storage clean --landed --yes.",EXIT.usage):landedCommand(flags.has("yes"),operator,refused,pool,context);if(action==="clean"){if(rest.length>0)return fail(context.write,context.json,command,"usage","Use storage clean to preview, then storage clean --yes.",EXIT.usage);if(!flags.has("yes")){const plan=await checkoutPlan(store,pool,context.clock(),{manual:!0}),temp2=leftovers(!0),leaving=new Set(plan.go.map(one=>one.path)),unused2=unusedShared(depsRoot,checkoutRows().filter(row=>!leaving.has(row.path)),context.clock()),sharedGo=sharedFacts(unused2.copies),sharedBytes=sharedGo.reduce((sum,one)=>sum+one.bytes,0),anything=plan.go.length>0||temp2.stale>0||sharedGo.length>0;return succeed(context.write,context.json,command,{preview:!0,go:plan.go,stay:plan.stay,freeBytes:plan.freeBytes,testTemp:temp2,sharedGo,sharedFreeBytes:sharedBytes},()=>[...plan.go.length===0?[anything?"No task folders to clean up.":"Nothing to clean up."]:[`Would remove ${plan.go.length} task folder${plan.go.length===1?"":"s"}, freeing about ${bytesWords(plan.freeBytes)} (their branches stay):`,...plan.go.map(itemLine)],...sharedGo.length===0?[]:[`Would remove ${sharedGo.length} shared dependency install${sharedGo.length===1?"":"s"} no checkout uses, about ${bytesWords(sharedBytes)}:`,...sharedGo.map(sharedLine)],...plan.stay.length===0?[]:[`Stays (${plan.stay.length}):`,...plan.stay.map(itemLine)],...temp2.stale===0?[]:[`Would remove ${temp2.stale} test temp folder${temp2.stale===1?"":"s"} older than a day, about ${bytesWords(temp2.staleBytes)}.`],anything?"Nothing was removed. Run toolroll storage clean --yes to remove them.":"Nothing was removed."])}const actor=await operator();if(actor===null)return refused("cleans up checkouts");const done=await cleanCheckouts(store,pool,context.clock,{manual:!0,actor}),temp=leftovers(!0),swept=await removeStaleTestTemp(roots,context.clock());swept.removed.length>0&&store.recordAction({at:context.clock().toISOString(),actor,repo:null,taskId:null,runId:null,action:"test temp folders removed",outcome:"removed",source:"request",detail:`${swept.removed.length} older than a day, about ${bytesWords(temp.staleBytes)}${swept.failed.length===0?"":`; ${swept.failed.length} couldn't be removed`}`});const unused=unusedShared(depsRoot,checkoutRows(),context.clock()),sharedRemoved=sharedFacts(unused.copies).filter(one=>removeShared(one.path));for(const one of sharedRemoved)store.recordAction({at:context.clock().toISOString(),actor,repo:one.repo,taskId:null,runId:null,action:"shared dependencies removed",outcome:"removed",source:"request",detail:`${one.key} (about ${bytesWords(one.bytes)}); no checkout used it`});for(const debris of unused.debris)removeShared(debris);const sharedFreed=sharedRemoved.reduce((sum,one)=>sum+one.bytes,0),parts=[{kind:"checkouts",count:done.removed.length,bytes:done.freed,failed:done.kept.filter(one=>one.why==="git refused").length,items:done.removed.slice(0,20).map(one=>one.path)},{kind:"test temp",count:swept.removed.length,bytes:temp.staleBytes,failed:swept.failed.length,items:swept.removed.slice(0,20)},{kind:"dependencies",count:sharedRemoved.length,bytes:sharedFreed,failed:unused.copies.length-sharedRemoved.length,items:sharedRemoved.slice(0,20).map(one=>one.path)}];return saveSweep(store,{at:context.clock().toISOString(),source:"manual",actor,parts}),succeed(context.write,context.json,command,{removed:done.removed,kept:done.kept,freedBytes:done.freed,testTempRemoved:swept.removed.length,testTempFailed:swept.failed,sharedRemoved,sharedFreedBytes:sharedFreed},()=>[done.removed.length===0?swept.removed.length===0&&sharedRemoved.length===0?"Nothing to clean up.":"No task folders to clean up.":`Removed ${done.removed.length} task folder${done.removed.length===1?"":"s"}, about ${bytesWords(done.freed)}; their branches stay.`,...done.removed.map(itemLine),...sharedRemoved.length===0?[]:[`Removed ${sharedRemoved.length} shared dependency install${sharedRemoved.length===1?"":"s"} no checkout used, about ${bytesWords(sharedFreed)}.`,...sharedRemoved.map(sharedLine)],...done.kept.map(one=>` kept ${one.path} (${whyWords({why:one.why})})`),...swept.removed.length===0?[]:[`Removed ${swept.removed.length} test temp folder${swept.removed.length===1?"":"s"} older than a day, about ${bytesWords(temp.staleBytes)}.`],...swept.failed.length===0?[]:[`Couldn't remove ${swept.failed.length} test temp folder${swept.failed.length===1?"":"s"}: ${swept.failed.slice(0,3).join(", ")}${swept.failed.length>3?" …":""}`]])}if(action==="discard"){const[path,...extra]=rest;if(path===void 0||extra.length>0)return fail(context.write,context.json,command,"usage","Use storage discard <path> --yes.",EXIT.usage);const target=resolve(path);if(store.getWorktree(target)===null)return fail(context.write,context.json,command,"not-found",`${target} is not a task checkout. toolroll storage clean lists them.`,EXIT.refused);if(!flags.has("yes"))return fail(context.write,context.json,command,"usage",`This throws away ${target} and its uncommitted changes (its branch stays). Add --yes to discard it.`,EXIT.usage);const actor=await operator();if(actor===null)return refused("discards a checkout");const done=await discardCheckout(store,pool,target,context.clock(),actor);return done.ok?succeed(context.write,context.json,command,{discarded:target,freedBytes:done.bytes},()=>[`Discarded ${target}, about ${bytesWords(done.bytes)}; its branch stays.`]):fail(context.write,context.json,command,"refused",done.message,EXIT.refused)}return fail(context.write,context.json,command,"usage","Use storage, storage cleanup <when>, storage clean [--landed] [--yes] or storage discard <path> --yes.",EXIT.usage)}async function landedCommand(yes,operator,refused,pool,context){const remotes=new RemoteMains(context.store,context.gitRunner,context.evidenceRoot);try{return await landedCommandWith(remotes,yes,operator,refused,pool,context)}finally{remotes.close()}}async function landedCommandWith(remotes,yes,operator,refused,pool,context){const command="storage clean --landed",git=gitOf(context.gitRunner),plurals=(count,one,many=`${one}s`)=>`${count} ${count===1?one:many}`,keepLine=one=>` ${projectName(one.repo)} ${one.what}: ${one.why}`,stepLine=one=>` ${projectName(one.repo)} ${one.target}${one.why===null?"":`: ${one.why}`}`,counts=plan2=>({results:plan2.results.length,complete:plan2.results.filter(one=>one.completes).length,checkouts:plan2.results.reduce((sum,one)=>sum+one.targets.filter(target=>target.kind==="checkout").length,0)+plan2.branches.filter(one=>one.checkout!==null).length,branches:plan2.results.reduce((sum,one)=>sum+one.targets.filter(target=>target.kind==="branch").length,0)+plan2.branches.length});if(!yes){const plan2=await landedBacklog(context.store,git,remotes,context.evidenceRoot,context.clock()),n=counts(plan2),anything=n.results+plan2.branches.length+plan2.pending>0;return succeed(context.write,context.json,command,{preview:!0,cutoff:plan2.cutoff,results:plan2.results,branches:plan2.branches,kept:plan2.kept,pending:plan2.pending},()=>[anything?`Would mark ${plurals(n.complete,"landed result")} complete and remove ${plurals(n.checkouts,"checkout")} and ${plurals(n.branches,"local branch","local branches")}.`:`Nothing landed more than ${BACKLOG_DAYS} days ago is left to clean up.`,...plan2.results.map(one=>` ${projectName(one.repo)} ${one.taskId}: ${one.reason}${one.completes?"":" (already complete)"}`),...plan2.branches.map(one=>` ${projectName(one.repo)} ${one.branch}: ${one.reason}`),...plan2.pending===0?[]:[`${plurals(plan2.pending,"item")} from an earlier clean-up will finish too.`],...plan2.kept.length===0?[]:[`Stays (${plan2.kept.length}):`,...plan2.kept.map(keepLine)],anything?"Nothing was changed. Run toolroll storage clean --landed --yes to do it.":"Nothing was changed."])}const actor=await operator();if(actor===null)return refused("cleans up landed work");const plan=await landedBacklog(context.store,git,remotes,context.evidenceRoot,context.clock()),done=await cleanLandedBacklog(context.store,pool,git,remotes,context.evidenceRoot,context.clock,plan,actor),gone=done.steps.filter(one=>one.outcome==="removed"||one.outcome==="already gone"),stays=done.steps.filter(one=>one.outcome==="waits"||one.outcome==="kept");return succeed(context.write,context.json,command,{completed:done.completed,steps:done.steps,refused:done.refused,kept:plan.kept},()=>[`Marked ${plurals(done.completed.length,"landed result")} complete. Removed ${plurals(gone.filter(one=>one.kind==="checkout").length,"checkout")} and ${plurals(gone.filter(one=>one.kind==="branch").length,"local branch","local branches")}.`,...stays.length+done.refused.length===0?[]:[`Stays (${stays.length+done.refused.length}):`,...stays.map(stepLine),...done.refused.map(keepLine)]])}function checkoutSummary(plan){return{count:plan.count,totalBytes:plan.totalBytes,waitingReview:plan.waitingReview,withChanges:plan.withChanges,cleanBytes:plan.freeBytes,cleanCount:plan.go.length,cleanup:plan.cleanup,idle:plan.idle,idleCount:plan.idleCount,idleBytes:plan.idleBytes,uncommitted:plan.stay.filter(one=>one.why==="has changes").map(one=>({path:one.path,taskId:one.taskId,bytes:one.bytes}))}}async function reviewSwitchCommand(positional,flags,context){const{store,write,json}=context,[action="show",...extra]=positional,command=`review ${action}`;if(extra.length>0||!["show","on","off"].includes(action))return fail(write,json,command,"usage","Use toolroll review show|on|off --repo <path>.",EXIT.usage);const allowed=new Set(["repo","db","json",...action==="show"?[]:["as","token","token-file","token-env"]]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const given=text(flags,"repo");if(given===void 0)return fail(write,json,command,"usage","Name the project: toolroll review "+action+" --repo <path>.",EXIT.usage);const repo=canonicalProject(given)??resolve(given),words=(on,source)=>`${projectName(repo)}: automatic review is ${on?"on":"off"}${source==="hands-off"?" (on while the hands-off mode lasts)":source==="default"?" (the default)":""}.`;if(action==="show"){const state=store.reviewSwitch(repo,context.clock());return succeed(write,json,command,{repo,...state},()=>[words(state.on,state.source)])}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage",`Sign in first, or pass --as <you> --token <t>: toolroll review ${action} --repo <path>.`,EXIT.usage);const verified=authenticateApprover(store,acting.name,acting.token,repo);if(!verified.ok)return fail(write,json,command,verified.reason,`Only an approver of ${projectName(repo)} can change its review switch.`,EXIT.refused);const changed=store.setReviewSwitch(repo,action==="on",acting.name,context.clock());return succeed(write,json,command,{repo,...changed.after,before:changed.before},()=>[words(changed.after.on,changed.after.source),changed.after.on?"Each finished build whose check passes gets one read-only review; only HIGH findings send it back, once.":"Finished builds go straight to you."])}async function policyCommand(positional,flags,context){const[action,...extra]=positional,command=`policy ${action??""}`.trim(),store=context.store,shown=policy=>{const parts=policyParts(policy);return[`Providers: ${parts.providers}`,`Models: ${parts.models}`,`Tools: ${parts.tools}`,`Ceiling: ${parts.ceiling}`,...policy.updatedBy===null?[]:[`Changed by ${policy.updatedBy} at ${policy.updatedAt}.`]]};if(extra.length>0||action!==void 0&&action!=="show"&&action!=="set")return fail(context.write,context.json,command,"usage","Use policy show or policy set.",EXIT.usage);if(action===void 0||action==="show"){for(const name of flags.keys())if(!["history","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a policy show option.`,EXIT.usage);const policy=store.orgPolicy(),history=flags.has("history")?store.policyHistory(50):[];return succeed(context.write,context.json,command,{policy,...flags.has("history")?{history}:{}},()=>[...shown(policy),...history.map(one=>` ${one.at.slice(0,16).replace("T"," ")} ${one.actor} ${one.action.replace(/^organisation policy: /,"")}: ${one.detail??""}`)])}const allowed=new Set(["providers","models","tools","ceiling","as","token","token-file","token-env","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a policy set option.`,EXIT.usage);if(!["providers","models","tools","ceiling"].some(name=>flags.has(name)))return fail(context.write,context.json,command,"usage","Say what to set: --providers, --models, --tools or --ceiling.",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets the policy: pass --as and --token (or use the remembered login).",EXIT.refused);const current=store.orgPolicy(),listFlag=(name,now)=>{if(!flags.has(name))return now;const given=text(flags,name)??"";return given.trim().toLowerCase()==="any"?null:parseList(given)??[]},checked=checkPolicy({providers:listFlag("providers",current.providers),models:listFlag("models",current.models),tools:listFlag("tools",current.tools),ceiling:text(flags,"ceiling")??current.ceiling});if(!checked.ok)return fail(context.write,context.json,command,"usage",`${checked.problem} Nothing changed.`,EXIT.usage);const saved=store.setOrgPolicy(checked.policy,acting.name,context.clock());return succeed(context.write,context.json,command,{policy:saved},()=>["Policy saved.",...shown(saved)])}function taskEvidenceCommand(rest,flags,context){const command="task evidence",allowed=new Set(["html","out","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a task evidence option.`,EXIT.usage);const[taskId,...extra]=rest;if(taskId===void 0||extra.length>0)return fail(context.write,context.json,command,"usage","Use task evidence <id> [--html] [--out <file>].",EXIT.usage);const pack=evidencePack(context.store,taskId,{principal:"operator",repos:null,includeUnplaced:!0},"command line",context.clock(),context.evidenceRoot);if(pack===null)return fail(context.write,context.json,command,"unknown-task",`No task ${taskId}.`,EXIT.refused);const content=flags.has("html")?standaloneEvidenceHtml(pack):`${JSON.stringify(pack,null,2)}
501
+ `),EXIT.refused,{report});const checked=`schema ${report.schemaVersion}, ledger chain verified (${report.ledger?.entries??0} entries)`;return succeed(write,json,command,{report},()=>dryRun?[`Dry run: ${report.file} can be restored (${checked}). Nothing was changed.`]:[`Restored ${report.file} (${checked}).`,`The database as it was is kept at ${report.savedAs}.`])}function exportCommand(positional,flags,context){const command="export";for(const name of flags.keys())if(!["out","zip","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not an export option.`,EXIT.usage);const out=text(flags,"out");if(positional.length>0||out===void 0||out==="")return fail(context.write,context.json,command,"usage","Use export --out <path> [--zip].",EXIT.usage);const target=resolve(out);if(existsSync(target))return fail(context.write,context.json,command,"exists","That path exists already; choose a new one.",EXIT.failed);const who="command line",now=context.clock(),zip=flags.has("zip");context.store.recordAction({at:now.toISOString(),actor:who,repo:null,taskId:null,runId:null,action:"everything exported",outcome:"exported",source:"access",detail:zip?"as a .zip":"as a folder"});const exported=buildExport(context.store,{who,now,evidenceRoot:context.evidenceRoot,configDir:dirname(context.databaseFile)});try{zip?writeFileSync(target,exportZip(exported),{mode:384,flag:"wx"}):writeExportFolder(target,exported)}catch{return fail(context.write,context.json,command,"unwritable","The export couldn't be written there.",EXIT.failed)}return succeed(context.write,context.json,command,{out:target,zip,files:exported.files.length,tables:exported.tables,packs:exported.packs},()=>[`Exported ${exportSummary(exported)} to ${target}.`,"manifest.json lists every file with its SHA-256; README.md explains the layout."])}async function budgetCommand(positional,flags,context){const[action]=positional,command=`budget ${action??""}`.trim(),store=context.store;if(action===void 0||action==="list"){const budgets=store.monthSpend(context.clock()).budgets;return succeed(context.write,context.json,command,{budgets},()=>budgets.length===0?["No budgets. `budget set --all|--project <path>|--person <name>|--subagent <id> --usd <n>` makes one."]:budgets.map(one=>`#${one.id} ${budgetLabel(one).replace(/'s$/,"")}: ${spendUsd(one.spentMicrousd)} of ${spendUsd(one.limitMicrousd)} this month (${one.percent}%)${one.hardStop?", stops API work at 100%":", alerts only"}`))}if(action!=="set"&&action!=="remove")return fail(context.write,context.json,command,"usage","Use budget list, budget set or budget remove.",EXIT.usage);const allowed=new Set(["all","project","person","subagent","teammate","usd","alerts-only","as","token","token-file","token-env","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a budget option.`,EXIT.usage);const chosen=[flags.has("all")?{scope:"installation",key:"*"}:null,text(flags,"project")===void 0?null:{scope:"project",key:resolve(text(flags,"project"))},text(flags,"person")===void 0?null:{scope:"person",key:text(flags,"person")},(text(flags,"subagent")??text(flags,"teammate"))===void 0?null:{scope:"subagent",key:text(flags,"subagent")??text(flags,"teammate")}].filter(one=>one!==null);if(chosen.length!==1)return fail(context.write,context.json,command,"usage","Name one of --all, --project <path>, --person <name> or --subagent <id>.",EXIT.usage);const target=chosen[0],acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets budgets: pass --as and --token (or use the remembered login).",EXIT.refused);if(!(target.scope==="installation"||(target.scope==="project"?store.knownRepos().includes(target.key):target.scope==="person"?store.accountFacts().some(one=>one.name===target.key&&one.revokedAt===null):store.handle.prepare("SELECT 1 FROM subagent WHERE id = ?").get(Number(target.key))!==void 0)))return fail(context.write,context.json,command,"not-found","That isn't a project, person or subagent here.",EXIT.refused);if(action==="remove"){const existing=store.budgets().find(one=>one.scope===target.scope&&one.key===target.key);return existing===void 0||!store.removeBudget(existing.id,acting.name,context.clock())?fail(context.write,context.json,command,"not-found","There's no such budget.",EXIT.refused):succeed(context.write,context.json,command,{removed:existing.id},()=>[`Removed the ${budgetLabel(existing).replace(/'s$/,"")} budget.`])}const dollars=Number(text(flags,"usd")??"");if(!Number.isFinite(dollars)||dollars<1||dollars>1e7)return fail(context.write,context.json,command,"usage","--usd is a whole number of dollars, at least 1.",EXIT.usage);const saved=store.setBudget({scope:target.scope,key:target.key,limitMicrousd:Math.round(dollars)*1e6,hardStop:!flags.has("alerts-only")},acting.name,context.clock());return succeed(context.write,context.json,command,{budget:saved},()=>[`${budgetLabel(saved).replace(/'s$/,"")}: ${spendUsd(saved.limitMicrousd)} a month${saved.hardStop?", API work stops at 100%":", alerts only"}.`])}async function notificationsCommand(positional,flags,context){const[action,value,...extra]=positional,command=`notifications${action===void 0?"":` ${action}`}`,store=context.store,muting=action==="mute"||action==="unmute";for(const name of flags.keys())if(!["as","token","token-file","token-env","db","json",...muting?["repo"]:[]].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a notifications option.`,EXIT.usage);const usage="Use notifications quiet, notifications all, notifications digest <HH:MM>|off, notifications screenshots off|first|all, or notifications mute|unmute --repo <project>.",valued=action==="digest"||action==="screenshots";if(extra.length>0||action!==void 0&&!["quiet","all","digest","screenshots","mute","unmute"].includes(action)||valued!==(value!==void 0)||muting&&(value!==void 0||text(flags,"repo")===void 0))return fail(context.write,context.json,command,"usage",usage,EXIT.usage);if(action==="screenshots"&&!RESULT_SCREENSHOTS.includes(value))return fail(context.write,context.json,command,"usage","Screenshots with results is off, first (the first one) or all (up to 4).",EXIT.usage);if(action==="digest"&&value!=="off"&&!isDigestTime(value))return fail(context.write,context.json,command,"usage","The digest time is HH:MM on a 24-hour clock, like 18:30, or off.",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return fail(context.write,context.json,command,"refused","Notifications are set per person: pass --as and --token (or use the remembered login).",EXIT.refused);const now=context.clock();if(muting){const typed=text(flags,"repo"),repo=canonicalProject(typed)??resolve(typed);if(!new Set([...store.knownRepos(),...store.listProjects().map(one=>one.path)]).has(repo)||!store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"unknown-project",`${typed} is not a project you can see.`,EXIT.refused);store.setProjectMuted(acting.name,repo,action==="mute",now);const muted2=store.mutedProjects(acting.name);return succeed(context.write,context.json,command,{repo,muted:action==="mute",mutedProjects:muted2},()=>[action==="mute"?`${basename(repo)} is muted: no pings for it. The console and your evening digest still show it.`:`${basename(repo)} pings you again.`])}const preference=action==="quiet"||action==="all"?store.setNotificationPreference(acting.name,{mode:action},acting.name,now):action==="digest"?store.setNotificationPreference(acting.name,{digestAt:value==="off"?null:value},acting.name,now):action==="screenshots"?store.setNotificationPreference(acting.name,{screenshots:value},acting.name,now):store.notificationPreference(acting.name),muted=store.mutedProjects(acting.name);return succeed(context.write,context.json,command,{mode:preference.mode,digestAt:preference.digestAt,screenshots:preference.screenshots,mutedProjects:muted},()=>[preference.mode==="quiet"?"Only when you're needed: one message per task, updated as it moves, and a new one when something needs you.":"Every step: a message for each update.",preference.digestAt===null?"No evening digest.":`Evening digest at ${preference.digestAt}: what finished, what waits and what failed.`,preference.screenshots==="off"?"Screenshots with results: off.":`Screenshots with results: ${preference.screenshots==="first"?"the first one":"up to 4"}.`,...muted.length===0?[]:[`Muted: ${muted.map(one=>basename(one)).join(", ")}.`]])}async function retentionCommand(positional,flags,context){const[action,...rest]=positional,command=`retention ${action??""}`.trim(),store=context.store,allowed=new Set(action==="set"?["as","token","token-file","token-env","db","json"]:["db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const label=kind2=>RETENTION_KINDS.find(one=>one.kind===kind2).label;if(action===void 0||action==="show"){const periods2=store.retentionPeriods(),chosen=store.retentionChosen(),defaulted=RETENTION_KINDS.map(one=>one.kind).filter(kind2=>!(kind2 in chosen)),last=lastSweepAt(store);return succeed(context.write,context.json,command,{periods:periods2,defaulted,lastSweep:last},()=>[...RETENTION_KINDS.map(one=>` ${one.kind.padEnd(14)} ${periodLabel(one.kind,periods2[one.kind],one.kind in chosen).toLowerCase().padEnd(18)} ${one.label}`),` ${NOTIFICATION_RETENTION_WORDS}`,last===null?"No sweep yet; the worker runs one a day.":`Last sweep ${last.slice(0,16).replace("T"," ")} UTC.`])}if(action==="preview"){const plan=retentionPlan(store,context.evidenceRoot,context.clock()),kept=plan.counts.filter(one=>one.days===null).map(one=>one.kind),fixed=notificationLifecyclePreview(store,context.clock());return succeed(context.write,context.json,command,{counts:plan.counts,lifecycle:fixed},()=>[...plan.counts.filter(one=>one.days!==null).map(one=>` ${label(one.kind).padEnd(26)} ${countWords(one)} older than ${periodWords(one.days)}, about ${bytesWords(one.bytes)}${one.more?" (more after this sweep)":""}`),` ${"Progress updates".padEnd(26)} ${fixed.pings} settled and older than ${LIFECYCLE_RETENTION_DAYS} days, task finished; ${fixed.legacy} undeliverable delivery records older than ${LIFECYCLE_RETENTION_DAYS} days`,kept.length===RETENTION_KINDS.length?"Everything else is kept forever.":`Nothing was removed.${kept.length===0?"":` Kept forever: ${kept.join(", ")}.`}`])}if(action!=="set")return fail(context.write,context.json,command,"usage","Use retention show, retention preview or retention set <kind> <period>.",EXIT.usage);const[kind,period,...extra]=rest;if(kind===void 0||!isRetentionKind(kind)||period===void 0||extra.length>0)return fail(context.write,context.json,command,"usage",`Use retention set <${RETENTION_KINDS.map(one=>one.kind).join("|")}> <days, like 1d, 90d or 1y, or forever>.`,EXIT.usage);const days=parsePeriod(period);if(days===void 0)return fail(context.write,context.json,command,"usage",`A period is forever, or ${MIN_DAYS} day to 10 years (1d, 90d, 12w, 1y).`,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets retention: pass --as and --token (or use the remembered login).",EXIT.refused);const periods=store.setRetentionPeriod(kind,days,acting.name,context.clock());return succeed(context.write,context.json,command,{periods},()=>[`${label(kind)}: kept ${days===null?"forever":`for ${periodWords(days)}`}.`])}async function storageCommand(positional,flags,context){const[action,...rest]=positional,command=`storage ${action??""}`.trim(),store=context.store,changes=action==="cleanup"&&rest.length>0||action==="clean"&&flags.has("yes")||action==="discard",allowed=new Set([...changes?["as","token","token-file","token-env"]:[],...action==="clean"||action==="discard"?["yes"]:[],...action==="clean"?["landed"]:[],"db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const pool=new WorktreePool(store,{root:join(dirname(context.databaseFile),"worktrees"),...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),operator=async()=>{const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);return acting!==null&&verified!==null&&verified.ok&&store.isInstanceOperator(acting.name)?acting.name:null},refused=what=>fail(context.write,context.json,command,"refused",`An instance operator ${what}: pass --as and --token (or use the remembered login).`,EXIT.refused),summary=plan=>[`Task folders: ${plan.count}, ${bytesWords(plan.totalBytes)}. ${plan.waitingReview} waiting for review, ${plan.withChanges} with uncommitted changes.`,plan.go.length===0?"A clean up now would free nothing.":`A clean up now would free about ${bytesWords(plan.freeBytes)} (${plan.go.length} task folder${plan.go.length===1?"":"s"}): toolroll storage clean`,`A finished task's clean folder is removed ${cleanupWords(plan.cleanup)}; its branch stays.`,idleCleanupWords(plan),...uncommittedLines(plan)],itemLine=one=>` ${bytesWords(one.bytes).padStart(8)} ${one.path}${one.why===null?"":` (${whyWords(one)})`}`,roots=context.tempRoots??tempRoots(),leftovers=measure=>{const found=testTempFolders(roots,context.clock()),sizes=measure?diskBytes(found.stale.map(one=>one.path)):new Map;return{count:found.all.length,stale:found.stale.length,staleBytes:[...sizes.values()].reduce((sum,one)=>sum+one,0)}},leftoverLine=temp=>temp.count===0?"Test temp folders: none.":`Test temp folders: ${temp.count}; ${temp.stale===0?"none older than a day.":`${temp.stale} older than a day: toolroll storage clean removes them.`}`,depsRoot=sharedDepsRoot(context.databaseFile),checkoutRows=()=>store.listWorktrees().map(row=>({path:row.path,repo:row.repo})),sharedFacts=copies=>{const sizes=diskBytes(copies.map(one=>one.dir));return copies.map(one=>({key:one.key,repo:one.repo,path:one.dir,bytes:sizes.get(one.dir)??0,checkouts:one.checkouts.length,usedBy:one.checkouts,retired:one.retired,node:one.node,createdAt:one.createdAt,usedAt:one.usedAt}))},sharedLine=one=>` ${bytesWords(one.bytes).padStart(8)} ${projectName(one.repo)} ${one.key.slice(0,8)}: ${one.checkouts===1?"1 checkout uses it":`${one.checkouts} checkouts use it`}${one.retired?" (changed after install; never linked again)":""}`,sweepFacts=()=>{const last=lastSweep(store),automatic=last?.source==="automatic"?last:lastSweep(store,"automatic");return{last,lastAutomatic:automatic,schedule:sweepSchedule(store,context.clock())}},sweepLines=facts=>{const when=at=>new Date(at).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),one=facts.last,head=one===null?"Not swept yet.":`Last swept ${when(one.at)}${one.source==="manual"?` by ${one.actor}`:" automatically"}: ${storageSweepWords(one.parts)}`,auto=one!==null&&one.source==="manual"&&facts.lastAutomatic!==null?[`Last automatic sweep ${when(facts.lastAutomatic.at)}: ${storageSweepWords(facts.lastAutomatic.parts)}`]:[];return[head,...auto,`Automatic sweep: ${sweepScheduleWords(facts.schedule,when)}`,...one===null?[]:sweepDetails(one.parts).slice(0,8).map(line=>` ${line}`)]};if(action===void 0){const plan=await checkoutPlan(store,pool,context.clock(),{manual:!0}),report=storageReport(store,context.databaseFile,plan.go.length===0?"nothing to clean up":`about ${bytesWords(plan.freeBytes)} to clean up`),{staleBytes:_,...temp}=leftovers(!1),shared=sharedFacts(sharedUse(depsRoot,checkoutRows())),sweep=sweepFacts();return succeed(context.write,context.json,"storage",{...report,checkouts:checkoutSummary(plan),testTemp:temp,shared,sweep},()=>[`${report.folder}: ${bytesWords(report.total)}`,...report.lines.map(one=>` ${one.what.padEnd(19)} ${bytesWords(one.bytes).padStart(8)}${one.count===void 0?"":` (${one.count})`}${one.note===void 0?"":` ${one.note}`}`),...shared.length===0?[]:["Shared dependencies:",...shared.map(sharedLine)],...summary(plan),leftoverLine({...temp,staleBytes:0}),...sweepLines(sweep)])}if(action==="cleanup"){if(rest.length===0){const cleanup2=store.checkoutCleanup(),idle=checkoutIdle(store);return succeed(context.write,context.json,command,{cleanup:cleanup2,idle},()=>[`A finished task's clean folder is removed ${cleanupWords(cleanup2)}; its branch stays.`,`A task's clean folder is removed ${idleWords(idle)}; its branch stays.`])}const usage=`Use storage cleanup <${CLEANUP_CHOICES.map(one=>one.value).join("|")}> or storage cleanup idle <7|14|30|never>.`;if(rest[0]==="idle"){const idle=rest.length===2?parseIdle(rest[1]):void 0;if(idle===void 0)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const actor2=await operator();if(actor2===null)return refused("sets idle cleanup");const saved2=setCheckoutIdle(store,idle,actor2,context.clock());return succeed(context.write,context.json,command,{idle:saved2},()=>[`Saved. A task's clean folder is removed ${idleWords(saved2)}; its branch stays.`])}const cleanup=rest.length===1?parseCleanup(rest[0]):void 0;if(cleanup===void 0)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const actor=await operator();if(actor===null)return refused("sets checkout cleanup");const saved=store.setCheckoutCleanup(cleanup,actor,context.clock());return succeed(context.write,context.json,command,{cleanup:saved},()=>[`Saved. A finished task's clean folder is removed ${cleanupWords(saved)}; its branch stays.`])}if(action==="clean"&&flags.has("landed"))return rest.length>0||flags.get("landed")!==!0?fail(context.write,context.json,"storage clean --landed","usage","Use storage clean --landed to preview, then storage clean --landed --yes.",EXIT.usage):landedCommand(flags.has("yes"),operator,refused,pool,context);if(action==="clean"){if(rest.length>0)return fail(context.write,context.json,command,"usage","Use storage clean to preview, then storage clean --yes.",EXIT.usage);if(!flags.has("yes")){const plan=await checkoutPlan(store,pool,context.clock(),{manual:!0}),temp2=leftovers(!0),leaving=new Set(plan.go.map(one=>one.path)),unused2=unusedShared(depsRoot,checkoutRows().filter(row=>!leaving.has(row.path)),context.clock()),sharedGo=sharedFacts(unused2.copies),sharedBytes=sharedGo.reduce((sum,one)=>sum+one.bytes,0),anything=plan.go.length>0||temp2.stale>0||sharedGo.length>0;return succeed(context.write,context.json,command,{preview:!0,go:plan.go,stay:plan.stay,freeBytes:plan.freeBytes,testTemp:temp2,sharedGo,sharedFreeBytes:sharedBytes},()=>[...plan.go.length===0?[anything?"No task folders to clean up.":"Nothing to clean up."]:[`Would remove ${plan.go.length} task folder${plan.go.length===1?"":"s"}, freeing about ${bytesWords(plan.freeBytes)} (their branches stay):`,...plan.go.map(itemLine)],...sharedGo.length===0?[]:[`Would remove ${sharedGo.length} shared dependency install${sharedGo.length===1?"":"s"} no checkout uses, about ${bytesWords(sharedBytes)}:`,...sharedGo.map(sharedLine)],...plan.stay.length===0?[]:[`Stays (${plan.stay.length}):`,...plan.stay.map(itemLine)],...temp2.stale===0?[]:[`Would remove ${temp2.stale} test temp folder${temp2.stale===1?"":"s"} older than a day, about ${bytesWords(temp2.staleBytes)}.`],anything?"Nothing was removed. Run toolroll storage clean --yes to remove them.":"Nothing was removed."])}const actor=await operator();if(actor===null)return refused("cleans up checkouts");const done=await cleanCheckouts(store,pool,context.clock,{manual:!0,actor}),temp=leftovers(!0),swept=await removeStaleTestTemp(roots,context.clock());swept.removed.length>0&&store.recordAction({at:context.clock().toISOString(),actor,repo:null,taskId:null,runId:null,action:"test temp folders removed",outcome:"removed",source:"request",detail:`${swept.removed.length} older than a day, about ${bytesWords(temp.staleBytes)}${swept.failed.length===0?"":`; ${swept.failed.length} couldn't be removed`}`});const unused=unusedShared(depsRoot,checkoutRows(),context.clock()),sharedRemoved=sharedFacts(unused.copies).filter(one=>removeShared(one.path));for(const one of sharedRemoved)store.recordAction({at:context.clock().toISOString(),actor,repo:one.repo,taskId:null,runId:null,action:"shared dependencies removed",outcome:"removed",source:"request",detail:`${one.key} (about ${bytesWords(one.bytes)}); no checkout used it`});for(const debris of unused.debris)removeShared(debris);const sharedFreed=sharedRemoved.reduce((sum,one)=>sum+one.bytes,0),parts=[{kind:"checkouts",count:done.removed.length,bytes:done.freed,failed:done.kept.filter(one=>one.why==="git refused").length,items:done.removed.slice(0,20).map(one=>one.path)},{kind:"test temp",count:swept.removed.length,bytes:temp.staleBytes,failed:swept.failed.length,items:swept.removed.slice(0,20)},{kind:"dependencies",count:sharedRemoved.length,bytes:sharedFreed,failed:unused.copies.length-sharedRemoved.length,items:sharedRemoved.slice(0,20).map(one=>one.path)}];return saveSweep(store,{at:context.clock().toISOString(),source:"manual",actor,parts}),succeed(context.write,context.json,command,{removed:done.removed,kept:done.kept,freedBytes:done.freed,testTempRemoved:swept.removed.length,testTempFailed:swept.failed,sharedRemoved,sharedFreedBytes:sharedFreed},()=>[done.removed.length===0?swept.removed.length===0&&sharedRemoved.length===0?"Nothing to clean up.":"No task folders to clean up.":`Removed ${done.removed.length} task folder${done.removed.length===1?"":"s"}, about ${bytesWords(done.freed)}; their branches stay.`,...done.removed.map(itemLine),...sharedRemoved.length===0?[]:[`Removed ${sharedRemoved.length} shared dependency install${sharedRemoved.length===1?"":"s"} no checkout used, about ${bytesWords(sharedFreed)}.`,...sharedRemoved.map(sharedLine)],...done.kept.map(one=>` kept ${one.path} (${whyWords({why:one.why})})`),...swept.removed.length===0?[]:[`Removed ${swept.removed.length} test temp folder${swept.removed.length===1?"":"s"} older than a day, about ${bytesWords(temp.staleBytes)}.`],...swept.failed.length===0?[]:[`Couldn't remove ${swept.failed.length} test temp folder${swept.failed.length===1?"":"s"}: ${swept.failed.slice(0,3).join(", ")}${swept.failed.length>3?" …":""}`]])}if(action==="discard"){const[path,...extra]=rest;if(path===void 0||extra.length>0)return fail(context.write,context.json,command,"usage","Use storage discard <path> --yes.",EXIT.usage);const target=resolve(path);if(store.getWorktree(target)===null)return fail(context.write,context.json,command,"not-found",`${target} is not a task checkout. toolroll storage clean lists them.`,EXIT.refused);if(!flags.has("yes"))return fail(context.write,context.json,command,"usage",`This throws away ${target} and its uncommitted changes (its branch stays). Add --yes to discard it.`,EXIT.usage);const actor=await operator();if(actor===null)return refused("discards a checkout");const done=await discardCheckout(store,pool,target,context.clock(),actor);return done.ok?succeed(context.write,context.json,command,{discarded:target,freedBytes:done.bytes},()=>[`Discarded ${target}, about ${bytesWords(done.bytes)}; its branch stays.`]):fail(context.write,context.json,command,"refused",done.message,EXIT.refused)}return fail(context.write,context.json,command,"usage","Use storage, storage cleanup <when>, storage clean [--landed] [--yes] or storage discard <path> --yes.",EXIT.usage)}async function landedCommand(yes,operator,refused,pool,context){const remotes=new RemoteMains(context.store,context.gitRunner,context.evidenceRoot);try{return await landedCommandWith(remotes,yes,operator,refused,pool,context)}finally{remotes.close()}}async function landedCommandWith(remotes,yes,operator,refused,pool,context){const command="storage clean --landed",git=gitOf(context.gitRunner),plurals=(count,one,many=`${one}s`)=>`${count} ${count===1?one:many}`,keepLine=one=>` ${projectName(one.repo)} ${one.what}: ${one.why}`,stepLine=one=>` ${projectName(one.repo)} ${one.target}${one.why===null?"":`: ${one.why}`}`,counts=plan2=>({results:plan2.results.length,complete:plan2.results.filter(one=>one.completes).length,checkouts:plan2.results.reduce((sum,one)=>sum+one.targets.filter(target=>target.kind==="checkout").length,0)+plan2.branches.filter(one=>one.checkout!==null).length,branches:plan2.results.reduce((sum,one)=>sum+one.targets.filter(target=>target.kind==="branch").length,0)+plan2.branches.length});if(!yes){const plan2=await landedBacklog(context.store,git,remotes,context.evidenceRoot,context.clock()),n=counts(plan2),anything=n.results+plan2.branches.length+plan2.pending>0;return succeed(context.write,context.json,command,{preview:!0,cutoff:plan2.cutoff,results:plan2.results,branches:plan2.branches,kept:plan2.kept,pending:plan2.pending},()=>[anything?`Would mark ${plurals(n.complete,"landed result")} complete and remove ${plurals(n.checkouts,"checkout")} and ${plurals(n.branches,"local branch","local branches")}.`:`Nothing landed more than ${BACKLOG_DAYS} days ago is left to clean up.`,...plan2.results.map(one=>` ${projectName(one.repo)} ${one.taskId}: ${one.reason}${one.completes?"":" (already complete)"}`),...plan2.branches.map(one=>` ${projectName(one.repo)} ${one.branch}: ${one.reason}`),...plan2.pending===0?[]:[`${plurals(plan2.pending,"item")} from an earlier clean-up will finish too.`],...plan2.kept.length===0?[]:[`Stays (${plan2.kept.length}):`,...plan2.kept.map(keepLine)],anything?"Nothing was changed. Run toolroll storage clean --landed --yes to do it.":"Nothing was changed."])}const actor=await operator();if(actor===null)return refused("cleans up landed work");const plan=await landedBacklog(context.store,git,remotes,context.evidenceRoot,context.clock()),done=await cleanLandedBacklog(context.store,pool,git,remotes,context.evidenceRoot,context.clock,plan,actor),gone=done.steps.filter(one=>one.outcome==="removed"||one.outcome==="already gone"),stays=done.steps.filter(one=>one.outcome==="waits"||one.outcome==="kept");return succeed(context.write,context.json,command,{completed:done.completed,steps:done.steps,refused:done.refused,kept:plan.kept},()=>[`Marked ${plurals(done.completed.length,"landed result")} complete. Removed ${plurals(gone.filter(one=>one.kind==="checkout").length,"checkout")} and ${plurals(gone.filter(one=>one.kind==="branch").length,"local branch","local branches")}.`,...stays.length+done.refused.length===0?[]:[`Stays (${stays.length+done.refused.length}):`,...stays.map(stepLine),...done.refused.map(keepLine)]])}function checkoutSummary(plan){return{count:plan.count,totalBytes:plan.totalBytes,waitingReview:plan.waitingReview,withChanges:plan.withChanges,cleanBytes:plan.freeBytes,cleanCount:plan.go.length,cleanup:plan.cleanup,idle:plan.idle,idleCount:plan.idleCount,idleBytes:plan.idleBytes,uncommitted:plan.stay.filter(one=>one.why==="has changes").map(one=>({path:one.path,taskId:one.taskId,bytes:one.bytes}))}}async function reviewSwitchCommand(positional,flags,context){const{store,write,json}=context,[action="show",...extra]=positional,command=`review ${action}`;if(extra.length>0||!["show","on","off"].includes(action))return fail(write,json,command,"usage","Use toolroll review show|on|off --repo <path>.",EXIT.usage);const allowed=new Set(["repo","db","json",...action==="show"?[]:["as","token","token-file","token-env"]]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const given=text(flags,"repo");if(given===void 0)return fail(write,json,command,"usage","Name the project: toolroll review "+action+" --repo <path>.",EXIT.usage);const repo=canonicalProject(given)??resolve(given),words=(on,source)=>source==="hands-off"?`${projectName(repo)}: automatic review is on (on while the hands-off mode lasts).`:source==="default"?`${projectName(repo)}: automatic review is ${on?"on: a reviewer is set":"off (the default)"}.`:`${projectName(repo)}: automatic review is ${on?"on":"off"}.`;if(action==="show"){const state=store.reviewSwitch(repo,context.clock());return succeed(write,json,command,{repo,...state},()=>[words(state.on,state.source)])}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage",`Sign in first, or pass --as <you> --token <t>: toolroll review ${action} --repo <path>.`,EXIT.usage);const verified=authenticateApprover(store,acting.name,acting.token,repo);if(!verified.ok)return fail(write,json,command,verified.reason,`Only an approver of ${projectName(repo)} can change its review switch.`,EXIT.refused);const changed=store.setReviewSwitch(repo,action==="on",acting.name,context.clock());return succeed(write,json,command,{repo,...changed.after,before:changed.before},()=>[words(changed.after.on,changed.after.source),changed.after.on?"Each finished build whose check passes gets one read-only review; only HIGH findings send it back, once.":"Finished builds go straight to you."])}async function policyCommand(positional,flags,context){const[action,...extra]=positional,command=`policy ${action??""}`.trim(),store=context.store,shown=policy=>{const parts=policyParts(policy);return[`Providers: ${parts.providers}`,`Models: ${parts.models}`,`Tools: ${parts.tools}`,`Ceiling: ${parts.ceiling}`,...policy.updatedBy===null?[]:[`Changed by ${policy.updatedBy} at ${policy.updatedAt}.`]]};if(extra.length>0||action!==void 0&&action!=="show"&&action!=="set")return fail(context.write,context.json,command,"usage","Use policy show or policy set.",EXIT.usage);if(action===void 0||action==="show"){for(const name of flags.keys())if(!["history","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a policy show option.`,EXIT.usage);const policy=store.orgPolicy(),history=flags.has("history")?store.policyHistory(50):[];return succeed(context.write,context.json,command,{policy,...flags.has("history")?{history}:{}},()=>[...shown(policy),...history.map(one=>` ${one.at.slice(0,16).replace("T"," ")} ${one.actor} ${one.action.replace(/^organisation policy: /,"")}: ${one.detail??""}`)])}const allowed=new Set(["providers","models","tools","ceiling","as","token","token-file","token-env","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a policy set option.`,EXIT.usage);if(!["providers","models","tools","ceiling"].some(name=>flags.has(name)))return fail(context.write,context.json,command,"usage","Say what to set: --providers, --models, --tools or --ceiling.",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator sets the policy: pass --as and --token (or use the remembered login).",EXIT.refused);const current=store.orgPolicy(),listFlag=(name,now)=>{if(!flags.has(name))return now;const given=text(flags,name)??"";return given.trim().toLowerCase()==="any"?null:parseList(given)??[]},checked=checkPolicy({providers:listFlag("providers",current.providers),models:listFlag("models",current.models),tools:listFlag("tools",current.tools),ceiling:text(flags,"ceiling")??current.ceiling});if(!checked.ok)return fail(context.write,context.json,command,"usage",`${checked.problem} Nothing changed.`,EXIT.usage);const saved=store.setOrgPolicy(checked.policy,acting.name,context.clock());return succeed(context.write,context.json,command,{policy:saved},()=>["Policy saved.",...shown(saved)])}function taskEvidenceCommand(rest,flags,context){const command="task evidence",allowed=new Set(["html","out","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a task evidence option.`,EXIT.usage);const[taskId,...extra]=rest;if(taskId===void 0||extra.length>0)return fail(context.write,context.json,command,"usage","Use task evidence <id> [--html] [--out <file>].",EXIT.usage);const pack=evidencePack(context.store,taskId,{principal:"operator",repos:null,includeUnplaced:!0},"command line",context.clock(),context.evidenceRoot);if(pack===null)return fail(context.write,context.json,command,"unknown-task",`No task ${taskId}.`,EXIT.refused);const content=flags.has("html")?standaloneEvidenceHtml(pack):`${JSON.stringify(pack,null,2)}
485
502
  `;return writeOut(context,command,text(flags,"out"),content,{task:pack.task.id,digest:pack.digest,chainOk:pack.ledger.chain.ok},`Evidence pack for ${pack.task.id} (${pack.ledger.entries.length} ledger entries, chain ${pack.ledger.chain.ok?"verified":"BROKEN"}).`,flags.has("html")?{html:content}:{pack})}async function ledgerCommand(positional,flags,context){const[action,...extra]=positional,command=`ledger ${action??""}`.trim(),allowed=new Set(action==="verify"?["checkpoint","db","json"]:action==="checkpoint"?["as","token","token-file","token-env","db","json"]:["from","to","out","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);if(extra.length>0||action!=="verify"&&action!=="checkpoint"&&action!=="export")return fail(context.write,context.json,command,"usage","Use ledger verify, ledger checkpoint or ledger export --from <day> --to <day>.",EXIT.usage);const store=context.store;if(action==="verify"){const report=store.ledgerChain({full:!0}),copied=text(flags,"checkpoint"),outside=copied===void 0?null:matchesOutsideCheckpoint(store.handle,copied),inside=store.ledgerCheckpoints(1)[0]??null,ok=report.ok&&(outside===null||outside.ok),lines=[report.ok?`Chain verified: ${report.entries} entries through #${report.through??0}, head ${report.head}.`:`Chain BROKEN: ${report.problem?.what??"it doesn't verify"}.`,...report.checkpoints>0&&report.ok?[`All ${report.checkpoints} checkpoints kept here still match${inside===null?"":`; the latest is ${inside.through}:${inside.hash}`}.`]:[],...outside===null?[]:[outside.what]];return context.write(context.json?envelopeJson({ok,command,chain:report,outside}):lines.join(`
486
503
  `)),ok?EXIT.ok:EXIT.failed}if(action==="checkpoint"){const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator makes checkpoints: pass --as and --token (or use the remembered login).",EXIT.refused);const made=store.ledgerCheckpoint(acting.name,context.clock());return made===null?fail(context.write,context.json,command,"empty","The ledger has no entries yet.",EXIT.refused):"problem"in made?fail(context.write,context.json,command,"broken",`No checkpoint: the chain doesn't verify (${made.problem}).`,EXIT.failed):succeed(context.write,context.json,command,{through:made.through,hash:made.hash,checkpoint:`${made.through}:${made.hash}`},()=>[`${made.through}:${made.hash}`,"Copy this somewhere outside this machine; ledger verify --checkpoint <it> proves nothing before it was rewritten."])}const from=exportDay(text(flags,"from")??null),last=exportDay(text(flags,"to")??null);if(from===null||last===null)return fail(context.write,context.json,command,"usage","Use ledger export --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--out <file>].",EXIT.usage);const to=new Date(Date.parse(last)+864e5).toISOString();if(to<=from)return fail(context.write,context.json,command,"usage","--to is on or after --from.",EXIT.usage);const who="command line",content=[...ledgerExportChunks(store,{from,to},{repos:null,instance:!0},{principal:"operator",repos:null,includeUnplaced:!0},who,context.clock(),context.evidenceRoot)].join(""),bundle=JSON.parse(content);return store.recordAction({at:context.clock().toISOString(),actor:who,repo:null,taskId:null,runId:null,action:"ledger exported",outcome:"exported",source:"access",detail:`${from.slice(0,10)} to ${last.slice(0,10)} · ${bundle.entries.length} entries · ${bundle.packs.length} evidence packs`}),writeOut(context,command,text(flags,"out"),`${content}
487
504
  `,{entries:bundle.entries.length,packs:bundle.packs.length,chainOk:bundle.chain.ok},`${bundle.entries.length} ledger entries and ${bundle.packs.length} evidence packs (chain ${bundle.chain.ok?"verified":"BROKEN"}).`,{export:bundle})}function succeed(write,json,command,data,lines){return write(json?envelopeJson({ok:!0,command,...data}):lines().join(`
488
- `)),EXIT.ok}function fail(write,json,command,reason,message,code,extra={}){return write(json?envelopeJson({ok:!1,command,reason,message,...extra}):message),code}function text(flags,name){const value=flags.get(name);return typeof value=="string"?value:void 0}function flag(flags,name){return flags.get(name)===!0||flags.get(name)==="true"}function consoleLinkFor(context,path){const base=loadConsoleUrl(process.env,dirname(context.databaseFile));return base===null?null:`${base}${path}`}function refuseDemo(context,command){return context.store.isDemo()?fail(context.write,context.json,command,"demo-database","this database is a demo sandbox — it never spends money or touches a remote; point this command at a real database",EXIT.refused):null}function readTtl(flags){const given=text(flags,"ttl");if(given===void 0)return DEFAULT_LEASE_MS;const seconds=Number(given);return!Number.isInteger(seconds)||seconds<=0?null:seconds*1e3}function mutationFrom(flags,now){const key=text(flags,"key");return key===void 0?{at:now}:{idempotencyKey:key,at:now}}function slug(title,now){const words=title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").split("-").filter(Boolean).slice(0,4).join("-"),stamp=now.toISOString().slice(11,19).replace(/:/g,"");return words===""?`task-${stamp}`:`${words}-${stamp}`}function describe(error){return error instanceof Error?error.message:String(error)}function databaseFailure(write,json,command,file,error){return isDatabaseBusy(error)?fail(write,json,command,"database-busy",`The database ${file} stayed busy for ${CONCURRENT_WRITER_WAIT_MS/1e3} seconds. Wait for the other Toolroll process to finish, then try again.`,EXIT.failed):fail(write,json,command,"database",describe(error),EXIT.failed)}function refuseApprover(context,command,verified,usage,subject){if(verified===null)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const reason=verified.ok?"":verified.reason;return fail(context.write,context.json,command,reason,describeApproveFailure(reason,subject??""),EXIT.refused)}async function knownProject(context,repoFlag,match){const registered=await loadRepos(registryPathOf(context)).catch(()=>({error:"unreadable"}));return[...new Set([...context.store.knownRepos(),...match.listed?context.store.listProjects().map(one=>one.path):[],..."error"in registered?[]:registered.repos])].find(one=>one===repoFlag||one===resolve(repoFlag)||match.canonical&&one===canonicalProject(repoFlag))}export function ownValueFlags(command,argv){if(command==="flows")return FLOWS_VALUE_FLAGS;if(command==="card")return CARD_PANEL_VALUE_FLAGS;if(command==="project"&&argv.find(arg=>!arg.startsWith("-"))==="network")return PROJECT_NETWORK_VALUE_FLAGS}async function projectCheckAccessCommand(positional,flags,context){const command="project check-access",wanted=positional[1],repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project check-access --repo <project path> [sandboxed | sign-ins | unsandboxed].",invalid:wanted!==void 0&&!isCheckAccess(wanted),match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const current=context.store.projectCheckAccess(repo),platform=context.platform??process.platform,fenced=context.fenceAvailable?.()??(macosFenceAvailable()||linuxFenceAvailable()),runsAs=one=>checkAccessRunsAs(one,{platform,fenced,unconfinedAllowed:context.store.unfencedAgentsAllowed(),localMode:localModeOn(context.store)}),here=runsAs(current),words=one=>{if(runsAs(one)==="unsandboxed"&&one!=="unsandboxed")return[`${repo}: saved as ${checkAccessWords(one)}, but this machine can't sandbox checks, so they run without a sandbox.`];if(runsAs(one)!==one)return[`${repo}: saved with model and GitHub sign-ins, but its checks run sandboxed: sign-ins can't be shared with checks safely yet.`];const missing=one==="sign-ins"?signInHostsMissing(context.store.projectNetwork(repo)):[];return[`${repo}: checks run ${checkAccessWords(one)}.`,...one==="sandboxed"?[]:[CHECK_ACCESS_WARNINGS[one]],...missing.length===0?[]:[`Model sign-ins need these hosts in this project's network allowlist: ${missing.join(", ")}. Add them with: toolroll project network --repo ${repo} --allow ${missing.join(",")}`]]};if(wanted===void 0)return succeed(context.write,context.json,command,{repo,checkAccess:current,...here===current?{}:{runsAs:here},...here==="sign-ins"?{missingHosts:signInHostsMissing(context.store.projectNetwork(repo))}:{}},()=>words(current));const unavailable=wanted==="sign-ins"?signInsUnavailableWords(platform):null;if(unavailable!==null)return fail(context.write,context.json,command,"refused",unavailable,EXIT.refused);const widening=widerThan(wanted,current);if(wanted==="unsandboxed"&&localModeOn(context.store))return fail(context.write,context.json,command,"refused",LOCAL_MODE_CONFINES,EXIT.refused);const acting=await askCredentials(flags,context),proved=acting===null?null:authenticateApprover(context.store,acting.name,acting.token,repo);if(widening){if(acting===null||proved===null||!proved.ok||proved.method!=="password-now"||!context.store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator widens what a project's checks reach, with their password typed now: pass --as and --token.",EXIT.refused)}else if(acting===null||proved===null||!proved.ok||!credentialProof(proved.method)||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project narrows what its checks reach, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectCheckAccess(repo,wanted,acting.name,context.clock(),{may:widening?"widen":"narrow"});return changed===null?fail(context.write,context.json,command,"refused","The project's check access changed meanwhile, and this would now widen it: an instance operator widens it, with their password typed now.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,checkAccess:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}async function projectSandboxCommand(positional,flags,context){const command="project sandbox",repo=await projectAsked(context,flags,positional,command,{own:["read-deny","mach"],most:1,usage:"Use project sandbox --repo <project path> [--read-deny <paths>] [--mach <services>] (comma-separated; empty clears).",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=one=>[`${repo}: ${readDenyWords(one.readDeny)}`,...one.machLookup.length===0?[]:[`macOS services also allowed: ${one.machLookup.join(", ")}`]],current=context.store.projectSandbox(repo),asked=name=>{const value=flags.get(name);return value===void 0?void 0:value===!0?[]:value.split(",")},changes={readDeny:asked("read-deny"),machLookup:asked("mach")};if(changes.readDeny===void 0&&changes.machLookup===void 0)return succeed(context.write,context.json,command,{repo,sandbox:current},()=>words(current));const parsed={readDeny:parseReadDeny(changes.readDeny??current.readDeny),machLookup:parseMachLookup(changes.machLookup??current.machLookup)};for(const[name,one]of Object.entries(parsed))if(!one.ok)return fail(context.write,context.json,command,"usage",`${name}: ${one.problem}. Nothing changed.`,EXIT.usage);const wanted={readDeny:parsed.readDeny.ok?parsed.readDeny.list:[],machLookup:parsed.machLookup.ok?parsed.machLookup.list:[]},acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectSandbox(repo,wanted,acting.name,context.clock());return changed===null?fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox. Nothing changed.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,sandbox:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}function gitTooOld(command,context){const problem=installedGitFloorProblem();return problem===null?null:fail(context.write,context.json,command,"git-too-old",problem,EXIT.refused)}function upBuildIdentity(){return buildIdentity(PACKAGE_VERSION,fileURLToPath(import.meta.url))}function upNeedsOneProcess(options){return options.openDatabase!==void 0||options.desktopIdentity!==void 0||options.additionalProjectRepos!==void 0||options.agentRunner!==void 0||options.gitRunner!==void 0||options.telegramTransport!==void 0||options.telegramEnv!==void 0||options.publishExec!==void 0||options.dispatchAdapter!==void 0||options.flowTriggerIo!==void 0||options.flowStepIo!==void 0||options.flowEveryMs!==void 0||options.watchHeartbeatMs!==void 0||options.loopRelaunchMs!==void 0||options.platform!==void 0||options.fenceAvailable!==void 0||options.flowFetch!==void 0||options.integrationIo!==void 0||options.shouldStop!==void 0||options.leadSeams!==void 0||options.waitSleep!==void 0||options.releaseIo!==void 0||options.installBin!==void 0||options.tempRoots!==void 0||options.filingSizer!==void 0||options.now!==void 0||options.folderLook!==void 0}function recordRunnerProcess(databaseFile,holder,role,pid){try{const started=processStart(pid);if(started===null)return!1;const file=runnerProcessFile(databaseFile,holder.runner.name),credential=credentialDigest(holder.credentialHash),current=readRunnerProcessRecord(file),same=current!==null&&current.runner===holder.runner.name&&current.registeredAt===holder.runner.registeredAt&&current.credential===credential;if(role!=="up"&&(!same||current.signature!==sealRunnerProcessRecord(current,holder.credentialHash).signature))return!1;const kept=same?current.processes.filter(one=>one.role!==role||!processGone(one)):[],record={v:1,runner:holder.runner.name,host:holder.runner.host,registeredAt:holder.runner.registeredAt,credential,processes:[...kept.filter(one=>one.pid!==pid),{pid,role,started}]};return record.processes.length>64?!1:(writeRunnerProcessRecord(file,sealRunnerProcessRecord(record,holder.credentialHash)),!0)}catch{return!1}}function upRoleChildCommand(role){const source=import.meta.url.endsWith(".ts"),entry=fileURLToPath(new URL(source?"./up-role-child.ts":"./up-role-child.js",import.meta.url));return{file:process.execPath,argv:[...source?["--import",import.meta.resolve("tsx")]:[],entry,role]}}function startUpRole(args){const{role}=args;let resolveReady=()=>{};const ready=new Promise(resolve2=>resolveReady=resolve2),generations=new RoleGenerations;let stopping=!1,endedForGood=!1;const endForGood=detail=>{stopping||endedForGood||(endedForGood=!0,args.onEnded(detail,!1))};let failed=null,fatal=null,closedProblem=null,livePid=null;const receive=(raw,abort)=>{const message=roleMessage(raw,role);if(message!==null){if(message.type==="ready"){if(message.build!==args.build){fatal=`the ${role} is a different build (${message.build}) from this one (${args.build}) — restart Toolroll`,failed={reason:"start",detail:fatal},generations.refused(fatal),abort();return}livePid=message.pid;const again=!generations.ready();again||resolveReady({ok:!0,url:message.url??"",port:message.port,pid:message.pid}),args.onReady(message,again);return}if(message.type==="failed"){failed={reason:message.reason,detail:message.detail},generations.refused(message.detail);return}if(message.type==="fatal"){fatal=message.detail;return}if(message.type==="closed"){closedProblem=message.problem;return}message.type!=="alive"&&args.onMessage(message)}};if(!args.split){const channel=memoryChannel(role);channel.parent.onMessage(message=>receive(message,()=>channel.parent.stop(!1)));const done2=upRoleCommand(args.context,{start:args.start(1),port:channel.port}).catch(error=>(fatal=describe(error),EXIT.failed)).then(code=>(livePid=null,generations.wasReady()?endForGood(fatal??`the ${role} stopped (exit ${code})`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${code})`}}),{problem:closedProblem}));return{ready,done:done2,send:message=>channel.parent.send(message),stop:()=>{stopping=!0,channel.parent.stop(!1)},hardStop:()=>{channel.parent.stop(!0)},kill:()=>{stopping=!0,channel.parent.stop(!0)},pid:()=>livePid}}const controller=new AbortController;let child=null;const command=upRoleChildCommand(role);let heardAt=Date.now(),stoppingSince=null,liveBuilds=0,saidPaused=!1,saidWaiting=!1;const watchdog=args.watchdog===void 0?null:setInterval(()=>{const owned=child;if(stopping||controller.signal.aborted||owned===null||owned.exitCode!==null||owned.signalCode!==null||!generations.current())return;const now=Date.now(),silentMs=now-heardAt,silenceMs=args.watchdog.silenceMs??WORKER_SILENCE_MS,facts={silentMs,silenceMs,stoppingForMs:stoppingSince===null?null:now-stoppingSince,graceMs:args.watchdog.graceMs,deadlineMs:SHUTDOWN_DEADLINE_MS,liveBuilds,paused:!1};if(watchdogVerdict(facts)==="fine"){saidPaused=!1,saidWaiting=!1;return}try{facts.paused=args.watchdog.paused()}catch{facts.paused=!0}const verdict=watchdogVerdict(facts);if(verdict==="leave"){saidPaused||args.watchdog.say(`the ${role} isn't answering, but an update or restart is under way; leaving it to that`),saidPaused=!0;return}if(verdict==="wait"){saidWaiting||args.watchdog.say(`the ${role} is still stopping: ${liveBuilds===1?"a build hasn't":`${liveBuilds} builds haven't`} confirmed ${liveBuilds===1?"it":"they"} stopped; leaving it to finish`),saidWaiting=!0;return}verdict==="restart"&&(args.watchdog.say(silentMs<silenceMs?`the ${role}'s stop overran its deadline; stopping it and starting it again`:`the ${role} hasn't answered for ${Math.round(silentMs/1e3)}s; stopping it and starting it again`),stopProcessTree(owned)||owned.kill("SIGKILL"),heardAt=now)},WORKER_ALIVE_EVERY_MS);watchdog?.unref?.();const done=superviseController({file:command.file,argv:command.argv,signal:controller.signal,ipc:!0,shutdownMs:args.shutdownMs,label:envValue(process.env,"LOG_FORMAT")==="json"?"":`[${role}]`,onSpawn:(owned,generation)=>{child=owned,fatal=null,failed=null,generations.spawned(),heardAt=Date.now(),stoppingSince=null,owned.on("message",raw=>{heardAt=Date.now();const alive=roleMessage(raw,role);alive?.type==="alive"&&(stoppingSince=alive.stopping?stoppingSince??heardAt:null,liveBuilds=alive.liveBuilds),receive(raw,()=>controller.abort())}),owned.on("error",()=>{});let recorded=!1;try{recorded=owned.pid!==void 0&&(args.onSpawned?.(owned.pid)??!0)}catch{}if(!recorded){fatal="The worker process record could not be saved",failed={reason:"start",detail:fatal},generations.refused(fatal),owned.kill("SIGKILL"),controller.abort(),resolveReady({ok:!1,...failed});return}owned.send(args.start(generation),error=>{error!=null&&owned.kill("SIGTERM")})},onState:state=>{if(state.phase!=="backoff")return;child=null,livePid=null;const exit=state.exit?.signal??state.exit?.code??"unknown";if(stopping&&generations.wasReady())return;const verdict=generations.ended();if(verdict==="fail-start"){controller.abort(),resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${exit})`}});return}if(verdict==="end"){controller.abort(),endForGood(generations.refusedWith()??fatal??`the ${role} kept stopping before it was ready (exit ${exit})`);return}if(controller.signal.aborted){endForGood(fatal??`the ${role} stopped (exit ${exit})`);return}if(generations.struggling()){args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} is still restarting (${generations.notReady()} tries so far, exit ${exit})`,!0);return}args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} stopped unexpectedly (exit ${exit})`,!0)}}).catch(error=>{generations.wasReady()||resolveReady({ok:!1,reason:"start",detail:describe(error)})}).finally(()=>{watchdog!==null&&clearInterval(watchdog)}).then(()=>(generations.wasReady()?endForGood(generations.refusedWith()??fatal??`the ${role} stopped`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} did not start`}}),{problem:closedProblem}));return{ready,done,send:message=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send(message,()=>{})}catch{}},stop:()=>{stopping=!0,controller.abort()},hardStop:()=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send({type:"hard-stop"},()=>{})}catch{}},kill:()=>{stopping=!0,controller.abort();const owned=child;owned!==null&&owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},pid:()=>livePid}}export async function runUpRole(start,port){return runOperate("up",["--db",start.databaseFile,...start.containment===null?[]:["--containment",start.containment]],line=>port.send({type:"log",line}),{upRole:{start,port}})}async function upRoleCommand(context,host){const{start,port}=host;return start.build!==upBuildIdentity()?(port.send({type:"failed",reason:"start",detail:`this ${start.role} is a different build (${upBuildIdentity()}) from the \`up\` that started it (${start.build})`}),EXIT.refused):resolve(start.databaseFile)!==resolve(context.databaseFile)?(port.send({type:"failed",reason:"start",detail:`the ${start.role} opened a different database`}),EXIT.refused):start.role==="console"?runUpConsoleRole(context,start.config,port,start.build):runUpWorkerRole(context,start.config,port,start.build)}async function runUpConsoleRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),activeRepos=new Set(config.repos);let instanceSecret=null,draining=!1;const keyEpoch=randomBytes(16).toString("hex");let console_;try{console_=await startConsole({keyEpoch,instanceSecret:()=>instanceSecret,draining:()=>draining,context,host:config.host,port:config.port,...config.allowedHosts===null?{}:{allowedHosts:config.allowedHosts},...config.publicUrl===null?{}:{publicUrl:config.publicUrl},localRunner:config.localRunner,poolRoot:config.poolRoot,repos:config.repos,currentRepos:()=>[...activeRepos],admittedRepos:()=>[...activeRepos],upConsole:!0,registryPath:config.registryPath,projectRoots:await(async()=>{const saved=await loadProjectRegistry(config.registryPath);return"error"in saved?config.projectRoots:saved.roots})(),...config.editor?{editorLinks:"vscode"}:{}})}catch(error){return port.send({type:"failed",reason:"port-busy",detail:describe(error)}),EXIT.refused}let codingClosed=!1;const closeCoding=()=>{codingClosed||(codingClosed=!0,console_.server.closeCoding().catch(()=>{}))};let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);port.onStop(()=>resolveStopped());const lifecycleComponent=consoleComponent(config.host,console_.port),lifecycleHolder=`${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,lifecycleComponent,"started",lifecycleHolder,clock(),{pid:process.pid})}catch{}const lifecycleBeat=setInterval(()=>{try{beatLifecycle(store,lifecycleComponent,lifecycleHolder,clock())}catch{}},RUNNER_HEARTBEAT_MS);lifecycleBeat.unref?.(),port.onMessage(message=>{if(message.type==="repos"){activeRepos.clear();for(const repo of message.repos)activeRepos.add(repo)}else if(message.type==="stopping"){draining=!0;try{reportLifecycle(store,lifecycleComponent,"draining",lifecycleHolder,clock(),{drainUntil:new Date(clock().getTime()+6e4)})}catch{}closeCoding()}else if(message.type==="sign-in-link"){let link=null;try{link=consoleSignInLink(console_.server,config.startAuthority,message)}catch{link=null}port.send({type:"sign-in-link",id:message.id,link})}});let mintedSecret=null;const instanceSocket=await openInstanceSocket(context.databaseFile,{pid:process.pid,build:packageVersion(),database:context.databaseFile,port:console_.port},()=>mintedSecret,()=>console_.server.mintLocalLink());instanceSocket.ok?(mintedSecret=await claimInstance(store,context.databaseFile,{pid:process.pid,port:console_.port,build:packageVersion(),socket:instanceSocket.name,keyEpoch:console_.server.keyEpoch},clock()),instanceSecret=mintedSecret,mintedSecret===null&&progress("attach: another console is running on this database — `toolroll` in a repository opens that one")):progress(`attach: ${instanceSocket.problem} — \`toolroll\` in a repository won't find this console`),port.send({type:"ready",role:"console",build:build2,pid:process.pid,url:console_.url,port:console_.port}),await stopped,draining=!0,closeCoding(),clearInterval(lifecycleBeat),instanceSocket.ok&&instanceSocket.close(),mintedSecret!==null&&clearInstance(store,mintedSecret);let closeProblem=null;await new Promise(done=>console_.server.close(error=>{closeProblem=error==null?null:error.message,done()}));try{reportLifecycle(store,lifecycleComponent,"stopped",lifecycleHolder,clock())}catch{}return port.send({type:"closed",problem:closeProblem}),closeProblem===null?EXIT.ok:EXIT.failed}async function runUpWorkerRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),runnerName=config.runner,runnerToken=config.token,pool=config.pool,registryPath=config.registryPath,pinnedRepos=new Set(config.pinnedRepos),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,activeRepos=new Set(config.repos),reportRepos=()=>port.send({type:"repos",repos:[...activeRepos]});let stopping=!1,fatal=null,graceTimer;const followControllers=[];let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Stopped ${terminated} running build(s). Their work is saved, and each resumes when the builder starts again.`)},loopHealth=new Map;let deadlineTimer;const stillWaitingOn=()=>{const named2=[...loopHealth.values()].map(read=>read()).filter(one=>one.cleanup!==null).map(one=>`${projectName(one.repo)}: ${one.cleanup}`);return named2.length===0?"the worker's own shutdown":named2.join(", ")},forceEnd=async()=>{const waiting=stillWaitingOn();progress(`Stopping is taking too long (still waiting on ${waiting}); stopping this worker's builds now`),await endAfterExitProof({hardStop,liveBuilds:liveProviderCount,say:progress,exit:port.exit,code:EXIT.failed,before:()=>port.send({type:"fatal",detail:`the worker's stop didn't finish (still waiting on ${waiting}); Toolroll is restarting it`})})},armDeadline=()=>{deadlineTimer===void 0&&(deadlineTimer=setTimeout(()=>{forceEnd()},config.stopGraceMs+SHUTDOWN_DEADLINE_MS),deadlineTimer.unref?.())},stop=()=>{if(stopping){hardStop();return}stopping=!0,armDeadline(),resolveStopped();for(const controller of followControllers)controller.abort();wakeHubFor(store,read=>briefly(store,read)).poke();const building=store.liveClaimCount(runnerName,clock());building>0&&progress(`Stopping: ${building} build(s) running. Waiting up to ${Math.round(config.stopGraceMs/1e3)}s for them to finish; any still running then is saved and resumes when the builder starts again.`),graceTimer=setTimeout(hardStop,config.stopGraceMs),graceTimer.unref?.()};port.onStop(hard=>{stopping||stop(),hard&&hardStop()});const loopFlagsFor=repo=>{const copy=new Map;return config.forMs!==null&&copy.set("for",String(config.forMs)),copy.set("runner",runnerName),copy.set("token",runnerToken),copy.set("repo",repo),copy.set("pool",pool),config.publicUrl!==null&&copy.set("public-url",config.publicUrl),copy},prefix=repo=>activeRepos.size>1?`[${projectName(repo)}] `:"",containmentDetail=config.verbose||!config.terminal;let containmentSaid=!1;const firstContainmentNotice=()=>{try{return noticeDueOnce(context.store,CONTAINMENT_NOTICE_FACT,clock())}catch{return!0}},containmentLines=effective=>{const notice=containmentNotice(effective);return notice!==null&&!containmentSaid&&(containmentDetail||firstContainmentNotice())&&progress(notice),containmentSaid=!0,containmentDetail||effective.refusal!==null?[`watch: ${describeContainment(effective)}`]:[]},loopResults=new Map,projectPasses=new ProjectPasses,releasedRepos=new Set,relaunches=new Map,relaunchAttempts=new Map,relaunchAbort=new AbortController;followControllers.push(relaunchAbort);const relaunchPause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),relaunchAbort.signal.removeEventListener("abort",done),resolvePause()}relaunchAbort.signal.aborted?done():relaunchAbort.signal.addEventListener("abort",done,{once:!0})}),stoppedAt=new Map,stillTimers=new Map,noticed=write=>{try{briefly(store,write)}catch{}},builderBack=(repo,relaunching)=>{const at=stoppedAt.get(repo);stoppedAt.delete(repo);const timer=stillTimers.get(repo);timer!==void 0&&clearTimeout(timer),stillTimers.delete(repo),noticed(relaunching&&at!==void 0?()=>noteRestarted(store,{repo,stoppedAt:at,now:clock()}):()=>closeStillRestarting(store,repo,clock()))},scheduleRelaunch=(repo,detail)=>{if(relaunches.has(repo)||stopping)return;if(!stoppedAt.has(repo)){const at=clock();stoppedAt.set(repo,at);const timer=setTimeout(()=>{!stopping&&stoppedAt.get(repo)===at&&noticed(()=>noteStillRestarting(store,{repo,stoppedAt:at,now:clock()}))},STILL_RESTARTING_AFTER_MS);timer.unref?.(),stillTimers.set(repo,timer)}const attempt=relaunchAttempts.get(repo)??0;relaunchAttempts.set(repo,attempt+1);const delay=relaunchDelayMs(attempt,context.loopRelaunchMs);progress(`${prefix(repo)}this project's builder stopped (${detail}); Toolroll is restarting it in ${Math.max(1,Math.round(delay/1e3))}s`);const pending=(async()=>{await relaunchPause(delay);let waited=0,saidWaiting=!1;for(;;){if(stopping)return;if(releasedRepos.has(repo)){fatal=`${prefix(repo)}${detail}`,stop();return}if(!activeRepos.has(repo))return;let admission;try{admission=briefly(store,()=>relaunchAdmission(store,runnerName,repo,clock()))}catch(error){if(!isDatabaseBusy(error))throw error;await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs));continue}if(admission==="identity"){fatal=`the builder identity changed while restarting ${projectName(repo)}`,stop();return}if(admission==="gone"){loopResults.delete(repo),activeRepos.delete(repo),reportRepos(),progress(`project removed — ${projectName(repo)} is no longer built here`);return}if(admission==="go")break;saidWaiting||progress(`${prefix(repo)}still restarting: waiting for ${RELAUNCH_WAIT_WORDS[admission]}`),saidWaiting=!0,await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs))}loopResults.delete(repo),relaunches.delete(repo),await launchRepo(repo,!1,!1,!0)})().catch(error=>{fatal=`${prefix(repo)}the builder couldn't be restarted (${describe(error)})`,stop()}).finally(()=>{relaunches.get(repo)===pending&&relaunches.delete(repo)});relaunches.set(repo,pending)},launchRepo=async(repo,bind,drain=!1,relaunching=!1)=>{if(loopResults.has(repo)||stopping)return;let readyAt=null;if(drain&&releasedRepos.add(repo),bind){const bound=addRunnerReposAuthed(store,{name:runnerName,token:runnerToken,repos:[repo]},clock());if(!bound.ok){fatal=`the builder identity changed while adding ${repo} (${bound.reason})`,stop();return}activeRepos.add(repo),reportRepos(),store.listProjects().some(one=>one.path===repo)||store.upsertProject(repo,projectName(repo),clock())}let markReady=()=>{};const ready=new Promise(resolveReady=>markReady=resolveReady),loop=runWatchLoop({flags:loopFlagsFor(repo),context,runner:runnerName,token:runnerToken,repo,progress:line=>progress(`${prefix(repo)}${line}`),isStopping:()=>stopping||releasedRepos.has(repo),onFollowController:controller=>followControllers.push(controller),containmentLines,passes:projectPasses,serviceBridge:!0,health:read=>loopHealth.set(repo,read),leaseWaitMs:config.leaseWaitMs,...drain?{leaseWaitStopping:()=>stopping}:{},onReady:()=>{readyAt=Date.now(),markReady(),bind&&progress(`${prefix(repo)}builder connected — queued work can start`),relaunching&&progress(`${prefix(repo)}builder restarted automatically — queued work can start`),builderBack(repo,relaunching)}}).then(result=>({repo,result}),error=>({repo,result:{ok:!1,reason:"loop-failed",detail:describe(error),ticks:0,built:0,broke:0,busy:isDatabaseBusy(error)}}));loopResults.set(repo,loop),loop.then(({repo:endedRepo,result})=>{if(releasedRepos.has(endedRepo)&&!stopping&&!result.ok){fatal=`${prefix(endedRepo)}${result.detail}`,stop(),markReady();return}if(releasedRepos.has(endedRepo)&&!stopping){const unbound=removeRunnerRepoAuthed(store,{name:runnerName,token:runnerToken,repo:endedRepo},clock());unbound.ok||(fatal=`the builder identity changed while removing ${endedRepo} (${unbound.reason})`,stop()),loopResults.delete(endedRepo),releasedRepos.delete(endedRepo),progress(`project removed — ${projectName(endedRepo)} is no longer built here`),markReady();return}if(!result.ok&&!stopping){if(readyAt!==null&&Date.now()-readyAt>=LOOP_STABLE_MS&&relaunchAttempts.delete(endedRepo),loopEndRecovery(result,relaunching)==="relaunch"&&activeRepos.has(endedRepo)){scheduleRelaunch(endedRepo,result.detail),markReady();return}fatal=`${prefix(endedRepo)}${result.detail}`,stop()}markReady()}),await ready},named=new Set(config.repos),boundNow=new Set(store.getRunner(runnerName)?.runner.repos??[]),draining=[...new Set(predecessorWatches(store,runnerName,clock()).map(one=>one.repo))].filter(repo=>!named.has(repo)&&boundNow.has(repo));for(const repo of draining)progress(`${projectName(repo)} was being removed when the previous worker stopped: recovering its work first`);await Promise.all(draining.map(repo=>launchRepo(repo,!1,!0))),await Promise.all(config.repos.map(repo=>launchRepo(repo,!1)));const telegramController=new AbortController;followControllers.push(telegramController),stopping&&telegramController.abort();const telegramSupervisor=(async()=>{const pause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),telegramController.signal.removeEventListener("abort",done),resolvePause()}telegramController.signal.aborted?done():telegramController.signal.addEventListener("abort",done,{once:!0})});for(;!stopping&&!telegramController.signal.aborted;){const follower=startTelegramFollower({context,publicUrl:config.publicUrl??void 0,signal:telegramController.signal,progress,label:"telegram:",died:{prefix:"",next:"starting it again"},owner:`service-${randomUUID()}`});if(follower!==null&&await follower,follower===null&&loadBotToken(process.env,context.telegramTokenFile)!==null)break;await pause(follower===null?2e3:5e3)}})(),dynamicCeiling=resolveCeiling(config.repos,config.projectRoots,path=>resolve(path)).ceiling,rejected=new Set,lineIdentities=projectIdentities(),admittedLines=new Map(Object.entries(config.repoLines??{})),deferred=upDeferredRetry(config.deferredRepos??[],input=>upProveSaved(gitRun,input)),deferredGenerations=config.deferredGenerations??{},reportDeferred=()=>port.send({type:"deferred",repos:deferred.list()}),registrySupervisor=(async()=>{const sleep=ms=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));for(;!stopping;){const loaded=await loadProjectRegistry(registryPath);if("error"in loaded){fatal=loaded.error,stop();break}deferred.keepOnly(loaded.repos)&&reportDeferred();const plain=loaded.repos.filter(one=>!deferred.has(one));await lineIdentities.refresh(plain);const saved=new Set(loaded.repos);let removed=!1;for(const repo of[...activeRepos]){const lines=admittedLines.get(repo)??[repo];stopping||pinnedRepos.has(repo)||saved.has(repo)||lines.some(line=>saved.has(line))||(activeRepos.delete(repo),removed=!0,releasedRepos.add(repo),loopResults.has(repo)||releasedRepos.delete(repo))}removed&&reportRepos();for(const candidate of loaded.repos){if(stopping)break;if(deferred.has(candidate)){await connectDeferred(candidate);continue}const canonical=lineIdentities.known(candidate);if(canonical===void 0||canonical!==null&&(activeRepos.has(canonical)||releasedRepos.has(canonical)))continue;const approvedAdditions=context.additionalProjectRepos?.()??[],admittedRepos=[...dynamicCeiling.repos,...approvedAdditions],admittedCeiling={repos:admittedRepos.length===0&&dynamicCeiling.roots.length===0?["/\0nothing-admitted"]:admittedRepos,roots:dynamicCeiling.roots,canon:path=>lineIdentities.known(path)??null};if(!(canonical!==null&&(await authorizedProject(admittedCeiling,canonical)||admissionRecorded(store,canonical))&&await proveRepo(canonical)===canonical)){rejected.has(candidate)||(rejected.add(candidate),progress(`project not connected — ${candidate} isn't a Git repository added with \`toolroll repos add\` or the console`));continue}rejected.delete(candidate),admittedLines.set(canonical,[...new Set([...admittedLines.get(canonical)??[],candidate])]),await launchRepo(canonical,!0)}stopping||await sleep(500)}})().catch(error=>{fatal=`the project registry stopped (${describe(error)})`,stop()});async function connectDeferred(candidate){const proved=await deferred.retry(candidate);if(proved===null||stopping)return;if(proved.line!==candidate||proved.root!==candidate){deferred.revoke(candidate),reportDeferred(),progress(proved.root!==proved.line?`saved project not connected — ${candidate} came back as part of ${proved.root}; add it again to connect it`:`saved project not connected — ${candidate} now leads to ${proved.line}; add it again to connect it`);return}const root=candidate;if(activeRepos.has(root)||releasedRepos.has(root)){deferred.revoke(candidate),reportDeferred();return}let launching=null,removedSince=!1;if(await updateProjectRegistry(registryPath,current=>{if(stopping||!deferred.has(candidate))return current;const count=registryRemovals(registryPath)?.[candidate]??(registryRemovals(registryPath)===null?-2:0);return!current.repos.includes(candidate)||count!==deferredGenerations[candidate]?(deferred.revoke(candidate),removedSince=!0,current):(deferred.revoke(candidate),admittedLines.set(root,[candidate]),launching=launchRepo(root,!0),current)}),removedSince){reportDeferred(),progress(`saved project not connected — ${candidate} was removed while it was away; add it again to connect it`);return}launching!==null&&(reportDeferred(),progress(`saved project is back — connecting ${root}`),await launching)}let readinessTimer;if(context.agentRunner===void 0){let observing=!1;const observeReadiness=()=>{observing||stopping||(observing=!0,observeProviderReadiness((file,args,options)=>run(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)).then(observed=>{stopping||reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},clock())}).catch(()=>{}).finally(()=>{observing=!1}))};observeReadiness(),readinessTimer=setInterval(observeReadiness,12e4),readinessTimer.unref?.()}try{notifyVersionLive(context.store,dirname(context.databaseFile),PACKAGE_VERSION,clock())}catch{}recordRunnerVersion(dirname(context.databaseFile),runnerName,PACKAGE_VERSION,clock());const stopLiveBackups=context.agentRunner===void 0?startLiveBackups(store,context.databaseFile,()=>[...new Set([...activeRepos,...store.knownRepos(),pool])]):null;fatal===null&&!stopping&&port.send({type:"ready",role:"worker",build:build2,pid:process.pid,url:null,port:null});const cleanupSince=new Map,aliveTimer=setInterval(()=>{const repos=[...loopHealth.entries()].filter(([repo])=>loopResults.has(repo)).map(([,read])=>read());if(port.send({type:"alive",stopping,repos,liveBuilds:liveProviderCount()}),!stopping)for(const one of repos){if(one.cleanup===null||one.cleanup==="its builds"){cleanupSince.delete(one.repo);continue}const since=cleanupSince.get(one.repo);if(since===void 0||since.stage!==one.cleanup){cleanupSince.set(one.repo,{stage:one.cleanup,at:Date.now()});continue}if(!(Date.now()-since.at<config.stopGraceMs+SHUTDOWN_DEADLINE_MS)){fatal=`${prefix(one.repo)}its loop stopped but never finished stopping (still waiting on ${one.cleanup})`,stop();return}}},WORKER_ALIVE_EVERY_MS);return aliveTimer.unref?.(),await stopped,readinessTimer!==void 0&&clearInterval(readinessTimer),await registrySupervisor,await Promise.all(relaunches.values()),await Promise.all(loopResults.values()),await stopLiveBackups?.(),await new Promise(done=>{const timer=setTimeout(done,TELEGRAM_STOP_WAIT_MS),finish=()=>{clearTimeout(timer),done()};telegramSupervisor.then(finish,finish)}),graceTimer!==void 0&&clearTimeout(graceTimer),deadlineTimer!==void 0&&clearTimeout(deadlineTimer),clearInterval(aliveTimer),fatal!==null?(port.send({type:"fatal",detail:fatal}),EXIT.failed):EXIT.ok}export async function refreshGithubNightlies(store,now,reads){return githubNightlyRepos(store).length===0?0:readGithubNightlies(store,{gh:reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),now})}export async function evalsCommand(positional,flags,context){const{write,json}=context,{admitEvalCampaign,campaignSpending,EVALS_ROOT,installedBuildDigest,loadEvalSet,planCampaign,recoverEvalCampaigns,runEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),{evalCliEntry,runEvalWorld}=await import("./eval-world.js"),action=positional[0],command=`evals${action===void 0?"":` ${action}`}`,usage="Use: toolroll evals run [--diagnostic] [--case <ids>] [--k <n>] --as <you> --token <password> | toolroll evals cases | toolroll evals recover [--abandon <campaign> --as <you> --token <password>]";if(action==="recover"&&flags.has("abandon"))return evalsAbandonCommand(flags,context);if(action==="recover"){const recovered=recoverEvalCampaigns(context.store,context.clock());return succeed(write,json,command,{campaigns:recovered},()=>recovered.length===0?["No campaign is running."]:recovered.map(one=>`${one.id}: ${one.recovered?"recovered":"left running"} (${one.why})`))}if(action==="cases"){const set2=loadEvalSet();if(!set2.ok)return fail(write,json,command,"unreadable",set2.problem,EXIT.failed);const cases2=set2.cases.map(one=>({id:one.id,kind:one.kind,version:one.version,pin:one.pin,validatedBy:one.validatedBy,draft:one.validatedBy===null}));return succeed(write,json,command,{manifestDigest:set2.manifestDigest,cases:cases2},()=>cases2.map(one=>`${one.id} (${one.kind}) ${one.version.slice(0,12)} on ${one.pin.model}: ${one.draft?"draft, awaiting a person's validation":`validated by ${one.validatedBy}`}`))}if(action==="attempt"){if(!inEvalWorld())return fail(write,json,command,"refused","An eval attempt runs only from its campaign's runner.",EXIT.refused);const[,campaign,caseId,n]=positional,world=text(flags,"world");if(campaign===void 0||caseId===void 0||n===void 0||!/^[1-9][0-9]?$/.test(n)||world===void 0)return fail(write,json,command,"usage","Use: toolroll evals attempt <campaign> <case> <n> --world <dir> --db <world>/toolroll/orders.db",EXIT.usage);let worldDir;try{worldDir=realpathSync(world)}catch{return fail(write,json,command,"refused","The world's folder can't be read.",EXIT.refused)}if(resolve(context.databaseFile)!==join(worldDir,"toolroll","orders.db"))return fail(write,json,command,"refused","An eval attempt runs only on its world's own database.",EXIT.refused);const set2=loadEvalSet(),one=set2.ok?set2.cases.find(item=>item.id===caseId):void 0;if(one===void 0)return fail(write,json,command,"refused",set2.ok?`No case is named ${caseId}.`:set2.problem,EXIT.refused);const deny=(text(flags,"deny")??"").split(",").filter(path=>path!==""&&isAbsolute(path)),report=await runEvalWorld(one,{worldDir,databaseFile:context.databaseFile,deny,timeoutMs:one.timeoutMinutes*6e4});return succeed(write,json,command,{...report},()=>[JSON.stringify(report)])}if(action!=="run"||positional.length!==1)return fail(write,json,command,"usage",usage,EXIT.usage);if(inEvalWorld())return fail(write,json,command,"refused","An eval world doesn't start campaigns of its own.",EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person starts an eval campaign: it spends money.",EXIT.refused);const k=text(flags,"k"),cases=text(flags,"case"),set=loadEvalSet();if(!set.ok)return fail(write,json,command,"unreadable",set.problem,EXIT.failed);const planned=planCampaign(set,{...cases===void 0?{}:{cases:cases.split(",").filter(Boolean)},...k===void 0?{}:{k:Number(k)},diagnostic:flag(flags,"diagnostic")});if(!planned.ok)return fail(write,json,command,"refused",planned.problem,EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","An eval campaign is started with your password: add --as <you> --token <password>.",EXIT.usage);const{plan}=planned,buildDigest=()=>installedBuildDigest(PACKAGE_VERSION),sealed={cases:plan.cases.map(one=>({id:one.id,version:one.version,pin:one.pin,maxDispatches:one.maxDispatches})),k:plan.k,baseline:null,evals:EVALS_ROOT};recoverEvalCampaigns(context.store,context.clock());const admitted=admitEvalCampaign(context.store,{kind:"eval",canonical:plan.canonical,manifestDigest:set.manifestDigest,buildDigest:buildDigest(),version:PACKAGE_VERSION,k:plan.k,sealed,as:acting.name,token:acting.token,now:context.clock()});if(!admitted.ok)return fail(write,json,command,admitted.reason,admitted.message,EXIT.refused);const stateDir=dirname(context.databaseFile),entry=evalCliEntry(),keep=["PATH","HOME","USER","LOGNAME","LANG","SHELL","TMPDIR"],ended=await runEvalCampaign(context.store,admitted.id,plan.cases,{workRoot:join(dirname(stateDir),"toolroll-eval-worlds",admitted.id),buildDigest,keepWorlds:flag(flags,"keep"),now:context.clock,command:input=>({file:entry.file,args:[...entry.args,"evals","attempt",input.campaign,input.caseId,String(input.n),"--world",input.worldDir,"--deny",stateDir,"--db",input.databaseFile,"--json"],env:{...Object.fromEntries(keep.flatMap(name=>process.env[name]===void 0?[]:[[name,process.env[name]]])),XDG_CONFIG_HOME:join(input.worldDir,"config")}})}),rows=context.store.handle.prepare("SELECT case_id, n, replaces, outcome, error_why, api_microusd, subscription_microusd, usage_unknown FROM eval_attempt WHERE campaign = ? ORDER BY case_id, n, replaces").all(admitted.id),nullable=value=>value==null?null:Number(value),attempts=rows.map(row=>({case:String(row.case_id),n:Number(row.n),replaces:Number(row.replaces),outcome:row.outcome===null?null:String(row.outcome),why:row.error_why===null?null:String(row.error_why),apiMicrousd:nullable(row.api_microusd),subscriptionMicrousd:nullable(row.subscription_microusd),usageUnknown:Number(row.usage_unknown)===1})),spent=campaignSpending(context.store,admitted.id),dollars=(micro,unknown)=>micro===null?`unknown (${unknown} attempt${unknown===1?"":"s"} with unknown spending)`:`$${(micro/1e6).toFixed(2)}`;return succeed(write,json,command,{campaign:admitted.id,canonical:plan.canonical,state:ended.state,why:ended.why,attempts,spending:spent},()=>[`Campaign ${admitted.id} (${plan.canonical?"canonical":"diagnostic"}) is ${ended.state}${ended.why===null?"":`: ${ended.why}`}.`,...attempts.map(one=>`${one.case} #${one.n}${one.replaces===0?"":" (replacement)"}: ${one.outcome??"not finished"}${one.why===null?"":` — ${one.why}`}`),`API dollars: ${dollars(spent.apiMicrousd,spent.unknownAttempts)}. Subscription usage, not billed: ${dollars(spent.subscriptionMicrousd,spent.unknownAttempts)}.`])}async function evalsAbandonCommand(flags,context){const{write,json}=context,command="evals recover",{abandonEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),id=text(flags,"abandon");if(id===void 0||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id))return fail(write,json,command,"usage","Use: toolroll evals recover --abandon <campaign> --as <you> --token <password>",EXIT.usage);if(inEvalWorld()||machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person abandons an eval campaign.",EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","A campaign is abandoned with your password: add --as <you> --token <password>.",EXIT.usage);const ended=abandonEvalCampaign(context.store,{id,as:acting.name,token:acting.token,now:context.clock()});return ended.ok?succeed(write,json,command,{campaign:id,state:"incomplete",attempts:ended.attempts,spending:"unknown"},()=>[`Campaign ${id} ended incomplete. ${ended.attempts} unfinished attempt${ended.attempts===1?"":"s"} recorded as errors; what it spent is unknown. Nothing was stopped: check for its processes yourself.`]):fail(write,json,command,ended.reason,ended.message,EXIT.refused)}export function upDeferredRetry(inputs,prove,everyMs=5e3,now=Date.now){const nextAt=new Map(inputs.map(input=>[input,now()+everyMs]));return{has:input=>nextAt.has(input),list:()=>[...nextAt.keys()],retry:async input=>{const due=nextAt.get(input);return due===void 0||now()<due?null:(nextAt.set(input,now()+everyMs),prove(input))},revoke:input=>{nextAt.delete(input)},keepOnly:saved=>{const keep=new Set(saved);let changed=!1;for(const input of[...nextAt.keys()])keep.has(input)||(nextAt.delete(input),changed=!0);return changed}}}export async function upProveSaved(gitRun,input,look={}){const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd:resolve(input)});if(top.code!==0)return null;const answered=await lookIdentities([resolve(input),top.stdout.trim()],look);if(!answered.ok)return null;const line=answered.value.get(resolve(input))??null,root=answered.value.get(top.stdout.trim())??null;return line===null||root===null?null:{line,root}}export function upNarrowDeferred(held,reported){const kept=new Set(reported);return held.filter(one=>kept.has(one))}export function consoleIdentitiesInBackground(identities,paths){identities.refresh(paths).catch(()=>!1)}export function writeModelRow(store,proved,scope,knownProject2,slot,to,now,extra=[]){return applyModelChoices(store,{scope,change:slot===null?[]:[{slot,to}],expected:null,strict:!1,knownProject:knownProject2,extra},{...proved,live:()=>!0},now)}function refuseMachineTidy(context,command,method){return machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||method!==void 0&&!personProof(method)?fail(context.write,context.json,command,"person-only","Only a person puts tasks away or restores them. Use the console or your own login.",EXIT.refused):null}async function archiveTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task archive",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task archive <id...> [--reason <why>] --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting a task away takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const reason=text(flags,"reason")??"Put away by hand",archived=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=archiveTaskFamily(store,id,{by:acting.name,byKind:"person",rule:null,reason},clock(),{guard:refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs))});done.ok?archived.push({id,versions:done.refs.length}):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...archived.map(one=>`Put away ${one.id}${one.versions>1?` (${one.versions} versions)`:""}.`),...refused.map(one=>`Not put away: ${one.message}`),...archived.length===0?[]:[`Restore with \`toolroll task restore ${archived.map(one=>one.id).join(" ")}\`.`]];return refused.length===0?succeed(write,json,command,{archived,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{archived,refused}):(write(lines().join(`
505
+ `)),EXIT.ok}function fail(write,json,command,reason,message,code,extra={}){return write(json?envelopeJson({ok:!1,command,reason,message,...extra}):message),code}function text(flags,name){const value=flags.get(name);return typeof value=="string"?value:void 0}function flag(flags,name){return flags.get(name)===!0||flags.get(name)==="true"}function consoleLinkFor(context,path){const base=loadConsoleUrl(process.env,dirname(context.databaseFile));return base===null?null:`${base}${path}`}function refuseDemo(context,command){return context.store.isDemo()?fail(context.write,context.json,command,"demo-database","this database is a demo sandbox — it never spends money or touches a remote; point this command at a real database",EXIT.refused):null}function readTtl(flags){const given=text(flags,"ttl");if(given===void 0)return DEFAULT_LEASE_MS;const seconds=Number(given);return!Number.isInteger(seconds)||seconds<=0?null:seconds*1e3}function mutationFrom(flags,now){const key=text(flags,"key");return key===void 0?{at:now}:{idempotencyKey:key,at:now}}function slug(title,now){const words=title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").split("-").filter(Boolean).slice(0,4).join("-"),stamp=now.toISOString().slice(11,19).replace(/:/g,"");return words===""?`task-${stamp}`:`${words}-${stamp}`}function describe(error){return error instanceof Error?error.message:String(error)}function databaseFailure(write,json,command,file,error){return isDatabaseBusy(error)?fail(write,json,command,"database-busy",`The database ${file} stayed busy for ${CONCURRENT_WRITER_WAIT_MS/1e3} seconds. Wait for the other Toolroll process to finish, then try again.`,EXIT.failed):fail(write,json,command,"database",describe(error),EXIT.failed)}function refuseApprover(context,command,verified,usage,subject){if(verified===null)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const reason=verified.ok?"":verified.reason;return fail(context.write,context.json,command,reason,describeApproveFailure(reason,subject??""),EXIT.refused)}async function knownProject(context,repoFlag,match){const registered=await loadRepos(registryPathOf(context)).catch(()=>({error:"unreadable"}));return[...new Set([...context.store.knownRepos(),...match.listed?context.store.listProjects().map(one=>one.path):[],..."error"in registered?[]:registered.repos])].find(one=>one===repoFlag||one===resolve(repoFlag)||match.canonical&&one===canonicalProject(repoFlag))}export function ownValueFlags(command,argv){if(command==="flows")return FLOWS_VALUE_FLAGS;if(command==="card")return CARD_PANEL_VALUE_FLAGS;if(command==="project"&&argv.find(arg=>!arg.startsWith("-"))==="network")return PROJECT_NETWORK_VALUE_FLAGS}async function projectCheckAccessCommand(positional,flags,context){const command="project check-access",wanted=positional[1],repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project check-access --repo <project path> [sandboxed | sign-ins | unsandboxed].",invalid:wanted!==void 0&&!isCheckAccess(wanted),match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const current=context.store.projectCheckAccess(repo),platform=context.platform??process.platform,fenced=context.fenceAvailable?.()??(macosFenceAvailable()||linuxFenceAvailable()),runsAs=one=>checkAccessRunsAs(one,{platform,fenced,unconfinedAllowed:context.store.unfencedAgentsAllowed(),localMode:localModeOn(context.store)}),here=runsAs(current),words=one=>{if(runsAs(one)==="unsandboxed"&&one!=="unsandboxed")return[`${repo}: saved as ${checkAccessWords(one)}, but this machine can't sandbox checks, so they run without a sandbox.`];if(runsAs(one)!==one)return[`${repo}: saved with model and GitHub sign-ins, but its checks run sandboxed: sign-ins can't be shared with checks safely yet.`];const missing=one==="sign-ins"?signInHostsMissing(context.store.projectNetwork(repo)):[];return[`${repo}: checks run ${checkAccessWords(one)}.`,...one==="sandboxed"?[]:[CHECK_ACCESS_WARNINGS[one]],...missing.length===0?[]:[`Model sign-ins need these hosts in this project's network allowlist: ${missing.join(", ")}. Add them with: toolroll project network --repo ${repo} --allow ${missing.join(",")}`]]};if(wanted===void 0)return succeed(context.write,context.json,command,{repo,checkAccess:current,...here===current?{}:{runsAs:here},...here==="sign-ins"?{missingHosts:signInHostsMissing(context.store.projectNetwork(repo))}:{}},()=>words(current));const unavailable=wanted==="sign-ins"?signInsUnavailableWords(platform):null;if(unavailable!==null)return fail(context.write,context.json,command,"refused",unavailable,EXIT.refused);const widening=widerThan(wanted,current);if(wanted==="unsandboxed"&&localModeOn(context.store))return fail(context.write,context.json,command,"refused",LOCAL_MODE_CONFINES,EXIT.refused);const acting=await askCredentials(flags,context),proved=acting===null?null:authenticateApprover(context.store,acting.name,acting.token,repo);if(widening){if(acting===null||proved===null||!proved.ok||proved.method!=="password-now"||!context.store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator widens what a project's checks reach, with their password typed now: pass --as and --token.",EXIT.refused)}else if(acting===null||proved===null||!proved.ok||!credentialProof(proved.method)||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project narrows what its checks reach, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectCheckAccess(repo,wanted,acting.name,context.clock(),{may:widening?"widen":"narrow"});return changed===null?fail(context.write,context.json,command,"refused","The project's check access changed meanwhile, and this would now widen it: an instance operator widens it, with their password typed now.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,checkAccess:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}async function projectSandboxCommand(positional,flags,context){const command="project sandbox",repo=await projectAsked(context,flags,positional,command,{own:["read-deny","mach"],most:1,usage:"Use project sandbox --repo <project path> [--read-deny <paths>] [--mach <services>] (comma-separated; empty clears).",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=one=>[`${repo}: ${readDenyWords(one.readDeny)}`,...one.machLookup.length===0?[]:[`macOS services also allowed: ${one.machLookup.join(", ")}`]],current=context.store.projectSandbox(repo),asked=name=>{const value=flags.get(name);return value===void 0?void 0:value===!0?[]:value.split(",")},changes={readDeny:asked("read-deny"),machLookup:asked("mach")};if(changes.readDeny===void 0&&changes.machLookup===void 0)return succeed(context.write,context.json,command,{repo,sandbox:current},()=>words(current));const parsed={readDeny:parseReadDeny(changes.readDeny??current.readDeny),machLookup:parseMachLookup(changes.machLookup??current.machLookup)};for(const[name,one]of Object.entries(parsed))if(!one.ok)return fail(context.write,context.json,command,"usage",`${name}: ${one.problem}. Nothing changed.`,EXIT.usage);const wanted={readDeny:parsed.readDeny.ok?parsed.readDeny.list:[],machLookup:parsed.machLookup.ok?parsed.machLookup.list:[]},acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectSandbox(repo,wanted,acting.name,context.clock());return changed===null?fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox. Nothing changed.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,sandbox:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}function gitTooOld(command,context){const problem=installedGitFloorProblem();return problem===null?null:fail(context.write,context.json,command,"git-too-old",problem,EXIT.refused)}function upBuildIdentity(){return buildIdentity(PACKAGE_VERSION,fileURLToPath(import.meta.url))}function upNeedsOneProcess(options){return options.openDatabase!==void 0||options.desktopIdentity!==void 0||options.additionalProjectRepos!==void 0||options.agentRunner!==void 0||options.gitRunner!==void 0||options.telegramTransport!==void 0||options.telegramEnv!==void 0||options.publishExec!==void 0||options.dispatchAdapter!==void 0||options.flowTriggerIo!==void 0||options.flowStepIo!==void 0||options.flowEveryMs!==void 0||options.watchHeartbeatMs!==void 0||options.loopRelaunchMs!==void 0||options.platform!==void 0||options.fenceAvailable!==void 0||options.flowFetch!==void 0||options.integrationIo!==void 0||options.shouldStop!==void 0||options.leadSeams!==void 0||options.waitSleep!==void 0||options.releaseIo!==void 0||options.installBin!==void 0||options.tempRoots!==void 0||options.filingSizer!==void 0||options.now!==void 0||options.folderLook!==void 0}function recordRunnerProcess(databaseFile,holder,role,pid){try{const started=processStart(pid);if(started===null)return!1;const file=runnerProcessFile(databaseFile,holder.runner.name),credential=credentialDigest(holder.credentialHash),current=readRunnerProcessRecord(file),same=current!==null&&current.runner===holder.runner.name&&current.registeredAt===holder.runner.registeredAt&&current.credential===credential;if(role!=="up"&&(!same||current.signature!==sealRunnerProcessRecord(current,holder.credentialHash).signature))return!1;const kept=same?current.processes.filter(one=>one.role!==role||!processGone(one)):[],record={v:1,runner:holder.runner.name,host:holder.runner.host,registeredAt:holder.runner.registeredAt,credential,processes:[...kept.filter(one=>one.pid!==pid),{pid,role,started}]};return record.processes.length>64?!1:(writeRunnerProcessRecord(file,sealRunnerProcessRecord(record,holder.credentialHash)),!0)}catch{return!1}}function upRoleChildCommand(role){const source=import.meta.url.endsWith(".ts"),entry=fileURLToPath(new URL(source?"./up-role-child.ts":"./up-role-child.js",import.meta.url));return{file:process.execPath,argv:[...source?["--import",import.meta.resolve("tsx")]:[],entry,role]}}function startUpRole(args){const{role}=args;let resolveReady=()=>{};const ready=new Promise(resolve2=>resolveReady=resolve2),generations=new RoleGenerations;let stopping=!1,endedForGood=!1;const endForGood=detail=>{stopping||endedForGood||(endedForGood=!0,args.onEnded(detail,!1))};let failed=null,fatal=null,closedProblem=null,livePid=null;const receive=(raw,abort)=>{const message=roleMessage(raw,role);if(message!==null){if(message.type==="ready"){if(message.build!==args.build){fatal=`the ${role} is a different build (${message.build}) from this one (${args.build}) — restart Toolroll`,failed={reason:"start",detail:fatal},generations.refused(fatal),abort();return}livePid=message.pid;const again=!generations.ready();again||resolveReady({ok:!0,url:message.url??"",port:message.port,pid:message.pid}),args.onReady(message,again);return}if(message.type==="failed"){failed={reason:message.reason,detail:message.detail},generations.refused(message.detail);return}if(message.type==="fatal"){fatal=message.detail;return}if(message.type==="closed"){closedProblem=message.problem;return}message.type!=="alive"&&args.onMessage(message)}};if(!args.split){const channel=memoryChannel(role);channel.parent.onMessage(message=>receive(message,()=>channel.parent.stop(!1)));const done2=upRoleCommand(args.context,{start:args.start(1),port:channel.port}).catch(error=>(fatal=describe(error),EXIT.failed)).then(code=>(livePid=null,generations.wasReady()?endForGood(fatal??`the ${role} stopped (exit ${code})`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${code})`}}),{problem:closedProblem}));return{ready,done:done2,send:message=>channel.parent.send(message),stop:()=>{stopping=!0,channel.parent.stop(!1)},hardStop:()=>{channel.parent.stop(!0)},kill:()=>{stopping=!0,channel.parent.stop(!0)},pid:()=>livePid}}const controller=new AbortController;let child=null;const command=upRoleChildCommand(role);let heardAt=Date.now(),stoppingSince=null,liveBuilds=0,saidPaused=!1,saidWaiting=!1;const watchdog=args.watchdog===void 0?null:setInterval(()=>{const owned=child;if(stopping||controller.signal.aborted||owned===null||owned.exitCode!==null||owned.signalCode!==null||!generations.current())return;const now=Date.now(),silentMs=now-heardAt,silenceMs=args.watchdog.silenceMs??WORKER_SILENCE_MS,facts={silentMs,silenceMs,stoppingForMs:stoppingSince===null?null:now-stoppingSince,graceMs:args.watchdog.graceMs,deadlineMs:SHUTDOWN_DEADLINE_MS,liveBuilds,paused:!1};if(watchdogVerdict(facts)==="fine"){saidPaused=!1,saidWaiting=!1;return}try{facts.paused=args.watchdog.paused()}catch{facts.paused=!0}const verdict=watchdogVerdict(facts);if(verdict==="leave"){saidPaused||args.watchdog.say(`the ${role} isn't answering, but an update or restart is under way; leaving it to that`),saidPaused=!0;return}if(verdict==="wait"){saidWaiting||args.watchdog.say(`the ${role} is still stopping: ${liveBuilds===1?"a build hasn't":`${liveBuilds} builds haven't`} confirmed ${liveBuilds===1?"it":"they"} stopped; leaving it to finish`),saidWaiting=!0;return}verdict==="restart"&&(args.watchdog.say(silentMs<silenceMs?`the ${role}'s stop overran its deadline; stopping it and starting it again`:`the ${role} hasn't answered for ${Math.round(silentMs/1e3)}s; stopping it and starting it again`),stopProcessTree(owned)||owned.kill("SIGKILL"),heardAt=now)},WORKER_ALIVE_EVERY_MS);watchdog?.unref?.();const done=superviseController({file:command.file,argv:command.argv,signal:controller.signal,ipc:!0,shutdownMs:args.shutdownMs,label:envValue(process.env,"LOG_FORMAT")==="json"?"":`[${role}]`,onSpawn:(owned,generation)=>{child=owned,fatal=null,failed=null,generations.spawned(),heardAt=Date.now(),stoppingSince=null,owned.on("message",raw=>{heardAt=Date.now();const alive=roleMessage(raw,role);alive?.type==="alive"&&(stoppingSince=alive.stopping?stoppingSince??heardAt:null,liveBuilds=alive.liveBuilds),receive(raw,()=>controller.abort())}),owned.on("error",()=>{});let recorded=!1;try{recorded=owned.pid!==void 0&&(args.onSpawned?.(owned.pid)??!0)}catch{}if(!recorded){fatal="The worker process record could not be saved",failed={reason:"start",detail:fatal},generations.refused(fatal),owned.kill("SIGKILL"),controller.abort(),resolveReady({ok:!1,...failed});return}owned.send(args.start(generation),error=>{error!=null&&owned.kill("SIGTERM")})},onState:state=>{if(state.phase!=="backoff")return;child=null,livePid=null;const exit=state.exit?.signal??state.exit?.code??"unknown";if(stopping&&generations.wasReady())return;const verdict=generations.ended();if(verdict==="fail-start"){controller.abort(),resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${exit})`}});return}if(verdict==="end"){controller.abort(),endForGood(generations.refusedWith()??fatal??`the ${role} kept stopping before it was ready (exit ${exit})`);return}if(controller.signal.aborted){endForGood(fatal??`the ${role} stopped (exit ${exit})`);return}if(generations.struggling()){args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} is still restarting (${generations.notReady()} tries so far, exit ${exit})`,!0);return}args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} stopped unexpectedly (exit ${exit})`,!0)}}).catch(error=>{generations.wasReady()||resolveReady({ok:!1,reason:"start",detail:describe(error)})}).finally(()=>{watchdog!==null&&clearInterval(watchdog)}).then(()=>(generations.wasReady()?endForGood(generations.refusedWith()??fatal??`the ${role} stopped`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} did not start`}}),{problem:closedProblem}));return{ready,done,send:message=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send(message,()=>{})}catch{}},stop:()=>{stopping=!0,controller.abort()},hardStop:()=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send({type:"hard-stop"},()=>{})}catch{}},kill:()=>{stopping=!0,controller.abort();const owned=child;owned!==null&&owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},pid:()=>livePid}}export async function runUpRole(start,port){return runOperate("up",["--db",start.databaseFile,...start.containment===null?[]:["--containment",start.containment]],line=>port.send({type:"log",line}),{upRole:{start,port}})}async function upRoleCommand(context,host){const{start,port}=host;return start.build!==upBuildIdentity()?(port.send({type:"failed",reason:"start",detail:`this ${start.role} is a different build (${upBuildIdentity()}) from the \`up\` that started it (${start.build})`}),EXIT.refused):resolve(start.databaseFile)!==resolve(context.databaseFile)?(port.send({type:"failed",reason:"start",detail:`the ${start.role} opened a different database`}),EXIT.refused):start.role==="console"?runUpConsoleRole(context,start.config,port,start.build):runUpWorkerRole(context,start.config,port,start.build)}async function runUpConsoleRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),activeRepos=new Set(config.repos);let instanceSecret=null,draining=!1;const keyEpoch=randomBytes(16).toString("hex");let console_;try{console_=await startConsole({keyEpoch,instanceSecret:()=>instanceSecret,draining:()=>draining,context,host:config.host,port:config.port,...config.allowedHosts===null?{}:{allowedHosts:config.allowedHosts},...config.publicUrl===null?{}:{publicUrl:config.publicUrl},localRunner:config.localRunner,poolRoot:config.poolRoot,repos:config.repos,currentRepos:()=>[...activeRepos],admittedRepos:()=>[...activeRepos],upConsole:!0,registryPath:config.registryPath,projectRoots:await(async()=>{const saved=await loadProjectRegistry(config.registryPath);return"error"in saved?config.projectRoots:saved.roots})(),...config.editor?{editorLinks:"vscode"}:{}})}catch(error){return port.send({type:"failed",reason:"port-busy",detail:describe(error)}),EXIT.refused}let codingClosed=!1;const closeCoding=()=>{codingClosed||(codingClosed=!0,console_.server.closeCoding().catch(()=>{}))};let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);port.onStop(()=>resolveStopped());const lifecycleComponent=consoleComponent(config.host,console_.port),lifecycleHolder=`${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,lifecycleComponent,"started",lifecycleHolder,clock(),{pid:process.pid})}catch{}const lifecycleBeat=setInterval(()=>{try{beatLifecycle(store,lifecycleComponent,lifecycleHolder,clock())}catch{}},RUNNER_HEARTBEAT_MS);lifecycleBeat.unref?.(),port.onMessage(message=>{if(message.type==="repos"){activeRepos.clear();for(const repo of message.repos)activeRepos.add(repo)}else if(message.type==="stopping"){draining=!0;try{reportLifecycle(store,lifecycleComponent,"draining",lifecycleHolder,clock(),{drainUntil:new Date(clock().getTime()+6e4)})}catch{}closeCoding()}else if(message.type==="sign-in-link"){let link=null;try{link=consoleSignInLink(console_.server,config.startAuthority,message)}catch{link=null}port.send({type:"sign-in-link",id:message.id,link})}});let mintedSecret=null;const instanceSocket=await openInstanceSocket(context.databaseFile,{pid:process.pid,build:packageVersion(),database:context.databaseFile,port:console_.port},()=>mintedSecret,()=>console_.server.mintLocalLink());instanceSocket.ok?(mintedSecret=await claimInstance(store,context.databaseFile,{pid:process.pid,port:console_.port,build:packageVersion(),socket:instanceSocket.name,keyEpoch:console_.server.keyEpoch},clock()),instanceSecret=mintedSecret,mintedSecret===null&&progress("attach: another console is running on this database — `toolroll` in a repository opens that one")):progress(`attach: ${instanceSocket.problem} — \`toolroll\` in a repository won't find this console`),port.send({type:"ready",role:"console",build:build2,pid:process.pid,url:console_.url,port:console_.port}),await stopped,draining=!0,closeCoding(),clearInterval(lifecycleBeat),instanceSocket.ok&&instanceSocket.close(),mintedSecret!==null&&clearInstance(store,mintedSecret);let closeProblem=null;await new Promise(done=>console_.server.close(error=>{closeProblem=error==null?null:error.message,done()}));try{reportLifecycle(store,lifecycleComponent,"stopped",lifecycleHolder,clock())}catch{}return port.send({type:"closed",problem:closeProblem}),closeProblem===null?EXIT.ok:EXIT.failed}async function runUpWorkerRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),runnerName=config.runner,runnerToken=config.token,pool=config.pool,registryPath=config.registryPath,pinnedRepos=new Set(config.pinnedRepos),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,activeRepos=new Set(config.repos),reportRepos=()=>port.send({type:"repos",repos:[...activeRepos]});let stopping=!1,fatal=null,graceTimer;const followControllers=[];let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Stopped ${terminated} running build(s). Their work is saved, and each resumes when the builder starts again.`)},loopHealth=new Map;let deadlineTimer;const stillWaitingOn=()=>{const named2=[...loopHealth.values()].map(read=>read()).filter(one=>one.cleanup!==null).map(one=>`${projectName(one.repo)}: ${one.cleanup}`);return named2.length===0?"the worker's own shutdown":named2.join(", ")},forceEnd=async()=>{const waiting=stillWaitingOn();progress(`Stopping is taking too long (still waiting on ${waiting}); stopping this worker's builds now`),await endAfterExitProof({hardStop,liveBuilds:liveProviderCount,say:progress,exit:port.exit,code:EXIT.failed,before:()=>port.send({type:"fatal",detail:`the worker's stop didn't finish (still waiting on ${waiting}); Toolroll is restarting it`})})},armDeadline=()=>{deadlineTimer===void 0&&(deadlineTimer=setTimeout(()=>{forceEnd()},config.stopGraceMs+SHUTDOWN_DEADLINE_MS),deadlineTimer.unref?.())},stop=()=>{if(stopping){hardStop();return}stopping=!0,armDeadline(),resolveStopped();for(const controller of followControllers)controller.abort();wakeHubFor(store,read=>briefly(store,read)).poke();const building=store.liveClaimCount(runnerName,clock());building>0&&progress(`Stopping: ${building} build(s) running. Waiting up to ${Math.round(config.stopGraceMs/1e3)}s for them to finish; any still running then is saved and resumes when the builder starts again.`),graceTimer=setTimeout(hardStop,config.stopGraceMs),graceTimer.unref?.()};port.onStop(hard=>{stopping||stop(),hard&&hardStop()});const loopFlagsFor=repo=>{const copy=new Map;return config.forMs!==null&&copy.set("for",String(config.forMs)),copy.set("runner",runnerName),copy.set("token",runnerToken),copy.set("repo",repo),copy.set("pool",pool),config.publicUrl!==null&&copy.set("public-url",config.publicUrl),copy},prefix=repo=>activeRepos.size>1?`[${projectName(repo)}] `:"",containmentDetail=config.verbose||!config.terminal;let containmentSaid=!1;const firstContainmentNotice=()=>{try{return noticeDueOnce(context.store,CONTAINMENT_NOTICE_FACT,clock())}catch{return!0}},containmentLines=effective=>{const notice=containmentNotice(effective);return notice!==null&&!containmentSaid&&(containmentDetail||firstContainmentNotice())&&progress(notice),containmentSaid=!0,containmentDetail||effective.refusal!==null?[`watch: ${describeContainment(effective)}`]:[]},loopResults=new Map,projectPasses=new ProjectPasses,releasedRepos=new Set,relaunches=new Map,relaunchAttempts=new Map,relaunchAbort=new AbortController;followControllers.push(relaunchAbort);const relaunchPause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),relaunchAbort.signal.removeEventListener("abort",done),resolvePause()}relaunchAbort.signal.aborted?done():relaunchAbort.signal.addEventListener("abort",done,{once:!0})}),stoppedAt=new Map,stillTimers=new Map,noticed=write=>{try{briefly(store,write)}catch{}},builderBack=(repo,relaunching)=>{const at=stoppedAt.get(repo);stoppedAt.delete(repo);const timer=stillTimers.get(repo);timer!==void 0&&clearTimeout(timer),stillTimers.delete(repo),noticed(relaunching&&at!==void 0?()=>noteRestarted(store,{repo,stoppedAt:at,now:clock()}):()=>closeStillRestarting(store,repo,clock()))},scheduleRelaunch=(repo,detail)=>{if(relaunches.has(repo)||stopping)return;if(!stoppedAt.has(repo)){const at=clock();stoppedAt.set(repo,at);const timer=setTimeout(()=>{!stopping&&stoppedAt.get(repo)===at&&noticed(()=>noteStillRestarting(store,{repo,stoppedAt:at,now:clock()}))},STILL_RESTARTING_AFTER_MS);timer.unref?.(),stillTimers.set(repo,timer)}const attempt=relaunchAttempts.get(repo)??0;relaunchAttempts.set(repo,attempt+1);const delay=relaunchDelayMs(attempt,context.loopRelaunchMs);progress(`${prefix(repo)}this project's builder stopped (${detail}); Toolroll is restarting it in ${Math.max(1,Math.round(delay/1e3))}s`);const pending=(async()=>{await relaunchPause(delay);let waited=0,saidWaiting=!1;for(;;){if(stopping)return;if(releasedRepos.has(repo)){fatal=`${prefix(repo)}${detail}`,stop();return}if(!activeRepos.has(repo))return;let admission;try{admission=briefly(store,()=>relaunchAdmission(store,runnerName,repo,clock()))}catch(error){if(!isDatabaseBusy(error))throw error;await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs));continue}if(admission==="identity"){fatal=`the builder identity changed while restarting ${projectName(repo)}`,stop();return}if(admission==="gone"){loopResults.delete(repo),activeRepos.delete(repo),reportRepos(),progress(`project removed — ${projectName(repo)} is no longer built here`);return}if(admission==="go")break;saidWaiting||progress(`${prefix(repo)}still restarting: waiting for ${RELAUNCH_WAIT_WORDS[admission]}`),saidWaiting=!0,await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs))}loopResults.delete(repo),relaunches.delete(repo),await launchRepo(repo,!1,!1,!0)})().catch(error=>{fatal=`${prefix(repo)}the builder couldn't be restarted (${describe(error)})`,stop()}).finally(()=>{relaunches.get(repo)===pending&&relaunches.delete(repo)});relaunches.set(repo,pending)},launchRepo=async(repo,bind,drain=!1,relaunching=!1)=>{if(loopResults.has(repo)||stopping)return;let readyAt=null;if(drain&&releasedRepos.add(repo),bind){const bound=addRunnerReposAuthed(store,{name:runnerName,token:runnerToken,repos:[repo]},clock());if(!bound.ok){fatal=`the builder identity changed while adding ${repo} (${bound.reason})`,stop();return}activeRepos.add(repo),reportRepos(),store.listProjects().some(one=>one.path===repo)||store.upsertProject(repo,projectName(repo),clock())}let markReady=()=>{};const ready=new Promise(resolveReady=>markReady=resolveReady),loop=runWatchLoop({flags:loopFlagsFor(repo),context,runner:runnerName,token:runnerToken,repo,progress:line=>progress(`${prefix(repo)}${line}`),isStopping:()=>stopping||releasedRepos.has(repo),onFollowController:controller=>followControllers.push(controller),containmentLines,passes:projectPasses,serviceBridge:!0,health:read=>loopHealth.set(repo,read),leaseWaitMs:config.leaseWaitMs,...drain?{leaseWaitStopping:()=>stopping}:{},onReady:()=>{readyAt=Date.now(),markReady(),bind&&progress(`${prefix(repo)}builder connected — queued work can start`),relaunching&&progress(`${prefix(repo)}builder restarted automatically — queued work can start`),builderBack(repo,relaunching)}}).then(result=>({repo,result}),error=>({repo,result:{ok:!1,reason:"loop-failed",detail:describe(error),ticks:0,built:0,broke:0,busy:isDatabaseBusy(error)}}));loopResults.set(repo,loop),loop.then(({repo:endedRepo,result})=>{if(releasedRepos.has(endedRepo)&&!stopping&&!result.ok){fatal=`${prefix(endedRepo)}${result.detail}`,stop(),markReady();return}if(releasedRepos.has(endedRepo)&&!stopping){const unbound=removeRunnerRepoAuthed(store,{name:runnerName,token:runnerToken,repo:endedRepo},clock());unbound.ok||(fatal=`the builder identity changed while removing ${endedRepo} (${unbound.reason})`,stop()),loopResults.delete(endedRepo),releasedRepos.delete(endedRepo),progress(`project removed — ${projectName(endedRepo)} is no longer built here`),markReady();return}if(!result.ok&&!stopping){if(readyAt!==null&&Date.now()-readyAt>=LOOP_STABLE_MS&&relaunchAttempts.delete(endedRepo),loopEndRecovery(result,relaunching)==="relaunch"&&activeRepos.has(endedRepo)){scheduleRelaunch(endedRepo,result.detail),markReady();return}fatal=`${prefix(endedRepo)}${result.detail}`,stop()}markReady()}),await ready},named=new Set(config.repos),boundNow=new Set(store.getRunner(runnerName)?.runner.repos??[]),draining=[...new Set(predecessorWatches(store,runnerName,clock()).map(one=>one.repo))].filter(repo=>!named.has(repo)&&boundNow.has(repo));for(const repo of draining)progress(`${projectName(repo)} was being removed when the previous worker stopped: recovering its work first`);await Promise.all(draining.map(repo=>launchRepo(repo,!1,!0))),await Promise.all(config.repos.map(repo=>launchRepo(repo,!1)));const telegramController=new AbortController;followControllers.push(telegramController),stopping&&telegramController.abort();const telegramSupervisor=(async()=>{const pause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),telegramController.signal.removeEventListener("abort",done),resolvePause()}telegramController.signal.aborted?done():telegramController.signal.addEventListener("abort",done,{once:!0})});for(;!stopping&&!telegramController.signal.aborted;){const follower=startTelegramFollower({context,publicUrl:config.publicUrl??void 0,signal:telegramController.signal,progress,label:"telegram:",died:{prefix:"",next:"starting it again"},owner:`service-${randomUUID()}`});if(follower!==null&&await follower,follower===null&&loadBotToken(process.env,context.telegramTokenFile)!==null)break;await pause(follower===null?2e3:5e3)}})(),dynamicCeiling=resolveCeiling(config.repos,config.projectRoots,path=>resolve(path)).ceiling,rejected=new Set,lineIdentities=projectIdentities(),admittedLines=new Map(Object.entries(config.repoLines??{})),deferred=upDeferredRetry(config.deferredRepos??[],input=>upProveSaved(gitRun,input)),deferredGenerations=config.deferredGenerations??{},reportDeferred=()=>port.send({type:"deferred",repos:deferred.list()}),registrySupervisor=(async()=>{const sleep=ms=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));for(;!stopping;){const loaded=await loadProjectRegistry(registryPath);if("error"in loaded){fatal=loaded.error,stop();break}deferred.keepOnly(loaded.repos)&&reportDeferred();const plain=loaded.repos.filter(one=>!deferred.has(one));await lineIdentities.refresh(plain);const saved=new Set(loaded.repos);let removed=!1;for(const repo of[...activeRepos]){const lines=admittedLines.get(repo)??[repo];stopping||pinnedRepos.has(repo)||saved.has(repo)||lines.some(line=>saved.has(line))||(activeRepos.delete(repo),removed=!0,releasedRepos.add(repo),loopResults.has(repo)||releasedRepos.delete(repo))}removed&&reportRepos();for(const candidate of loaded.repos){if(stopping)break;if(deferred.has(candidate)){await connectDeferred(candidate);continue}const canonical=lineIdentities.known(candidate);if(canonical===void 0||canonical!==null&&(activeRepos.has(canonical)||releasedRepos.has(canonical)))continue;const approvedAdditions=context.additionalProjectRepos?.()??[],admittedRepos=[...dynamicCeiling.repos,...approvedAdditions],admittedCeiling={repos:admittedRepos.length===0&&dynamicCeiling.roots.length===0?["/\0nothing-admitted"]:admittedRepos,roots:dynamicCeiling.roots,canon:path=>lineIdentities.known(path)??null};if(!(canonical!==null&&(await authorizedProject(admittedCeiling,canonical)||admissionRecorded(store,canonical))&&await proveRepo(canonical)===canonical)){rejected.has(candidate)||(rejected.add(candidate),progress(`project not connected — ${candidate} isn't a Git repository added with \`toolroll repos add\` or the console`));continue}rejected.delete(candidate),admittedLines.set(canonical,[...new Set([...admittedLines.get(canonical)??[],candidate])]),await launchRepo(canonical,!0)}stopping||await sleep(500)}})().catch(error=>{fatal=`the project registry stopped (${describe(error)})`,stop()});async function connectDeferred(candidate){const proved=await deferred.retry(candidate);if(proved===null||stopping)return;if(proved.line!==candidate||proved.root!==candidate){deferred.revoke(candidate),reportDeferred(),progress(proved.root!==proved.line?`saved project not connected — ${candidate} came back as part of ${proved.root}; add it again to connect it`:`saved project not connected — ${candidate} now leads to ${proved.line}; add it again to connect it`);return}const root=candidate;if(activeRepos.has(root)||releasedRepos.has(root)){deferred.revoke(candidate),reportDeferred();return}let launching=null,removedSince=!1;if(await updateProjectRegistry(registryPath,current=>{if(stopping||!deferred.has(candidate))return current;const count=registryRemovals(registryPath)?.[candidate]??(registryRemovals(registryPath)===null?-2:0);return!current.repos.includes(candidate)||count!==deferredGenerations[candidate]?(deferred.revoke(candidate),removedSince=!0,current):(deferred.revoke(candidate),admittedLines.set(root,[candidate]),launching=launchRepo(root,!0),current)}),removedSince){reportDeferred(),progress(`saved project not connected — ${candidate} was removed while it was away; add it again to connect it`);return}launching!==null&&(reportDeferred(),progress(`saved project is back — connecting ${root}`),await launching)}let readinessTimer;if(context.agentRunner===void 0){let observing=!1;const observeReadiness=()=>{observing||stopping||(observing=!0,observeProviderReadiness((file,args,options)=>run(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)).then(observed=>{stopping||reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},clock())}).catch(()=>{}).finally(()=>{observing=!1}))};observeReadiness(),readinessTimer=setInterval(observeReadiness,12e4),readinessTimer.unref?.()}try{notifyVersionLive(context.store,dirname(context.databaseFile),PACKAGE_VERSION,clock())}catch{}recordRunnerVersion(dirname(context.databaseFile),runnerName,PACKAGE_VERSION,clock());const stopLiveBackups=context.agentRunner===void 0?startLiveBackups(store,context.databaseFile,()=>[...new Set([...activeRepos,...store.knownRepos(),pool])]):null;fatal===null&&!stopping&&port.send({type:"ready",role:"worker",build:build2,pid:process.pid,url:null,port:null});const cleanupSince=new Map,aliveTimer=setInterval(()=>{const repos=[...loopHealth.entries()].filter(([repo])=>loopResults.has(repo)).map(([,read])=>read());if(port.send({type:"alive",stopping,repos,liveBuilds:liveProviderCount()}),!stopping)for(const one of repos){if(one.cleanup===null||one.cleanup==="its builds"){cleanupSince.delete(one.repo);continue}const since=cleanupSince.get(one.repo);if(since===void 0||since.stage!==one.cleanup){cleanupSince.set(one.repo,{stage:one.cleanup,at:Date.now()});continue}if(!(Date.now()-since.at<config.stopGraceMs+SHUTDOWN_DEADLINE_MS)){fatal=`${prefix(one.repo)}its loop stopped but never finished stopping (still waiting on ${one.cleanup})`,stop();return}}},WORKER_ALIVE_EVERY_MS);return aliveTimer.unref?.(),await stopped,readinessTimer!==void 0&&clearInterval(readinessTimer),await registrySupervisor,await Promise.all(relaunches.values()),await Promise.all(loopResults.values()),await stopLiveBackups?.(),await new Promise(done=>{const timer=setTimeout(done,TELEGRAM_STOP_WAIT_MS),finish=()=>{clearTimeout(timer),done()};telegramSupervisor.then(finish,finish)}),graceTimer!==void 0&&clearTimeout(graceTimer),deadlineTimer!==void 0&&clearTimeout(deadlineTimer),clearInterval(aliveTimer),fatal!==null?(port.send({type:"fatal",detail:fatal}),EXIT.failed):EXIT.ok}export async function refreshGithubNightlies(store,now,reads){return githubNightlyRepos(store).length===0?0:readGithubNightlies(store,{gh:reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),now})}export async function evalsCommand(positional,flags,context){const{write,json}=context,{admitEvalCampaign,campaignSpending,EVALS_ROOT,installedBuildDigest,loadEvalSet,planCampaign,recoverEvalCampaigns,runEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),{evalCliEntry,runEvalWorld}=await import("./eval-world.js"),action=positional[0],command=`evals${action===void 0?"":` ${action}`}`,usage="Use: toolroll evals run [--diagnostic] [--case <ids>] [--k <n>] --as <you> --token <password> | toolroll evals cases | toolroll evals recover [--abandon <campaign> --as <you> --token <password>]";if(action==="recover"&&flags.has("abandon"))return evalsAbandonCommand(flags,context);if(action==="recover"){const recovered=recoverEvalCampaigns(context.store,context.clock());return succeed(write,json,command,{campaigns:recovered},()=>recovered.length===0?["No campaign is running."]:recovered.map(one=>`${one.id}: ${one.recovered?"recovered":"left running"} (${one.why})`))}if(action==="cases"){const set2=loadEvalSet();if(!set2.ok)return fail(write,json,command,"unreadable",set2.problem,EXIT.failed);const cases2=set2.cases.map(one=>({id:one.id,kind:one.kind,version:one.version,pin:one.pin,validatedBy:one.validatedBy,draft:one.validatedBy===null}));return succeed(write,json,command,{manifestDigest:set2.manifestDigest,cases:cases2},()=>cases2.map(one=>`${one.id} (${one.kind}) ${one.version.slice(0,12)} on ${one.pin.model}: ${one.draft?"draft, awaiting a person's validation":`validated by ${one.validatedBy}`}`))}if(action==="attempt"){if(!inEvalWorld())return fail(write,json,command,"refused","An eval attempt runs only from its campaign's runner.",EXIT.refused);const[,campaign,caseId,n]=positional,world=text(flags,"world");if(campaign===void 0||caseId===void 0||n===void 0||!/^[1-9][0-9]?$/.test(n)||world===void 0)return fail(write,json,command,"usage","Use: toolroll evals attempt <campaign> <case> <n> --world <dir> --db <world>/toolroll/orders.db",EXIT.usage);let worldDir;try{worldDir=realpathSync(world)}catch{return fail(write,json,command,"refused","The world's folder can't be read.",EXIT.refused)}if(resolve(context.databaseFile)!==join(worldDir,"toolroll","orders.db"))return fail(write,json,command,"refused","An eval attempt runs only on its world's own database.",EXIT.refused);const set2=loadEvalSet(),one=set2.ok?set2.cases.find(item=>item.id===caseId):void 0;if(one===void 0)return fail(write,json,command,"refused",set2.ok?`No case is named ${caseId}.`:set2.problem,EXIT.refused);const deny=(text(flags,"deny")??"").split(",").filter(path=>path!==""&&isAbsolute(path)),report=await runEvalWorld(one,{worldDir,databaseFile:context.databaseFile,deny,timeoutMs:one.timeoutMinutes*6e4});return succeed(write,json,command,{...report},()=>[JSON.stringify(report)])}if(action!=="run"||positional.length!==1)return fail(write,json,command,"usage",usage,EXIT.usage);if(inEvalWorld())return fail(write,json,command,"refused","An eval world doesn't start campaigns of its own.",EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person starts an eval campaign: it spends money.",EXIT.refused);const k=text(flags,"k"),cases=text(flags,"case"),set=loadEvalSet();if(!set.ok)return fail(write,json,command,"unreadable",set.problem,EXIT.failed);const planned=planCampaign(set,{...cases===void 0?{}:{cases:cases.split(",").filter(Boolean)},...k===void 0?{}:{k:Number(k)},diagnostic:flag(flags,"diagnostic")});if(!planned.ok)return fail(write,json,command,"refused",planned.problem,EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","An eval campaign is started with your password: add --as <you> --token <password>.",EXIT.usage);const{plan}=planned,buildDigest=()=>installedBuildDigest(PACKAGE_VERSION),sealed={cases:plan.cases.map(one=>({id:one.id,version:one.version,pin:one.pin,maxDispatches:one.maxDispatches})),k:plan.k,baseline:null,evals:EVALS_ROOT};recoverEvalCampaigns(context.store,context.clock());const admitted=admitEvalCampaign(context.store,{kind:"eval",canonical:plan.canonical,manifestDigest:set.manifestDigest,buildDigest:buildDigest(),version:PACKAGE_VERSION,k:plan.k,sealed,as:acting.name,token:acting.token,now:context.clock()});if(!admitted.ok)return fail(write,json,command,admitted.reason,admitted.message,EXIT.refused);const stateDir=dirname(context.databaseFile),entry=evalCliEntry(),keep=["PATH","HOME","USER","LOGNAME","LANG","SHELL","TMPDIR"],ended=await runEvalCampaign(context.store,admitted.id,plan.cases,{workRoot:join(dirname(stateDir),"toolroll-eval-worlds",admitted.id),buildDigest,keepWorlds:flag(flags,"keep"),now:context.clock,command:input=>({file:entry.file,args:[...entry.args,"evals","attempt",input.campaign,input.caseId,String(input.n),"--world",input.worldDir,"--deny",stateDir,"--db",input.databaseFile,"--json"],env:{...Object.fromEntries(keep.flatMap(name=>process.env[name]===void 0?[]:[[name,process.env[name]]])),XDG_CONFIG_HOME:join(input.worldDir,"config")}})}),rows=context.store.handle.prepare("SELECT case_id, n, replaces, outcome, error_why, api_microusd, subscription_microusd, usage_unknown FROM eval_attempt WHERE campaign = ? ORDER BY case_id, n, replaces").all(admitted.id),nullable=value=>value==null?null:Number(value),attempts=rows.map(row=>({case:String(row.case_id),n:Number(row.n),replaces:Number(row.replaces),outcome:row.outcome===null?null:String(row.outcome),why:row.error_why===null?null:String(row.error_why),apiMicrousd:nullable(row.api_microusd),subscriptionMicrousd:nullable(row.subscription_microusd),usageUnknown:Number(row.usage_unknown)===1})),spent=campaignSpending(context.store,admitted.id),dollars=(micro,unknown)=>micro===null?`unknown (${unknown} attempt${unknown===1?"":"s"} with unknown spending)`:`$${(micro/1e6).toFixed(2)}`;return succeed(write,json,command,{campaign:admitted.id,canonical:plan.canonical,state:ended.state,why:ended.why,attempts,spending:spent},()=>[`Campaign ${admitted.id} (${plan.canonical?"canonical":"diagnostic"}) is ${ended.state}${ended.why===null?"":`: ${ended.why}`}.`,...attempts.map(one=>`${one.case} #${one.n}${one.replaces===0?"":" (replacement)"}: ${one.outcome??"not finished"}${one.why===null?"":` — ${one.why}`}`),`API dollars: ${dollars(spent.apiMicrousd,spent.unknownAttempts)}. Subscription usage, not billed: ${dollars(spent.subscriptionMicrousd,spent.unknownAttempts)}.`])}async function evalsAbandonCommand(flags,context){const{write,json}=context,command="evals recover",{abandonEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),id=text(flags,"abandon");if(id===void 0||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id))return fail(write,json,command,"usage","Use: toolroll evals recover --abandon <campaign> --as <you> --token <password>",EXIT.usage);if(inEvalWorld()||machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person abandons an eval campaign.",EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","A campaign is abandoned with your password: add --as <you> --token <password>.",EXIT.usage);const ended=abandonEvalCampaign(context.store,{id,as:acting.name,token:acting.token,now:context.clock()});return ended.ok?succeed(write,json,command,{campaign:id,state:"incomplete",attempts:ended.attempts,spending:"unknown"},()=>[`Campaign ${id} ended incomplete. ${ended.attempts} unfinished attempt${ended.attempts===1?"":"s"} recorded as errors; what it spent is unknown. Nothing was stopped: check for its processes yourself.`]):fail(write,json,command,ended.reason,ended.message,EXIT.refused)}export function upDeferredRetry(inputs,prove,everyMs=5e3,now=Date.now){const nextAt=new Map(inputs.map(input=>[input,now()+everyMs]));return{has:input=>nextAt.has(input),list:()=>[...nextAt.keys()],retry:async input=>{const due=nextAt.get(input);return due===void 0||now()<due?null:(nextAt.set(input,now()+everyMs),prove(input))},revoke:input=>{nextAt.delete(input)},keepOnly:saved=>{const keep=new Set(saved);let changed=!1;for(const input of[...nextAt.keys()])keep.has(input)||(nextAt.delete(input),changed=!0);return changed}}}export async function upProveSaved(gitRun,input,look={}){const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd:resolve(input)});if(top.code!==0)return null;const answered=await lookIdentities([resolve(input),top.stdout.trim()],look);if(!answered.ok)return null;const line=answered.value.get(resolve(input))??null,root=answered.value.get(top.stdout.trim())??null;return line===null||root===null?null:{line,root}}export function upNarrowDeferred(held,reported){const kept=new Set(reported);return held.filter(one=>kept.has(one))}export function consoleIdentitiesInBackground(identities,paths){identities.refresh(paths).catch(()=>!1)}export function writeModelRow(store,proved,scope,knownProject2,slot,to,now,extra=[]){const followRepair=slot!==null&&to!==null&&slot.phase==="build"&&(slot.tier==="routine"||slot.tier==="strong");return applyModelChoices(store,{scope,change:slot===null?[]:[{slot,to}],expected:null,strict:!1,knownProject:knownProject2,extra,followRepair},{...proved,live:()=>!0},now)}function refuseMachineTidy(context,command,method){return machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||method!==void 0&&!personProof(method)?fail(context.write,context.json,command,"person-only","Only a person puts tasks away or restores them. Use the console or your own login.",EXIT.refused):null}async function archiveTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task archive",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task archive <id...> [--reason <why>] --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting a task away takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const reason=text(flags,"reason")??"Put away by hand",archived=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=archiveTaskFamily(store,id,{by:acting.name,byKind:"person",rule:null,reason},clock(),{guard:refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs))});done.ok?archived.push({id,versions:done.refs.length}):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...archived.map(one=>`Put away ${one.id}${one.versions>1?` (${one.versions} versions)`:""}.`),...refused.map(one=>`Not put away: ${one.message}`),...archived.length===0?[]:[`Restore with \`toolroll task restore ${archived.map(one=>one.id).join(" ")}\`.`]];return refused.length===0?succeed(write,json,command,{archived,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{archived,refused}):(write(lines().join(`
489
506
  `)),EXIT.refused)}async function restoreTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task restore",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task restore <id...> --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"restoring takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const restored=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=restoreTaskFamily(store,id,acting.name,clock(),refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs)));done.ok?restored.push(id):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...restored.map(id=>`Restored ${id}.`),...refused.map(one=>`Not restored: ${one.message}`)];return refused.length===0?succeed(write,json,command,{restored,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{restored,refused}):(write(lines().join(`
490
507
  `)),EXIT.refused)}async function tidyTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task tidy",preview=flag(flags,"preview"),apply=flag(flags,"apply"),days=tidyDays(text(flags,"days")),digest=text(flags,"digest"),except=(text(flags,"except")??"").split(",").map(one=>one.trim()).filter(one=>one!==""),usage="`toolroll task tidy --preview [--days N]`, then `toolroll task tidy --apply --digest <d> [--days N] [--except <id,...>]`";if(positional.length>0||preview===apply||days===null||preview&&(digest!==void 0||except.length>0)||apply&&digest===void 0)return fail(write,json,command,"usage",usage,EXIT.usage);const releases=releaseFactsFor(context.databaseFile),previewAs=text(flags,"as")??readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name,daysArg=`${days===TIDY_DEFAULT_DAYS?"":` --days ${days}`}${previewAs===void 0?"":` --as ${previewAs}`}`,lens=context.principal?.lens??null,access=previewAs!==void 0?withinLens(accessOf(store,previewAs),lens):{principal:"operator",repos:lens,includeUnplaced:lens===null};if(preview){const items=tidyPreview(store,clock(),{releases,days,access}),shown=tidyDigest(items,days),groups=tidyGroups(items,days),next=`toolroll task tidy --apply --digest ${shown}${daysArg}`;return succeed(write,json,command,{preview:!0,days,digest:shown,count:items.length,groups,next:items.length===0?null:next,...releases.problem===null?{}:{releasesSkipped:releases.problem}},()=>items.length===0?["Nothing to put away."]:[`Put away old tasks: ${items.length} task${items.length===1?"":"s"}.`,...groups.flatMap(group=>["",`${group.label} (${group.items.length})`,...group.items.map(one=>` ${one.taskId} ${one.reason}${one.members.length>1?` (${one.members.length} versions)`:""}`)]),...releases.problem===null?[]:["",`Release tasks were left out: ${releases.problem}.`],"",`To put these away, run: ${next}`,"Leave some out with --except <id,...>.",...previewAs===void 0?["Limited to some projects? Preview with --as <you> so the list is yours."]:[]])}const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,[]));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting tasks away takes `--as <you> --token <t>` — it is recorded against your name",void 0);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const mine=withinLens(accessOf(store,acting.name),lens),shownItems=tidyPreview(store,clock(),{releases,days,access:mine}),only=except.length===0?null:shownItems.map(one=>one.taskId).filter(id=>!except.includes(id));if(except.some(id=>!shownItems.some(one=>one.taskId===id)))return fail(write,json,command,"outside","--except names a task that isn't in the list. Check it again with --preview.",EXIT.refused);const done=applyTidy(store,clock(),{by:acting.name,days,digest,only,releases,access:mine});if(!done.ok){const again=`toolroll task tidy --apply --digest ${done.digest}${daysArg}`;return fail(write,json,command,done.reason,done.reason==="changed"?`${done.message} Look again with \`toolroll task tidy --preview${daysArg}\`.`:done.message,EXIT.refused,{digest:done.digest,count:done.items.length,...done.reason==="changed"?{next:done.items.length===0?null:again}:{}})}return succeed(write,json,command,{archived:done.archived.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),skipped:done.skipped},()=>[`Put away ${done.archived.length} task${done.archived.length===1?"":"s"}.`,...done.skipped.map(one=>`Not put away: ${one.message}`),"Find them with `toolroll task list --view archived`; bring one back with `toolroll task restore <id>`."])}function firstVisibleRepo(store,name,ids){for(const id of ids){const repo=store.lookupRef(id)?.repo??null;if(repo!==null&&store.accountCanAccess(name,repo))return repo}return store.accountCanAccess(name,null)?null:store.knownRepos().find(repo=>store.accountCanAccess(name,repo))??null}const SHIP_CHECK_WORDS={queued:"queued",running:"running",passed:"passed",failed:"failed",skipped:"skipped",cancelled:"cancelled",neutral:"neutral"};function taskShipCommand(positional,context){const{store,write,json}=context,command="task ship",id=positional[0];if(id===void 0||positional.length>1)return fail(write,json,command,"usage","`toolroll task ship <task>`",EXIT.usage);const ref=store.lookupRef(id),lens=context.principal?.lens??null;if(ref===null||store.getTask(id)===null||lens!==null&&(ref.repo===null||!lens.includes(ref.repo)))return fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused);const ship=shipChecksForTask(store,id);if(ship===null)return fail(write,json,command,"no-pull-request",`${id} has no pull request with observed checks yet`,EXIT.refused);const now=(context.clock??(()=>context.now))(),checks=ship.checks.map(one=>({...one,seconds:elapsedSeconds(one.startedAt,one.completedAt,now)})),passed=checks.filter(one=>one.state==="passed").length,overall=ship.observed==="failing"?"failing":ship.observed==="passing"?"passing":ship.observed==="running"?"running":"not read";return succeed(write,json,command,{task:id,pullRequest:ship.prNumber,githubRepo:ship.githubRepo,head:ship.headSha,observedAt:ship.observedAt,status:ship.observed,checks},()=>[`Pull request #${ship.prNumber} (${ship.githubRepo}) at ${ship.headSha.slice(0,7)}: checks ${overall} · ${passed} of ${checks.length} passed`,...checks.map(one=>` ${(one.workflow===null?one.name:`${one.workflow} / ${one.name}`).padEnd(32)} ${(SHIP_CHECK_WORDS[one.state]??one.state).padEnd(9)} ${one.seconds===null?"–":dur(one.seconds)}`)])}function upLaptopProjectsRoot(home){const folder=join(home,"Projects");try{mkdirSync(folder,{recursive:!0,mode:448})}catch{return null}return canonicalProject(folder)}function upLaptopLocalMode(context,asFlag,caller){const fence=context.upSeams?.fenceAvailable??defaultFenceAvailable,owner=asFlag??process.env.USER??process.env.USERNAME??"operator";return initLocalModeForPerson(context.store,caller,{owner,fence,now:context.clock()})}export function upLinkRequest(authority,account){return authority==="local"?{kind:"local"}:authority==="full"&&account!==null?{kind:"full",account}:null}export function consoleSignInLink(server,startAuthority,message){return message.kind==="local"?startAuthority==="local"?server.mintLocalLink():null:startAuthority==="full"?server.mintSignInLink(message.account):null}function localOwnerCommand(store,command,positional,flags){const binding=localOwnerBinding(store);if(binding===null)return{ok:!1,message:"Local mode is off. Sign in with your password in the browser."};const act=localOwnerRowAct(command,positional,flags);return act===null?{ok:!1,message:localOwnerRefusal(store.accountOf(binding.account)?.passwordSet===!0,"/").message}:{ok:!0,principal:{account:binding.account,localGeneration:binding.localGeneration,accountGeneration:binding.accountGeneration,transport:"terminal",act,sessionHash:null,request:null}}}function localOwnerRowAct(command,positional,flags){if(["as","token","token-file","token-env"].some(name=>flags.has(name)))return null;const row=remoteRowOf(command,positional);if(row?.invocation==="repos add"&&flags.has("remote"))return null;const mark=row===null?void 0:LOCAL_POLICY.get(row.invocation);return mark===void 0||mark.local!=="allow"?null:mark.act}function laptopSeamsOf(context){return{terminal:!context.json&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!underAgent(process.env),confirm:promptConfirm,...context.laptopSeams}}async function backgroundCommand(positional,flags,context){const{write,json}=context,[action="show",...rest]=positional,command=`background ${action}`;if(!["on","off","show"].includes(action)||rest.length>0)return fail(write,json,"background","usage","Use `toolroll background on|off|show [--port <n>]`.",EXIT.usage);for(const name of flags.keys())if(!["db","json","port"].includes(name))return fail(write,json,command,"usage",`--${name} is not a background option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","The background service is this computer's own; run it there.",EXIT.refused);const portGiven=text(flags,"port"),port=portGiven===void 0?null:Number(portGiven);if(port!==null&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,command,"usage","--port is a whole number under 65536",EXIT.usage);const seams=laptopSeamsOf(context);if(action==="show"){const shown=await backgroundShow(context.store,context.databaseFile,port,seams);if(!shown.ok)return fail(write,json,command,shown.reason,shown.message,EXIT.refused);const show=shown.show,state=show.installed==="absent"?"off":show.loaded?"on":"installed, not running";return succeed(write,json,command,{...show,background:show.installed==="absent"?"off":"on"},()=>[`Background: ${state}${show.installed==="different"?" (set up for a different version or port; `toolroll background on` updates it)":""}`,show.running===null?"Toolroll isn't running.":`Toolroll is running at ${show.running.url}`,...show.conflicts.map(one=>`Also here: ${one.reason}`)])}const demo=refuseDemo(context,command);if(demo!==null)return demo;if(action==="off"){const off=await backgroundOff(context.store,context.databaseFile,seams);return off.ok?succeed(write,json,command,off,()=>[off.action==="already-off"?"Toolroll wasn't set to run in the background.":"Toolroll no longer runs in the background. Start it with `toolroll` when you need it."]):fail(write,json,command,off.reason,off.message,off.reason==="supervisor"||off.reason==="still-running"?EXIT.failed:EXIT.refused)}const on=await backgroundOn(context.store,context.databaseFile,port,seams);if(on.ok&&recordBuilderWish(context.store,"running","background on",packageVersion(),context.clock()),!on.ok){const code=["agent","conflict","declined","running-elsewhere","unsupported","console-unproven","invalid-unit","unreadable"].includes(on.reason)?EXIT.refused:EXIT.failed;if(json)return write(envelopeJson({ok:!1,command,reason:on.reason,message:on.message,...on.rolledBack===void 0?{}:{rolledBack:on.rolledBack}})),code;write(`✗ ${on.message}.`);for(const line of on.rolledBack??[])write(` ${line}`);return code}return succeed(write,json,command,on,()=>[on.action==="unchanged"?`Toolroll already runs in the background at ${on.url}.`:`Toolroll now runs in the background at ${on.url}. It starts when you log in.`])}async function stopCommand(positional,flags,context){const{write,json}=context,command="stop";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll stop`.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a stop option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","Stopping Toolroll is done on its own computer.",EXIT.refused);const stopped=await laptopStop(context.store,context.databaseFile,laptopSeamsOf(context));return stopped.ok?succeed(write,json,command,stopped,()=>[stopped.action==="not-running"?"Toolroll isn't running.":stopped.action==="service-stopped"?"Toolroll stopped. It starts again when you log in — run `toolroll background off` to stop that.":"Toolroll stopped."]):fail(write,json,command,stopped.reason,stopped.message,stopped.reason==="still-running"||stopped.reason==="supervisor"?EXIT.failed:EXIT.refused)}function personAtTerminal(context){return!context.json&&(context.easySeams?.terminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!underAgent(process.env)))}async function openCommand(positional,flags,context){const{write,json}=context,command="open";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll open [--web]`.",EXIT.usage);for(const name of flags.keys())if(!["db","json","web"].includes(name))return fail(write,json,command,"usage",`--${name} is not an open option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","Toolroll opens on its own computer.",EXIT.refused);if(!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Run `toolroll open` yourself at a terminal: it opens Toolroll here, signed in.",EXIT.refused);const easy=await import("./easy-start.js"),seams=easy.defaultEasyStartSeams({databaseFile:context.databaseFile,write,build:packageVersion(),admit:async()=>EXIT.ok});return easy.runEasyStart("open",{web:flags.has("web"),projectRoot:null},{...seams,...context.easySeams?.seams})}async function welcomeCommand(positional,flags,context){const{write,json}=context,command="welcome";if(positional[0]==="sample")return welcomeSampleCommand(positional.slice(1),flags,context);if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll welcome [--json]`, or `toolroll welcome sample`.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a welcome option.`,EXIT.usage);const{welcomeHere,welcomeLines,welcomeStepLines,WELCOME_STEPS,sampleOffered}=await import("./welcome-facts.js"),read=async()=>(await welcomeHere(context.store,context.databaseFile,context.clock(),context.easySeams?.check===void 0?{}:{check:context.easySeams.check})).model;let model=await read();const shellMayAdd=()=>{const mode=localModeOf(context.store);return mode?.enabled===!0&&context.store.accountOf(mode.owner)?.passwordSet!==!0},offer=()=>sampleOffered(model,shellMayAdd(),context.store.isDemo())?"command":null;if(json||!personAtTerminal(context)||localOwnerRequested())return succeed(write,json,command,{...model},()=>welcomeLines(model,offer()));const askNow=context.easySeams?.ask??ask;write(model.left===0?"Setup is done.":`Welcome to Toolroll. ${model.left} ${model.left===1?"step":"steps"} to your first result.`);for(const key of WELCOME_STEPS)for(;;){write("");for(const line of welcomeStepLines(model,key,offer()))write(line);if(model[key].done)break;const said=(await askNow("Press Enter once it's done, s to skip, q to stop: ")).trim().toLowerCase();if(said==="q")return EXIT.ok;if(said==="s")break;model=await read()}return write(""),write(model.left===0?"You're set. Run `toolroll` to open Toolroll.":"Run `toolroll` to open Toolroll; the steps left are there too."),EXIT.ok}async function passwordCommand(positional,flags,context){const{write,json,store}=context,[action,...rest]=positional,command=action===void 0?"password":`password ${action}`;if(action==="reset")return passwordResetCommand(rest,flags,context);if(action!=="set"||rest.length>0)return fail(write,json,command,"usage","Use `toolroll password set` (a first password) or `toolroll password reset` (a forgotten one).",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a password set option: the password is only ever typed.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","A password is set on Toolroll's own computer.",EXIT.refused);if(localOwnerRequested()||!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Set your password yourself at a terminal: run `toolroll password set`.",EXIT.refused);const binding=localOwnerBinding(store);if(binding===null)return fail(write,json,command,"not-local","This Toolroll already signs in with a password. Sign in with it in the browser.",EXIT.refused);if(store.accountOf(binding.account)?.passwordSet===!0)return fail(write,json,command,"already-set","A password is already set. Sign in with it in the browser.",EXIT.refused);const typeHidden=context.easySeams?.askHidden??askHidden;write("Setting a password signs out open browser tabs and the open Toolroll screen. You can open it again right after."),write(`Choose a password for ${binding.account}. It signs you in from other devices and approves what this computer's browser can't.`);const chosen=await typeHidden("New password: ");if(chosen.length<8)return fail(write,json,command,"weak-password","A password needs at least 8 characters. Nothing changed.",EXIT.refused);if(await typeHidden("Type it again: ")!==chosen)return fail(write,json,command,"mismatch","The two passwords didn't match. Nothing changed.",EXIT.refused);const enrolled=enrollOwnerPassword(store,binding.account,hashPassword(chosen),binding.localGeneration,context.clock());if(!enrolled.ok){const words=enrolled.reason==="already-set"?"A password was just set. Sign in with it in the browser.":enrolled.reason==="local-mode-changed"?"Local mode changed while you were typing. Nothing changed.":"Only this computer's owner sets the first password. Nothing changed.";return fail(write,json,command,enrolled.reason,words,EXIT.refused)}return succeed(write,json,command,{account:binding.account,generation:enrolled.generation},()=>["Password set.","Sign in with it in your browser; an open Toolroll screen asks to open again."])}export function upLaptopPortCandidates(store,fromSeam,localInstall=!1){const saved=laptopPortOf(store);if(saved!==null)return[saved];const range=fromSeam??Array.from({length:20},(_,index)=>4180+index);return installationCreatedBy(store)!=="laptop"&&!localInstall?[range[0]??4180]:[...range]}const MEMORY_WRITE_VERBS=new Set(["decide","retire","apply","propose","tidy","restore","unmerge"]);function memoryWriteVerb(positional){return MEMORY_WRITE_VERBS.has(positional[0]??"")}const MEMORY_WRITE_REFUSAL="Project memory is changed by a person with their own sign-in, not the lead. The lead proposes decisions in chat for you to confirm.";async function releaseApproveCommand(positional,flags,context){const{store,write,json}=context,command="release approve",usage="`toolroll release approve [<branch>] [--repo <path>]` (with --json: --as <you> --token <password> --digest <card digest>)",branchFlag=text(flags,"branch");if(positional[0]!=="approve"||positional.length>2||branchFlag!==void 0&&positional.length>1)return fail(write,json,command,"usage",usage,EXIT.usage);const branch=branchFlag??positional[1];if(branch!==void 0&&(!/^[A-Za-z0-9._/-]{1,255}$/.test(branch)||branch.startsWith("-")||branch.includes("..")))return fail(write,json,command,"usage",`${branch} is not a branch name this command takes.`,EXIT.usage);const repoFlag=text(flags,"repo"),repo=repoFlag===void 0?null:resolve(repoFlag),stateDir=dirname(context.databaseFile),{journals,unreadable}=waitingJournals(stateDir,name2=>journalFile(stateDir,name2)),named=branch===void 0?journals:journals.filter(one=>one.branch===branch||/^\d+\.\d+\.\d+$/.test(branch)&&one.version===branch&&one.file.endsWith(`/from-main/${branch}.json`));if(branch!==void 0&&named.length===0&&unreadable.includes(basename(journalFile(stateDir,branch))))return fail(write,json,command,"unreadable",`${branch}'s release journal can't be read as one; nothing was approved. Run \`toolroll release ${branch}\` again.`,EXIT.refused);const matches=[],refusals=[];for(const one of named){if(releaseTaskOf(store,one.taskId)!==null&&approvalOf(store.getScope(one.taskId)).approved)continue;const proved=journalMatchesPlane(store,one,repo);proved.ok?matches.push(one):refusals.push(proved.why)}if(matches.length===0){const why=refusals.length>0?`${refusals[0]}; nothing was approved`:branch===void 0?"No release is waiting for your approval":`No release of ${branch} is waiting for your approval`;return fail(write,json,command,refusals.length>0?"mismatch":"none",`${why}.`,EXIT.refused)}if(matches.length>1)return fail(write,json,command,"ambiguous",`More than one release is waiting: ${matches.map(one=>`${one.branch} (${one.version})`).join(", ")}. Name the branch: \`toolroll release approve <branch>\`.`,EXIT.refused,{releases:matches.map(one=>({branch:one.branch,version:one.version,task:one.taskId}))});const chosen=matches[0],built=releaseApprovalCard(store,chosen.taskId);if(!built.ok)return fail(write,json,command,"none",built.why,EXIT.refused);const shown=built.card,cardData={task:shown.taskId,version:shown.seal.identity.packageVersion,branch:shown.seal.identity.branch,candidate:shown.seal.identity.approvedSha,digest:shown.digest,ci:shown.ci?.state??null};if(shown.approved!==null)return fail(write,json,command,"approved",`Release ${cardData.version} is already approved by ${shown.approved.by}.`,EXIT.refused,{release:cardData});if(shown.refusal!==null){if(!json)for(const line of releaseCardLines(shown))write(line);return fail(write,json,command,"refused",`Can't approve now: ${shown.refusal}`,EXIT.refused,{release:cardData})}let name,token;if(json){const given=credentialsFrom(flags,context);if(given.name===void 0||given.token===void 0||given.name===""||given.token==="")return fail(write,json,command,"credentials","Approving a release needs who is agreeing: --as <you> --token <password>. Nothing was approved.",EXIT.usage,{release:cardData});if(text(flags,"digest")!==shown.digest)return fail(write,json,command,"unconfirmed","Name the card you read: --digest <card digest>. Nothing was approved.",EXIT.refused,{release:cardData});name=given.name,token=given.token}else{for(const line of releaseCardLines(shown))write(line);if(write(""),interactive()){if(!await confirm(`Approve release ${cardData.version}?`))return write("Nothing approved."),EXIT.refused}else if(!flags.has("yes")||text(flags,"digest")!==shown.digest)return write(`Nothing has been approved. Agree to exactly this card with: toolroll release approve ${chosen.branch} --yes --digest ${shown.digest} --as <you> --token <your password>`),EXIT.refused;const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"credentials","Approving a release needs who is agreeing. Nothing was approved.",EXIT.usage);name=acting.name,token=acting.token}const again=releaseApprovalCard(store,chosen.taskId);if(!again.ok||again.card.digest!==shown.digest)return fail(write,json,command,"changed","This release changed while you were being asked; nothing was approved. Run the command again to read it.",EXIT.refused);const now=context.clock(),answer=approveReleaseCard(store,{taskId:chosen.taskId,cardDigest:shown.digest,approveNow:scopeDigest=>approve(store,chosen.taskId,name,now,scopeDigest,token,mutationFrom(flags,now))});if(!answer.ok){if(answer.reason!=="approve")return fail(write,json,command,answer.reason,`${answer.message} Nothing was approved.`,EXIT.refused);const refused=answer.result;return refused.reason==="policy"?fail(write,json,command,"policy",`${chosen.taskId}: ${refused.message}`,EXIT.refused):fail(write,json,command,refused.reason,describeApproveFailure(refused.reason,chosen.taskId),EXIT.refused)}return succeed(write,json,command,{release:cardData},()=>[`Approved release ${cardData.version} (${cardData.candidate.slice(0,7)}). The release check runs next; it deploys, merges and publishes once GitHub CI and the check pass.`,...shown.stopped===null?[]:[`The release isn't running: run \`toolroll release ${chosen.branch}\` to go on.`]])}function taskReadyCommand(positional,context){const{store,write,json}=context,command="task ready",id=positional[0];if(id===void 0||positional.length>1)return fail(write,json,command,"usage","`toolroll task ready <task>`",EXIT.usage);const lens=context.principal?.lens??null,ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||lens!==null&&(ref.repo===null||!lens.includes(ref.repo)))return fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused);const now=(context.clock??(()=>context.now))(),list=mergeChecklistOf(store,id,now,{principal:"operator",repos:lens,includeUnplaced:lens===null,dependencyRepos:lens},context.evidenceRoot);return list===null?fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused):succeed(write,json,command,list,()=>checklistLines(list))}function uncommittedLines(plan){const changed=plan.stay.filter(one=>one.why==="has changes");return changed.length===0?[]:[`${changed.length===1?"This folder has":"These folders have"} uncommitted changes and stay${changed.length===1?"s":""} until you decide (toolroll storage discard <path> --yes throws one away):`,...changed.map(one=>` ${bytesWords(one.bytes).padStart(8)} ${one.path}${one.taskId===null?"":` (${one.taskId})`}`)]}async function mapCommand(positional,flags,context){const{store}=context,local=currentLocalOwner(),{name,token}=credentialsFrom(flags,context);let actor=null,repos=null;const all=[...new Set([...store.knownRepos(),...store.listProjects().map(one=>one.path)])];if(local!==null)actor=local.account,repos=all.filter(repo=>store.accountCanAccess(local.account,repo));else if(name!==void 0&&token!==void 0){if(!authenticateAccount(store,name,token).ok)return fail(context.write,context.json,"map","unauthenticated","Sign in again: that login doesn't work here.",EXIT.refused);const remote=activeRemote();actor=name,repos=all.filter(repo=>store.accountCanAccess(name,repo)&&(remote===null||remote.allows(repo)))}else repos=all;return runMapCommand(positional,flags,{store,write:context.write,json:context.json,now:context.clock(),actor,repos,approver:repo=>local===null&&name!==void 0&&token!==void 0&&authenticateApprover(store,name,token,repo).ok,door:repo=>{if(local!==null)return{kind:"local-owner",actor:local.account};if(name===void 0||token===void 0)return null;const generation=store.accountOf(name)?.generation??-1,proved=authenticateApprover(store,name,token,repo);return proved.ok?{kind:"person",person:{actor:name,generation,method:proved.method}}:null}})}async function newTaskCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),command="task new",local=currentLocalOwner();if(context.principal!==void 0||machineActing())return fail(write,json,command,"person-only","Only a person starts a build this way. File it with `task add`.",EXIT.refused);if(local===null&&(json||!personAtTerminal(context)))return fail(write,json,command,"person-only","`task new` asks a person at a terminal. Use `task add` from a script or an agent.",EXIT.refused);let{name,token}=credentialsFrom(flags,context);const passwordFree=token!==void 0&&(local!==null||sessionStandsIn(store)),facts={passwordless:local===null&&passwordFree,localOwner:local!==null,freshAt:null,returnTo:"/"},buildNow=(preview,digest)=>fastStartBuild(store,{preview,digest,actor:name??"",via:local===null?"cli":"terminal-ui",password:facts,approveNow:(taskId,sawDigest,fast)=>approve(store,taskId,name??"",clock(),sawDigest,token??"",{},fast)},clock()),answerBuild=built=>built.ok?succeed(write,json,command,{task:built.taskId},()=>[`Building ${built.taskId}. It starts next.`]):fail(write,json,command,built.reason,built.message,EXIT.refused),pressed=text(flags,"build");if(pressed!==void 0)return local===null?fail(write,json,command,"person-only","--build is the terminal UI's own.",EXIT.refused):answerBuild(buildNow(pressed,text(flags,"digest")??""));const fromLink=text(flags,"from");if(fromLink!==void 0)return importTaskCommand(fromLink,flags,context,name);const words=positional.join(" ").trim(),repo=text(flags,"repo");if(words==="")return fail(write,json,command,"usage",`Say what should change: \`toolroll task new "<what should change>" --repo ${repo??"<project>"}\``,EXIT.usage);if(repo===void 0)return fail(write,json,command,"usage","Name the project it's for with --repo (its folder, or `--repo .` for the one you're in): `toolroll task new \"<what should change>\" --repo <project>`",EXIT.usage);const placed=canonicalProject(repo)??resolve(repo);if(local===null&&(flags.has("token")||!facts.passwordless&&!passwordFreeOwner(store))){let given=flags.has("token")?token:void 0;if(given===void 0){const usual=name===void 0?soloOperatorOf(store):null;if(name===void 0){const answered=await(context.easySeams?.ask??ask)(usual===null?"username: ":`username [${usual}]: `);name=answered===""&&usual!==null?usual:answered}given=await(context.easySeams?.askHidden??askHidden)("password: ")}else name===void 0&&(name=soloOperatorOf(store)??void 0);if(name===void 0||name===""||given==="")return write("Nothing was filed."),EXIT.refused;const person=name;if(!verifyApproverByPassword(store,person,given,store.knownRepos().filter(one=>store.accountCanAccess(person,one))).ok)return fail(write,json,command,"unauthenticated","That username and password didn't work. Nothing was filed.",EXIT.refused);token=given,facts.freshAt=clock().getTime()}const prepared=name===void 0||token===void 0?{eligible:!1,reason:"password"}:await prepareFastStart(store,{actor:name,repo:placed,title:words,via:local===null?"cli":"terminal-ui",password:facts},clock()),terms=prepared.eligible?fastTermsLines(store,prepared.scope,placed):[];if(flags.has("preview"))return local===null?fail(write,json,command,"person-only","--preview is the terminal UI's own.",EXIT.refused):succeed(write,json,command,prepared.eligible?{eligible:!0,preview:prepared.preview,digest:prepared.digest,terms}:{eligible:!1,reason:prepared.reason,message:fastRefusalWords(prepared.reason)},()=>[]);if(!prepared.eligible)return write(`${fastRefusalWords(prepared.reason)} Filing it for a plan.`),addTask([words],flags,context,!0);write("Build approves exactly this:"),write("");for(const line of terms)write(` ${line.label}: ${line.words}`);return write(""),await(context.easySeams?.confirm??confirm)("Build now?")?answerBuild(buildNow(prepared.preview,prepared.digest)):(write("Nothing started. File it for a plan with `toolroll task add`."),EXIT.refused)}async function keepGrownCommand(positional,flags,context){const{store,write,json,clock}=context,id=positional[0];if(id===void 0)return fail(write,json,"task keep","usage","`toolroll task keep <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task keep",verified,"keeping a change takes `--as <you> --token <t>`",id);const kept=keepGrownChange(store,id,clock());return kept.ok?succeed(write,json,"task keep",{id,digest:kept.digest},()=>[`Its plan now names the exact commit. ${passwordFreeOwner(store)?"Approve it in `toolroll`: press a on the task.":`Approve it with \`toolroll task approve ${id}\`.`}`]):fail(write,json,"task keep","refused",kept.message,EXIT.refused)}let resumingReleases=!1;async function resumeHeldReleases(store,stateDir,now){if(!resumingReleases){resumingReleases=!0;try{await resumeAllowedReleases(store,stateDir,journal=>runRelease({branch:journal.branch,checkout:journal.checkout,stateDir,limits:{}},releaseAdapters({checkout:journal.checkout,say:()=>{}})),now)}catch{}finally{resumingReleases=!1}}}async function importTaskCommand(url,flags,context,actor){const{store,write,json}=context,clock=context.clock??(()=>new Date),command="task new",repo=text(flags,"repo");if(repo===void 0)return fail(write,json,command,"usage","`toolroll task new --from <url> --repo <project>`",EXIT.usage);const placed=canonicalProject(repo)??resolve(repo),read=await readGithubItem(store,{url,repo:placed},context.easySeams?.github??{});if(!read.ok)return fail(write,json,command,read.reason,read.message,EXIT.refused);write(`${read.item.kind==="pull"?"Pull request":"Issue"} #${read.item.number}, written outside Toolroll:`),write(` > ${read.item.title}`);for(const line of read.item.body.split(/\r?\n/))write(` > ${line}`);if(write(""),!await(context.easySeams?.confirm??confirm)("Add this task? You approve its plan before anything builds."))return write("Nothing filed."),EXIT.refused;const filed=await fileGithubItem(store,{url,repo:placed,actor:actor??"cli",shownHead:read.item.head},clock(),context.easySeams?.github??{});return filed.ok?succeed(write,json,command,{task:filed.taskId},()=>[`Filed ${filed.taskId}. Its plan is ready for you to approve.`]):fail(write,json,command,filed.reason,filed.message,EXIT.refused)}async function flakyCommand(positional,flags,context){const acting=await askCredentials(flags,context),verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runFlakyCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[]})}export async function refreshLearning(store,now,reads){try{backfillMemoryUse(store,now())}catch{}for(const repo of store.knownRepos())try{scheduledTidy(store,repo,now())}catch{}for(const repo of store.knownRepos())try{const key=ciCursorKey(repo),at=now();if(at.getTime()-store.serviceCursor(key)<CI_READ_EVERY_MS||ciRepositoriesOf(store,repo).length===0)continue;store.setServiceCursor(key,at.getTime(),at),await observeCiAttempts(store,repo,reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),at)}catch{}}async function cardCommand(positional,flags,context){if(activeRemote()===null&&isPanelCardCliInvocation(positional,flags,CARD_SOURCES))return runPanelCardCommand(positional,flags,{json:context.json,now:context.clock(),repos:context.store.knownRepos(),ok:(result,lines)=>succeed(context.write,context.json,"card",result,lines),no:(reason,message)=>fail(context.write,context.json,"card",reason,message,reason==="usage"?EXIT.usage:EXIT.refused)});const acting=await askCredentials(flags,context),verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runCardCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[],evidenceRoot:context.evidenceRoot,ok:(result,lines)=>succeed(context.write,context.json,"card",result,lines),no:(reason,message)=>fail(context.write,context.json,"card",reason,message,reason==="usage"?EXIT.usage:EXIT.refused)})}function localReader(context){const local=currentLocalOwner();return local===null?null:{name:local.account,repos:context.store.knownRepos().filter(repo=>context.store.accountCanAccess(local.account,repo))}}function followThroughContext(context,flags){const{store,write,json,clock,evidenceRoot}=context;return{store,evidenceRoot,now:clock(),ok:(command,result,lines)=>succeed(write,json,command,result,lines),no:(command,reason,message)=>fail(write,json,command,reason,message,reason==="usage"?EXIT.usage:EXIT.refused),prove:async(command,repo)=>{const acting=await askCredentials(flags,context);return acting===null?(fail(write,json,command,"usage","this takes `--as <you> --token <t>`",EXIT.usage),null):authenticateApprover(store,acting.name,acting.token,repo).ok?acting.name:(fail(write,json,command,"not-an-approver","that is not an approver, or the token does not match",EXIT.refused),null)}}}async function projectFallbackCommand(positional,flags,context){const command="project fallback",agents=text(flags,"agents"),clearing=flags.has("clear"),allowing=flags.has("allow-paid"),withdrawing=flags.has("no-paid"),repo=await projectAsked(context,flags,positional,command,{own:["agents","clear","allow-paid","no-paid"],most:1,usage:"Use project fallback --repo <project path> [--agents provider:model:plan|api-key,…] [--clear] [--allow-paid|--no-paid].",invalid:clearing&&agents!==void 0||allowing&&withdrawing,match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=()=>{const setting=fallbackSettingOf(context.store,repo);return setting===null?[`${repo}: no fallback agents. A task stops when its agent runs out of its plan.`]:[`${repo}: when an agent runs out of its plan, the work moves on to:`,...setting.entries.map((one,at)=>` ${at+1}. ${entryWords(one)}. ${entryMovesOnWords(one)}.`),setting.paidGrant===null?"Paid fallback: not allowed.":`Paid fallback: allowed by ${setting.paidGrant.by}.`]},shown=()=>{const setting=fallbackSettingOf(context.store,repo);return{repo,agents:setting?.entries??[],paidAllowed:setting?.paidGrant!=null}};if(agents===void 0&&!clearing&&!allowing&&!withdrawing)return succeed(context.write,context.json,command,shown(),words);const parsed=agents===void 0?[]:agents.split(",").map(one=>parseEntry(one.trim())),bad=parsed.find(one=>typeof one=="string");if(bad!==void 0)return fail(context.write,context.json,command,"usage",bad,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its fallback agents, with their password: pass --as and --token.",EXIT.refused);const now=context.clock(),done=context.store.transact(()=>{if(clearing){const one=clearFallbackChain(context.store,repo,acting.name,now);if(!one.ok)return one}if(agents!==void 0){const one=setFallbackChain(context.store,repo,parsed,acting.name,now);if(!one.ok)return one}if(allowing||withdrawing){const one=setPaidGrant(context.store,repo,allowing,acting.name,now);if(!one.ok)return one}return{ok:!0}});return done.ok?succeed(context.write,context.json,command,shown(),()=>[...words(),"Tasks scoped from now on use this; tasks already approved keep the chain they were approved with."]):fail(context.write,context.json,command,"refused",done.problem,EXIT.refused)}async function quickAnswersConfig(action,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","quick answers are installation-wide: no --repo",EXIT.usage);const said=()=>{const on=leadQuickAnswersOn(store),model=quickLeadModel(store);return{payload:{quickAnswers:{on,model}},lines:()=>[on?`Quick answers are on: plain status questions are answered by ${modelName(model)}; anything that asks for a change stays on the lead's main model.`:"Quick answers are off: the lead's main model answers everything."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","changing quick answers takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting.name,acting.token).ok||!store.isInstanceOperator(acting.name))return fail(write,json,command,"unauthenticated","an instance operator changes quick answers, with their password",EXIT.refused);setLeadQuickAnswers(store,action==="set",acting.name,clock());const shown=said();return succeed(write,json,command,shown.payload,shown.lines)}export const DELIVERY_EVERY_MS=5e3,FAST_CI_EVERY_MS=3e4,FAST_CI_LIMIT=10;const FAST_CI_NONE_WINDOW_MS=30*6e4,serviceBeats=new WeakMap;function newestNotificationId(store){return Number(store.handle.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM notification").get()?.id??0)}export function fastCiWaiting(store,now,limit=FAST_CI_LIMIT,attempted=new Map){const waiting=store.openedPublications().filter(publication=>{if(publication.prNumber===null)return!1;const state=publication.lastCheckState;if(state===null||state==="running")return!0;if(state==="none")return now.getTime()-Date.parse(publication.lastCheckAt??publication.updatedAt)<FAST_CI_NONE_WINDOW_MS&&now.getTime()-Date.parse(publication.updatedAt)<FAST_CI_NONE_WINDOW_MS;if(state!=="passing")return!1;const intent=store.mergeIntentFor(publication.id);if(intent!==null&&["pending","claimed","waiting-human","firing"].includes(intent.state))return!0;const follow=store.handle.prepare("SELECT flow_card, ready_head, merge_commit FROM pull_request_follow WHERE publication = ?").get(publication.id);return follow!==void 0&&follow.flow_card==null&&follow.merge_commit==null&&follow.ready_head!==publication.headSha}),last=one=>{const read=one.lastCheckAt??"",tried=attempted.get(one.id)??"";return tried>read?tried:read};return waiting.sort((a,b)=>last(a).localeCompare(last(b))||a.id-b.id).slice(0,limit)}export function joinServiceBeats(member){const store=member.context.store;let beats=serviceBeats.get(store);beats===void 0&&(beats=startServiceBeats(store)),beats.members.add(member);const joined=beats;return async()=>{!joined.members.delete(member)||joined.members.size>0||(joined.stopped=!0,serviceBeats.get(store)===joined&&serviceBeats.delete(store),joined.poker.poke(),await joined.delivery.stop(),await joined.fastCi.stop(),await joined.wakeLoop)}}function startServiceBeats(store){const anyMember=()=>beats.members.values().next().value;let deliveredThrough=newestNotificationId(store),deliveryProblem=null;const attempted=new Map,delivery=startMaintenance({intervalMs:DELIVERY_EVERY_MS,shouldStop:()=>beats.stopped,onError:error=>{const detail=describe(error);detail!==deliveryProblem&&anyMember()?.progress(`watch: outgoing webhooks failed — ${detail}; they try again in a few seconds`),deliveryProblem=detail},run:async()=>{const member=anyMember();if(member===void 0)return;const{context}=member,dir=dirname(context.databaseFile);deliveredThrough=newestNotificationId(store);try{await pushPass(store,{configDir:dir,clock:()=>new Date})}catch{}const primary=effectivePrimary(process.env,dir,loadBotToken(process.env,context.telegramTokenFile)!==null),targets=activeWebhookTargets(process.env,dir,primary.channel);targets.length>0&&await webhookPass(store,{targets,consoleUrl:loadConsoleUrl(process.env,dir),clock:context.clock}),deliveryProblem=null}}),fastCi=startMaintenance({intervalMs:FAST_CI_EVERY_MS,shouldStop:()=>beats.stopped,onError:()=>{},run:async()=>{const standingMembers=()=>[...beats.members].filter(one=>one.stopping?.()!==!0),standing=()=>{const members=standingMembers();return!beats.stopped&&members.length>0&&members.every(one=>one.ciReady())};if(!standing())return;const{context,progress}=standingMembers()[0],now=context.clock(),waiting=fastCiWaiting(store,now,FAST_CI_LIMIT,attempted);if(waiting.length===0)return;attempted.size>500&&attempted.clear();for(const one of waiting)attempted.set(one.id,now.toISOString());const exec=context.publishExec===void 0?{}:{exec:context.publishExec},checks=await observeChecks(store,{...exec,publications:waiting});if(!standing())return;checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...exec,proceed:standing});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}}),poker=new WakePoker,hub=wakeHubFor(store,read=>briefly(store,read)),beats={members:new Set,stopped:!1,delivery,fastCi,poker,wakeLoop:Promise.resolve()};return beats.wakeLoop=(async()=>{for(;!beats.stopped;)try{await hub.changed({baseline:store.wakeSeq(),deadline:Number.MAX_SAFE_INTEGER,until:()=>beats.stopped,poker})==="wake"&&!beats.stopped&&newestNotificationId(store)>deliveredThrough&&delivery.runNow()}catch{await new Promise(resolveLater=>{setTimeout(resolveLater,1e3).unref?.()})}})(),serviceBeats.set(store,beats),delivery.runNow(),beats}function claimAndMarkRunning(store,backend,id,taskRef,runner,options){const{now}=options;return store.transact(()=>{const result=acquire(store,taskRef,runner,options);if(!result.ok||backend!==BUILT_IN)return result;if(result.replayed===!0){const task=store.getTask(id),stillMine=store.currentLiveLease(taskRef,now)===result.claim.leaseId;return task!==null&&task.state==="queued"&&stillMine&&store.setTaskState(id,"running",now),result}if(!moveTask(store.handle,id,"claim",now))throw new Error(`claim: ${id} could not be marked running`);return store.bumpWake(),result})}function closedClaimWords(store,id,state,now){const head=`${id} is ${state}, so it can't be claimed.`;return state==="cancelled"?`${head} To run it again, reopen it: \`toolroll task state ${id} queued\``:requeueEligibility(store,id,now).ok?`${head} To run it again: \`toolroll task requeue ${id}\``:`${head} See its result: \`toolroll task show ${id}\``}function releaseToQueue(store,lease,now){return store.transact(()=>{const result=release(store,lease,now);if(!result.ok||result.duplicate===!0)return result;const ref=store.refForId(result.claim.taskRef);return ref===null||ref.backend!==BUILT_IN||store.getTask(ref.externalId)?.state==="running"&&store.setTaskState(ref.externalId,"queued",now),result})}async function localPlanCommand(positional,flags,context){const{store,write,json,clock}=context,command="task plan";if(flags.has("provider")||flags.has("model")){const passwordSet=store.accountOf(currentLocalOwner()?.account??"")?.passwordSet===!0;return fail(write,json,command,"local-owner",`Choosing which agent plans needs your password. ${passwordSet?"Sign in with your password to do this.":"Set a password first: run `toolroll password set`."}`,EXIT.refused)}for(const name of flags.keys())if(!["json","db","digest","incident"].includes(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const id=positional[0],digest=flags.get("digest"),incident=flags.get("incident"),usage="Use task plan <task> --digest <the plan source you read> [--incident <the planning incident you read>].";if(positional.length!==1||!id||id.length>64||/[\x00-\x1f]/.test(id))return fail(write,json,command,"usage",usage,EXIT.usage);if(typeof digest!="string"||!/^[a-f0-9]{64}$/.test(digest))return fail(write,json,command,"usage",`--digest needs the exact task you read. ${usage}`,EXIT.usage);if(incident!==void 0){if(typeof incident!="string"||!/^[1-9]\d{0,14}$/.test(incident))return fail(write,json,command,"usage",`--incident needs the incident you read. ${usage}`,EXIT.usage);const again=planAgainAsLocalOwner(store,id,{incident:Number(incident),source:digest},clock());return again.ok?succeed(write,json,command,{id,replayed:again.replayed,again:!0},()=>[again.replayed?`${id} · Already planning again.`:`${id} · Planning again. You approve the plan before anything is built.`]):fail(write,json,command,again.reason,again.message,EXIT.refused)}const done=requestPlanAsLocalOwner(store,id,digest,clock());return done.ok?succeed(write,json,command,{id,replayed:done.replayed,autoPlan:!1},()=>[done.replayed?`${id} · Already asked for a plan.`:`${id} · Asked for a plan. You approve the plan before anything is built.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}async function localRetryCommand(positional,flags,context){const{store,write,json,clock}=context,command="task requeue";for(const name of flags.keys())if(!["json","db","run","digest"].includes(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const id=positional[0],run2=flags.get("run"),digest=flags.get("digest"),usage="Use task requeue <task> --run <the build you read> --digest <its approved plan>.";if(positional.length!==1||!id||id.length>64||/[\x00-\x1f]/.test(id))return fail(write,json,command,"usage",usage,EXIT.usage);if(typeof run2!="string"||!/^[1-9]\d{0,14}$/.test(run2))return fail(write,json,command,"usage",`--run needs the exact build you read. ${usage}`,EXIT.usage);if(typeof digest!="string"||!/^[a-f0-9]{32}$/.test(digest))return fail(write,json,command,"usage",`--digest needs the exact plan you read. ${usage}`,EXIT.usage);await proveTaskBuildsStopped(store,id,clock);const done=retryAsLocalOwner(store,id,{run:Number(run2),digest},clock());return done.ok?succeed(write,json,command,{id,replayed:done.replayed,retries:done.retries},()=>[done.replayed?`${id} · Already retrying build #${run2}.`:`${id} · Retrying build #${run2}. It starts next.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}export function personMayInitLocalMode(caller){return caller.stdin&&caller.stdout&&!caller.agent&&!caller.json&&!caller.remote}function defaultFenceAvailable(){return process.platform==="darwin"?macosFenceAvailable():linuxFenceAvailable()}function upLocalInitCaller(context,flags){const terminal=context.upSeams?.terminal;return{stdin:terminal??process.stdin.isTTY===!0,stdout:terminal??process.stdout.isTTY===!0,agent:underAgent(context.upSeams?.env??process.env),json:context.json,remote:context.principal!==void 0||localOwnerRequested()||["token","token-file","token-env"].some(name=>flags.has(name))}}export async function initLocalModeForPerson(store,caller,input){if(!personMayInitLocalMode(caller))return{ok:!1,reason:"not-a-person"};if(!localModeCandidate(store))return{ok:!1,reason:"already"};const consolesDown=await consolesProvenDown(store,input.now,input.probe);return initLocalMode(store,{owner:input.owner,fenceAvailable:input.fence(),now:input.now,consolesProvenDown:consolesDown})}export async function easyStartInitLocalMode(databaseFile,caller,options={}){if(!personMayInitLocalMode(caller)||!(options.fence??defaultFenceAvailable)())return!1;let store;try{store=openStore(databaseFile,{createdBy:"laptop"})}catch{return!1}try{const owner=options.owner??process.env.USER??process.env.USERNAME??"operator";return await initLocalModeForPerson(store,caller,{owner,fence:()=>!0,now:options.now??new Date,...options.probe===void 0?{}:{probe:options.probe}}),localOwnerBinding(store)!==null}catch{return!1}finally{store.close()}}function serveConsoleLifecycle(store,host,port,clock){const component=consoleComponent(host,port),holder=`serve:${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,component,"started",holder,clock(),{pid:process.pid})}catch{return null}const beat=setInterval(()=>{try{beatLifecycle(store,component,holder,clock())}catch{}},RUNNER_HEARTBEAT_MS);return beat.unref?.(),()=>{clearInterval(beat);try{reportLifecycle(store,component,"stopped",holder,clock())}catch{}}}const probeConsoleAddress=(host,port)=>new Promise(resolve2=>{const socket=createNetConnection({host,port}),done=answer=>{socket.destroy(),resolve2(answer)};socket.setTimeout(1e3,()=>done("unknown")),socket.once("connect",()=>done("listening")),socket.once("error",error=>{const code=error.code??"";done(["ECONNREFUSED","EADDRNOTAVAIL","EAFNOSUPPORT"].includes(code)?"refused":"unknown")})});export async function consolesProvenDown(store,now,probe=probeConsoleAddress){const down=new Set;let rows;try{rows=openConsoleRows(store,now)}catch{return down}for(const row of rows){if(row.beatRecent||row.port===null)continue;const addresses=row.host===null||["0.0.0.0","::","localhost"].includes(row.host)?["127.0.0.1","::1"]:[row.host];let allRefused=!0;for(const address of addresses)await probe(address,row.port)!=="refused"&&(allRefused=!1);allRefused&&down.add(row.key)}return down}async function closeServedConsole(server){await new Promise(resolve2=>{server.close(()=>resolve2()),server.closeAllConnections?.()})}async function welcomeSampleCommand(positional,flags,context){const{write,json,store}=context,command="welcome sample";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll welcome sample`: it takes no folder or name.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a welcome sample option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","The sample project is added on Toolroll's own computer.",EXIT.refused);const lead=envValue(process.env,"LEAD_TOKEN");if(context.leadToken!==void 0||lead!==void 0&&lead!=="")return fail(write,json,command,"refused","A lead token can't add the sample project. Run `toolroll` yourself and press s.",EXIT.refused);if(store.isDemo())return fail(write,json,command,"refused","The sandbox never makes projects.",EXIT.refused);const viaScreen=localOwnerRequested();if(!viaScreen&&!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Add the sample project yourself at a terminal: run `toolroll` and press s, or `toolroll welcome sample`.",EXIT.refused);const binding=localOwnerBinding(store);if(binding===null)return fail(write,json,command,"not-local","This Toolroll signs in with a password. Open it in the browser and choose Try a sample project on the welcome page.",EXIT.refused);if(!viaScreen&&store.accountOf(binding.account)?.passwordSet===!0)return fail(write,json,command,"password-set","This Toolroll has a password. Run `toolroll` and press s, or sign in in the browser and choose Try a sample project.",EXIT.refused);const principal=viaScreen?currentLocalOwner():{account:binding.account,localGeneration:binding.localGeneration,accountGeneration:binding.accountGeneration,transport:"terminal",act:"add-project",sessionHash:null,request:null};if(principal===null||principal.act!=="add-project")return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const registryFile=registryPathOf(context),{readProjectRegistryNow}=await import("./repos.js"),ceiling=registry=>{const read=registry??readProjectRegistryNow(registryFile);return"error"in read?{repos:[],roots:[]}:resolveCeiling(read.repos,read.roots).ceiling};if("error"in readProjectRegistryNow(registryFile))return fail(write,json,command,"registry","Toolroll's project list can't be read, so nothing was added.",EXIT.refused);const{addSampleProject}=await import("./sample-project.js"),added=await asLocalOwner(principal,async()=>{const stands=()=>localActNow(store,"add-project")!==null;return addSampleProject({store,registryFile,now:context.clock(),ceiling,authority:{actor:{label:principal.account,origin:"cli"},stands}})});if(!added.ok){const words={"no-root":"There's no projects folder to put the sample in. Run `toolroll` once to choose one, then try again.",exists:"A folder named toolroll-sample is already in your projects folder and wasn't made by Toolroll, so nothing was changed.",failed:"The sample project couldn't be made. Nothing was added. Try again.","not-added":"The sample project was made but couldn't be added. Try again.",refused:"Your local sign-in changed while the sample was being added. Nothing was added. Run `toolroll` to sign in again.",incomplete:"The sample project wasn't added, and its line in your project list couldn't be taken back."};return fail(write,json,command,added.reason,added.message??words[added.reason],EXIT.refused)}return succeed(write,json,command,{repo:added.repo,created:added.created,added:added.added,checkSet:added.checkSet},()=>[added.added?`Added the sample project: ${added.repo}`:`The sample project is already added: ${added.repo}`,"Next: write a first task. Run `toolroll` and press n."])}async function passwordResetCommand(rest,flags,context){const{write,json,store}=context,command="password reset";if(rest.length>0)return fail(write,json,command,"usage","Use `toolroll password reset` (or `--as <name>` when several people sign in here).",EXIT.usage);for(const name of flags.keys())if(!["db","json","as"].includes(name))return fail(write,json,command,"usage",`--${name} is not a password reset option: the new password is only ever typed.`,EXIT.usage);const leadInShell=envValue(process.env,"LEAD_TOKEN");if(context.principal!==void 0||activeRemote()!==null||context.leadToken!==void 0||leadInShell!==void 0&&leadInShell!=="")return fail(write,json,command,"not-remote","A password is reset by a person at the computer running Toolroll, from their own shell (not with a remote or lead token).",EXIT.refused);if(localOwnerRequested()||!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Reset the password yourself at a terminal on the computer running Toolroll: run `toolroll password reset`.",EXIT.refused);const asked=flags.get("as");if(asked===!0||asked==="")return fail(write,json,command,"usage","Say whose password: `--as <name>`.",EXIT.usage);let account;if(typeof asked=="string")account=asked;else{const people=store.listApprovers().map(one=>one.name).filter(name=>store.accountOf(name)?.revokedAt===null);if(people.length===0)return fail(write,json,command,"no-account","No one signs in to this Toolroll yet. Nothing changed.",EXIT.refused);if(people.length>1)return fail(write,json,command,"several",`Several people sign in here (${people.join(", ")}). Say whose: \`toolroll password reset --as <name>\`.`,EXIT.usage);account=people[0]}const sso=(await import("./sso-settings.js")).readSsoSettings(dirname(context.databaseFile)),operatorsOnly=sso!==null&&sso.passwords==="operators",refusalWords=reason=>reason==="no-account"?`No account named \`${account}\`. Nothing changed.`:reason==="revoked"?`${account} was removed and can't sign in. Nothing changed.`:reason==="sso-only"?`${account} signs in with ${sso?.label??"your identity provider"} and has no password to reset. Nothing changed.`:reason==="no-password"?`${account} has no password yet. Set one with \`toolroll password set\`. Nothing changed.`:reason==="password-not-allowed"?`${account} signs in with ${sso?.label??"your identity provider"}: passwords are only for instance operators here. Nothing changed.`:"The account changed while you were typing. Nothing changed; run `toolroll password reset` again.",before=passwordResetRefusal(store,account,operatorsOnly);if(before!==null)return fail(write,json,command,before,refusalWords(before),EXIT.refused);const generation=store.accountOf(account).generation;write(`Reset the password for ${account}.`),write(`This ends ${account}'s browser sessions and remembered passwords, the terminal UI's sign-in, paired chats, phone notifications, lead sessions and lead tokens (mint a new one with \`toolroll lead token\`).`),write("It keeps API and MCP tokens (revoke them in Settings → Sessions & tokens) and coordinator credentials (`toolroll coordinator revoke`). Revoke those too if someone else may know the old password.");const typeHidden=context.easySeams?.askHidden??askHidden,chosen=await typeHidden("New password: ");if(chosen.length<8)return fail(write,json,command,"weak-password","A password needs at least 8 characters. Nothing changed.",EXIT.refused);if(await typeHidden("Type it again: ")!==chosen)return fail(write,json,command,"mismatch","The two passwords didn't match. Nothing changed.",EXIT.refused);const reset=resetAccountPassword(store,account,hashPassword(chosen),generation,operatorsOnly,context.clock());if(!reset.ok)return fail(write,json,command,reset.reason,refusalWords(reset.reason),EXIT.refused);const cleanup=removeStaleSavedLogin(dirname(context.databaseFile),account,chosen),{shownPath}=await import("./server/login-help.js"),shown=path=>shownPath(path,homedir(),null)??path;return succeed(write,json,command,{account,generation:reset.generation,removed:cleanup.removed},()=>[`Password reset for ${account}. Every session of ${account} has ended; sign in with the new password.`,...reset.leadTokens>0?[`${account}'s lead token ended: mint a new one with \`toolroll lead token\`.`]:[],...cleanup.removed.map(path=>`Removed ${shown(path)}: it held the old password.`),...cleanup.stale.map(path=>`The saved first password at ${shown(path)} no longer works; delete it yourself.`),...cleanup.unchecked.map(path=>`${shown(path)} isn't a plain file in Toolroll's folder, so it was left alone. If it holds ${account}'s old password, delete it yourself.`)])}function shellCallerFacts(context){return{json:context.json,agent:context.easySeams?.agent??underAgent(process.env),terminal:context.easySeams?.terminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)}}async function projectFlexibleCommand(positional,flags,context){const action=positional[1]??"show",command=`project flexible ${action}`,{write,json}=context,own={show:[],enable:["max","default","digest"],lower:["max"],off:[]}[action];if(own===void 0||positional.length>2)return fail(write,json,command,"usage","Use project flexible [show | enable [--max <level>] [--default <level>] [--digest <d>] | lower --max <level> | off] --repo <project path>.",EXIT.usage);const allowed=new Set(["repo","db","json",...own,...action==="show"?[]:["as","token","token-file","token-env"]]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,command,"usage",`--${name} is not a project flexible ${action} option.`,EXIT.usage);const repoFlag=text(flags,"repo");if(repoFlag===void 0)return fail(write,json,command,"usage","Name the project with --repo <path>.",EXIT.usage);const level=name=>{const value=text(flags,name);return value===void 0?void 0:isFlexibleLevel(value)?value:null},max=level("max"),chosenDefault=level("default");if(max===null||chosenDefault===null)return fail(write,json,command,"usage","A level is supervised, auto or full.",EXIT.usage);const repo=await knownProject(context,repoFlag,{listed:!0,canonical:!0});if(repo===void 0)return fail(write,json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused);const store=context.store,termsLines=(terms,digest)=>[...flexibleTermsWords(terms),`Terms ${digest}`],shown=standing=>{if(standing.state==="secure")return{data:{state:"secure"},lines:[`${repo}: Secure. Work is planned and approved before it starts.`]};if(standing.state==="unreadable")return{data:{state:"unreadable"},lines:[`${repo}: its thread terms can't be read, so they allow nothing. Turn interactive agent threads off for it, then on again.`]};const data={state:standing.state,digest:standing.digest,terms:standing.terms,signedBy:standing.signedBy,signedAt:standing.signedAt,...standing.state==="lapsed"?{lapse:standing.reason}:{}};return standing.state==="lapsed"?{data,lines:[`${repo}: Flexible terms no longer count. ${FLEXIBLE_LAPSE_WORDS[standing.reason]} Turn it on again to sign new terms.`]}:{data,lines:[`${repo}: interactive agent threads are on, turned on by ${standing.signedBy}.`,...termsLines(standing.terms,standing.digest)]}};if(action==="show"){const now=shown(flexibleStanding(store,repo));return succeed(write,json,command,{repo,flexible:now.data},()=>now.lines)}const refused=message=>fail(write,json,command,"person-only",message,EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return refused("Only a person changes a project's thread terms, never the lead, a token or a chat app.");const acting=await askCredentials(flags,context);if(acting===null)return refused(action==="enable"?"Turning on interactive agent threads needs your Toolroll password: run it again with `--as <your name>` and type the password when asked (`--token` is that password, only for scripts: it stays in shell history). Or turn them on in the browser, on the project's page in Settings.":"This needs your sign-in: run it again with `--as <your name>` and type your Toolroll password when asked.");if(action==="enable"){if(!flexibleAvailable(store))return fail(write,json,command,"not-available",FLEXIBLE_UNAVAILABLE,EXIT.refused);const proved2=credentialApprover(store,acting.name,acting.token,repo);if(!proved2.ok)return refused("Only an approver of this project, with their password typed now, turns on interactive agent threads.");const choice={...max===void 0?{}:{max},...chosenDefault===void 0?{}:{default:chosenDefault}},proposed=proposedFlexibleTerms(store,repo,acting.name,choice);if(!proposed.ok)return fail(write,json,command,proposed.reason,proposed.message,EXIT.refused);let digest=text(flags,"digest");if(digest===void 0){if(!interactive()||json)return fail(write,json,command,"review-terms",[...termsLines(proposed.terms,proposed.digest),`Read these terms, then run again with --digest ${proposed.digest} to agree to them. Nothing changed.`].join(`
491
508
  `),EXIT.refused,{digest:proposed.digest,terms:proposed.terms});if(write(termsLines(proposed.terms,proposed.digest).join(`
492
- `)),!await confirm("Turn on interactive agent threads in this project with these terms?"))return fail(write,json,command,"declined","Nothing changed.",EXIT.refused);digest=proposed.digest}const done2=enableFlexible(store,{repo,by:acting.name,proof:proved2.method,choice,shownDigest:digest,now:context.clock()});return done2.ok?succeed(write,json,command,{repo,flexible:shown(flexibleStanding(store,repo)).data,replaced:done2.replaced},()=>[`Interactive agent threads are on in ${repo} (terms ${done2.digest}). Start one with T in the terminal workbench.`]):fail(write,json,command,done2.reason,done2.message,EXIT.refused)}const proved=authenticateApprover(store,acting.name,acting.token,repo);if(!proved.ok||!personProof(proved.method))return refused("Only an approver of this project, signed in as a person, changes its thread terms.");if(action==="lower"){if(max===void 0)return fail(write,json,command,"usage","Name the highest level with --max supervised, auto or full.",EXIT.usage);const done2=lowerFlexible(store,{repo,by:acting.name,max,now:context.clock()});return done2.ok?succeed(write,json,command,{repo,changed:done2.changed,flexible:shown(flexibleStanding(store,repo)).data},()=>[done2.changed?`Lowered: threads in ${repo} run at ${FLEXIBLE_LEVEL_WORDS[done2.terms.max]} at most. New threads start under these terms only.`:"Nothing changed.",...termsLines(done2.terms,done2.digest)]):fail(write,json,command,done2.reason,done2.message,EXIT.refused)}const done=turnFlexibleOff(store,{repo,by:acting.name,now:context.clock()});return done.ok?succeed(write,json,command,{repo,changed:done.changed,flexible:{state:"secure"}},()=>[done.changed?`Interactive agent threads are off in ${repo}. No new ones start.`:`Interactive agent threads are already off in ${repo}.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}async function taskSizingConfig(action,value,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","task sizing is installation-wide: no --repo",EXIT.usage);const said=()=>{const read=taskSizingSetting(store),on=read.on&&!read.byEnv,name=one=>one==="jev"?"Jev via OpenRouter (your credit)":"Claude Haiku (on your plan)";return{payload:{taskSizing:{on,setting:read.chosen?"on":"off",sizer:read.sizer,available:read.available,byEnv:read.byEnv}},lines:()=>[read.byEnv?"Task sizing is off: TOOLROLL_NO_TASK_CLASSIFIER is set, so no model call happens before you approve; uncertain tasks get a plan first.":on?`Task sizing is on: each new task is sized by ${name(read.sizer)} before you approve.`:read.chosen&&read.sizer!==null?`Task sizing is off: it was turned on for ${name(read.sizer)}, but ${name(read.available)} is the one available now, so nothing is sent. Run \`toolroll config set task-sizing on\` to choose it.`:"Task sizing is off: no model call before you approve; uncertain tasks get a plan first."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}if(action!=="set"||value!=="on"&&value!=="off")return fail(write,json,command,"usage","`toolroll config set task-sizing on|off --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","changing task sizing takes `--as <you> --token <t>`",EXIT.usage);if(!store.transact(()=>!authenticateApprover(store,acting.name,acting.token).ok||!store.isInstanceOperator(acting.name)?!1:(setTaskSizing(store,value==="on"?taskSizingSetting(store).available:!1,acting.name,clock()),!0)))return fail(write,json,command,"unauthenticated","an instance operator changes task sizing, with their password",EXIT.refused);const shown=said();return succeed(write,json,command,shown.payload,shown.lines)}async function flexibleConfig(action,value,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","interactive agent threads are installation-wide: no --repo",EXIT.usage);const said=()=>{const read=flexibleSetting(store);return{payload:{flexible:{on:read.on,by:read.by,at:read.at}},lines:()=>[read.on?"Interactive agent threads (beta) are on: T in the workbench starts a Claude Code thread. Claude Code only for now; it runs inside Toolroll's sandbox with your Claude sign-in relayed, and Toolroll never gives the agent your key.":"Interactive agent threads (beta) are off. Turn them on with `toolroll config set flexible on`."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}if(action!=="set"||value!=="on"&&value!=="off")return fail(write,json,command,"usage","`toolroll config set flexible on|off --as <you> --token <t>`",EXIT.usage);const personOnly=value==="on"?"Only an instance operator, with their password typed for this command, turns interactive agent threads on; never a remembered sign-in, a token, the lead or a chat app.":"Only an instance operator, as a person with their password, turns interactive agent threads off; never a token, the lead or a chat app.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);const solo=value==="off"&&!flags.has("token")?soloOperatorOf(store):null;let acting=solo!==null&&(text(flags,"as")??solo)===solo?{name:solo,token:""}:null;if(acting===null){if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=value==="on"?await typedForCommand(flags,context):await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage",value==="on"?"Turning threads on asks for your Toolroll password at a hidden prompt: run it in your own terminal.":"This needs your name and password: run it in your own terminal to be asked, or add `--as <your Toolroll name> --token <your password>`.",EXIT.usage);const by=acting;if(!store.transact(()=>{const verified=by.token===""&&value==="off"?null:value==="on"?credentialApprover(store,by.name,by.token):authenticateApprover(store,by.name,by.token);return!(verified===null?soloOperatorOf(store)===by.name:verified.ok&&personProof(verified.method))||!store.isInstanceOperator(by.name)?!1:(setFlexibleSetting(store,value==="on",by.name,clock()),!0)}))return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);const shown=said();if(value==="on")return succeed(write,json,command,shown.payload,()=>[...shown.lines(),...flexibleNextStepWords(store,by.name)]);const report=await stopFlexibleThreadsEverywhere(store,{reason:"interactive agent threads were turned off",clock}),short=thread=>thread.slice(0,8),lines=[...shown.lines(),...report.stopped.length===0?[]:[`Stopped ${report.stopped.length===1?"1 running thread":`${report.stopped.length} running threads`}: every process of ${report.stopped.length===1?"its agent":"their agents"} is gone and ${report.stopped.length===1?"its turn":"their turns"} ended (${report.stopped.map(one=>short(one.thread)).join(", ")}).`],...report.stopped.some(one=>one.network)?["The console that started them closes their network on its next check, within a few seconds."]:[],...report.survivors.map(one=>`Thread ${short(one.thread)} couldn't be stopped yet${one.pids.length===0?"":`: process${one.pids.length===1?"":"es"} ${one.pids.join(", ")} still running`} (${one.why}). A running console keeps trying every few seconds; run this command again to try now.`)];return succeed(write,json,command,{...shown.payload,stopped:report.stopped,survivors:report.survivors},()=>lines)}async function flexibleSignInConfig(action,extra,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action} flexible-sign-in`;if([...extra,...[...flags.values()].filter(value=>typeof value=="string")].some(value=>looksLikeClaudeCredential(value)))return fail(write,json,command,"argument","Toolroll never takes your Claude sign-in as an argument: it is now in your shell history. Run `claude setup-token` again, then `toolroll config set flexible-sign-in` and paste the new token when asked. Nothing was saved.",EXIT.usage);if(extra.length>0)return fail(write,json,command,"usage","`toolroll config set flexible-sign-in` takes no value: it asks for the token at a hidden prompt.",EXIT.usage);if(repoGiven)return fail(write,json,command,"usage","your Claude sign-in is yours, not a project's: no --repo",EXIT.usage);if(flags.has("no-check")&&action!=="set")return fail(write,json,command,"usage","--no-check is only for `config set flexible-sign-in`",EXIT.usage);if(flags.has("check")&&action!=="show")return fail(write,json,command,"usage","--check is only for `config show flexible-sign-in --check`",EXIT.usage);const personOnly="Only you, as a person with your Toolroll password, change your own Claude sign-in for threads; never a token, the lead, a chat app or a machine.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);if(action!=="show"&&action!=="set"&&action!=="clear")return fail(write,json,command,"usage","`toolroll config set|clear|show flexible-sign-in`",EXIT.usage);if(action==="set"&&passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);let acting;const solo=(action==="clear"||action==="show"&&!flags.has("check"))&&!flags.has("token")?soloOperatorOf(store):null;if(solo!==null&&(text(flags,"as")??solo)===solo)acting={name:solo,token:""};else if(action==="set"){if(flags.has("token"))return fail(write,json,command,"usage","Saving your Claude sign-in asks for your Toolroll password at a hidden prompt, typed for this command: never --token or a saved sign-in.",EXIT.usage);const typed=context.easySeams?.askHidden??(interactive()&&!json?askHidden:null),named=context.easySeams?.ask??(interactive()&&!json?ask:null);if(typed===null)return fail(write,json,command,"usage","Run this in your own terminal: it asks for your Toolroll password and the token from `claude setup-token` at hidden prompts.",EXIT.usage);const usual=soloOperatorOf(store)??savedLoginName(context),answered=text(flags,"as")??(named===null?void 0:await named(usual===null?"username: ":`username [${usual}]: `)),name=answered===""&&usual!==null?usual:answered,password=await typed("password: ");acting=name===void 0||name.length===0||password.length===0?null:{name,token:password}}else{if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage","This needs your name and password: run it in your own terminal to be asked.",EXIT.usage);const statusWords=status=>status.state==="none"?"Your Claude sign-in for threads: none. Run `claude setup-token`, then `toolroll config set flexible-sign-in`.":status.state==="refused"?"Claude didn't accept your sign-in for threads. Run `claude setup-token` again and save the new token with `toolroll config set flexible-sign-in`.":`Your Claude sign-in for threads: saved ${status.savedAt.slice(0,10)}. ${signInCheckWords(statusCheck(status))} It powers only threads you start.`,statusData=status=>status.state==="none"?{state:"none"}:{state:status.state,savedAt:status.savedAt,check:status.checkOutcome,checkStatus:status.checkStatus};if(action==="show"){const shown=store.transact(()=>{if(acting.token===""&&!flags.has("check"))return soloOperatorOf(store)===acting.name?flexibleSignInStatus(store,acting.name):null;const proved=authenticateApprover(store,acting.name,acting.token);return proved.ok&&personProof(proved.method)?flexibleSignInStatus(store,acting.name):null});if(shown===null)return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);if(!flags.has("check"))return succeed(write,json,command,{signIn:statusData(shown)},()=>[statusWords(shown)]);let state2;try{state2=dirname(realpathSync(context.databaseFile))}catch{return fail(write,json,command,"no-sign-in","Toolroll's state folder can't be found.",EXIT.refused)}const again=await recheckFlexibleSignIn(store,state2,{person:acting.name,clock});if(!again.ok)return fail(write,json,command,"no-sign-in",statusWords({state:"none"}),EXIT.refused);const now=flexibleSignInStatus(store,acting.name);return succeed(write,json,command,{signIn:statusData(now),check:again.check.outcome},()=>[signInCheckWords(again.check),statusWords(now)])}if(action==="clear"){const removed=store.transact(()=>{if(acting.token===""){if(soloOperatorOf(store)!==acting.name)return null}else{const proved=authenticateApprover(store,acting.name,acting.token);if(!proved.ok||!personProof(proved.method))return null}return removeFlexibleSignIn(store,{person:acting.name,by:acting.name,now:clock()})});if(removed===null)return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);try{await tidyFlexibleSignIns(store,dirname(realpathSync(context.databaseFile)),{now:clock(),person:acting.name})}catch{}const report=removed.ended.threads.length===0?{stopped:[],survivors:[]}:await stopFlexibleThreadsEverywhere(store,{reason:"its owner's Claude sign-in for threads was removed",owner:acting.name,clock}),named=ids=>ids.map(id=>flexibleThreadTitleOf(store,id)).join(", "),stoppedWords2=report.stopped.length===0?[]:[`Stopped ${report.stopped.length===1?"1 running thread":`${report.stopped.length} running threads`} (${named(report.stopped.map(one=>one.thread))}).`],leftWords=report.survivors.length===0?[]:[`${named(report.survivors.map(one=>one.thread))} couldn't be stopped yet; a running console keeps trying every few seconds.`];return succeed(write,json,command,{removed:removed.removed,stopped:report.stopped,survivors:report.survivors},()=>[removed.removed?"Removed. Your threads can't reach Claude until you add one again. The token still works at Claude until you revoke it in your Claude account.":"You had no Claude sign-in for threads saved. Nothing changed.",...stoppedWords2,...leftWords])}const typeHidden=context.easySeams?.askHidden??(interactive()&&!json?askHidden:null);if(typeHidden===null)return fail(write,json,command,"usage","Run this in your own terminal: it asks for the token from `claude setup-token` at a hidden prompt.",EXIT.usage);const pasted=await typeHidden("Paste the token from `claude setup-token`: "),shaped=setupTokenFromPaste(pasted);if(!shaped.ok)return fail(write,json,command,shaped.reason,shaped.message,EXIT.refused);let state;try{state=dirname(realpathSync(context.databaseFile))}catch{return fail(write,json,command,"not-saved","Toolroll's state folder can't be found. Nothing was saved.",EXIT.refused)}const saved=await saveFlexibleSignIn(store,{state,person:acting.name,password:acting.token,token:shaped.token,check:!flags.has("no-check"),clock});if(!saved.ok)return fail(write,json,command,saved.reason,saved.message,EXIT.refused);const checked=saved.check===null?{outcome:"not-checked"}:saved.check;return succeed(write,json,command,{saved:!0,replaced:saved.replaced,check:checked.outcome,signIn:statusData(flexibleSignInStatus(store,acting.name))},()=>[`${saved.replaced?"Replaced":"Saved"}. ${signInCheckWords(checked)} It powers only threads you start; a password reset ends it.`])}function passwordFreeRefusal(store,flags,key,remote){return passwordFreeInstall(store,flags,remote)?`This Toolroll has no password yet, so this runs from Toolroll itself: run \`toolroll\`, select the task and press ${key}, or open it in the browser.`:null}function soloOperatorOf(store){if(installModeNow(store).mode!=="solo")return null;const operators=store.accountFacts().filter(one=>store.isInstanceOperator(one.name)).map(one=>one.name);return operators.length===1?operators[0]:null}function savedLoginName(context){try{return readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null}catch{return null}}async function typedForCommand(flags,context,promptOnly=!1){const given=text(flags,"token");if(given!==void 0){const name2=text(flags,"as")??soloOperatorOf(context.store);return promptOnly||given===""||name2===null||name2===void 0?null:{name:name2,token:given}}const typed=context.easySeams?.askHidden??(interactive()&&!context.json?askHidden:null),named=context.easySeams?.ask??(interactive()&&!context.json?ask:null);if(typed===null)return null;const usual=soloOperatorOf(context.store)??savedLoginName(context),answered=text(flags,"as")??(named===null?void 0:await named(usual===null?"username: ":`username [${usual}]: `)),name=answered===""&&usual!==null?usual:answered,password=await typed("password: ");return name===void 0||name.length===0||password.length===0?null:{name,token:password}}function flexibleNextStepWords(store,person){const steps=[];return flexibleSignInStatus(store,person).state!=="active"&&steps.push("your own Claude sign-in: run `claude setup-token`, then `toolroll config set flexible-sign-in`"),steps.push("this project's terms: `toolroll project flexible enable --repo <path>`"),[`Next: ${steps.map((one,at)=>`${at+1}) ${one}`).join(" ")}.`]}async function threadCommand(positional,flags,context){const{store,write,json,clock}=context,verb=positional[0]??"list",command=`thread ${verb}`;if(!["list","show","end","remove","ship","save"].includes(verb))return fail(write,json,command,"usage","`toolroll thread list|show|end|remove|ship|save <thread>`",EXIT.usage);const personOnly="Only you, as a person, work with your own threads here; never a token, the lead, a chat app or a machine.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);const pick=owner=>{const asked=positional[1]??"";if(!/^[0-9a-f]{8,32}$/.test(asked))return null;const found=flexibleThreadRecords(store,{owner}).filter(one=>one.id.startsWith(asked));return found.length===1?found[0].id:null};if(verb==="ship"){const needs=flexibleShipNeedsFor(store,positional[1]??"");if(needs!==null)return fail(write,json,command,needs.reason,needs.message,EXIT.refused);if(passwordFreeOwner(store))return fail(write,json,command,"laptop","Nobody on this install has a password, so this thread ships from the workbench (`toolroll`), after its terms are read there.",EXIT.refused);const acting2=await typedForCommand(flags,context,!0);if(acting2===null)return fail(write,json,command,"usage","Shipping asks for your Toolroll password at a hidden prompt, typed for this command: run it in your own terminal (never --token).",EXIT.usage);const account2=store.accountOf(acting2.name),thread2=account2===null?null:pick(acting2.name);if(account2===null||thread2===null)return fail(write,json,command,"not-found","You have no such thread.",EXIT.refused);const by={name:acting2.name,generation:account2.generation},shown=await flexibleThreadShipTerms(store,{thread:thread2,by});if(!shown.ok)return fail(write,json,command,shown.reason,shown.message,EXIT.refused);const key=text(flags,"key"),lines=[...key!==void 0&&key!==shown.summary.key?["The terms changed since the workbench showed them. Here they are again."]:[],"Ship approves exactly this:",...summaryLines(shown.summary)];if(json)return fail(write,json,command,"usage","Ship asks before it ships: run it in your own terminal.",EXIT.usage);for(const line of lines)write(line);const confirm2=context.easySeams?.ask??(interactive()?ask:null),yes=confirm2===null?"":await confirm2("Ship exactly this? [y/N] ");if(!/^y(es)?$/i.test(yes.trim()))return fail(write,json,command,"declined","Nothing was shipped.",EXIT.refused);const shipped=await shipFlexibleThread(store,null,{thread:thread2,by,proof:{kind:"password-now",password:acting2.token},shownDigest:shown.digest,shownKey:shown.summary.key,now:clock(),waitMs:15e3});if(!shipped.ok)return fail(write,json,command,shipped.reason,shipped.message,EXIT.refused);const ship=latestFlexibleShip(store,thread2);return succeed(write,json,command,{thread:thread2,ship:ship?.id??null,seq:ship?.seq??null,task:ship?.taskId??null},()=>[`Shipping: checks run on commit ${ship?.candidate.slice(0,12)??""}; Toolroll merges it once they pass.`])}const solo=flags.has("token")?null:soloOperatorOf(store);let acting=solo!==null&&(text(flags,"as")??solo)===solo?{name:solo,token:""}:null;if(acting===null){if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage","This needs your name and password: run it in your own terminal to be asked.",EXIT.usage);const who={...acting,solo:solo!==null&&acting.name===solo&&!flags.has("token")&&acting.token.length===0},proveNow=()=>{if(who.solo)return soloOperatorOf(store)===who.name;const one=authenticateApprover(store,who.name,who.token);return one.ok&&personProof(one.method)};if(!store.transact(proveNow))return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);const account=store.accountOf(who.name);if(verb==="list"){const rows=flexibleThreadRecords(store,{owner:who.name});return succeed(write,json,command,{threads:rows},()=>rows.length===0?["You have no threads yet. Start one in the workbench (`toolroll`)."]:rows.map(one=>`${one.id.slice(0,8)} ${one.title} · ${threadStateWord(one)}${one.project===null?"":` · ${one.project}`}${shipOutcomeWord(one.ship)}`))}const thread=pick(who.name);if(thread===null)return fail(write,json,command,"not-found","You have no such thread.",EXIT.refused);const row=flexibleThreadRecords(store,{owner:who.name}).find(one=>one.id===thread);if(verb==="show")return succeed(write,json,command,{thread:row},()=>[`${row.title} (${row.id})`,`Project: ${row.project??row.repo}`,`Latest turn: ${row.turn??"none"}${row.endWords===null?"":`. ${row.endWords}`}`,...row.ended?["Ended."]:[],...row.shipWords===null?[]:[row.shipWords],"Reply to it in the workbench (`toolroll`)."]);if(verb==="end"){const done=await closeFlexibleThread(store,null,{thread,by:{name:who.name,generation:account.generation},act:"end",clock,prove:proveNow});if(!done.ok)return fail(write,json,command,done.reason,done.message,EXIT.refused);done.stopPending&&await stopFlexibleThreadsEverywhere(store,{reason:"its owner ended the thread",thread,clock});const keeps=flexibleShipNeedsFor(store,thread)===null?"ship its work, or save it as a branch,":`save its work as a branch (\`toolroll thread save ${thread.slice(0,8)}\`)`,left=done.already?0:(await flexibleUncommittedFiles(store,{thread})).length,leftWords=`Ended. Its agent left uncommitted edits in ${left} file${left===1?"":"s"}: \`toolroll thread save ${thread.slice(0,8)}\` saves them with its work as a branch. Its copy is kept for a week.`;return succeed(write,json,command,{thread,already:done.already},()=>[done.already?"This thread had already ended.":left>0?leftWords:`Ended. You can still ${keeps} for a week; then its copy is tidied.`])}if(verb==="save"){const saved=await saveFlexibleBranch(store,{thread,by:{name:who.name,generation:account.generation},now:clock(),prove:proveNow});return saved.ok?succeed(write,json,command,{thread,branch:saved.branch,commit:saved.candidate,already:saved.already,files:saved.changedPaths,next:saved.next,leftover:saved.leftover,uncommitted:saved.uncommitted},()=>[flexibleSavedWords(saved),saved.next]):fail(write,json,command,saved.reason,saved.message,EXIT.refused)}const removed=await removeFlexibleThreadCopy(store,{thread,by:who.name,now:clock(),prove:proveNow});return removed.ok?succeed(write,json,command,{thread},()=>["Removed its working copy. Its record stays."]):fail(write,json,command,removed.reason,removed.message,EXIT.refused)}export function threadStateWord(one){return one.ended?"Ended":one.turn==="admitted"||one.turn==="running"?"Working":one.ship!==null&&["approved","imported","armed","completed","merging"].includes(one.ship)?"Shipping":one.turn==="unknown"?"Outcome unknown":one.turn==="interrupted"?"Stopped":one.ship==="cancelled"?"Ship stopped":one.ship==="refused"||one.ship==="failed"?"Ship refused":"Ready"}export function shipOutcomeWord(ship){const word=ship==="merged"?"Merged":ship==="sent-back"?"sent back":null;return word===null?"":` · Ship: ${word}`}class BuiltinReplacementRefused extends Error{reason;constructor(reason){super(reason),this.reason=reason}}function createBuiltinReplacement(store,input){try{return store.transact(()=>store.savepoint(()=>{if(store.getTask(input.replaces)===null)return{ok:!1,reason:"unknown-task"};const task=store.createTask({id:input.id,title:input.title,...input.report?{deliverable:"report"}:{}},input.now),ref=store.refFor(BUILT_IN,task.id).id;if(store.stampFiledVia(ref,"cli"),input.repo!==null){const placed=store.placeTask(ref,canonicalProject(input.repo)??resolve(input.repo));if(typeof placed=="object"&&!placed.ok)throw new BuiltinReplacementRefused("scoped")}const moved=store.setTaskState(input.replaces,"cancelled",input.now,{},void 0,task.id);if(!moved.ok)throw new BuiltinReplacementRefused(moved.reason);return{ok:!0,task}}))}catch(error){if(error instanceof BuiltinReplacementRefused)return{ok:!1,reason:error.reason};throw error}}function builtinReplacementHeld(store,source,target){if(store.handle.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD)===void 0)return!1;for(const taskId of[source,target]){const ref=store.lookupRef(taskId);if(ref===null?store.getTask(taskId)!==null:readCheckRecoveryHoldsForTaskRef(store,ref.id).kind!=="no-evidence")return!0}return!1}async function finishFiledRequest(command,req,flags,context){if(flags.get("wait")===!0){const timeoutSeconds=Number(text(flags,"timeout")??"300"),safeTimeout=Number.isFinite(timeoutSeconds)&&timeoutSeconds>0?Math.min(3600,Math.round(timeoutSeconds)):300,settled=await waitForAgentRequest(context.databaseFile,req.id,safeTimeout);if(settled?.status==="approved")return succeed(context.write,context.json,command,{requested:!0,request:settled},()=>[`Approved (${settled.id}): ${settled.summary}`]);const reason=settled?.status==="declined"?"declined":"timeout",msg=settled?.status==="declined"?`Request ${req.id} was declined${settled.resolutionNote?`: ${settled.resolutionNote}`:"."}`:`Request ${req.id} is still pending in Toolroll.app after ${safeTimeout}s.`;return fail(context.write,context.json,command,reason,msg,EXIT.refused)}return succeed(context.write,context.json,command,{requested:!0,request:req},()=>[`Requested (${req.id}): ${req.summary}`,`Project: ${req.repo}`,...req.why?[`Why: ${req.why}`]:[],`Waiting for your 1-click approval in Toolroll.app (or run \`toolroll request wait ${req.id}\`).`])}async function projectLiveViewCommand(positional,flags,context){const command="project live-view",allowed=new Set(["repo","request","why","by","wait","timeout","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a project live-view option.`,EXIT.usage);const repoFlag=text(flags,"repo"),wanted=positional[1];if(positional.length>2||repoFlag===void 0||wanted!==void 0&&wanted!=="on"&&wanted!=="off")return fail(context.write,context.json,command,"usage","Use project live-view --repo <project path> [on | off] [--request <why>].",EXIT.usage);const repo=await knownProject(context,repoFlag,{listed:!0,canonical:!0});if(repo===void 0)return fail(context.write,context.json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused);const current=liveCommandsShown(context.store,repo);if(wanted===void 0)return succeed(context.write,context.json,command,{repo,showCommands:current},()=>[`${repo}: Live View shell commands are ${current?"shown":"hidden (redacted)"}.`]);if(!flags.has("request"))return fail(context.write,context.json,command,"refused",'Changing Live View shell commands takes operator approval in Toolroll.app → Project Settings, or pass --request "<why>" to ask for 1-click approval.',EXIT.refused);const showCommands=wanted==="on",req=fileAgentRequest(context.databaseFile,{kind:"live-view",repo,...text(flags,"by")===void 0?{}:{requester:text(flags,"by")},summary:showCommands?"Show live shell commands in Activity":"Hide live shell commands in Activity",why:text(flags,"why")??text(flags,"request")??"",params:{showCommands}},context.clock());return finishFiledRequest(command,req,flags,context)}async function requestCommand(positional,flags,context){const action=positional[0]??"list",command=`request ${action}`,allowed=new Set(["all","repo","timeout","note","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a request option.`,EXIT.usage);if(action==="list"){const repoFlag=text(flags,"repo"),repo=repoFlag===void 0?void 0:await knownProject(context,repoFlag,{listed:!0,canonical:!0})??resolve(repoFlag),items=listAgentRequests(context.databaseFile,{...flags.has("all")?{}:{status:"pending"},...repo===void 0?{}:{repo}});return succeed(context.write,context.json,command,{requests:items},()=>items.length===0?["No pending agent requests."]:items.map(one=>`${one.id} [${one.status}] (${one.requester} · ${one.projectName}) ${one.summary}${one.why?` — ${one.why}`:""}`))}if(action==="show"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request show <id>`.",EXIT.usage);const found=listAgentRequests(context.databaseFile).find(one=>one.id===id)??null;return found===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):succeed(context.write,context.json,command,{request:found},()=>[`${found.id} [${found.status}] ${found.summary}`,`Project: ${found.repo}`,`By: ${found.requester}`,...found.why?[`Why: ${found.why}`]:[]])}if(action==="wait"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request wait <id> [--timeout <seconds>]`.",EXIT.usage);const timeoutSeconds=Number(text(flags,"timeout")??"300"),safeTimeout=Number.isFinite(timeoutSeconds)&&timeoutSeconds>0?Math.min(3600,Math.round(timeoutSeconds)):300,settled=await waitForAgentRequest(context.databaseFile,id,safeTimeout);return settled===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):settled.status==="approved"?succeed(context.write,context.json,command,{request:settled},()=>[`Approved (${settled.id}): ${settled.summary}`]):fail(context.write,context.json,command,settled.status==="declined"?"declined":"timeout",settled.status==="declined"?`Request ${settled.id} was declined.`:`Request ${settled.id} is still pending after ${safeTimeout}s.`,EXIT.refused)}if(action==="decline"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request decline <id> [--note <reason>]`.",EXIT.usage);const resolved=resolveAgentRequest(context.databaseFile,id,"declined",text(flags,"note"),context.clock());return resolved===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):succeed(context.write,context.json,command,{request:resolved},()=>[`Declined (${resolved.id}): ${resolved.summary}`])}if(action==="clear"){const removed=clearResolvedAgentRequests(context.databaseFile);return succeed(context.write,context.json,command,{removed},()=>[`Cleared ${removed} resolved agent request${removed===1?"":"s"}.`])}return fail(context.write,context.json,"request","usage","Use `toolroll request [list [--all]|show <id>|wait <id>|decline <id>|clear]`.",EXIT.usage)}async function landTaskCommand(positional,flags,context){const{store,write,json,now}=context,command="task land",allowed=new Set(["json","db","into","undo","yes","key","as","token","token-file","token-env"]);for(const key2 of flags.keys())if(!allowed.has(key2))return fail(write,json,command,"usage",`--${key2} is not a ${command} option.`,EXIT.usage);const id=positional[0]===void 0?void 0:resolveTaskId(store,positional[0]);if(id===void 0||positional.length!==1)return fail(write,json,command,"usage","Use `toolroll task land <id>` to see what landing does, then `--yes --key <preview-key>` to land it.",EXIT.usage);const into=text(flags,"into"),undo=flags.get("undo")===!0,yes=flags.get("yes")===!0,key=text(flags,"key");if(flags.has("into")&&into===void 0)return fail(write,json,command,"usage","--into needs a branch name.",EXIT.usage);if(undo&&into!==void 0)return fail(write,json,command,"usage","--undo lands on the branch the work landed on; it takes no --into.",EXIT.usage);const landRepo=store.lookupRef(id)?.repo??null;if(landRepo!==null&&publishesThroughPullRequests(store,landRepo))return fail(write,json,command,"pull-requests",PULL_REQUESTS_INSTEAD,EXIT.refused);const local=currentLocalOwner(),localRepos=local===null?null:store.knownRepos().filter(repo=>store.accountCanAccess(local.account,repo)),options={root:context.evidenceRoot,...into===void 0?{}:{into},...undo?{undo:!0}:{}};if(!yes){if(key!==void 0)return fail(write,json,command,"usage","--key goes with --yes.",EXIT.usage);const read=await readLanding(store,id,{repos:localRepos},now,options);if(!read.ok)return fail(write,json,command,read.reason,read.message,EXIT.refused);if(!("plan"in read))return succeed(write,json,command,{landed:read.landed},()=>[`${id} · ${landedLine(read.landed)}`]);const plan=read.plan;return local===null&&passwordFreeOwner(store)?succeed(write,json,command,{plan},()=>[...landingWords(plan),LAND_NEEDS_PASSWORD]):succeed(write,json,command,{plan},()=>[...landingWords(plan),`To ${undo?"undo it":"land it"}: toolroll task land ${id}${into===void 0?"":` --into ${into}`}${undo?" --undo":""} --yes --key ${plan.key}${local===null?" --as <you>":""}`,...local===null?["That asks for your Toolroll password."]:[]])}if(key===void 0||!/^[0-9a-f]{16}$/.test(key))return fail(write,json,command,"usage","--yes needs the --key `toolroll task land` showed you, so what lands is what you read.",EXIT.usage);let authority;if(local!==null)authority={kind:"local"};else{if(passwordFreeOwner(store))return fail(write,json,command,"unauthenticated",LAND_NEEDS_PASSWORD,EXIT.refused);{const acting=await askCredentials(flags,context),ref=store.lookupRef(id),repos=store.knownRepos().filter(repo=>acting!==null&&store.accountCanAccess(acting.name,repo)),proved=acting===null||ref===null?null:verifyApproverByPassword(store,acting.name,acting.token,repos);if(proved===null||!proved.ok)return fail(write,json,command,"unauthenticated","Landing work is a person's act: it takes `--as <you>` and your password.",EXIT.refused);authority={kind:"person",who:proved.who}}}const access={repos:authority.kind==="person"?authority.who.repos:localRepos},result=await land(store,id,{key,...into===void 0?{}:{into},...undo?{undo:!0}:{}},authority,access,now,{root:context.evidenceRoot});if(!result.ok)return fail(write,json,command,result.reason,result.message,EXIT.refused);if(result.handoff!==null){const handoff=result.handoff;return succeed(write,json,command,{landing:result},()=>[`${id} · Landing commit ${result.commit.slice(0,7)} is ready (kept at ${handoff.ref}). Your project folder has ${result.branch} checked out, so Toolroll didn't touch it.`,handoffWords(handoff,result.commit)])}return succeed(write,json,command,{landing:result},()=>[`${id} · ${result.replayed?"Already ":""}${result.kind==="undo"?"Undone":"Landed"} on ${result.branch} (${result.commit.slice(0,7)})${result.mode==="ref"?"; no folder had it open":result.mode==="files"?"; your project folder's files are updated":""}.`,...result.warning===null?[]:[result.warning]])}function resolveTaskId(store,typed){return store.getTask(typed)!==null||typed.startsWith("task-")?typed:store.getTask(`task-${typed}`)!==null?`task-${typed}`:typed}function verifyRepoOf(store,raw){const absolute=isAbsolute(raw)?raw:resolve(process.cwd(),raw);let real;try{real=realpathSync(absolute)}catch{return absolute}for(const known of new Set([...store.listProjects().map(one=>one.path),...store.knownRepos()]))try{if(known===absolute||realpathSync(known)===real)return known}catch{}return absolute}const LAND_NEEDS_PASSWORD="Land it from the workbench (B) or the task page in the browser; from a shell it needs a Toolroll password (`toolroll password set`).";function passwordFreeInstall(store,flags,remote){if(remote||["as","token","token-file","token-env"].some(name=>flags.has(name))||localOwnerRequested()||envValue(process.env,"LEAD_TOKEN")!==void 0)return!1;const binding=localOwnerBinding(store);return binding!==null&&store.accountOf(binding.account)?.passwordSet!==!0}function acceptedWords(completion){const by=completedByOf(completion);return by===null?"accepted":`accepted by ${by}`}function renewalRefusedWords(reason){switch(reason){case"taken":return"another watch took this project over";case"missing":return"the project's lease record is gone (the project was removed)";case"unbound":return"the project is no longer connected to this builder";case"paused":return"the lease lapsed while an update or restart was under way";case"error":return"the renewal failed";default:return`the builder's credential no longer holds (${reason})`}}const CHAT_CONFIG_FAILURE=/\b(invalid_auth|not_authed|account_inactive|token_revoked|unauthori[sz]ed|forbidden|401|403|missing_scope|invalid token|bad token)\b/i;async function superviseChatFollower(name,signal,progress,start){const pause=abortablePause(signal);let attempt=0;for(;!signal.aborted;){const began=Date.now();try{await start();return}catch(error){if(signal.aborted)return;Date.now()-began>=6e4&&(attempt=0);const delay=Math.min(3e4,1e3*2**Math.min(attempt++,5)),detail=describe(error);progress(CHAT_CONFIG_FAILURE.test(detail)?`watch: ${name} stopped (${detail.slice(0,160)}). Check ${name} settings; Toolroll tries again in ${Math.round(delay/1e3)}s.`:`watch: ${name} stopped for a moment (${isDatabaseBusy(error)?"the database was busy":detail.slice(0,160)}); reconnecting in ${Math.round(delay/1e3)}s.`),await pause(delay)}}}function busyFailure(error){return isDatabaseBusy(error)||/\b(database[- ](is )?(locked|busy)|SQLITE_BUSY)\b/i.test(describe(error))}const flagsOnly=run2=>(_positional,flags,context)=>run2(flags,context),needsGit=(command,run2)=>(_positional,flags,context)=>gitTooOld(command,context)??run2(flags,context),PROJECT_COMMANDS={rules:projectRulesCommand,delete:projectDeleteCommand,concurrency:projectConcurrencyCommand,network:projectNetworkCommand,fallback:projectFallbackCommand,writes:projectWritesCommand,"check-access":projectCheckAccessCommand,sandbox:projectSandboxCommand,flexible:projectFlexibleCommand,checks:projectChecksCommand,demo:projectDemoCommand,"live-view":projectLiveViewCommand};export const COMMANDS={plugin:pluginCommand,status:statusCommand,release:releaseApproveCommand,evals:evalsCommand,ready:flagsOnly(readyCommand),task:taskCommand,ledger:ledgerCommand,audit:(positional,flags,context)=>auditCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),...context.principal===void 0?{}:{principal:context.principal}}),spend:flagsOnly(spendCommand),budget:budgetCommand,retention:retentionCommand,notifications:notificationsCommand,lead:leadCommand,backup:backupCommand,export:exportCommand,policy:policyCommand,storage:storageCommand,integrations:integrationsCommand,review:reviewSwitchCommand,monitoring:monitoringCommand,"check-progress":(positional,_flags,context)=>checkProgressCommand(positional,context),project:(positional,flags,context)=>(Object.prototype.hasOwnProperty.call(PROJECT_COMMANDS,positional[0]??"")?PROJECT_COMMANDS[positional[0]]:runProjectCommand)(positional,flags,context),request:requestCommand,assignment:(positional,flags,context)=>positional[0]==="claim"&&currentActor()?.lead===!0&&!flags.has("token-env")&&!flags.has("token-file")?leadClaimCommand(positional,flags,context):runAssignmentCommand(positional,flags,context),knowledge:knowledgeCommand,map:mapCommand,models:modelsCommand,memory:memoryCommand,card:cardCommand,flaky:flakyCommand,finding:(positional,flags,context)=>findingCommand(positional,flags,followThroughContext(context,flags)),captures:(positional,flags,context)=>capturesCommand(positional,followThroughContext(context,flags)),claim:claimCommand,heartbeat:(positional,flags,context)=>leaseCommand("heartbeat",positional,flags,context),worker:(positional,flags,context)=>positional[0]==="release"?leaseCommand("release",positional.slice(1),flags,context):fail(context.write,context.json,"worker","usage","`toolroll worker release <lease>` returns a lease.",EXIT.usage),reap:(_positional,_flags,context)=>reapCommand(context),runner:runnerCommand,approver:approverCommand,coordinator:coordinatorCommand,build:buildCommand,tick:flagsOnly(tickCommand),reconcile:flagsOnly(reconcileCommand),run:runCommand,cap:capCommand,gaps:flagsOnly(gapsCommand),outbox:outboxCommand,peek:peekCommand,brief:(_positional,flags,context)=>["history","local","since","latest-watch"].some(flag2=>flags.has(flag2))?briefCommand(flags,context):runAssignmentCommand(["brief"],flags,{...context,commandName:"brief"}),decide:decideCommand,incident:incidentCommand,flows:flowsCommand,thread:threadCommand,config:(positional,flags,context)=>positional[0]==="unconfined-agents"?unconfinedAgentsCommand(positional,flags,context):configCommand(positional,flags,context),chat:flagsOnly(chatCommand),proposals:proposalsCommand,mode:modeCommand,"chat-approval":chatApprovalCommand,people:peopleCommand,tokens:(positional,flags,context)=>runTokensCommand(positional,flags,{store:context.store,write:context.write,json:context.json,clock:context.clock,caller:activeRemote()!==null?"remote":currentActor()?.lead===!0||context.leadToken!==void 0?"lead":"local",rememberedName:readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null,interactive,ask,askHidden,readStdin:readBoundedStdin}),keys:keysCommand,agents:agentsCommand,setup:setupCommand,verify:verifyCommand,intake:intakeCommand,providers:(positional,flags,context)=>positional[0]==="resume"?resumeProviderCommand(positional.slice(1),flags,context):providersCommand(flags,context),template:templateCommand,webhook:webhookCommand,sync:flagsOnly(syncCommand),serve:needsGit("serve",serveCommand),watch:needsGit("watch",watchCommand),up:needsGit("up",upCommand),onboard:flagsOnly(onboardCommand),daemon:daemonCommand,background:backgroundCommand,stop:stopCommand,open:openCommand,welcome:welcomeCommand,password:passwordCommand,bridge:bridgeCommand,publish:publishCommand,enroll:enrollCommand,grants:(_positional,_flags,context)=>grantsCommand(context),revoke:revokeCommand};function monitoringCommand(_positional,_flags,context){const settings=readMonitoring(dirname(context.databaseFile)),head=context.store.ledgerHeadId(),destinations=[...settings.webhook===null?[]:[{sink:"webhook",to:origin(settings.webhook.url),address:settings.webhook.url}],...settings.folder===null?[]:[{sink:"folder",to:settings.folder.path,address:settings.folder.path}],...settings.traces===null?[]:[{sink:"traces",to:origin(settings.traces.endpoint),address:settings.traces.endpoint}]].map(one=>({...one,status:context.store.monitoringStatus(one.sink).find(row=>row.target===targetOf(one.address))??null}));return succeed(context.write,context.json,"monitoring",{destinations,ledgerHead:head},()=>destinations.length===0?["Monitoring is off. Settings → Monitoring sets it up."]:destinations.map(one=>`${one.sink.padEnd(8)} ${one.to} — ${one.status===null?"starting":one.status.failures>0?`failing: ${one.status.lastError??"?"}`:`sent through #${one.status.through}${one.sink==="traces"?"":` (${Math.max(0,head-one.status.through)} to go)`}`}`))}async function knowledgeCommand(positional,flags,context){if(positional[0]!=="apply")return runKnowledgeCommand(positional,flags,{...context,now:context.clock()});if(positional.length!==1)return fail(context.write,context.json,"knowledge apply","usage","knowledge apply takes no query.",EXIT.usage);const acting=currentActor()?.lead===!0?null:await askCredentials(flags,context),repo=text(flags,"repo"),lead=acting!==null&&parseLeadToken(acting.token)!==null,verified=acting===null||lead?null:authenticateApprover(context.store,acting.name,acting.token,repo===void 0?null:resolve(repo));return runKnowledgeApply(flags,{...context,now:context.clock(),actor:verified!==null&&verified.ok?acting.name:null})}async function modelsCommand(positional,flags,context){const acting=currentLocalOwner()!==null&&!flags.has("as")&&!flags.has("token")&&["turn-off","dismiss","suggestions","stop"].includes(positional[0]??"")?null:await askCredentials(flags,context),provedGeneration=acting===null?-1:context.store.accountOf(acting.name)?.generation??-1,verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token),proof=verified!==null&&verified.ok?{actor:acting.name,generation:provedGeneration,method:verified.method}:null;return runModelsCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:proof?.actor??null,proof})}async function memoryCommand(positional,flags,context){if(memoryWriteVerb(positional)&&currentActor()?.lead===!0)return fail(context.write,context.json,`memory ${positional[0]}`,"unauthenticated",MEMORY_WRITE_REFUSAL,EXIT.refused);const acting=await askCredentials(flags,context);if(memoryWriteVerb(positional)&&acting!==null&&parseLeadToken(acting.token)!==null)return fail(context.write,context.json,`memory ${positional[0]}`,"unauthenticated",MEMORY_WRITE_REFUSAL,EXIT.refused);const verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runMemoryCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[],configDir:dirname(context.databaseFile),...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}})}function injectedSeams(options){const seams={};for(const key of SEAMS)options[key]!==void 0&&(seams[key]=options[key]);return seams}async function projectAsked(context,flags,positional,command,ask2){for(const name of flags.keys())if(!["repo",...ask2.own,"as","token","token-file","token-env","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const repoFlag=text(flags,"repo");return positional.length>ask2.most||repoFlag===void 0||ask2.invalid===!0?fail(context.write,context.json,command,"usage",ask2.usage,EXIT.usage):await knownProject(context,repoFlag,ask2.match)??fail(context.write,context.json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused)}function onStopSignals(stop){return process.on("SIGINT",stop),process.on("SIGTERM",stop),()=>{process.removeListener("SIGINT",stop),process.removeListener("SIGTERM",stop)}}function longCommandProgress(write,json){return line=>{if(envValue(process.env,"LOG_FORMAT")==="json")return logEvent(/\b(fail|failed|died|stopped|error|red)\b/i.test(line)?"warn":"info","worker",{message:line});json?process.stderr.write(`${line}
509
+ `)),!await confirm("Turn on interactive agent threads in this project with these terms?"))return fail(write,json,command,"declined","Nothing changed.",EXIT.refused);digest=proposed.digest}const done2=enableFlexible(store,{repo,by:acting.name,proof:proved2.method,choice,shownDigest:digest,now:context.clock()});return done2.ok?succeed(write,json,command,{repo,flexible:shown(flexibleStanding(store,repo)).data,replaced:done2.replaced},()=>[`Interactive agent threads are on in ${repo} (terms ${done2.digest}). Start one with T in the terminal workbench.`]):fail(write,json,command,done2.reason,done2.message,EXIT.refused)}const proved=authenticateApprover(store,acting.name,acting.token,repo);if(!proved.ok||!personProof(proved.method))return refused("Only an approver of this project, signed in as a person, changes its thread terms.");if(action==="lower"){if(max===void 0)return fail(write,json,command,"usage","Name the highest level with --max supervised, auto or full.",EXIT.usage);const done2=lowerFlexible(store,{repo,by:acting.name,max,now:context.clock()});return done2.ok?succeed(write,json,command,{repo,changed:done2.changed,flexible:shown(flexibleStanding(store,repo)).data},()=>[done2.changed?`Lowered: threads in ${repo} run at ${FLEXIBLE_LEVEL_WORDS[done2.terms.max]} at most. New threads start under these terms only.`:"Nothing changed.",...termsLines(done2.terms,done2.digest)]):fail(write,json,command,done2.reason,done2.message,EXIT.refused)}const done=turnFlexibleOff(store,{repo,by:acting.name,now:context.clock()});return done.ok?succeed(write,json,command,{repo,changed:done.changed,flexible:{state:"secure"}},()=>[done.changed?`Interactive agent threads are off in ${repo}. No new ones start.`:`Interactive agent threads are already off in ${repo}.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}async function taskSizingConfig(action,value,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","task sizing is installation-wide: no --repo",EXIT.usage);const said=()=>{const read=taskSizingSetting(store),on=read.on&&!read.byEnv,name=one=>one==="jev"?"Jev via OpenRouter (your credit)":"Claude Haiku (on your plan)";return{payload:{taskSizing:{on,setting:read.chosen?"on":"off",sizer:read.sizer,available:read.available,byEnv:read.byEnv}},lines:()=>[read.byEnv?"Task sizing is off: TOOLROLL_NO_TASK_CLASSIFIER is set, so no model call happens before you approve; uncertain tasks get a plan first.":on?`Task sizing is on: each new task is sized by ${name(read.sizer)} before you approve.`:read.chosen&&read.sizer!==null?`Task sizing is off: it was turned on for ${name(read.sizer)}, but ${name(read.available)} is the one available now, so nothing is sent. Run \`toolroll config set task-sizing on\` to choose it.`:"Task sizing is off: no model call before you approve; uncertain tasks get a plan first."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}if(action!=="set"||value!=="on"&&value!=="off")return fail(write,json,command,"usage","`toolroll config set task-sizing on|off --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","changing task sizing takes `--as <you> --token <t>`",EXIT.usage);if(!store.transact(()=>!authenticateApprover(store,acting.name,acting.token).ok||!store.isInstanceOperator(acting.name)?!1:(setTaskSizing(store,value==="on"?taskSizingSetting(store).available:!1,acting.name,clock()),!0)))return fail(write,json,command,"unauthenticated","an instance operator changes task sizing, with their password",EXIT.refused);const shown=said();return succeed(write,json,command,shown.payload,shown.lines)}async function flexibleConfig(action,value,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","interactive agent threads are installation-wide: no --repo",EXIT.usage);const said=()=>{const read=flexibleSetting(store);return{payload:{flexible:{on:read.on,by:read.by,at:read.at}},lines:()=>[read.on?"Interactive agent threads (beta) are on: T in the workbench starts a Claude Code thread. Claude Code only for now; it runs inside Toolroll's sandbox with your Claude sign-in relayed, and Toolroll never gives the agent your key.":"Interactive agent threads (beta) are off. Turn them on with `toolroll config set flexible on`."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}if(action!=="set"||value!=="on"&&value!=="off")return fail(write,json,command,"usage","`toolroll config set flexible on|off --as <you> --token <t>`",EXIT.usage);const personOnly=value==="on"?"Only an instance operator, with their password typed for this command, turns interactive agent threads on; never a remembered sign-in, a token, the lead or a chat app.":"Only an instance operator, as a person with their password, turns interactive agent threads off; never a token, the lead or a chat app.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);const solo=value==="off"&&!flags.has("token")?soloOperatorOf(store):null;let acting=solo!==null&&(text(flags,"as")??solo)===solo?{name:solo,token:""}:null;if(acting===null){if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=value==="on"?await typedForCommand(flags,context):await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage",value==="on"?"Turning threads on asks for your Toolroll password at a hidden prompt: run it in your own terminal.":"This needs your name and password: run it in your own terminal to be asked, or add `--as <your Toolroll name> --token <your password>`.",EXIT.usage);const by=acting;if(!store.transact(()=>{const verified=by.token===""&&value==="off"?null:value==="on"?credentialApprover(store,by.name,by.token):authenticateApprover(store,by.name,by.token);return!(verified===null?soloOperatorOf(store)===by.name:verified.ok&&personProof(verified.method))||!store.isInstanceOperator(by.name)?!1:(setFlexibleSetting(store,value==="on",by.name,clock()),!0)}))return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);const shown=said();if(value==="on")return succeed(write,json,command,shown.payload,()=>[...shown.lines(),...flexibleNextStepWords(store,by.name)]);const report=await stopFlexibleThreadsEverywhere(store,{reason:"interactive agent threads were turned off",clock}),short=thread=>thread.slice(0,8),lines=[...shown.lines(),...report.stopped.length===0?[]:[`Stopped ${report.stopped.length===1?"1 running thread":`${report.stopped.length} running threads`}: every process of ${report.stopped.length===1?"its agent":"their agents"} is gone and ${report.stopped.length===1?"its turn":"their turns"} ended (${report.stopped.map(one=>short(one.thread)).join(", ")}).`],...report.stopped.some(one=>one.network)?["The console that started them closes their network on its next check, within a few seconds."]:[],...report.survivors.map(one=>`Thread ${short(one.thread)} couldn't be stopped yet${one.pids.length===0?"":`: process${one.pids.length===1?"":"es"} ${one.pids.join(", ")} still running`} (${one.why}). A running console keeps trying every few seconds; run this command again to try now.`)];return succeed(write,json,command,{...shown.payload,stopped:report.stopped,survivors:report.survivors},()=>lines)}async function flexibleSignInConfig(action,extra,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action} flexible-sign-in`;if([...extra,...[...flags.values()].filter(value=>typeof value=="string")].some(value=>looksLikeClaudeCredential(value)))return fail(write,json,command,"argument","Toolroll never takes your Claude sign-in as an argument: it is now in your shell history. Run `claude setup-token` again, then `toolroll config set flexible-sign-in` and paste the new token when asked. Nothing was saved.",EXIT.usage);if(extra.length>0)return fail(write,json,command,"usage","`toolroll config set flexible-sign-in` takes no value: it asks for the token at a hidden prompt.",EXIT.usage);if(repoGiven)return fail(write,json,command,"usage","your Claude sign-in is yours, not a project's: no --repo",EXIT.usage);if(flags.has("no-check")&&action!=="set")return fail(write,json,command,"usage","--no-check is only for `config set flexible-sign-in`",EXIT.usage);if(flags.has("check")&&action!=="show")return fail(write,json,command,"usage","--check is only for `config show flexible-sign-in --check`",EXIT.usage);const personOnly="Only you, as a person with your Toolroll password, change your own Claude sign-in for threads; never a token, the lead, a chat app or a machine.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);if(action!=="show"&&action!=="set"&&action!=="clear")return fail(write,json,command,"usage","`toolroll config set|clear|show flexible-sign-in`",EXIT.usage);if(action==="set"&&passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);let acting;const solo=(action==="clear"||action==="show"&&!flags.has("check"))&&!flags.has("token")?soloOperatorOf(store):null;if(solo!==null&&(text(flags,"as")??solo)===solo)acting={name:solo,token:""};else if(action==="set"){if(flags.has("token"))return fail(write,json,command,"usage","Saving your Claude sign-in asks for your Toolroll password at a hidden prompt, typed for this command: never --token or a saved sign-in.",EXIT.usage);const typed=context.easySeams?.askHidden??(interactive()&&!json?askHidden:null),named=context.easySeams?.ask??(interactive()&&!json?ask:null);if(typed===null)return fail(write,json,command,"usage","Run this in your own terminal: it asks for your Toolroll password and the token from `claude setup-token` at hidden prompts.",EXIT.usage);const usual=soloOperatorOf(store)??savedLoginName(context),answered=text(flags,"as")??(named===null?void 0:await named(usual===null?"username: ":`username [${usual}]: `)),name=answered===""&&usual!==null?usual:answered,password=await typed("password: ");acting=name===void 0||name.length===0||password.length===0?null:{name,token:password}}else{if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage","This needs your name and password: run it in your own terminal to be asked.",EXIT.usage);const statusWords=status=>status.state==="none"?"Your Claude sign-in for threads: none. Run `claude setup-token`, then `toolroll config set flexible-sign-in`.":status.state==="refused"?"Claude didn't accept your sign-in for threads. Run `claude setup-token` again and save the new token with `toolroll config set flexible-sign-in`.":`Your Claude sign-in for threads: saved ${status.savedAt.slice(0,10)}. ${signInCheckWords(statusCheck(status))} It powers only threads you start.`,statusData=status=>status.state==="none"?{state:"none"}:{state:status.state,savedAt:status.savedAt,check:status.checkOutcome,checkStatus:status.checkStatus};if(action==="show"){const shown=store.transact(()=>{if(acting.token===""&&!flags.has("check"))return soloOperatorOf(store)===acting.name?flexibleSignInStatus(store,acting.name):null;const proved=authenticateApprover(store,acting.name,acting.token);return proved.ok&&personProof(proved.method)?flexibleSignInStatus(store,acting.name):null});if(shown===null)return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);if(!flags.has("check"))return succeed(write,json,command,{signIn:statusData(shown)},()=>[statusWords(shown)]);let state2;try{state2=dirname(realpathSync(context.databaseFile))}catch{return fail(write,json,command,"no-sign-in","Toolroll's state folder can't be found.",EXIT.refused)}const again=await recheckFlexibleSignIn(store,state2,{person:acting.name,clock});if(!again.ok)return fail(write,json,command,"no-sign-in",statusWords({state:"none"}),EXIT.refused);const now=flexibleSignInStatus(store,acting.name);return succeed(write,json,command,{signIn:statusData(now),check:again.check.outcome},()=>[signInCheckWords(again.check),statusWords(now)])}if(action==="clear"){const removed=store.transact(()=>{if(acting.token===""){if(soloOperatorOf(store)!==acting.name)return null}else{const proved=authenticateApprover(store,acting.name,acting.token);if(!proved.ok||!personProof(proved.method))return null}return removeFlexibleSignIn(store,{person:acting.name,by:acting.name,now:clock()})});if(removed===null)return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);try{await tidyFlexibleSignIns(store,dirname(realpathSync(context.databaseFile)),{now:clock(),person:acting.name})}catch{}const report=removed.ended.threads.length===0?{stopped:[],survivors:[]}:await stopFlexibleThreadsEverywhere(store,{reason:"its owner's Claude sign-in for threads was removed",owner:acting.name,clock}),named=ids=>ids.map(id=>flexibleThreadTitleOf(store,id)).join(", "),stoppedWords2=report.stopped.length===0?[]:[`Stopped ${report.stopped.length===1?"1 running thread":`${report.stopped.length} running threads`} (${named(report.stopped.map(one=>one.thread))}).`],leftWords=report.survivors.length===0?[]:[`${named(report.survivors.map(one=>one.thread))} couldn't be stopped yet; a running console keeps trying every few seconds.`];return succeed(write,json,command,{removed:removed.removed,stopped:report.stopped,survivors:report.survivors},()=>[removed.removed?"Removed. Your threads can't reach Claude until you add one again. The token still works at Claude until you revoke it in your Claude account.":"You had no Claude sign-in for threads saved. Nothing changed.",...stoppedWords2,...leftWords])}const typeHidden=context.easySeams?.askHidden??(interactive()&&!json?askHidden:null);if(typeHidden===null)return fail(write,json,command,"usage","Run this in your own terminal: it asks for the token from `claude setup-token` at a hidden prompt.",EXIT.usage);const pasted=await typeHidden("Paste the token from `claude setup-token`: "),shaped=setupTokenFromPaste(pasted);if(!shaped.ok)return fail(write,json,command,shaped.reason,shaped.message,EXIT.refused);let state;try{state=dirname(realpathSync(context.databaseFile))}catch{return fail(write,json,command,"not-saved","Toolroll's state folder can't be found. Nothing was saved.",EXIT.refused)}const saved=await saveFlexibleSignIn(store,{state,person:acting.name,password:acting.token,token:shaped.token,check:!flags.has("no-check"),clock});if(!saved.ok)return fail(write,json,command,saved.reason,saved.message,EXIT.refused);const checked=saved.check===null?{outcome:"not-checked"}:saved.check;return succeed(write,json,command,{saved:!0,replaced:saved.replaced,check:checked.outcome,signIn:statusData(flexibleSignInStatus(store,acting.name))},()=>[`${saved.replaced?"Replaced":"Saved"}. ${signInCheckWords(checked)} It powers only threads you start; a password reset ends it.`])}function passwordFreeRefusal(store,flags,key,remote){return passwordFreeInstall(store,flags,remote)?`This Toolroll has no password yet, so this runs from Toolroll itself: run \`toolroll\`, select the task and press ${key}, or open it in the browser.`:null}function soloOperatorOf(store){if(installModeNow(store).mode!=="solo")return null;const operators=store.accountFacts().filter(one=>store.isInstanceOperator(one.name)).map(one=>one.name);return operators.length===1?operators[0]:null}function savedLoginName(context){try{return readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null}catch{return null}}async function typedForCommand(flags,context,promptOnly=!1){const given=text(flags,"token");if(given!==void 0){const name2=text(flags,"as")??soloOperatorOf(context.store);return promptOnly||given===""||name2===null||name2===void 0?null:{name:name2,token:given}}const typed=context.easySeams?.askHidden??(interactive()&&!context.json?askHidden:null),named=context.easySeams?.ask??(interactive()&&!context.json?ask:null);if(typed===null)return null;const usual=soloOperatorOf(context.store)??savedLoginName(context),answered=text(flags,"as")??(named===null?void 0:await named(usual===null?"username: ":`username [${usual}]: `)),name=answered===""&&usual!==null?usual:answered,password=await typed("password: ");return name===void 0||name.length===0||password.length===0?null:{name,token:password}}function flexibleNextStepWords(store,person){const steps=[];return flexibleSignInStatus(store,person).state!=="active"&&steps.push("your own Claude sign-in: run `claude setup-token`, then `toolroll config set flexible-sign-in`"),steps.push("this project's terms: `toolroll project flexible enable --repo <path>`"),[`Next: ${steps.map((one,at)=>`${at+1}) ${one}`).join(" ")}.`]}async function threadCommand(positional,flags,context){const{store,write,json,clock}=context,verb=positional[0]??"list",command=`thread ${verb}`;if(!["list","show","end","remove","ship","save"].includes(verb))return fail(write,json,command,"usage","`toolroll thread list|show|end|remove|ship|save <thread>`",EXIT.usage);const personOnly="Only you, as a person, work with your own threads here; never a token, the lead, a chat app or a machine.";if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return fail(write,json,command,"person-only",personOnly,EXIT.refused);const pick=owner=>{const asked=positional[1]??"";if(!/^[0-9a-f]{8,32}$/.test(asked))return null;const found=flexibleThreadRecords(store,{owner}).filter(one=>one.id.startsWith(asked));return found.length===1?found[0].id:null};if(verb==="ship"){const needs=flexibleShipNeedsFor(store,positional[1]??"");if(needs!==null)return fail(write,json,command,needs.reason,needs.message,EXIT.refused);if(passwordFreeOwner(store))return fail(write,json,command,"laptop","Nobody on this install has a password, so this thread ships from the workbench (`toolroll`), after its terms are read there.",EXIT.refused);const acting2=await typedForCommand(flags,context,!0);if(acting2===null)return fail(write,json,command,"usage","Shipping asks for your Toolroll password at a hidden prompt, typed for this command: run it in your own terminal (never --token).",EXIT.usage);const account2=store.accountOf(acting2.name),thread2=account2===null?null:pick(acting2.name);if(account2===null||thread2===null)return fail(write,json,command,"not-found","You have no such thread.",EXIT.refused);const by={name:acting2.name,generation:account2.generation},shown=await flexibleThreadShipTerms(store,{thread:thread2,by});if(!shown.ok)return fail(write,json,command,shown.reason,shown.message,EXIT.refused);const key=text(flags,"key"),lines=[...key!==void 0&&key!==shown.summary.key?["The terms changed since the workbench showed them. Here they are again."]:[],"Ship approves exactly this:",...summaryLines(shown.summary)];if(json)return fail(write,json,command,"usage","Ship asks before it ships: run it in your own terminal.",EXIT.usage);for(const line of lines)write(line);const confirm2=context.easySeams?.ask??(interactive()?ask:null),yes=confirm2===null?"":await confirm2("Ship exactly this? [y/N] ");if(!/^y(es)?$/i.test(yes.trim()))return fail(write,json,command,"declined","Nothing was shipped.",EXIT.refused);const shipped=await shipFlexibleThread(store,null,{thread:thread2,by,proof:{kind:"password-now",password:acting2.token},shownDigest:shown.digest,shownKey:shown.summary.key,now:clock(),waitMs:15e3});if(!shipped.ok)return fail(write,json,command,shipped.reason,shipped.message,EXIT.refused);const ship=latestFlexibleShip(store,thread2);return succeed(write,json,command,{thread:thread2,ship:ship?.id??null,seq:ship?.seq??null,task:ship?.taskId??null},()=>[`Shipping: checks run on commit ${ship?.candidate.slice(0,12)??""}; Toolroll merges it once they pass.`])}const solo=flags.has("token")?null:soloOperatorOf(store);let acting=solo!==null&&(text(flags,"as")??solo)===solo?{name:solo,token:""}:null;if(acting===null){if(passwordFreeOwner(store))return fail(write,json,command,"local-owner","You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.",EXIT.refused);acting=await askCredentials(flags,context)}if(acting===null)return fail(write,json,command,"usage","This needs your name and password: run it in your own terminal to be asked.",EXIT.usage);const who={...acting,solo:solo!==null&&acting.name===solo&&!flags.has("token")&&acting.token.length===0},proveNow=()=>{if(who.solo)return soloOperatorOf(store)===who.name;const one=authenticateApprover(store,who.name,who.token);return one.ok&&personProof(one.method)};if(!store.transact(proveNow))return fail(write,json,command,"unauthenticated",personOnly,EXIT.refused);const account=store.accountOf(who.name);if(verb==="list"){const rows=flexibleThreadRecords(store,{owner:who.name});return succeed(write,json,command,{threads:rows},()=>rows.length===0?["You have no threads yet. Start one in the workbench (`toolroll`)."]:rows.map(one=>`${one.id.slice(0,8)} ${one.title} · ${threadStateWord(one)}${one.project===null?"":` · ${one.project}`}${shipOutcomeWord(one.ship)}`))}const thread=pick(who.name);if(thread===null)return fail(write,json,command,"not-found","You have no such thread.",EXIT.refused);const row=flexibleThreadRecords(store,{owner:who.name}).find(one=>one.id===thread);if(verb==="show")return succeed(write,json,command,{thread:row},()=>[`${row.title} (${row.id})`,`Project: ${row.project??row.repo}`,`Latest turn: ${row.turn??"none"}${row.endWords===null?"":`. ${row.endWords}`}`,...row.ended?["Ended."]:[],...row.shipWords===null?[]:[row.shipWords],"Reply to it in the workbench (`toolroll`)."]);if(verb==="end"){const done=await closeFlexibleThread(store,null,{thread,by:{name:who.name,generation:account.generation},act:"end",clock,prove:proveNow});if(!done.ok)return fail(write,json,command,done.reason,done.message,EXIT.refused);done.stopPending&&await stopFlexibleThreadsEverywhere(store,{reason:"its owner ended the thread",thread,clock});const keeps=flexibleShipNeedsFor(store,thread)===null?"ship its work, or save it as a branch,":`save its work as a branch (\`toolroll thread save ${thread.slice(0,8)}\`)`,left=done.already?0:(await flexibleUncommittedFiles(store,{thread})).length,leftWords=`Ended. Its agent left uncommitted edits in ${left} file${left===1?"":"s"}: \`toolroll thread save ${thread.slice(0,8)}\` saves them with its work as a branch. Its copy is kept for a week.`;return succeed(write,json,command,{thread,already:done.already},()=>[done.already?"This thread had already ended.":left>0?leftWords:`Ended. You can still ${keeps} for a week; then its copy is tidied.`])}if(verb==="save"){const saved=await saveFlexibleBranch(store,{thread,by:{name:who.name,generation:account.generation},now:clock(),prove:proveNow});return saved.ok?succeed(write,json,command,{thread,branch:saved.branch,commit:saved.candidate,already:saved.already,files:saved.changedPaths,next:saved.next,leftover:saved.leftover,uncommitted:saved.uncommitted},()=>[flexibleSavedWords(saved),saved.next]):fail(write,json,command,saved.reason,saved.message,EXIT.refused)}const removed=await removeFlexibleThreadCopy(store,{thread,by:who.name,now:clock(),prove:proveNow});return removed.ok?succeed(write,json,command,{thread},()=>["Removed its working copy. Its record stays."]):fail(write,json,command,removed.reason,removed.message,EXIT.refused)}export function threadStateWord(one){return one.ended?"Ended":one.turn==="admitted"||one.turn==="running"?"Working":one.ship!==null&&["approved","imported","armed","completed","merging"].includes(one.ship)?"Shipping":one.turn==="unknown"?"Outcome unknown":one.turn==="interrupted"?"Stopped":one.ship==="cancelled"?"Ship stopped":one.ship==="refused"||one.ship==="failed"?"Ship refused":"Ready"}export function shipOutcomeWord(ship){const word=ship==="merged"?"Merged":ship==="sent-back"?"sent back":null;return word===null?"":` · Ship: ${word}`}class BuiltinReplacementRefused extends Error{reason;constructor(reason){super(reason),this.reason=reason}}function createBuiltinReplacement(store,input){try{return store.transact(()=>store.savepoint(()=>{if(store.getTask(input.replaces)===null)return{ok:!1,reason:"unknown-task"};const filed=input.proposal===void 0?null:fileTaskProposal(store,{id:input.id,title:input.title,...input.proposal,...input.repo===null?{}:{repo:input.repo},...input.report?{deliverable:"report"}:{},filedVia:"cli"},input.now);if(filed!==null&&!filed.ok)return filed;const task=filed===null?store.createTask({id:input.id,title:input.title,...input.report?{deliverable:"report"}:{}},input.now):store.getTask(input.id),ref=store.refFor(BUILT_IN,task.id).id;if(store.stampFiledVia(ref,"cli"),input.repo!==null&&filed===null){const placed=store.placeTask(ref,canonicalProject(input.repo)??resolve(input.repo));if(typeof placed=="object"&&!placed.ok)throw new BuiltinReplacementRefused("scoped")}const moved=store.setTaskState(input.replaces,"cancelled",input.now,{},void 0,task.id);if(!moved.ok)throw new BuiltinReplacementRefused(moved.reason);return{ok:!0,task}}))}catch(error){if(error instanceof BuiltinReplacementRefused)return{ok:!1,reason:error.reason};throw error}}function builtinReplacementHeld(store,source,target){if(store.handle.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD)===void 0)return!1;for(const taskId of[source,target]){const ref=store.lookupRef(taskId);if(ref===null?store.getTask(taskId)!==null:readCheckRecoveryHoldsForTaskRef(store,ref.id).kind!=="no-evidence")return!0}return!1}async function finishFiledRequest(command,req,flags,context){if(flags.get("wait")===!0){const timeoutSeconds=Number(text(flags,"timeout")??"300"),safeTimeout=Number.isFinite(timeoutSeconds)&&timeoutSeconds>0?Math.min(3600,Math.round(timeoutSeconds)):300,settled=await waitForAgentRequest(context.databaseFile,req.id,safeTimeout);if(settled?.status==="approved")return succeed(context.write,context.json,command,{requested:!0,request:settled},()=>[`Approved (${settled.id}): ${settled.summary}`]);const reason=settled?.status==="declined"?"declined":"timeout",msg=settled?.status==="declined"?`Request ${req.id} was declined${settled.resolutionNote?`: ${settled.resolutionNote}`:"."}`:`Request ${req.id} is still pending in Toolroll.app after ${safeTimeout}s.`;return fail(context.write,context.json,command,reason,msg,EXIT.refused)}return succeed(context.write,context.json,command,{requested:!0,request:req},()=>[`Requested (${req.id}): ${req.summary}`,`Project: ${req.repo}`,...req.why?[`Why: ${req.why}`]:[],`Waiting for your 1-click approval in Toolroll.app (or run \`toolroll request wait ${req.id}\`).`])}async function projectLiveViewCommand(positional,flags,context){const command="project live-view",allowed=new Set(["repo","request","why","by","wait","timeout","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a project live-view option.`,EXIT.usage);const repoFlag=text(flags,"repo"),wanted=positional[1];if(positional.length>2||repoFlag===void 0||wanted!==void 0&&wanted!=="on"&&wanted!=="off")return fail(context.write,context.json,command,"usage","Use project live-view --repo <project path> [on | off] [--request <why>].",EXIT.usage);const repo=await knownProject(context,repoFlag,{listed:!0,canonical:!0});if(repo===void 0)return fail(context.write,context.json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused);const current=liveCommandsShown(context.store,repo);if(wanted===void 0)return succeed(context.write,context.json,command,{repo,showCommands:current},()=>[`${repo}: Live View shell commands are ${current?"shown":"hidden (redacted)"}.`]);if(!flags.has("request"))return fail(context.write,context.json,command,"refused",'Changing Live View shell commands takes operator approval in Toolroll.app → Project Settings, or pass --request "<why>" to ask for 1-click approval.',EXIT.refused);const showCommands=wanted==="on",req=fileAgentRequest(context.databaseFile,{kind:"live-view",repo,...text(flags,"by")===void 0?{}:{requester:text(flags,"by")},summary:showCommands?"Show live shell commands in Activity":"Hide live shell commands in Activity",why:text(flags,"why")??text(flags,"request")??"",params:{showCommands}},context.clock());return finishFiledRequest(command,req,flags,context)}async function requestCommand(positional,flags,context){const action=positional[0]??"list",command=`request ${action}`,allowed=new Set(["all","repo","timeout","note","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a request option.`,EXIT.usage);if(action==="list"){const repoFlag=text(flags,"repo"),repo=repoFlag===void 0?void 0:await knownProject(context,repoFlag,{listed:!0,canonical:!0})??resolve(repoFlag),items=listAgentRequests(context.databaseFile,{...flags.has("all")?{}:{status:"pending"},...repo===void 0?{}:{repo}});return succeed(context.write,context.json,command,{requests:items},()=>items.length===0?["No pending agent requests."]:items.map(one=>`${one.id} [${one.status}] (${one.requester} · ${one.projectName}) ${one.summary}${one.why?` — ${one.why}`:""}`))}if(action==="show"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request show <id>`.",EXIT.usage);const found=listAgentRequests(context.databaseFile).find(one=>one.id===id)??null;return found===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):succeed(context.write,context.json,command,{request:found},()=>[`${found.id} [${found.status}] ${found.summary}`,`Project: ${found.repo}`,`By: ${found.requester}`,...found.why?[`Why: ${found.why}`]:[]])}if(action==="wait"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request wait <id> [--timeout <seconds>]`.",EXIT.usage);const timeoutSeconds=Number(text(flags,"timeout")??"300"),safeTimeout=Number.isFinite(timeoutSeconds)&&timeoutSeconds>0?Math.min(3600,Math.round(timeoutSeconds)):300,settled=await waitForAgentRequest(context.databaseFile,id,safeTimeout);return settled===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):settled.status==="approved"?succeed(context.write,context.json,command,{request:settled},()=>[`Approved (${settled.id}): ${settled.summary}`]):fail(context.write,context.json,command,settled.status==="declined"?"declined":"timeout",settled.status==="declined"?`Request ${settled.id} was declined.`:`Request ${settled.id} is still pending after ${safeTimeout}s.`,EXIT.refused)}if(action==="decline"){const id=positional[1];if(id===void 0)return fail(context.write,context.json,command,"usage","Use `toolroll request decline <id> [--note <reason>]`.",EXIT.usage);const resolved=resolveAgentRequest(context.databaseFile,id,"declined",text(flags,"note"),context.clock());return resolved===null?fail(context.write,context.json,command,"not-found",`No agent request ${id}.`,EXIT.refused):succeed(context.write,context.json,command,{request:resolved},()=>[`Declined (${resolved.id}): ${resolved.summary}`])}if(action==="clear"){const removed=clearResolvedAgentRequests(context.databaseFile);return succeed(context.write,context.json,command,{removed},()=>[`Cleared ${removed} resolved agent request${removed===1?"":"s"}.`])}return fail(context.write,context.json,"request","usage","Use `toolroll request [list [--all]|show <id>|wait <id>|decline <id>|clear]`.",EXIT.usage)}async function landTaskCommand(positional,flags,context){const{store,write,json,now}=context,command="task land",allowed=new Set(["json","db","into","undo","yes","key","as","token","token-file","token-env"]);for(const key2 of flags.keys())if(!allowed.has(key2))return fail(write,json,command,"usage",`--${key2} is not a ${command} option.`,EXIT.usage);const id=positional[0]===void 0?void 0:resolveTaskId(store,positional[0]);if(id===void 0||positional.length!==1)return fail(write,json,command,"usage","Use `toolroll task land <id>` to see what landing does, then `--yes --key <preview-key>` to land it.",EXIT.usage);const into=text(flags,"into"),undo=flags.get("undo")===!0,yes=flags.get("yes")===!0,key=text(flags,"key");if(flags.has("into")&&into===void 0)return fail(write,json,command,"usage","--into needs a branch name.",EXIT.usage);if(undo&&into!==void 0)return fail(write,json,command,"usage","--undo lands on the branch the work landed on; it takes no --into.",EXIT.usage);const landRepo=store.lookupRef(id)?.repo??null;if(landRepo!==null&&publishesThroughPullRequests(store,landRepo))return fail(write,json,command,"pull-requests",PULL_REQUESTS_INSTEAD,EXIT.refused);const local=currentLocalOwner(),localRepos=local===null?null:store.knownRepos().filter(repo=>store.accountCanAccess(local.account,repo)),options={root:context.evidenceRoot,...into===void 0?{}:{into},...undo?{undo:!0}:{}};if(!yes){if(key!==void 0)return fail(write,json,command,"usage","--key goes with --yes.",EXIT.usage);const read=await readLanding(store,id,{repos:localRepos},now,options);if(!read.ok)return fail(write,json,command,read.reason,read.message,EXIT.refused);if(!("plan"in read))return succeed(write,json,command,{landed:read.landed},()=>[`${id} · ${landedLine(read.landed)}`]);const plan=read.plan;return local===null&&passwordFreeOwner(store)?succeed(write,json,command,{plan},()=>[...landingWords(plan),LAND_NEEDS_PASSWORD]):succeed(write,json,command,{plan},()=>[...landingWords(plan),`To ${undo?"undo it":"land it"}: toolroll task land ${id}${into===void 0?"":` --into ${into}`}${undo?" --undo":""} --yes --key ${plan.key}${local===null?" --as <you>":""}`,...local===null?["That asks for your Toolroll password."]:[]])}if(key===void 0||!/^[0-9a-f]{16}$/.test(key))return fail(write,json,command,"usage","--yes needs the --key `toolroll task land` showed you, so what lands is what you read.",EXIT.usage);let authority;if(local!==null)authority={kind:"local"};else{if(passwordFreeOwner(store))return fail(write,json,command,"unauthenticated",LAND_NEEDS_PASSWORD,EXIT.refused);{const acting=await askCredentials(flags,context),ref=store.lookupRef(id),repos=store.knownRepos().filter(repo=>acting!==null&&store.accountCanAccess(acting.name,repo)),proved=acting===null||ref===null?null:verifyApproverByPassword(store,acting.name,acting.token,repos);if(proved===null||!proved.ok)return fail(write,json,command,"unauthenticated","Landing work is a person's act: it takes `--as <you>` and your password.",EXIT.refused);authority={kind:"person",who:proved.who}}}const access={repos:authority.kind==="person"?authority.who.repos:localRepos},result=await land(store,id,{key,...into===void 0?{}:{into},...undo?{undo:!0}:{}},authority,access,now,{root:context.evidenceRoot});if(!result.ok)return fail(write,json,command,result.reason,result.message,EXIT.refused);if(result.handoff!==null){const handoff=result.handoff;return succeed(write,json,command,{landing:result},()=>[`${id} · Landing commit ${result.commit.slice(0,7)} is ready (kept at ${handoff.ref}). Your project folder has ${result.branch} checked out, so Toolroll didn't touch it.`,handoffWords(handoff,result.commit)])}return succeed(write,json,command,{landing:result},()=>[`${id} · ${result.replayed?"Already ":""}${result.kind==="undo"?"Undone":"Landed"} on ${result.branch} (${result.commit.slice(0,7)})${result.mode==="ref"?"; no folder had it open":result.mode==="files"?"; your project folder's files are updated":""}.`,...result.warning===null?[]:[result.warning]])}function resolveTaskId(store,typed){return store.getTask(typed)!==null||typed.startsWith("task-")?typed:store.getTask(`task-${typed}`)!==null?`task-${typed}`:typed}function verifyRepoOf(store,raw){const absolute=isAbsolute(raw)?raw:resolve(process.cwd(),raw);let real;try{real=realpathSync(absolute)}catch{return absolute}for(const known of new Set([...store.listProjects().map(one=>one.path),...store.knownRepos()]))try{if(known===absolute||realpathSync(known)===real)return known}catch{}return absolute}const LAND_NEEDS_PASSWORD="Land it from the workbench (B) or the task page in the browser; from a shell it needs a Toolroll password (`toolroll password set`).";function passwordFreeInstall(store,flags,remote){if(remote||["as","token","token-file","token-env"].some(name=>flags.has(name))||localOwnerRequested()||envValue(process.env,"LEAD_TOKEN")!==void 0)return!1;const binding=localOwnerBinding(store);return binding!==null&&store.accountOf(binding.account)?.passwordSet!==!0}function acceptedWords(completion){const by=completedByOf(completion);return by===null?"accepted":`accepted by ${by}`}function renewalRefusedWords(reason){switch(reason){case"taken":return"another watch took this project over";case"missing":return"the project's lease record is gone (the project was removed)";case"unbound":return"the project is no longer connected to this builder";case"paused":return"the lease lapsed while an update or restart was under way";case"error":return"the renewal failed";default:return`the builder's credential no longer holds (${reason})`}}const CHAT_CONFIG_FAILURE=/\b(invalid_auth|not_authed|account_inactive|token_revoked|unauthori[sz]ed|forbidden|401|403|missing_scope|invalid token|bad token)\b/i;async function superviseChatFollower(name,signal,progress,start){const pause=abortablePause(signal);let attempt=0;for(;!signal.aborted;){const began=Date.now();try{await start();return}catch(error){if(signal.aborted)return;Date.now()-began>=6e4&&(attempt=0);const delay=Math.min(3e4,1e3*2**Math.min(attempt++,5)),detail=describe(error);progress(CHAT_CONFIG_FAILURE.test(detail)?`watch: ${name} stopped (${detail.slice(0,160)}). Check ${name} settings; Toolroll tries again in ${Math.round(delay/1e3)}s.`:`watch: ${name} stopped for a moment (${isDatabaseBusy(error)?"the database was busy":detail.slice(0,160)}); reconnecting in ${Math.round(delay/1e3)}s.`),await pause(delay)}}}function busyFailure(error){return isDatabaseBusy(error)||/\b(database[- ](is )?(locked|busy)|SQLITE_BUSY)\b/i.test(describe(error))}const flagsOnly=run2=>(_positional,flags,context)=>run2(flags,context),needsGit=(command,run2)=>(_positional,flags,context)=>gitTooOld(command,context)??run2(flags,context),PROJECT_COMMANDS={rules:projectRulesCommand,delete:projectDeleteCommand,concurrency:projectConcurrencyCommand,network:projectNetworkCommand,fallback:projectFallbackCommand,writes:projectWritesCommand,"check-access":projectCheckAccessCommand,sandbox:projectSandboxCommand,flexible:projectFlexibleCommand,checks:projectChecksCommand,demo:projectDemoCommand,"live-view":projectLiveViewCommand};export const COMMANDS={plugin:pluginCommand,status:statusCommand,release:releaseApproveCommand,evals:evalsCommand,ready:flagsOnly(readyCommand),task:taskCommand,ledger:ledgerCommand,audit:(positional,flags,context)=>auditCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),...context.principal===void 0?{}:{principal:context.principal}}),spend:flagsOnly(spendCommand),budget:budgetCommand,retention:retentionCommand,notifications:notificationsCommand,lead:leadCommand,backup:backupCommand,export:exportCommand,policy:policyCommand,storage:storageCommand,integrations:integrationsCommand,review:reviewSwitchCommand,monitoring:monitoringCommand,"check-progress":(positional,_flags,context)=>checkProgressCommand(positional,context),project:(positional,flags,context)=>(Object.prototype.hasOwnProperty.call(PROJECT_COMMANDS,positional[0]??"")?PROJECT_COMMANDS[positional[0]]:runProjectCommand)(positional,flags,context),request:requestCommand,assignment:(positional,flags,context)=>positional[0]==="claim"&&currentActor()?.lead===!0&&!flags.has("token-env")&&!flags.has("token-file")?leadClaimCommand(positional,flags,context):runAssignmentCommand(positional,flags,context),knowledge:knowledgeCommand,map:mapCommand,models:modelsCommand,memory:memoryCommand,card:cardCommand,flaky:flakyCommand,finding:(positional,flags,context)=>findingCommand(positional,flags,followThroughContext(context,flags)),captures:(positional,flags,context)=>capturesCommand(positional,followThroughContext(context,flags)),claim:claimCommand,heartbeat:(positional,flags,context)=>leaseCommand("heartbeat",positional,flags,context),worker:(positional,flags,context)=>positional[0]==="release"?leaseCommand("release",positional.slice(1),flags,context):fail(context.write,context.json,"worker","usage","`toolroll worker release <lease>` returns a lease.",EXIT.usage),reap:(_positional,_flags,context)=>reapCommand(context),runner:runnerCommand,approver:approverCommand,coordinator:coordinatorCommand,build:buildCommand,tick:flagsOnly(tickCommand),reconcile:flagsOnly(reconcileCommand),run:runCommand,cap:capCommand,gaps:flagsOnly(gapsCommand),outbox:outboxCommand,peek:peekCommand,brief:(_positional,flags,context)=>["history","local","since","latest-watch"].some(flag2=>flags.has(flag2))?briefCommand(flags,context):runAssignmentCommand(["brief"],flags,{...context,commandName:"brief"}),decide:decideCommand,incident:incidentCommand,flows:flowsCommand,thread:threadCommand,config:(positional,flags,context)=>positional[0]==="unconfined-agents"?unconfinedAgentsCommand(positional,flags,context):configCommand(positional,flags,context),chat:flagsOnly(chatCommand),proposals:proposalsCommand,mode:modeCommand,"chat-approval":chatApprovalCommand,people:peopleCommand,tokens:(positional,flags,context)=>runTokensCommand(positional,flags,{store:context.store,write:context.write,json:context.json,clock:context.clock,caller:activeRemote()!==null?"remote":currentActor()?.lead===!0||context.leadToken!==void 0?"lead":"local",rememberedName:readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name??null,interactive,ask,askHidden,readStdin:readBoundedStdin}),keys:keysCommand,agents:agentsCommand,setup:setupCommand,verify:verifyCommand,intake:intakeCommand,providers:(positional,flags,context)=>positional[0]==="resume"?resumeProviderCommand(positional.slice(1),flags,context):providersCommand(flags,context),template:templateCommand,webhook:webhookCommand,sync:flagsOnly(syncCommand),serve:needsGit("serve",serveCommand),watch:needsGit("watch",watchCommand),up:needsGit("up",upCommand),onboard:flagsOnly(onboardCommand),daemon:daemonCommand,background:backgroundCommand,stop:stopCommand,open:openCommand,welcome:welcomeCommand,password:passwordCommand,bridge:bridgeCommand,publish:publishCommand,enroll:enrollCommand,grants:(_positional,_flags,context)=>grantsCommand(context),revoke:revokeCommand};function monitoringCommand(_positional,_flags,context){const settings=readMonitoring(dirname(context.databaseFile)),head=context.store.ledgerHeadId(),destinations=[...settings.webhook===null?[]:[{sink:"webhook",to:origin(settings.webhook.url),address:settings.webhook.url}],...settings.folder===null?[]:[{sink:"folder",to:settings.folder.path,address:settings.folder.path}],...settings.traces===null?[]:[{sink:"traces",to:origin(settings.traces.endpoint),address:settings.traces.endpoint}]].map(one=>({...one,status:context.store.monitoringStatus(one.sink).find(row=>row.target===targetOf(one.address))??null}));return succeed(context.write,context.json,"monitoring",{destinations,ledgerHead:head},()=>destinations.length===0?["Monitoring is off. Settings → Monitoring sets it up."]:destinations.map(one=>`${one.sink.padEnd(8)} ${one.to} — ${one.status===null?"starting":one.status.failures>0?`failing: ${one.status.lastError??"?"}`:`sent through #${one.status.through}${one.sink==="traces"?"":` (${Math.max(0,head-one.status.through)} to go)`}`}`))}async function knowledgeCommand(positional,flags,context){if(positional[0]!=="apply")return runKnowledgeCommand(positional,flags,{...context,now:context.clock()});if(positional.length!==1)return fail(context.write,context.json,"knowledge apply","usage","knowledge apply takes no query.",EXIT.usage);const acting=currentActor()?.lead===!0?null:await askCredentials(flags,context),repo=text(flags,"repo"),lead=acting!==null&&parseLeadToken(acting.token)!==null,verified=acting===null||lead?null:authenticateApprover(context.store,acting.name,acting.token,repo===void 0?null:resolve(repo));return runKnowledgeApply(flags,{...context,now:context.clock(),actor:verified!==null&&verified.ok?acting.name:null})}async function modelsCommand(positional,flags,context){const acting=currentLocalOwner()!==null&&!flags.has("as")&&!flags.has("token")&&["turn-off","dismiss","suggestions","stop"].includes(positional[0]??"")?null:await askCredentials(flags,context),provedGeneration=acting===null?-1:context.store.accountOf(acting.name)?.generation??-1,verified=acting===null?null:authenticateApprover(context.store,acting.name,acting.token),proof=verified!==null&&verified.ok?{actor:acting.name,generation:provedGeneration,method:verified.method}:null;return runModelsCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:proof?.actor??null,proof})}async function memoryCommand(positional,flags,context){if(memoryWriteVerb(positional)&&currentActor()?.lead===!0)return fail(context.write,context.json,`memory ${positional[0]}`,"unauthenticated",MEMORY_WRITE_REFUSAL,EXIT.refused);const acting=await askCredentials(flags,context);if(memoryWriteVerb(positional)&&acting!==null&&parseLeadToken(acting.token)!==null)return fail(context.write,context.json,`memory ${positional[0]}`,"unauthenticated",MEMORY_WRITE_REFUSAL,EXIT.refused);const verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runMemoryCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[],configDir:dirname(context.databaseFile),...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}})}function injectedSeams(options){const seams={};for(const key of SEAMS)options[key]!==void 0&&(seams[key]=options[key]);return seams}async function projectAsked(context,flags,positional,command,ask2){for(const name of flags.keys())if(!["repo",...ask2.own,"as","token","token-file","token-env","db","json"].includes(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const repoFlag=text(flags,"repo");return positional.length>ask2.most||repoFlag===void 0||ask2.invalid===!0?fail(context.write,context.json,command,"usage",ask2.usage,EXIT.usage):await knownProject(context,repoFlag,ask2.match)??fail(context.write,context.json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused)}function onStopSignals(stop){return process.on("SIGINT",stop),process.on("SIGTERM",stop),()=>{process.removeListener("SIGINT",stop),process.removeListener("SIGTERM",stop)}}function longCommandProgress(write,json){return line=>{if(envValue(process.env,"LOG_FORMAT")==="json")return logEvent(/\b(fail|failed|died|stopped|error|red)\b/i.test(line)?"warn":"info","worker",{message:line});json?process.stderr.write(`${line}
493
510
  `):write(line)}}function formatLiveLogLines(raw,sub){const out=[];if(sub){for(const line of raw.split(`
494
511
  `)){const trimmed=line.trim();if(trimmed!=="")try{const parsed=JSON.parse(trimmed),stream=typeof parsed.s=="number"?`sub#${parsed.s}`:"sub",kind=typeof parsed.k=="string"?parsed.k:"",textVal=typeof parsed.t=="string"?parsed.t:typeof parsed.n=="string"?parsed.n:typeof parsed.w=="string"?parsed.w:"";textVal!==""?out.push(`[${stream}] ${kind?`${kind}: `:""}${textVal}`):kind!==""&&out.push(`[${stream}] ${kind}`)}catch{out.push(trimmed)}}return out}const records=parseLiveRecords(raw);if(records.length>0){for(const rec of records)if(rec.k==="say")for(const line of rec.t)line.trim()!==""&&out.push(line);else if(rec.k==="step")out.push(`[${rec.kind}]${rec.target?` ${rec.target}`:""}`);else if(rec.k==="done")if(rec.out&&rec.out.length>0)for(const line of rec.out)line.trim()!==""&&out.push(line);else out.push(`[done] ${rec.ok===!1?"failed":"ok"}`);return out}return raw.split(`
495
512
  `).map(l=>l.trimEnd()).filter(l=>l!=="")}function readTaskLogSnapshot(evidenceRoot,run2,sub,maxLines){const candidates=sub?[liveSubLogPath(evidenceRoot,run2.id)]:[liveLogPath(evidenceRoot,run2.id),legacyLiveLogPath(evidenceRoot,run2.id)];for(const filePath of candidates)if(existsSync(filePath))try{const raw=readFileSync(filePath,"utf8"),all=formatLiveLogLines(raw,sub);return{lines:all.length>maxLines?all.slice(all.length-maxLines):all,totalLines:all.length,path:filePath}}catch{}if(!sub&&run2.reason&&run2.reason.trim()!==""){const reasonLines=run2.reason.trim().split(`