toolroll 0.9.133 → 0.9.135

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (377) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/acp-agents.js +1 -1
  3. package/dist/acp-check-repo-schema.js +52 -0
  4. package/dist/acp-check.js +1 -1
  5. package/dist/acp-client.js +3 -3
  6. package/dist/acp-inspect.js +2 -1
  7. package/dist/acp-providers-schema.js +1 -1
  8. package/dist/agent-detect.js +1 -1
  9. package/dist/agent-fence.js +4 -4
  10. package/dist/agent-handoff.js +11 -0
  11. package/dist/agent-thread/acp-chat.js +1 -0
  12. package/dist/agent-thread/acp-turn.js +4 -0
  13. package/dist/agent-thread/chat-credential.js +1 -0
  14. package/dist/agent-thread/chat-home.js +1 -0
  15. package/dist/agent-thread/chat-spend.js +7 -0
  16. package/dist/agent-thread/chat-tools.js +1 -0
  17. package/dist/agent-thread/chat-turn.js +4 -0
  18. package/dist/agent-thread/custody.js +1 -1
  19. package/dist/agent-thread/direct-host.js +13 -8
  20. package/dist/agent-thread/fence.js +2 -2
  21. package/dist/agent-thread/gemini-chat.js +1 -0
  22. package/dist/agent-thread/git-workspace.js +3 -3
  23. package/dist/agent-thread/guards.js +1 -1
  24. package/dist/agent-thread/openrouter-chat.js +1 -0
  25. package/dist/agent-thread/providers.js +3 -3
  26. package/dist/agent-thread/ship.js +2 -2
  27. package/dist/agentconfig.js +1 -1
  28. package/dist/agents-live.js +2 -2
  29. package/dist/approval-decision.js +1 -0
  30. package/dist/approval-password.js +1 -1
  31. package/dist/approval-summary.js +1 -1
  32. package/dist/assignment.js +1 -1
  33. package/dist/attest.js +1 -1
  34. package/dist/batch-checks.js +2 -2
  35. package/dist/boot-identity.js +1 -1
  36. package/dist/bounded-spawn.js +2 -2
  37. package/dist/brief-fence.js +3 -1
  38. package/dist/browser/{chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +5 -5
  39. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.br +0 -0
  40. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.gz +0 -0
  41. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js +2 -0
  42. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.br +0 -0
  43. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.gz +0 -0
  44. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js +4 -0
  45. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.br +0 -0
  46. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.gz +0 -0
  47. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js +116 -0
  48. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.br +0 -0
  49. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.gz +0 -0
  50. package/dist/browser/{chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js → chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js} +7 -7
  51. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.br +0 -0
  52. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.gz +0 -0
  53. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js +4 -0
  54. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.br +0 -0
  55. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.gz +0 -0
  56. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js +6 -0
  57. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.br +0 -0
  58. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.gz +0 -0
  59. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js +2 -0
  60. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.br +0 -0
  61. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.gz +0 -0
  62. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js +20 -0
  63. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.br +0 -0
  64. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.gz +0 -0
  65. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js +3 -0
  66. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.br +0 -0
  67. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.gz +0 -0
  68. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js +2 -0
  69. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.br +0 -0
  70. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.gz +0 -0
  71. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js +2 -0
  72. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.br +0 -0
  73. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.gz +0 -0
  74. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js +5 -0
  75. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.br +0 -0
  76. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.gz +0 -0
  77. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js +2 -0
  78. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.br +0 -0
  79. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.gz +0 -0
  80. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js +2 -0
  81. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.br +0 -0
  82. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.gz +0 -0
  83. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js +2 -0
  84. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.br +0 -0
  85. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.gz +0 -0
  86. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js +4 -0
  87. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.br +0 -0
  88. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.gz +0 -0
  89. package/dist/browser/{chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js → chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js} +1 -1
  90. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.br +0 -0
  91. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.gz +0 -0
  92. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js +2 -0
  93. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.br +0 -0
  94. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.gz +0 -0
  95. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js +2 -0
  96. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.br +0 -0
  97. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.gz +0 -0
  98. package/dist/browser/manifest.json +204 -204
  99. package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js} +1 -1
  100. package/dist/browser/terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.br +0 -0
  101. package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.gz → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.gz} +0 -0
  102. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css +4 -0
  103. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.br +0 -0
  104. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.gz +0 -0
  105. package/dist/browser/{workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js → workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js} +4 -4
  106. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.br +0 -0
  107. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.gz +0 -0
  108. package/dist/browser-open.js +1 -1
  109. package/dist/build-review.js +2 -2
  110. package/dist/builder-revision.js +4 -0
  111. package/dist/builder.js +31 -17
  112. package/dist/canvas-capture.js +2 -2
  113. package/dist/canvas-freshness.js +1 -1
  114. package/dist/central-recovery-stage.js +1 -1
  115. package/dist/chat-actions.js +11 -7
  116. package/dist/chat-channel.js +1 -1
  117. package/dist/chat-decide.js +8 -4
  118. package/dist/chat-review.js +1 -1
  119. package/dist/chat-terms.js +2 -2
  120. package/dist/check-levels.js +1 -1
  121. package/dist/cli-help.js +142 -13
  122. package/dist/cli.js +4 -3
  123. package/dist/companion/bonjour.js +1 -1
  124. package/dist/companion/daemon.js +1 -1
  125. package/dist/companion/passkey-gate.js +1 -1
  126. package/dist/companion/reads.js +1 -1
  127. package/dist/companion/store.js +1 -1
  128. package/dist/companion/webauthn.js +1 -1
  129. package/dist/companion/work.js +1 -1
  130. package/dist/container-state.js +2 -2
  131. package/dist/containment.js +2 -2
  132. package/dist/contracts/chat-actions.js +1 -1
  133. package/dist/contracts/console-api.js +1 -1
  134. package/dist/contracts/engine-api.js +1 -1
  135. package/dist/contracts/lead-tools.js +1 -1
  136. package/dist/contracts/project-memory.js +1 -1
  137. package/dist/contracts/provider.js +1 -1
  138. package/dist/controller-supervisor.js +2 -2
  139. package/dist/converse.js +1 -1
  140. package/dist/credential-broker.js +1 -1
  141. package/dist/decision.js +1 -1
  142. package/dist/demo.js +2 -2
  143. package/dist/dispatch.js +2 -2
  144. package/dist/dispose.js +1 -1
  145. package/dist/easy-start.js +2 -2
  146. package/dist/egress.js +1 -1
  147. package/dist/engine-chat.js +1 -1
  148. package/dist/engine-handoff.js +1 -1
  149. package/dist/engine-reads.js +3 -3
  150. package/dist/evals.js +2 -2
  151. package/dist/every-agent-schema.js +105 -0
  152. package/dist/evidence-pack.js +1 -1
  153. package/dist/evidence.js +1 -1
  154. package/dist/exec.js +5 -4
  155. package/dist/fallback.js +1 -1
  156. package/dist/fast-owner-schema.js +33 -0
  157. package/dist/fast-start.js +1 -1
  158. package/dist/flow-unattended.js +2 -2
  159. package/dist/git-identity.js +2 -2
  160. package/dist/github-import.js +1 -1
  161. package/dist/github-read.js +1 -1
  162. package/dist/handoff-relay.js +2 -0
  163. package/dist/install-mode.js +2 -3
  164. package/dist/invoke.js +9 -7
  165. package/dist/keys.js +1 -1
  166. package/dist/laptop-background.js +1 -1
  167. package/dist/lead-capabilities.js +1 -1
  168. package/dist/lead-cli.js +2 -2
  169. package/dist/lead-contract.js +1 -1
  170. package/dist/lead-debrief.js +7 -0
  171. package/dist/lead-doors.js +1 -1
  172. package/dist/lead-tools.js +5 -5
  173. package/dist/lead.js +2 -2
  174. package/dist/live-backup-change.js +2 -2
  175. package/dist/live-backup.js +2 -2
  176. package/dist/live-records.js +3 -3
  177. package/dist/live-terminal.js +4 -4
  178. package/dist/local-checks.js +1 -1
  179. package/dist/local-landing.js +22 -3
  180. package/dist/local-owner-acts.js +2 -2
  181. package/dist/local-owner.js +1 -1
  182. package/dist/machine-identity.js +1 -1
  183. package/dist/memory-pass.js +3 -3
  184. package/dist/model-catalog.js +8 -5
  185. package/dist/model-choices.js +3 -3
  186. package/dist/model-routing.js +1 -1
  187. package/dist/models-cli.js +2 -2
  188. package/dist/names.js +1 -1
  189. package/dist/needs-you.js +1 -1
  190. package/dist/onboard.js +1 -1
  191. package/dist/openrouter-key.js +2 -0
  192. package/dist/operate-commands.js +1 -1
  193. package/dist/operate-remote-arguments.js +1 -1
  194. package/dist/operate-remote.js +1 -1
  195. package/dist/operate.js +46 -19
  196. package/dist/orphan-sweep.js +1 -1
  197. package/dist/owner-mode.js +4 -0
  198. package/dist/panels.js +6 -0
  199. package/dist/peek-cli.js +2 -2
  200. package/dist/phase-routing.js +1 -1
  201. package/dist/pi-build.js +4 -0
  202. package/dist/pi-rpc.js +10 -0
  203. package/dist/pi-tools-extension.js +4 -0
  204. package/dist/plan-login.js +2 -2
  205. package/dist/plane-review.js +1 -1
  206. package/dist/planner-source.js +2 -2
  207. package/dist/planner.js +2 -2
  208. package/dist/plugin-bundle-source.js +1 -0
  209. package/dist/plugin-bundles-schema.js +43 -0
  210. package/dist/policy.js +1 -1
  211. package/dist/pre-run-phase.js +2 -0
  212. package/dist/presence-hold.js +1 -1
  213. package/dist/process-liveness.js +1 -1
  214. package/dist/process-tree.js +1 -1
  215. package/dist/project-knowledge.js +2 -2
  216. package/dist/project-learning.js +6 -5
  217. package/dist/project-memory.js +1 -1
  218. package/dist/project-skills.js +1 -1
  219. package/dist/project-tools.js +3 -3
  220. package/dist/prompt.js +1 -1
  221. package/dist/proposal.js +1 -1
  222. package/dist/protected-storage.js +2 -2
  223. package/dist/provider-auth.js +1 -1
  224. package/dist/provider-connection.js +2 -2
  225. package/dist/provider-home.js +1 -1
  226. package/dist/provider-limits.js +1 -1
  227. package/dist/provider.js +2 -2
  228. package/dist/public-access.js +1 -1
  229. package/dist/pull-request-flow.js +2 -2
  230. package/dist/read-executor.js +1 -1
  231. package/dist/release-adapters.js +2 -2
  232. package/dist/release-carry.js +3 -3
  233. package/dist/release-resume.js +2 -2
  234. package/dist/release-start.js +1 -0
  235. package/dist/reported-usage.js +1 -1
  236. package/dist/repository-context.js +1 -1
  237. package/dist/result-follow-ups.js +2 -2
  238. package/dist/result-projection.js +1 -1
  239. package/dist/review-switch.js +1 -1
  240. package/dist/route-change.js +25 -3
  241. package/dist/run-closeout.js +2 -2
  242. package/dist/runner.js +2 -2
  243. package/dist/sandbox-launch.js +2 -2
  244. package/dist/sandbox-runtime.js +1 -1
  245. package/dist/scope.js +1 -1
  246. package/dist/scout-browser.js +1 -1
  247. package/dist/scout.js +2 -2
  248. package/dist/serve.js +3 -3
  249. package/dist/server/chat-projection.js +1 -1
  250. package/dist/server/chat.js +3 -3
  251. package/dist/server/direct-chat.js +1 -1
  252. package/dist/server/engine-api.js +1 -1
  253. package/dist/server/handoff.js +1 -0
  254. package/dist/server/http.js +1 -1
  255. package/dist/server/live.js +1 -1
  256. package/dist/server/merge-ready-view.js +1 -1
  257. package/dist/server/one-time-secret.js +1 -1
  258. package/dist/server/panels.js +1 -0
  259. package/dist/server/people-tokens.js +1 -1
  260. package/dist/server/route-table.js +1 -1
  261. package/dist/server/runtime.js +1 -1
  262. package/dist/server/send-back-build.js +1 -1
  263. package/dist/server/settings-phone.js +1 -1
  264. package/dist/server/settings-section-table.js +1 -1
  265. package/dist/server/settings-sections.js +1 -1
  266. package/dist/server/settings.js +3 -2
  267. package/dist/server/task-overview.js +1 -0
  268. package/dist/server/task-view-data.js +3 -3
  269. package/dist/server/task-views.js +1 -1
  270. package/dist/server/tasks.js +6 -6
  271. package/dist/server/terminals.js +1 -1
  272. package/dist/settings-data.js +1 -1
  273. package/dist/settings-proofs.js +1 -1
  274. package/dist/setup-guide.js +1 -1
  275. package/dist/shared-deps.js +4 -4
  276. package/dist/sign-in-page.js +2 -2
  277. package/dist/skill-library.js +13 -22
  278. package/dist/skills-manifest.js +1 -1
  279. package/dist/spend-report.js +2 -1
  280. package/dist/spend.js +6 -4
  281. package/dist/ssr-workspace.js +89 -89
  282. package/dist/staged-runtimes.js +1 -1
  283. package/dist/status-probe.js +2 -2
  284. package/dist/stop-proof.js +2 -2
  285. package/dist/storage-sweep-child.js +2 -2
  286. package/dist/storage-sweep-process.js +1 -1
  287. package/dist/storage.js +2 -2
  288. package/dist/store-baseline.js +17 -79
  289. package/dist/store.js +24 -19
  290. package/dist/structured-json.js +1 -0
  291. package/dist/structured-output.js +1 -1
  292. package/dist/subscription-chat.js +16 -4
  293. package/dist/subscription-usage.js +3 -4
  294. package/dist/surface.js +1 -1
  295. package/dist/task-outcome-cli.js +5 -2
  296. package/dist/task-overview.js +1 -0
  297. package/dist/task-review-brief.js +1 -1
  298. package/dist/task-status.js +1 -1
  299. package/dist/teardown-git.js +4 -4
  300. package/dist/test-temp.js +1 -1
  301. package/dist/text-limits.js +1 -1
  302. package/dist/tool-broker.js +1 -1
  303. package/dist/toolroll-update.js +3 -3
  304. package/dist/trusted-path.js +1 -1
  305. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  306. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  307. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  308. package/dist/tui/linux-x64/toolroll-tui +0 -0
  309. package/dist/tui-contract.js +1 -1
  310. package/dist/tui-launch.js +2 -1
  311. package/dist/verification-evidence.js +1 -1
  312. package/dist/welcome-facts.js +1 -1
  313. package/dist/work-index.js +13 -5
  314. package/package.json +2 -1
  315. package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.br +0 -0
  316. package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.gz +0 -0
  317. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js +0 -2
  318. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.br +0 -0
  319. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.gz +0 -0
  320. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js +0 -4
  321. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.br +0 -0
  322. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.gz +0 -0
  323. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js +0 -116
  324. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.br +0 -0
  325. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.gz +0 -0
  326. package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.br +0 -0
  327. package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.gz +0 -0
  328. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js +0 -4
  329. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.br +0 -0
  330. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.gz +0 -0
  331. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js +0 -6
  332. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.br +0 -0
  333. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.gz +0 -0
  334. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js +0 -2
  335. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.br +0 -0
  336. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.gz +0 -0
  337. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js +0 -20
  338. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.br +0 -0
  339. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.gz +0 -0
  340. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js +0 -3
  341. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.br +0 -0
  342. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.gz +0 -0
  343. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js +0 -2
  344. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.br +0 -0
  345. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.gz +0 -0
  346. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js +0 -5
  347. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.br +0 -0
  348. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.gz +0 -0
  349. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js +0 -2
  350. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.br +0 -0
  351. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.gz +0 -0
  352. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js +0 -2
  353. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.br +0 -0
  354. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.gz +0 -0
  355. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js +0 -2
  356. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.br +0 -0
  357. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.gz +0 -0
  358. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js +0 -2
  359. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.br +0 -0
  360. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.gz +0 -0
  361. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js +0 -4
  362. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.br +0 -0
  363. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.gz +0 -0
  364. package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.br +0 -0
  365. package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.gz +0 -0
  366. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js +0 -2
  367. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.br +0 -0
  368. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.gz +0 -0
  369. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js +0 -2
  370. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.br +0 -0
  371. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.gz +0 -0
  372. package/dist/browser/terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.br +0 -0
  373. package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.br +0 -0
  374. package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.gz +0 -0
  375. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css +0 -4
  376. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.br +0 -0
  377. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.gz +0 -0
@@ -1,4 +1,4 @@
1
- import{checkoutGitSync,viewedGitSync}from"./teardown-git.js";import{createHash,randomUUID}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{scanForSecrets}from"./evidence.js";import{compilerOptionsOf,extractFile,resolveAll}from"./code-extract.js";const VERSION=1,MAX_FILES=1200,MAX_FILE_BYTES=256e3,MAX_SOURCE_BYTES=12e6,CODE=/\.(?:[cm]?[jt]sx?)$/i,TEXT=/\.(?:[cm]?[jt]sx?|md|txt|css|html|json)$/i,MAX_NODES=16e3,MAX_EDGES=12e3,sha=value=>createHash("sha256").update(value).digest("hex"),git=(repo,args,binding)=>checkoutGitSync(repo,args,{timeoutMs:1e4,maxBuffer:2e6,binding}).trimEnd(),inside=(root,path)=>{const r=relative(root,path);return r!==".."&&!r.startsWith(".."+sep)&&!isAbsolute(r)},skippedPath=file=>!TEXT.test(file)||/(?:^|\/)(?:node_modules|vendor|dist|build|coverage|\.git)(?:\/|$)/.test(file),unsafePath=file=>file.split("/").some(p=>p==="..")||/[\x00-\x1f]/.test(file),unreadableText=(data,text)=>data.length>MAX_FILE_BYTES||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ufffd]/u.test(text)||scanForSecrets(text).length>0;function workingTreeSources(repo,binding){const files=git(repo,["ls-files","-z","--cached"],binding).split("\0").filter(Boolean).sort(),sources=[];let omitted=0,omittedBytes=0,bytes=0;for(const file of[...new Set(files)]){if(skippedPath(file))continue;const path=resolve(repo,file);if(!inside(repo,path)||unsafePath(file)){omitted++;continue}try{const stat=lstatSync(path);if(!stat.isFile()||stat.isSymbolicLink()||realpathSync(path)!==path){omitted++;continue}if(sources.length>=MAX_FILES||stat.size>MAX_FILE_BYTES||bytes+stat.size>MAX_SOURCE_BYTES){omitted++,omittedBytes+=stat.size;continue}const data=readFileSync(path),text=data.toString("utf8");if(unreadableText(data,text)){omitted++,omittedBytes+=data.length;continue}sources.push({file,text,sha256:sha(data)}),bytes+=data.length}catch{omitted++}}return{sources,omitted,omittedBytes}}function baseCommitSources(repo,base,binding){const read=(args,maxBuffer,input)=>{const ran=viewedGitSync(repo,["--no-replace-objects",...args],{timeoutMs:1e4,maxBuffer,binding,buffer:!0,...input===void 0?{}:{input}});if(ran.status!==0)throw Error("The task base could not be read.");return ran.stdout},wanted=[];let omitted=0,omittedBytes=0,bytes=0;for(const entry of read(["ls-tree","-r","-l","-z",base],16e6).toString("utf8").split("\0")){const match=/^(\d{6}) (\w+) ([0-9a-f]{40,64}) +(\d+|-)\t(.+)$/s.exec(entry);if(!match)continue;const[,mode,kind,oid,sized,file]=match;if(skippedPath(file))continue;const size=sized==="-"?0:Number(sized);if(unsafePath(file)||kind!=="blob"||mode!=="100644"&&mode!=="100755"){omitted++;continue}if(wanted.length>=MAX_FILES||size>MAX_FILE_BYTES||bytes+size>MAX_SOURCE_BYTES){omitted++,omittedBytes+=size;continue}wanted.push({file,oid}),bytes+=size}wanted.sort((a,b)=>a.file<b.file?-1:a.file>b.file?1:0);const sources=[];if(wanted.length===0)return{sources,omitted,omittedBytes};const out=read(["cat-file","--batch"],MAX_SOURCE_BYTES+wanted.length*128+4096,Buffer.from(wanted.map(w=>w.oid).join(`
1
+ import{checkoutGitSync,viewedGitSync}from"./teardown-git.js";import{createHash,randomUUID}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{scanForSecrets}from"./evidence.js";import{compilerOptionsOf,extractFile,resolveAll}from"./code-extract.js";const VERSION=1,MAX_FILES=1200,MAX_FILE_BYTES=256e3,MAX_SOURCE_BYTES=12e6,MAX_WORKING_TREE_READ_MS=2500,CODE=/\.(?:[cm]?[jt]sx?)$/i,TEXT=/\.(?:[cm]?[jt]sx?|md|txt|css|html|json)$/i,MAX_NODES=16e3,MAX_EDGES=12e3,sha=value=>createHash("sha256").update(value).digest("hex"),git=(repo,args,binding)=>checkoutGitSync(repo,args,{timeoutMs:1e4,maxBuffer:2e6,binding}).trimEnd(),inside=(root,path)=>{const r=relative(root,path);return r!==".."&&!r.startsWith(".."+sep)&&!isAbsolute(r)},skippedPath=file=>!TEXT.test(file)||/(?:^|\/)(?:node_modules|vendor|dist|build|coverage|\.git)(?:\/|$)/.test(file),unsafePath=file=>file.split("/").some(p=>p==="..")||/[\x00-\x1f]/.test(file),unreadableText=(data,text)=>data.length>MAX_FILE_BYTES||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ufffd]/u.test(text)||scanForSecrets(text).length>0;function workingTreeSources(repo,binding){const files=git(repo,["ls-files","-z","--cached"],binding).split("\0").filter(Boolean).sort(),sources=[],deadline=Date.now()+MAX_WORKING_TREE_READ_MS;let omitted=0,omittedBytes=0,bytes=0;for(const file of[...new Set(files)]){if(skippedPath(file))continue;if(Date.now()>deadline){omitted++;continue}const path=resolve(repo,file);if(!inside(repo,path)||unsafePath(file)){omitted++;continue}try{const stat=lstatSync(path);if(!stat.isFile()||stat.isSymbolicLink()||realpathSync(path)!==path){omitted++;continue}if(process.platform==="darwin"&&stat.size>0&&stat.blocks===0){omitted++,omittedBytes+=stat.size;continue}if(sources.length>=MAX_FILES||stat.size>MAX_FILE_BYTES||bytes+stat.size>MAX_SOURCE_BYTES){omitted++,omittedBytes+=stat.size;continue}const data=readFileSync(path),text=data.toString("utf8");if(unreadableText(data,text)){omitted++,omittedBytes+=data.length;continue}sources.push({file,text,sha256:sha(data)}),bytes+=data.length}catch{omitted++}}return{sources,omitted,omittedBytes}}function baseCommitSources(repo,base,binding){const read=(args,maxBuffer,input)=>{const ran=viewedGitSync(repo,["--no-replace-objects",...args],{timeoutMs:1e4,maxBuffer,binding,buffer:!0,...input===void 0?{}:{input}});if(ran.status!==0)throw Error("The task base could not be read.");return ran.stdout},wanted=[];let omitted=0,omittedBytes=0,bytes=0;for(const entry of read(["ls-tree","-r","-l","-z",base],16e6).toString("utf8").split("\0")){const match=/^(\d{6}) (\w+) ([0-9a-f]{40,64}) +(\d+|-)\t(.+)$/s.exec(entry);if(!match)continue;const[,mode,kind,oid,sized,file]=match;if(skippedPath(file))continue;const size=sized==="-"?0:Number(sized);if(unsafePath(file)||kind!=="blob"||mode!=="100644"&&mode!=="100755"){omitted++;continue}if(wanted.length>=MAX_FILES||size>MAX_FILE_BYTES||bytes+size>MAX_SOURCE_BYTES){omitted++,omittedBytes+=size;continue}wanted.push({file,oid}),bytes+=size}wanted.sort((a,b)=>a.file<b.file?-1:a.file>b.file?1:0);const sources=[];if(wanted.length===0)return{sources,omitted,omittedBytes};const out=read(["cat-file","--batch"],MAX_SOURCE_BYTES+wanted.length*128+4096,Buffer.from(wanted.map(w=>w.oid).join(`
2
2
  `)+`
3
3
  `));let at=0;for(const{file,oid}of wanted){const end=out.indexOf(10,at),header=end<0?null:/^([0-9a-f]{40,64}) blob (\d+)$/.exec(out.subarray(at,end).toString("latin1"));if(end<0||header===null||header[1]!==oid)throw Error("The task base could not be read.");const size=Number(header[2]),data=out.subarray(end+1,end+1+size);at=end+1+size+1;const text=data.toString("utf8");if(unreadableText(data,text)){omitted++,omittedBytes+=data.length;continue}sources.push({file,text,sha256:sha(data)})}return{sources,omitted,omittedBytes}}function capture(request){const repo=realpathSync(request.repo);if(repo!==resolve(request.repo))throw Error("The project location changed.");const binding={repo:request.project??null};if(realpathSync(git(repo,["rev-parse","--show-toplevel"],binding))!==repo)throw Error("Choose the project checkout root.");const head=git(repo,["rev-parse","--verify","HEAD"],binding),baseRevision=request.baseRevision??head;if(!/^[a-f0-9]{40,64}$/.test(baseRevision)||git(repo,["rev-parse","--verify",`${baseRevision}^{commit}`],binding)!==baseRevision)throw Error("The requested context base is unavailable.");if(request.audience==="crew"&&baseRevision!==head)throw Error("Crew context must start at its exact task base.");const gitDir=realpathSync(git(repo,["rev-parse","--absolute-git-dir"],binding)),crew=request.audience==="crew",{sources,omitted,omittedBytes}=crew?baseCommitSources(repo,baseRevision,binding):workingTreeSources(repo,binding);if(git(repo,["rev-parse","--verify","HEAD"],binding)!==head)throw Error("The checkout changed while context was being read.");const warnings=[];omitted&&warnings.push(`${omitted} source files were omitted because they were unavailable, excluded, sensitive or beyond the read limits.`),warnings.push("Tracked files only. Static imports do not establish every runtime dependency or sufficient test coverage.");const sourceHash=sha(JSON.stringify(sources.map(({file,sha256})=>[file,sha256])));return{checkout:{repo,gitDir,head,baseRevision,sourceHash,source:crew?"base-commit":"working-tree"},sources,omitted,omittedBytes,warnings}}function cacheFile(root,checkout){const absolute=resolve(root);let parent=absolute;for(;!existsSync(parent)&&dirname(parent)!==parent;)parent=dirname(parent);if(realpathSync(parent)!==parent||inside(checkout.repo,absolute))throw Error("Repository context cache must be outside the checkout.");return join(absolute,`repository-${sha(JSON.stringify([checkout.repo,checkout.gitDir,checkout.baseRevision]))}.json`)}function validIndex(value){if(!value||typeof value!="object")return!1;const i=value;return i.version===VERSION&&!!i.checkout&&i.checkout.source==="working-tree"&&["repo","gitDir","head","baseRevision","sourceHash"].every(k=>typeof i.checkout[k]=="string")&&typeof i.extractor=="string"&&Array.isArray(i.warnings)&&i.warnings.length<100&&i.warnings.every(w=>typeof w=="string")&&Array.isArray(i.nodes)&&i.nodes.length<=MAX_NODES&&i.nodes.every(n=>typeof n.file=="string"&&typeof n.name=="string"&&Number.isSafeInteger(n.line)&&n.line>0&&Number.isSafeInteger(n.endLine)&&n.endLine>=n.line)&&Array.isArray(i.relationships)&&i.relationships.length<=MAX_EDGES&&i.relationships.every(e=>typeof e.from=="string"&&typeof e.to=="string"&&typeof e.file=="string"&&Number.isSafeInteger(e.line)&&e.line>0&&["imports","re-exports","dynamic-import"].includes(e.kind)&&e.provenance==="explicit")}function readIndex(path){if(!existsSync(path))return null;if(!lstatSync(path).isFile()||lstatSync(path).isSymbolicLink()||lstatSync(path).size>5e6)throw Error("Unreadable repository index.");const envelope=JSON.parse(readFileSync(path,"utf8"));if(sha(JSON.stringify(envelope.index))!==envelope.sha256||!validIndex(envelope.index))throw Error("Invalid repository index.");return envelope.index}function writeIndex(path,index){if(mkdirSync(dirname(path),{recursive:!0,mode:448}),realpathSync(dirname(path))!==dirname(path))throw Error("The context cache changed.");const tmp=`${path}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify({index,sha256:sha(JSON.stringify(index))}),{flag:"wx",mode:384}),renameSync(tmp,path)}finally{try{unlinkSync(tmp)}catch{}}}async function buildIndex(snapshot){const compiler=(await import("typescript-parser")).default,byPath=new Map(snapshot.sources.map(source=>[resolve(snapshot.checkout.repo,source.file),source])),directories=new Set([snapshot.checkout.repo]);for(const file of byPath.keys()){let dir=dirname(file);for(;inside(snapshot.checkout.repo,dir)&&(directories.add(dir),dir!==snapshot.checkout.repo);)dir=dirname(dir)}const config=byPath.get(join(snapshot.checkout.repo,"tsconfig.json")),{options,problem}=compilerOptionsOf(compiler,join(snapshot.checkout.repo,"tsconfig.json"),config?.text,snapshot.checkout.repo),warnings=[];problem==="extends"?warnings.push("Inherited tsconfig settings are not indexed; unresolved aliases remain omitted."):problem==="unreadable"&&warnings.push("TypeScript configuration could not be read; relative imports still work.");const resolveOne=resolveAll(compiler,snapshot.checkout.repo,byPath,directories,options,resolve),nodes=[],relationships=[];let unresolved=0,parseFailures=0;for(const source of snapshot.sources.filter(s=>CODE.test(s.file))){const fileName=resolve(snapshot.checkout.repo,source.file),read=extractFile(compiler,fileName,source.text);read.parseFailed&&parseFailures++;for(const one of read.declarations)nodes.length<MAX_NODES&&nodes.push({file:source.file,name:one.name,line:one.line,endLine:one.endLine});for(const one of read.specifiers){const resolved=resolveOne(one.specifier,fileName);if(resolved===null){unresolved++;continue}relationships.length<MAX_EDGES&&relationships.push({from:source.file,to:byPath.get(resolved).file,kind:one.kind,file:source.file,line:one.line,provenance:"explicit"})}}return unresolved&&warnings.push(`${unresolved} external or unresolved imports were omitted.`),parseFailures&&warnings.push(`${parseFailures} files had syntax errors; extracted relationships may be incomplete.`),(nodes.length===MAX_NODES||relationships.length===MAX_EDGES)&&warnings.push("Repository relationships reached the index limit; remaining entries were omitted."),{version:VERSION,checkout:snapshot.checkout,extractor:`typescript-parser@${compiler.version}/imports-v1`,nodes,relationships,warnings}}const terms=query=>[...new Set(query.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu)??[])].filter(t=>!["the","and","for","this","that","what","where","with","from","does","show","code"].includes(t)).slice(0,12);function search(snapshot,query,index){const words=terms(query),hits=[];if(!words.length)return[];for(const source of snapshot.sources){const names=index?.nodes.filter(n=>n.file===source.file)??[],pathScore=words.reduce((n,word)=>n+(source.file.toLowerCase().includes(word)?3:0),0),symbol=names.map(node=>({node,score:words.reduce((n,word)=>n+(node.name.toLowerCase().includes(word)?5:0),0)})).sort((a,b)=>b.score-a.score)[0],lines=source.text.split(`
4
4
  `);let bestLine=symbol?.score?symbol.node.line:1,bestScore=0;lines.forEach((line,i)=>{const score2=words.reduce((n,word)=>n+(line.toLowerCase().includes(word)?1:0),0);score2>bestScore&&(bestScore=score2,symbol?.score||(bestLine=i+1))});const score=pathScore+(symbol?.score??0)+bestScore;score&&hits.push({source,line:bestLine,score,symbol:symbol?.score?symbol.node.name:null,reason:symbol?.score?"Matching code symbol":pathScore?"Matching file and source text":"Matching source text"})}return hits.sort((a,b)=>b.score-a.score||a.source.file.localeCompare(b.source.file))}function impact(snapshot,query,index,warnings){const normalized=query.replace(/^\.\//,"").trim(),direct=snapshot.sources.find(s=>s.file===normalized),matching=index.nodes.filter(n=>n.name.toLowerCase()===normalized.toLowerCase()),files=[...new Set(matching.map(n=>n.file))],target=direct?.file??(files.length===1?files[0]:void 0);if(!target)return warnings.push(files.length>1?"That symbol occurs in several files. Use its exact repository-relative file path for impact.":"No exact indexed file or symbol matched. Ordinary search results are shown."),{hits:search(snapshot,query,index),edges:[]};const depths=new Map([[target,0]]),edges=[];for(let depth=0;depth<2;depth++)for(const edge of index.relationships)depths.get(edge.to)===depth&&edges.length<200&&(edges.push(edge),depths.has(edge.from)||depths.set(edge.from,depth+1));const byFile=new Map(snapshot.sources.map(s=>[s.file,s]));return{hits:[...depths].flatMap(([file,depth])=>{const source=byFile.get(file);if(!source)return[];const edge=edges.find(e=>e.from===file);return[{source,line:edge?.line??matching.find(n=>n.file===file)?.line??1,score:100-depth,reason:depth===0?"Selected source":`Imports the selected source within ${depth} step${depth===1?"":"s"}`,symbol:null}]}),edges}}function initialResult(request){return{version:1,readOnly:!request.refresh,query:request.query.slice(0,1e3),mode:request.mode??"search",asOf:new Date().toISOString(),checkout:null,index:{engine:"text-search",status:"unavailable",generation:null,extractor:null},excerpts:[],relationships:[],omissions:{files:0,excerpts:0,relationships:0,sourceBytes:0},warnings:[]}}function captureForResult(request,result){try{const snapshot=capture(request);return result.checkout=snapshot.checkout,result.warnings.push(...snapshot.warnings),result.omissions.files=snapshot.omitted,result.omissions.sourceBytes=snapshot.omittedBytes,snapshot}catch{return result.warnings.push(request.audience==="crew"?"Repository context is unavailable at the exact task base. Continue with the saved project context and read the assigned worktree.":"Repository context is unavailable. Continue with the saved project context and ordinary file reading."),null}}const responseBudget=request=>Math.max(3e3,Math.min(2e4,Number.isFinite(request.maxBytes)?Math.floor(request.maxBytes):request.audience==="crew"?12e3:6500));function finishContext(request,result,snapshot,index){const mode=request.mode??"search",budget=responseBudget(request);index?(result.index={engine:"typescript-ast",status:"ready",generation:sha(JSON.stringify(index)),extractor:index.extractor},result.warnings.push(...index.warnings)):result.warnings.push("No current repository index is available. Ordinary source search is being used; refresh context to restore relationship lookup.");const found=mode==="impact"&&index?impact(snapshot,request.query,index,result.warnings):{hits:search(snapshot,request.query,index),edges:[]};mode==="impact"&&!index&&result.warnings.push("These are text matches, not an impact analysis.");const selected=found.hits.slice(0,request.audience==="crew"?8:5);result.omissions.excerpts=Math.max(0,found.hits.length-selected.length);for(const hit of selected){const lines=hit.source.text.split(`
@@ -1,4 +1,4 @@
1
- import{keepCheckScreenshots}from"./check-screenshots.js";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForRun}from"./check-recovery-hold.js";import{widerThan}from"./check-access.js";import{localChecksStanding,LocalChecksLapsed}from"./local-checks.js";import{recheckStanding}from"./check-only-standing.js";import{actualCheckAccess,checkoutLaunchOf,checkoutRunner,ranAtLine,widestRan}from"./invoke.js";import{mkdtempSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{verifyCommandAt}from"./store.js";import{refArchived}from"./task-archive.js";import{belongsToRelease}from"./release-authority.js";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{approvedCommandShell,SETUP_ENV_ALLOWLIST,SETUP_ENV_DENYLIST}from"./builder.js";import{runWithIsolatedDatabase}from"./child-database.js";import{boundStreamHeadTail,readVerifiedArtifact,redactSecretLines,scanForSecrets,storeEvidence}from"./evidence.js";import{CHECK_LEVEL_WORDS,checkCommandFor,quickVerifyKey,repoClause,repoOfRun,runCheckLevel}from"./check-levels.js";import{fileTaskProposal}from"./proposal.js";export const CHECKS_REQUESTED="checks requested",CHECKS_STARTED="checks started",CHECKS_FINISHED="checks finished",FOLLOW_UP_LOG="follow-up check log v1",FOLLOW_UP_RECEIPT="follow-up check receipt v1",ADD_TESTS_ACTION="tests task filed";const ABANDONED_GRACE_MS=10*6e4,refuse=(reason,message)=>({ok:!1,reason,message});function ledgerFor(store,runId){const[where,params]=repoClause(repoOfRun(store,runId));return store.handle.prepare(`SELECT id, actor, at, outcome, detail, action FROM action_ledger WHERE ${where} AND run_id = ? AND action IN (?, ?, ?) ORDER BY id`).all(...params,runId,CHECKS_REQUESTED,CHECKS_STARTED,CHECKS_FINISHED).map(row=>({id:Number(row.id),actor:String(row.actor),at:String(row.at),outcome:String(row.outcome),detail:row.detail===null?null:String(row.detail),action:String(row.action)}))}export function followUpChecksOf(store,runId,now=new Date,root,asOf){const rows=asOf===void 0?ledgerFor(store,runId):ledgerFor(store,runId).filter(row=>Date.parse(row.at)<=asOf.getTime()),receipts=new Map;if(root!==void 0)for(const artifact of store.artifactsFor(runId).filter(one=>one.kind==="structured-output"&&one.capture===FOLLOW_UP_RECEIPT)){const read=readVerifiedArtifact(root,artifact);if(read.ok)try{const body=JSON.parse(read.content.toString("utf8"));if(typeof body.request!="number")continue;const head=typeof body.head=="string"?body.head:null;receipts.set(body.request,{ran:body.result?.ran===!0,exitCode:typeof body.result?.exitCode=="number"?body.result.exitCode:null,log:typeof body.log?.artifactId=="number"?body.log.artifactId:null,head,tested:typeof body.tested=="string"?body.tested:head,batch:batchFactsOf(body.batch,runId,head)})}catch{}}const repo=root===void 0?null:repoOfRun(store,runId),logVerifies=artifactId=>{if(root===void 0||artifactId===null)return!1;const artifact=store.getArtifact(artifactId);return artifact!==null&&artifact.run===runId&&artifact.kind==="structured-output"&&artifact.capture===FOLLOW_UP_LOG&&artifact.captureStatus!=="failed"&&readVerifiedArtifact(root,artifact).ok},stillApproved=(level,digest)=>{if(repo===null)return!1;try{return asOf===void 0?checkCommandFor(store,repo,level).command?.digest===digest:((level==="quick"?verifyCommandAt(store,quickVerifyKey(repo),asOf):null)??verifyCommandAt(store,repo,asOf))?.digest===digest}catch{return!1}};return rows.filter(row=>row.action===CHECKS_REQUESTED&&(row.outcome==="quick"||row.outcome==="full")).map(request=>{const[head="",why="person",digest="",recordedBase=""]=(request.detail??"").split(" · "),started=rows.find(row=>row.action===CHECKS_STARTED&&row.outcome===String(request.id))??null,finished=rows.find(row=>row.action===CHECKS_FINISHED&&row.outcome.startsWith(`${request.id}:`))??null,base={request:request.id,runId,level:request.outcome,head,digest,actor:request.actor,at:request.at,why:why==="pull-request"?"pull-request":why==="batch"?"batch":why==="recheck"?"recheck":why==="local-owner"?"local-owner":"person",exitCode:null,logArtifactId:null,note:null,...why==="batch"?{base:/^[a-f0-9]{40}$/.test(recordedBase)?recordedBase:null}:{}};if(finished!==null){const status=finished.outcome.slice(String(request.id).length+1),sealed=receipts.get(request.id)??null;if(status==="passed"&&root!==void 0&&(sealed===null||!sealed.ran||sealed.exitCode!==0||sealed.head!==null&&sealed.head!==head||base.why==="batch"&&sealed.batch===null||!logVerifies(sealed.log)||!stillApproved(base.level,digest)))return{...base,state:"not-run",note:"The saved check result could not be verified."};const exit=/exit (\d+)/.exec(finished.detail??""),outdated=status==="failed"&&root!==void 0&&asOf===void 0&&repo!==null&&!stillApproved(base.level,digest)&&(()=>{try{return checkCommandFor(store,repo,base.level).command!==null}catch{return!1}})();return{...base,...outdated?{outdated:!0}:{},state:status==="passed"?"passed":status==="failed"?"failed":"not-run",exitCode:exit===null?sealed?.exitCode??null:Number(exit[1]),logArtifactId:sealed?.log??null,note:status==="not-run"?finished.detail:null,...sealed===null?{}:{tested:sealed.ran?sealed.tested:null,batch:sealed.batch}}}if(started!==null){const limit=Number(/limit (\d+)/.exec(started.detail??"")?.[1]??36e5);return now.getTime()-Date.parse(started.at)>limit+ABANDONED_GRACE_MS?{...base,state:"not-run",note:"The check didn't finish."}:{...base,state:"running"}}return{...base,state:"waiting"}})}function batchFactsOf(value,runId,head){if(value===null||typeof value!="object")return null;const raw=value,mode=["together","split","conflict","alone"].find(one=>one===raw.mode);if(mode===void 0||typeof raw.tested!="string"||!/^[a-f0-9]{40}$/.test(raw.tested)||!Array.isArray(raw.members))return null;const members=raw.members.flatMap(one=>{const m=one;return typeof m?.task=="string"&&typeof m.run=="number"&&typeof m.head=="string"?[{task:m.task,run:m.run,head:m.head}]:[]});return members.length!==raw.members.length||!members.some(one=>one.run===runId&&one.head===head)||mode!=="together"&&(members.length!==1||raw.tested!==head)?null:{mode,tested:raw.tested,base:typeof raw.base=="string"?raw.base:null,members}}function checkTarget(store,runId,level){const run=store.getRun(runId),ref=run===null?null:store.refById(run.taskRef);if(run===null||ref===null)return refuse("unknown","No such result.");if(run.finishedAt===null||run.headRevision===null||!/^[a-f0-9]{40}$/.test(run.headRevision))return refuse("no-commit","This result has no finished commit to check.");if(ref.repo===null)return refuse("unplaced","This result isn't in a project, so there is no check to run.");if(refArchived(store,ref.id))return refuse("archived","This task is put away. Restore it first.");const chosen=checkCommandFor(store,ref.repo,level);return chosen.command===null?refuse("no-check",`${ref.repo} has no approved ${level==="quick"?"quick or full":"full"} check. Set one in Settings → Projects → Checks.`):{ok:!0,repo:ref.repo,taskId:ref.externalId,head:run.headRevision,level:chosen.level,command:chosen.command}}export function requestFollowUpChecks(store,input,now){return store.transact(()=>{if(recoveryCheckBlock(store,input.runId)!==null)return refuse("recovery-held",CHECK_RECOVERY_MESSAGE);const target=checkTarget(store,input.runId,input.level);if(!target.ok)return target;const open=followUpChecksOf(store,input.runId,now).find(one=>one.level===target.level&&one.head===target.head&&(one.state==="waiting"||one.state==="running"));if(open!==void 0)return{ok:!0,request:open.request,level:target.level,existing:!0};const request=store.recordAction({at:now.toISOString(),actor:input.actor,repo:target.repo,taskId:target.taskId,runId:input.runId,action:CHECKS_REQUESTED,outcome:target.level,source:"work",detail:`${target.head} · ${input.why??"person"} · ${target.command.digest}`});return store.bumpWake(),{ok:!0,request,level:target.level,existing:!1}})}export function waitingCheckRequests(store,now){return waitingRequestsOfAnyKind(store,now).filter(one=>one.why!=="batch")}export function waitingRequestsOfAnyKind(store,now){return store.handle.prepare(`SELECT DISTINCT r.run_id AS run FROM action_ledger r WHERE r.action = ? AND r.run_id IS NOT NULL
1
+ import{wholeChangeBaseOf}from"./task-base.js";import{keepCheckScreenshots}from"./check-screenshots.js";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForRun}from"./check-recovery-hold.js";import{widerThan}from"./check-access.js";import{localChecksStanding,LocalChecksLapsed}from"./local-checks.js";import{recheckStanding}from"./check-only-standing.js";import{actualCheckAccess,checkoutLaunchOf,checkoutRunner,ranAtLine,widestRan}from"./invoke.js";import{mkdtempSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{verifyCommandAt}from"./store.js";import{refArchived}from"./task-archive.js";import{belongsToRelease}from"./release-authority.js";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{approvedCommandShell,SETUP_ENV_DENYLIST,setupEnvAllowlistFor}from"./builder.js";import{runWithIsolatedDatabase}from"./child-database.js";import{boundStreamHeadTail,readVerifiedArtifact,redactSecretLines,scanForSecrets,storeEvidence}from"./evidence.js";import{CHECK_LEVEL_WORDS,checkCommandFor,quickVerifyKey,repoClause,repoOfRun,runCheckLevel}from"./check-levels.js";import{fileTaskProposal}from"./proposal.js";export const CHECKS_REQUESTED="checks requested",CHECKS_STARTED="checks started",CHECKS_FINISHED="checks finished",FOLLOW_UP_LOG="follow-up check log v1",FOLLOW_UP_RECEIPT="follow-up check receipt v1",ADD_TESTS_ACTION="tests task filed";const ABANDONED_GRACE_MS=10*6e4,refuse=(reason,message)=>({ok:!1,reason,message});function ledgerFor(store,runId){const[where,params]=repoClause(repoOfRun(store,runId));return store.handle.prepare(`SELECT id, actor, at, outcome, detail, action FROM action_ledger WHERE ${where} AND run_id = ? AND action IN (?, ?, ?) ORDER BY id`).all(...params,runId,CHECKS_REQUESTED,CHECKS_STARTED,CHECKS_FINISHED).map(row=>({id:Number(row.id),actor:String(row.actor),at:String(row.at),outcome:String(row.outcome),detail:row.detail===null?null:String(row.detail),action:String(row.action)}))}export function followUpChecksOf(store,runId,now=new Date,root,asOf){const rows=asOf===void 0?ledgerFor(store,runId):ledgerFor(store,runId).filter(row=>Date.parse(row.at)<=asOf.getTime()),receipts=new Map;if(root!==void 0)for(const artifact of store.artifactsFor(runId).filter(one=>one.kind==="structured-output"&&one.capture===FOLLOW_UP_RECEIPT)){const read=readVerifiedArtifact(root,artifact);if(read.ok)try{const body=JSON.parse(read.content.toString("utf8"));if(typeof body.request!="number")continue;const head=typeof body.head=="string"?body.head:null;receipts.set(body.request,{ran:body.result?.ran===!0,exitCode:typeof body.result?.exitCode=="number"?body.result.exitCode:null,log:typeof body.log?.artifactId=="number"?body.log.artifactId:null,head,tested:typeof body.tested=="string"?body.tested:head,batch:batchFactsOf(body.batch,runId,head)})}catch{}}const repo=root===void 0?null:repoOfRun(store,runId),logVerifies=artifactId=>{if(root===void 0||artifactId===null)return!1;const artifact=store.getArtifact(artifactId);return artifact!==null&&artifact.run===runId&&artifact.kind==="structured-output"&&artifact.capture===FOLLOW_UP_LOG&&artifact.captureStatus!=="failed"&&readVerifiedArtifact(root,artifact).ok},stillApproved=(level,digest)=>{if(repo===null)return!1;try{return asOf===void 0?checkCommandFor(store,repo,level).command?.digest===digest:((level==="quick"?verifyCommandAt(store,quickVerifyKey(repo),asOf):null)??verifyCommandAt(store,repo,asOf))?.digest===digest}catch{return!1}};return rows.filter(row=>row.action===CHECKS_REQUESTED&&(row.outcome==="quick"||row.outcome==="full")).map(request=>{const[head="",why="person",digest="",recordedBase=""]=(request.detail??"").split(" · "),started=rows.find(row=>row.action===CHECKS_STARTED&&row.outcome===String(request.id))??null,finished=rows.find(row=>row.action===CHECKS_FINISHED&&row.outcome.startsWith(`${request.id}:`))??null,base={request:request.id,runId,level:request.outcome,head,digest,actor:request.actor,at:request.at,why:why==="pull-request"?"pull-request":why==="batch"?"batch":why==="recheck"?"recheck":why==="local-owner"?"local-owner":"person",exitCode:null,logArtifactId:null,note:null,...why==="batch"?{base:/^[a-f0-9]{40}$/.test(recordedBase)?recordedBase:null}:{}};if(finished!==null){const status=finished.outcome.slice(String(request.id).length+1),sealed=receipts.get(request.id)??null;if(status==="passed"&&root!==void 0&&(sealed===null||!sealed.ran||sealed.exitCode!==0||sealed.head!==null&&sealed.head!==head||base.why==="batch"&&sealed.batch===null||!logVerifies(sealed.log)||!stillApproved(base.level,digest)))return{...base,state:"not-run",note:"The saved check result could not be verified."};const exit=/exit (\d+)/.exec(finished.detail??""),outdated=status==="failed"&&root!==void 0&&asOf===void 0&&repo!==null&&!stillApproved(base.level,digest)&&(()=>{try{return checkCommandFor(store,repo,base.level).command!==null}catch{return!1}})();return{...base,...outdated?{outdated:!0}:{},state:status==="passed"?"passed":status==="failed"?"failed":"not-run",exitCode:exit===null?sealed?.exitCode??null:Number(exit[1]),logArtifactId:sealed?.log??null,note:status==="not-run"?finished.detail:null,...sealed===null?{}:{tested:sealed.ran?sealed.tested:null,batch:sealed.batch}}}if(started!==null){const limit=Number(/limit (\d+)/.exec(started.detail??"")?.[1]??36e5);return now.getTime()-Date.parse(started.at)>limit+ABANDONED_GRACE_MS?{...base,state:"not-run",note:"The check didn't finish."}:{...base,state:"running"}}return{...base,state:"waiting"}})}function batchFactsOf(value,runId,head){if(value===null||typeof value!="object")return null;const raw=value,mode=["together","split","conflict","alone"].find(one=>one===raw.mode);if(mode===void 0||typeof raw.tested!="string"||!/^[a-f0-9]{40}$/.test(raw.tested)||!Array.isArray(raw.members))return null;const members=raw.members.flatMap(one=>{const m=one;return typeof m?.task=="string"&&typeof m.run=="number"&&typeof m.head=="string"?[{task:m.task,run:m.run,head:m.head}]:[]});return members.length!==raw.members.length||!members.some(one=>one.run===runId&&one.head===head)||mode!=="together"&&(members.length!==1||raw.tested!==head)?null:{mode,tested:raw.tested,base:typeof raw.base=="string"?raw.base:null,members}}function checkTarget(store,runId,level){const run=store.getRun(runId),ref=run===null?null:store.refById(run.taskRef);if(run===null||ref===null)return refuse("unknown","No such result.");if(run.finishedAt===null||run.headRevision===null||!/^[a-f0-9]{40}$/.test(run.headRevision))return refuse("no-commit","This result has no finished commit to check.");if(ref.repo===null)return refuse("unplaced","This result isn't in a project, so there is no check to run.");if(refArchived(store,ref.id))return refuse("archived","This task is put away. Restore it first.");const chosen=checkCommandFor(store,ref.repo,level);if(chosen.command===null)return refuse("no-check",`${ref.repo} has no approved ${level==="quick"?"quick or full":"full"} check. Set one in Settings → Projects → Checks.`);const base=(run.branch===null?null:wholeChangeBaseOf(store,run.taskRef,run.branch))??run.baseRevision;return chosen.level==="quick"&&base===null?refuse("no-base","This result has no saved task base. Restore it before running Quick checks."):{ok:!0,repo:ref.repo,taskId:ref.externalId,head:run.headRevision,level:chosen.level,command:chosen.command,base}}export function requestFollowUpChecks(store,input,now){return store.transact(()=>{if(recoveryCheckBlock(store,input.runId)!==null)return refuse("recovery-held",CHECK_RECOVERY_MESSAGE);const target=checkTarget(store,input.runId,input.level);if(!target.ok)return target;const open=followUpChecksOf(store,input.runId,now).find(one=>one.level===target.level&&one.head===target.head&&(one.state==="waiting"||one.state==="running"));if(open!==void 0)return{ok:!0,request:open.request,level:target.level,existing:!0};const request=store.recordAction({at:now.toISOString(),actor:input.actor,repo:target.repo,taskId:target.taskId,runId:input.runId,action:CHECKS_REQUESTED,outcome:target.level,source:"work",detail:`${target.head} · ${input.why??"person"} · ${target.command.digest}`});return store.bumpWake(),{ok:!0,request,level:target.level,existing:!1}})}export function waitingCheckRequests(store,now){return waitingRequestsOfAnyKind(store,now).filter(one=>one.why!=="batch")}export function waitingRequestsOfAnyKind(store,now){return store.handle.prepare(`SELECT DISTINCT r.run_id AS run FROM action_ledger r WHERE r.action = ? AND r.run_id IS NOT NULL
2
2
  AND NOT EXISTS (SELECT 1 FROM action_ledger s WHERE s.run_id = r.run_id AND s.action = ? AND s.outcome = CAST(r.id AS TEXT)) ORDER BY r.id`).all(CHECKS_REQUESTED,CHECKS_STARTED).map(row=>Number(row.run)).flatMap(runId=>recoveryCheckBlock(store,runId)!==null?[]:followUpChecksOf(store,runId,now).filter(one=>one.state==="waiting"))}export async function runFollowUpCheck(store,root,request,deps={}){const now=deps.now??(()=>new Date),runner=deps.runner??execRun,cleanupGit=deps.git??hardenedGit(execRun),asked=store.handle.prepare("SELECT run_id FROM action_ledger WHERE id = ? AND action = ?").get(request,CHECKS_REQUESTED);if(asked===void 0)return null;const runId=Number(asked.run_id),wanted=followUpChecksOf(store,runId,now()).find(one=>one.request===request);if(wanted===void 0)return null;const heldNow=()=>{const evidence=recoveryCheckBlock(store,runId);return evidence===null?null:{...wanted,state:"recovery-held",priorState:wanted.state,note:CHECK_RECOVERY_MESSAGE,recovery:evidence,priorExecution:"unverified"}},initiallyHeld=heldNow();if(initiallyHeld!==null)return initiallyHeld;if(wanted.state!=="waiting")return wanted;const target=checkTarget(store,runId,wanted.level),finish=(status,detail,stamp)=>store.transact(()=>{const at2=(stamp??now()).toISOString(),held=heldNow();return held!==null?held:(store.recordAction({at:at2,actor:"system",repo:target.ok?target.repo:null,taskId:target.ok?target.taskId:null,runId,action:CHECKS_FINISHED,outcome:`${request}:${status}`,source:"work",detail}),store.bumpWake(),null)}),claimed=store.transact(()=>{const at2=now().toISOString(),held=heldNow();return held!==null?held:store.handle.prepare("SELECT 1 FROM action_ledger WHERE run_id = ? AND action = ? AND outcome = ?").get(runId,CHECKS_STARTED,String(request))!==void 0?!1:(store.recordAction({at:at2,actor:"system",repo:target.ok?target.repo:null,taskId:target.ok?target.taskId:null,runId,action:CHECKS_STARTED,outcome:String(request),source:"work",detail:`limit ${target.ok?target.command.timeoutMs:0}`}),!0)});if(typeof claimed=="object")return claimed;if(!claimed){const stamp=now();return heldNow()??followUpChecksOf(store,runId,stamp,root).find(one=>one.request===request)??null}if(!target.ok)return finish("not-run",target.message)??followUpChecksOf(store,runId,now(),root).find(one=>one.request===request)??null;if(target.head!==wanted.head)return finish("not-run","The result's commit changed after checks were asked for.")??followUpChecksOf(store,runId,now(),root).find(one=>one.request===request)??null;const authorized=wanted.why==="recheck"?recheckStanding(store,{request,runId,head:target.head,digest:wanted.digest}):wanted.why==="local-owner"?localChecksStanding(store,{by:wanted.actor,taskId:target.taskId}):null;if((wanted.why==="recheck"||wanted.why==="local-owner")&&!authorized?.ok)return finish("not-run",authorized?.problem??"Its authorization couldn't be read.")??followUpChecksOf(store,runId,now(),root).find(one=>one.request===request)??null;const proveLaunch=()=>{const held=heldNow();if(held!==null)throw new CheckRecoveryBlocked(held);if(wanted.why==="local-owner"){const standing=localChecksStanding(store,{by:wanted.actor,taskId:target.taskId});if(!standing.ok)throw new LocalChecksLapsed(standing.problem)}},guardedRunner=(file,args,options)=>(proveLaunch(),runner(file,args,options)),git=deps.git??hardenedGit((file,args,options)=>(proveLaunch(),execRun(file,args,options))),launched=inner=>(file,args,options)=>(proveLaunch(),authorized?.ok&&widerThan(actualCheckAccess(store,checkoutLaunchOf(store,target.repo,[runId]).access),authorized.access)?Promise.resolve({code:126,stdout:"",stderr:"",notFound:!0,timedOut:!1}):inner(file,args,options)),folder=mkdtempSync(join(deps.scratch??tmpdir(),"toolroll-checks-")),checkout=join(folder,"checkout"),log=[],ranAt=[],bound=text=>{const hits=scanForSecrets(text);return boundStreamHeadTail(hits.length>0?redactSecretLines(text,hits):text,24*1024)},note=(label,command,result2)=>log.push(`=== ${label} ===
3
3
  $ ${command}
4
4
  (exit ${result2.code}${result2.notFound?", could not start":""}${result2.timedOut?", timed out":""})
@@ -7,7 +7,7 @@ $ ${command}
7
7
  ${bound(result2.stdout)}
8
8
 
9
9
  --- stderr ---
10
- ${bound(result2.stderr)}`);let result,heldControl=null,checkoutCreated=!1;try{proveLaunch();const added=await git("git",["-C",target.repo,"worktree","add","--detach",checkout,target.head],{timeoutMs:12e4});if(checkoutCreated=added.code===0,note("Checkout",`git worktree add --detach <fresh folder> ${target.head}`,added),proveLaunch(),added.code!==0)result={ran:!1,failure:"The commit couldn't be checked out. It may have been removed from this computer."};else{const setup=store.liveWorktreeSetup(target.repo);let ready=!0;if(setup!==null){const shell=approvedCommandShell(setup.command),prepared=await runWithIsolatedDatabase(launched(checkoutRunner(store,target.repo,checkout,guardedRunner,[runId],level=>ranAt.push(level),void 0,root)),shell.file,shell.args,{cwd:checkout,timeoutMs:setup.timeoutMs,processGroup:!0,envAllowlist:SETUP_ENV_ALLOWLIST,omitEnv:SETUP_ENV_DENYLIST});note("Approved project setup",setup.command,prepared),proveLaunch(),(prepared.code!==0||prepared.timedOut||prepared.notFound)&&(ready=!1,result={ran:!1,failure:"The project's setup failed, so the check didn't run."})}if(ready){const live=store.liveVerifyCommand(target.command.repo);if(live===null||live.digest!==target.command.digest||live.digest!==wanted.digest)result={ran:!1,failure:"The approved check changed before it started."};else{const shell=approvedCommandShell(live.command),ran=await runWithIsolatedDatabase(launched(checkoutRunner(store,target.repo,checkout,guardedRunner,[runId],level=>ranAt.push(level),void 0,root)),shell.file,shell.args,{cwd:checkout,timeoutMs:live.timeoutMs,processGroup:!0,envAllowlist:SETUP_ENV_ALLOWLIST,omitEnv:SETUP_ENV_DENYLIST});if(note(`${CHECK_LEVEL_WORDS[target.level]} check`,live.command,ran),proveLaunch(),!ran.timedOut&&!ran.notFound){const kept=keepCheckScreenshots(store,root,runId,checkout,target.head,now());kept.length>0&&log.push(`=== Screenshots ===
10
+ ${bound(result2.stderr)}`);let result,heldControl=null,checkoutCreated=!1;try{proveLaunch();const added=await git("git",["-C",target.repo,"worktree","add","--detach",checkout,target.head],{timeoutMs:12e4});if(checkoutCreated=added.code===0,note("Checkout",`git worktree add --detach <fresh folder> ${target.head}`,added),proveLaunch(),added.code!==0)result={ran:!1,failure:"The commit couldn't be checked out. It may have been removed from this computer."};else{const setup=store.liveWorktreeSetup(target.repo);let ready=!0;if(setup!==null){const shell=approvedCommandShell(setup.command),prepared=await runWithIsolatedDatabase(launched(checkoutRunner(store,target.repo,checkout,guardedRunner,[runId],level=>ranAt.push(level),void 0,root)),shell.file,shell.args,{cwd:checkout,timeoutMs:setup.timeoutMs,processGroup:!0,env:target.base===null?{}:{TOOLROLL_TASK_BASE:target.base},envAllowlist:setupEnvAllowlistFor(store),omitEnv:SETUP_ENV_DENYLIST});note("Approved project setup",setup.command,prepared),proveLaunch(),(prepared.code!==0||prepared.timedOut||prepared.notFound)&&(ready=!1,result={ran:!1,failure:"The project's setup failed, so the check didn't run."})}if(ready){const live=store.liveVerifyCommand(target.command.repo);if(live===null||live.digest!==target.command.digest||live.digest!==wanted.digest)result={ran:!1,failure:"The approved check changed before it started."};else{const shell=approvedCommandShell(live.command),ran=await runWithIsolatedDatabase(launched(checkoutRunner(store,target.repo,checkout,guardedRunner,[runId],level=>ranAt.push(level),void 0,root)),shell.file,shell.args,{cwd:checkout,timeoutMs:live.timeoutMs,processGroup:!0,env:target.base===null?{}:{TOOLROLL_TASK_BASE:target.base},envAllowlist:setupEnvAllowlistFor(store),omitEnv:SETUP_ENV_DENYLIST});if(note(`${CHECK_LEVEL_WORDS[target.level]} check`,live.command,ran),proveLaunch(),!ran.timedOut&&!ran.notFound){const kept=keepCheckScreenshots(store,root,runId,checkout,target.head,now());kept.length>0&&log.push(`=== Screenshots ===
11
11
  ${kept.join(`
12
12
  `)}`)}result=ran.timedOut?{ran:!1,failure:"The check ran out of time."}:ran.notFound?{ran:!1,failure:"The check couldn't start."}:{ran:!0,exitCode:ran.code}}}else result??={ran:!1,failure:"The project's setup failed, so the check didn't run."}}}catch(error){if(error instanceof LocalChecksLapsed)result={ran:!1,failure:error.message};else{if(!(error instanceof CheckRecoveryBlocked))throw error;heldControl=error.control}}finally{checkoutCreated&&await cleanupGit("git",["-C",target.repo,"worktree","remove","--force",checkout],{timeoutMs:12e4}).catch(()=>null),rmSync(folder,{recursive:!0,force:!0})}const at=now(),saveHeldLog=held=>{const logArtifactId=log.length===0?null:storeEvidence(store,root,runId,"structured-output",`follow-up-check-${request}-held.log`,Buffer.from(log.join(`
13
13
 
@@ -1,4 +1,4 @@
1
1
  import{createHash}from"node:crypto";import{assignmentActionHref,assignmentPresentationOf,assignmentStatusOf,assignmentWithEvidence,historicalAssessmentReason,shortenedMaterialReason}from"./assignment-presentation.js";import{assignmentChecksForRun,owedAcceptance}from"./assignment.js";import{CHECK_LEVEL_WORDS,liveQuickCommand}from"./check-levels.js";import{CHECK_SCREENSHOT_CAPTURE}from"./check-screenshots.js";import{LIMITS}from"./decision.js";import{readVerifiedArtifact,readVerifiedProofForRun,reportShotsOf}from"./evidence.js";import{isInternalErrorReason,NEEDS,runReasonWords}from"./needs-you.js";import{oneLineOf}from"./plain-words.js";import{projectName}from"./project.js";import{coverageStateWords,coverageWords,dispatchStatusToken,GOAL_ASSESSMENT_PENDING,manualReviewCriterionOf,manualReviewOnly,passFraction,personCheckWords,plainReasonWords,reviewConflict,semanticCoverage}from"./proof.js";import{releaseCoverageOf}from"./release-coverage.js";import{acceptWithChecksOf,resultActsOf,SEND_BACK_PUBLISHED,SEND_BACK_UNPUBLISHED}from"./result-acts.js";import{SCREENSHOT_CAPTURE,structuredHandoffView,terminalDiffView}from"./result-evidence-readers.js";import{ADD_TESTS_ACTION,followUpChecksOf}from"./result-follow-ups.js";import{evidenceHealthOf,evidenceProblemDetailsOf,evidenceResultStatusOf,isRevisionFeedback,RESULT_TABS,resultFactsAttributeMap,resultLeadOf,revisionBatchOf,revisionSourceOf}from"./result-review.js";import{findingWords}from"./review-switch.js";import{parseReport}from"./scout-report.js";import{safePrUrl,taskLinkOf}from"./task-link.js";import{publicationFactsOf,statusActionHref}from"./task-projection.js";import{approvedCheckOf,approvedCheckStateOf,checkBackingOf,CHECKED_AT_RELEASE,checksFactOf,CHECK_UNREADABLE,demoChecksOf,pullRequestFactOf,receiptChecksOf,requirementsOf,requirementWordOf}from"./task-status.js";import{ACCEPT_NEEDS_REASON as WORKSPACE_ACCEPT_NEEDS_REASON,acceptWordsOf,cantAcceptYetOf,evidenceProblemOf,MISMATCH_HEADLINE,receiptHeadingOf,receiptPublicationWords,reportMismatchesOf,RESULT_DECISION_SENTENCE,resultHeadlineOf,resultStatusOf,REVIEW_TOKENS}from"./workspace-projection.js";import{when}from"./server/chrome-helpers.js";import{chatResultHref,reviewHref,taskChatHref,taskHref}from"./server/http.js";export function editorFileHref(worktree,path,line){if(!worktree.startsWith("/")||/[\u0000-\u001f\u007f]/.test(worktree)||path===""||/[\u0000-\u001f\u007f]/.test(path)||path.startsWith("/")||path.includes("\\"))return null;const segments=path.split("/");if(segments.some(segment=>segment===""||segment==="."||segment===".."))return null;const rootSegments=worktree.replace(/\/+$/,"").split("/");if(rootSegments.some(segment=>segment==="."||segment===".."))return null;try{const root=rootSegments.map(segment=>encodeURIComponent(segment)).join("/"),file=segments.map(segment=>encodeURIComponent(segment)).join("/"),at=line!=null&&Number.isInteger(line)&&line>=1&&line<=1e6?`:${line}`:"";return`vscode://file${root}/${file}${at}`}catch{return null}}const CHECK_LOG_CAPTURE=/^sh -c "(.+)" \(exit \d+(?:, timed out)?\)$/;export function evidenceLinksFor(artifacts){const map=new Map;for(const artifact of artifacts)if(artifact.kind==="screenshot"){const path=SCREENSHOT_CAPTURE.exec(artifact.capture)?.[1];path!==void 0&&map.set(`screenshot:${path}`,artifact.id)}else if(artifact.kind==="check-log"){const command=CHECK_LOG_CAPTURE.exec(artifact.capture)?.[1];command!==void 0&&map.set(`check:${command}`,artifact.id)}else artifact.kind==="terminal-diff"&&map.set("changed-path:*",artifact.id);return map}export const ACCEPT_ANYWAY_NEEDS_REASON="Accepting anyway needs a reason.",RESULT_REFUSALS={reason:ACCEPT_ANYWAY_NEEDS_REASON};export function withRefusal(href,code){const at=href.indexOf("#"),[path,hash]=at===-1?[href,""]:[href.slice(0,at),href.slice(at)];return`${path}${path.includes("?")?"&":"?"}refused=${code}${hash}`}export const REVIEW_QUEUE_CAP=100;const PRIORITY_LABELS={0:"needs action",1:"review",2:"no flags"};export function reviewPriorityOf(row){if(row.assignment!=null&&(row.assignment.receipt?.runId??null)===row.runId){const presentation=assignmentPresentationOf(row.assignment),band2=row.assignment.state==="needs-decision"?0:row.assignment.state==="ready-to-check"?1:2;return{band:band2,label:PRIORITY_LABELS[band2],reasons:band2===2?[]:[presentation.status.label]}}const reasons=[];let band=2;const raise=(to,why)=>{to<band&&(band=to),reasons.push(why)};if(row.runId===null)return raise(1,"no build record"),{band,label:PRIORITY_LABELS[band],reasons};const ids=predicate=>row.proofMatrix.filter(predicate).map(one=>one.id).join(", "),contradicted=ids(one=>one.review?.judgement==="contradicts"),broken=ids(one=>one.state==="failed"||one.state==="missing"),manual=ids(one=>one.state==="manual-review"),humanReview=manualReviewOnly({verdict:row.proofVerdict??"",reasons:row.proofReasons??[],matrix:row.proofMatrix});return row.proofVerdict==="refuted"?raise(row.proofAccepted?1:0,row.proofAccepted?"the report doesn't match the changes — accepted with a reason":"the report doesn't match the changes"):humanReview?raise(1,row.proofAccepted?"accepted after human review":"human review needed"):row.proofVerdict==="short"&&raise(row.proofAccepted?1:0,row.proofAccepted?"not all requirements shown — accepted with a reason":"not all requirements shown"),contradicted!==""&&raise(row.proofAccepted?1:0,`reviewer raised a concern with ${contradicted}`),broken!==""&&raise(row.proofAccepted?1:0,`not shown, or shown failing, for ${broken}`),row.ciFailing&&raise(0,"CI failing on its pull request — observed, not inferred"),row.publicationState==="failed"&&raise(1,"publication failed — the branch never reached its remote"),manual!==""&&!row.proofAccepted&&!humanReview&&raise(1,`manual review needed for ${manual}`),row.proofVerdict===null&&row.outcome!=="no-change"&&raise(1,"no verification result"),{band,label:PRIORITY_LABELS[band],reasons}}export function rankReviewQueue(rows){return rows.map(row=>({...row,priority:reviewPriorityOf(row)})).sort((a,b)=>a.priority.band!==b.priority.band?a.priority.band-b.priority.band:a.ciFailing!==b.ciFailing?Number(b.ciFailing)-Number(a.ciFailing):a.completedAt!==b.completedAt?b.completedAt.localeCompare(a.completedAt):a.taskId.localeCompare(b.taskId))}export function withinSignedTouches(path,touches){return touches.some(raw=>{const touch=raw.trim().replace(/^\.\//,"");if(touch==="")return!1;if(touch.includes("*"))return touchGlob(touch).test(path);const dir=touch.endsWith("/")?touch:`${touch}/`;return path===touch||path.startsWith(dir)})}function touchGlob(raw){const touch=raw.replace(/\/+$/,"");let pattern="";for(let at=0;at<touch.length;)touch.startsWith("**/",at)?(pattern+="(?:[^/]*/)*",at+=3):touch.startsWith("**",at)?(pattern+=".*",at+=2):touch[at]==="*"?(pattern+="[^/]*",at+=1):(pattern+=touch[at].replace(/[.+?^${}()|[\]\\]/g,"\\$&"),at+=1);return new RegExp(`^${pattern}(?:/.*)?$`)}export function diffFileAnchor(path){return`diff-file-${createHash("sha256").update(path,"utf8").digest("hex").slice(0,16)}`}const SENSITIVE_PATH=/(^|\/)(\.github|migrations?)\/|(^|\/)(package(-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|Dockerfile|\.env(\.[^/]+)?|schema[^/]*\.(sql|prisma)|(?:[^/]*[-_.])?(auth|secrets?|tokens?|credentials?)(?:[-_.][^/]*)?)$/i,LARGE_CHANGE_LINES=200;export function reviewFilePriority(file,proofCitesPaths){const reasons=[];let band=2;const raise=(to,why)=>{to<band&&(band=to),reasons.push(why)};return file.outsideTouches&&raise(0,"outside approved paths"),(file.additions===null||file.deletions===null)&&raise(1,"binary file — preview unavailable"),SENSITIVE_PATH.test(file.path)&&raise(1,"dependencies, CI, schema, or credentials"),proofCitesPaths&&!file.cited&&raise(1,"not referenced by a requirement"),file.additions!==null&&file.deletions!==null&&file.additions+file.deletions>=LARGE_CHANGE_LINES&&raise(1,"a large change"),file.anchor===null&&raise(1,"not in the recorded diff — see the full diff"),{band,label:PRIORITY_LABELS[band],reasons}}export function orderChangedFiles(files,proofCitesPaths){const churn=file=>(file.additions??0)+(file.deletions??0);return files.map(file=>({...file,priority:reviewFilePriority(file,proofCitesPaths)})).sort((a,b)=>a.priority.band!==b.priority.band?a.priority.band-b.priority.band:churn(a)!==churn(b)?churn(b)-churn(a):a.path.localeCompare(b.path))}export function verificationExplanation(verdict,reasons){const plain=reasons.map(reason=>{if(reason==="the approved verification command passed after the approved setup command ran"||reason==="the approved verification command passed after the approved setup command restored project dependencies")return"Toolroll ran the approved setup automatically, then the project check passed.";if(reason==="the approved verification command could not start because a required project executable was unavailable and no approved recovery was enabled"||reason==="the approved verification command could not start because a project dependency was unavailable and no approved recovery was enabled")return"The project check couldn't start because a required project executable was missing. Automatic recovery wasn't enabled for this check.";if(reason==="automatic recovery stopped because the approved setup changed after self-healing was authorized"||reason==="automatic recovery stopped because its approved setup or project-check settings changed"||reason==="automatic recovery stopped because the project setup or check changed")return"Automatic recovery stopped because the project setup or check changed. Review and reapprove automatic recovery before retrying.";if(reason==="the approved setup command failed during automatic recovery"||reason==="the approved setup command could not restore the project dependencies")return"The approved project setup failed, so automatic recovery stopped before retrying the project check.";if(reason==="automatic recovery stopped because the setup command changed tracked files after the build")return"Automatic recovery stopped because project setup changed files after the build. Review those changes before retrying.";if(reason==="automatic recovery stopped because tracked files no longer matched the built result")return"Automatic recovery stopped because files changed after the build was saved. Review those changes before retrying.";if(reason==="automatic recovery stopped because the checkout moved away from the built commit")return"Automatic recovery stopped because Toolroll found a different project version than the one it built. Review the build log before retrying.";if(reason==="automatic recovery stopped because Toolroll could not confirm that the built checkout was unchanged")return"Automatic recovery stopped because Toolroll couldn't confirm that no files changed after the build was saved. Review the build log, then try again.";if(reason==="the required project executable was still unavailable after replaying the approved setup command"||reason==="project dependencies were still unavailable after replaying the approved setup command")return"Automatic recovery ran once, but the required project executable was still missing.";if(reason==="the retried verification command timed out after automatic recovery")return"Automatic recovery ran the approved setup, but the retried project check timed out.";if(reason==="the retried verification command could not be started after automatic recovery")return"Automatic recovery ran the approved setup, but Toolroll still couldn't start the project check.";if(reason==="automatic recovery stopped because this worker no longer owned the build")return"Automatic recovery stopped because this builder no longer had the build. Another builder can retry it safely.";if(reason==="the approved verification command could not be run")return"Toolroll couldn't run the project check.";const recoveredFailure=/^the repository's approved verification command exited (-?[0-9]+) after the approved setup command was replayed$/.exec(reason);if(recoveredFailure!==null)return`Automatic recovery ran the approved setup, but the project check still failed (exit ${Number(recoveredFailure[1])}).`;const exit=/^the repository's approved verification command exited (-?[0-9]+)$/.exec(reason);if(exit!==null){const code=Number(exit[1]);return code===127?"Toolroll couldn't run the project check because a required command wasn't available.":`The project check failed (exit ${code}).`}if(reason==="the sealed diff is unavailable or truncated; the claimed changed paths cannot be verified against it")return"The recorded changes were incomplete, so they could not be verified.";const plainWords=plainReasonWords(reason);if(plainWords!==reason)return plainWords;const sentence=reason.trim();return sentence===""?"":`${sentence[0]?.toUpperCase()??""}${sentence.slice(1)}${/[.!?]$/.test(sentence)?"":"."}`}).filter(Boolean);return plain.length>0?[...new Set(plain)].join(" "):verdict==="verified"?"Toolroll independently verified this result.":verdict==="attested"?"The agent reported its own checks, but no project check could run to confirm them.":verdict==="short"?"Some approved requirements aren't shown yet.":verdict==="refuted"?"What the build reported doesn't match its changes.":"No verification result is available for this build."}export function verificationRecovered(reasons){return reasons.some(reason=>reason==="the approved verification command passed after the approved setup command ran"||reason==="the approved verification command passed after the approved setup command restored project dependencies")}export function owedAcceptanceOf(receipt){const owed=owedAcceptance(receipt);return owed===null?null:owed==="person-check"?{note:null}:{note:"Why is this safe to accept?"}}export const PHASE_WORDS={"agent-running":"agent working","validating-handoff":"checking the handoff","correcting-proof":"correcting its report","capturing-evidence":"saving its files",committing:"committing"};export function homePhaseWords(run){if(run.role==="planner")return"Planning";if(run.role==="reviewer")return"Reviewing";if(run.role==="scout")return"Investigating";const words={"agent-running":"Writing the change","validating-handoff":"Checking its handoff","capturing-evidence":"Saving its files",committing:"Committing","verifying-proof":"Running the checks","correcting-proof":"Correcting its report"};return run.phase===null?"Starting":words[run.phase]??"Working"}export function phaseWords(phase){return PHASE_WORDS[phase]??"the agent is working"}export function reasonWords(reason){return isInternalErrorReason(reason)?"stopped with an internal error":oneLineOf(runReasonWords(reason.trim().split(/\r?\n/,1)[0]??""),140)}const INCIDENT_WORDS={"malformed-decision":"the agent's question was malformed","attempts-exhausted":"failed too many times in a row","commit-failure":"the commit failed","malformed-plan":"the plan was malformed","plan-attempts-exhausted":"planning failed too many times","malformed-report":"the research report was malformed"};export function incidentWords(kind){return INCIDENT_WORDS[kind]??"something went wrong — the run records have the detail"}export const EVIDENCE_WORDS={diff:"Diff",status:"Build status","park-payload":"Question record",plan:"Plan","terminal-diff":"Final diff","diff-stat":"Change summary","base-tree":"Starting files",handoff:"Agent handoff","revision-brief":"Revision brief",report:"Report",proof:"Agent report","check-log":"Check log",screenshot:"Screenshot","structured-output":"Agent response","plan-contract":"Your request","review-context":"Review context"};export function humanBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${Math.round(bytes/1024)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}export function evidenceWords(kind){return EVIDENCE_WORDS[kind]??"a stored record"}export const runNoun=run=>run.role==="planner"?"plan":run.role==="reviewer"?"review":run.role==="scout"?"report":"build";function runReportView(artifacts,root){const artifact=[...artifacts].reverse().find(one=>one.kind==="report");if(artifact===void 0)return null;let read;try{read=readVerifiedArtifact(root,artifact)}catch{return{ok:!1,artifactId:artifact.id,problem:"the report file could not be read"}}if(!read.ok)return{ok:!1,artifactId:artifact.id,problem:read.problem};const parsed=parseReport(read.content.toString("utf8"),{stored:!0});return parsed.ok?{ok:!0,artifactId:artifact.id,title:parsed.report.title,summary:parsed.report.summary,document:parsed.report.report,followUps:parsed.report.followUps.length,truncated:artifact.truncated,items:parsed.report.items,shots:reportShotsOf(artifacts,root,artifact.run,parsed.report.images)}:{ok:!1,artifactId:artifact.id,problem:artifact.truncated?"the report was shortened at storage and cannot be read; the missing part was never captured":"the stored report is not a report this console can read"}}function sharedResultFactsOf(run,proof,terminal,handoff,report,publication){const stat=terminal?.stat??null,statOk=stat!==null&&!("problem"in stat),passed=proof===null||proof.matrix.length===0?null:passFraction(proof.matrix),patch=terminal?.patch??null,evidenceProblems=evidenceProblemDetailsOf({proofProblem:proof?.proofProblem??null,diff:patch===null?null:"problem"in patch?{problem:patch.problem}:{truncated:patch.truncated},stat:stat===null?null:"problem"in stat?{problem:stat.problem}:{filesTruncated:stat.filesTruncated},checkLog:proof?.checkLog===null||proof?.checkLog===void 0?null:proof.checkLog.problem===null?{truncated:proof.checkLog.truncated}:{problem:proof.checkLog.problem},screenshots:proof?.screenshots??[],uncapturedScreenshots:proof?.uncapturedScreenshots??[],report:report===null?null:report.ok?{ok:!0,truncated:report.truncated}:{problem:report.problem},reportExpected:run.role==="scout",handoffPresent:handoff!==null,outcome:run.outcome});return{runId:run.id,base:statOk?stat.base:run.baseRevision,head:statOk?stat.head:run.headRevision,headSource:statOk?"saved diff":run.headRevision===null?null:"build record",checks:passed===null?null:{passed:passed.passed,total:passed.total},caveats:proof?.proof?.caveats??[],evidenceProblems:evidenceProblems.map(one=>one.words),evidenceHealth:evidenceHealthOf(evidenceProblems),publicationState:publication===null?"none":publication.state,publicationWords:receiptPublicationWords(publication)}}export function proofBundleView(store,run,artifacts,root){const verdictRow=store.proofVerdictFor(run.id),acceptanceRow=store.proofAcceptance(run.id),proofView=readVerifiedProofForRun(store,root,run.id),checkLogArtifact=artifacts.find(one=>one.kind==="check-log")??null,screenshotArtifacts=artifacts.filter(one=>one.kind==="screenshot");if(verdictRow===null&&proofView===null&&checkLogArtifact===null&&screenshotArtifacts.length===0)return null;const proof=proofView!==null&&proofView.ok?proofView.proof:null,captionFor=path=>proof?.screenshots.find(one=>one.path===path)?.caption??path,screenshots=screenshotArtifacts.flatMap(artifact=>{const fromCheck=CHECK_SCREENSHOT_CAPTURE.exec(artifact.capture);if(fromCheck!==null&&fromCheck[2]!==run.headRevision)return[];const path=fromCheck?.[1]??SCREENSHOT_CAPTURE.exec(artifact.capture)?.[1];if(path===void 0)return[];let problem=null;try{const read=readVerifiedArtifact(root,artifact);read.ok||(problem=read.problem)}catch{problem="the file could not be read"}return[{path,caption:fromCheck!==null?`From Checks: ${path.slice(16)}`:captionFor(path),artifactId:artifact.id,sha256:artifact.sha256,problem}]}),stored=new Set(screenshots.map(one=>one.path)),uncapturedScreenshots=(proof?.screenshots??[]).map(one=>one.path).filter(path=>!stored.has(path));let checkLog=null;if(checkLogArtifact!==null){let read;try{read=readVerifiedArtifact(root,checkLogArtifact)}catch{read={ok:!1,problem:"the file could not be read"}}const sizes={bytesOriginal:checkLogArtifact.bytesOriginal,bytesStored:checkLogArtifact.bytesStored};checkLog=read.ok?{text:read.content.toString("utf8"),artifactId:checkLogArtifact.id,truncated:checkLogArtifact.truncated,problem:null,...sizes}:{text:"",artifactId:checkLogArtifact.id,truncated:checkLogArtifact.truncated,problem:read.problem,...sizes}}return{...run.finishedAt!==null&&run.role!=="scout"&&run.role!=="reviewer"&&run.role!=="planner"?{checks:savedChecksOf(store,root,run,new Date)}:{},verdict:verdictRow?.verdict??null,reasons:verdictRow?.reasons??[],accepted:acceptanceRow===null?null:{by:acceptanceRow.approver,note:acceptanceRow.note,at:acceptanceRow.acceptedAt},proof:proof===null?null:{criteria:proof.criteria.map(one=>({statement:one.statement,verdict:one.verdict,how:one.how})),checks:proof.checks,caveats:proof.caveats},proofProblem:proofView!==null&&!proofView.ok?proofView.problem:null,checkLog,screenshots,uncapturedScreenshots,matrix:verdictRow?.matrix??[],matrixLinks:(()=>{const damaged=new Set([...screenshots.filter(one=>one.problem!==null).map(one=>one.artifactId),...checkLog!==null&&checkLog.problem!==null?[checkLog.artifactId]:[]]);return new Map([...evidenceLinksFor(artifacts)].filter(([,id])=>!damaged.has(id)))})(),machineVerdict:verdictRow?.machineVerdict??null,qualityMode:run.qualityMode??"default",repairChain:store.repairChainFor(run.id)??(()=>{const ref=store.refById(run.taskRef);return ref===null?null:store.repairChainForDraft(ref.externalId)})()}}export function completionWords(verdict,reasons,checks){const recorded=verificationExplanation(verdict,reasons);if(verdict!=="verified")return recorded;const now=approvedCheckStateOf(approvedCheckOf(verdict,reasons,checks));if(checks!==void 0&&(now==="passed"||now==="running"&&checks?.status==="passed"))return recorded;if(checks===void 0)return"Open the result to see its checks.";const said=now==="failed"?`the approved check failed against it${checks?.exitCode==null?"":` (exit ${checks.exitCode})`}.`:checks?.cause==="command-changed"?"the check command changed since this check.":`${CHECK_UNREADABLE.charAt(0).toLowerCase()}${CHECK_UNREADABLE.slice(1)}`;return`At completion: ${recorded} Now: ${said} It doesn't count as passed.`}function savedChecksOf(store,root,run,now){const own=checksFactOf(assignmentChecksForRun(store,root,run.id,now),run.headRevision);if(own.level!=="off"||own.status==="passed"||own.status==="failed")return own;const repo=store.refById(run.taskRef)?.repo??null,release=releaseCoverageOf(store,root,repo,run.headRevision);return release==null?own:{...own,release}}export function completionReceiptView(store,run,artifacts,root,review=null,now=new Date){const handoff=structuredHandoffView(artifacts,root),proof=proofBundleView(store,run,artifacts,root),terminal=terminalDiffView(artifacts,root),report=runReportView(artifacts,root),stat=terminal?.stat??null,coverage=semanticCoverage(proof?.matrix??[],run.qualityMode??"default"),publication=publicationFactsOf(store.publicationForRun(run.id));return{runId:run.id,role:run.role,outcome:run.outcome,summary:run.role==="scout"?report?.ok?report.summary:"The report needs attention.":handoff?.conclusion??run.handoff,verdict:proof?.verdict??null,reasons:proof?.reasons??[],accepted:proof?.accepted!==null&&proof?.accepted!==void 0,recordComplete:handoff!==null&&terminal!==null,publication,review,matrix:proof?.matrix??[],diff:stat===null||"problem"in stat?stat:{fileCount:stat.fileCount,additions:stat.additions,deletions:stat.deletions,binaryCount:stat.binaryCount,filesTruncated:stat.filesTruncated},screenshots:proof?.screenshots??[],caveats:proof?.proof?.caveats??[],coverage:coverage.contextGaps.length>0||(proof?.matrix??[]).some(row=>row.review!=null||row.assessment!==void 0)?coverageWords(coverage):[],coverageSecondary:coverage.contextGaps.length===0&&(coverage.satisfied===!0||coverage.satisfied===null&&!coverage.required),report,facts:sharedResultFactsOf(run,proof,terminal,handoff,report,publication),...run.role==="scout"?{}:{checks:savedChecksOf(store,root,run,now)}}}const REVIEW_DIFF_LINE_CAP=4e3;export function parseReviewDiff(text){const files=[];let file=null,hunk=null,oldLine=0,newLine=0,rendered=0,linesTruncated=!1;const pathOf=raw=>{let decoded=raw.split(" ",1)[0]?.trim()??raw.trim();if(decoded.startsWith('"')&&decoded.endsWith('"'))try{decoded=JSON.parse(decoded)}catch{decoded=decoded.slice(1,-1)}return decoded==="/dev/null"?decoded:decoded.replace(/^[ab]\//,"")};for(const raw of text.replace(/\r\n/g,`
2
2
  `).split(`
3
3
  `)){if(raw.startsWith("diff --git ")){const at=raw.lastIndexOf(" b/");file={path:at===-1?"changed file":pathOf(raw.slice(at+1)),oldPath:null,meta:[raw],hunks:[]},files.push(file),hunk=null;continue}if(file===null)continue;if(hunk===null&&raw.startsWith("--- ")){file.oldPath=pathOf(raw.slice(4)),file.meta.push(raw);continue}if(hunk===null&&raw.startsWith("+++ ")){const nextPath=pathOf(raw.slice(4));nextPath!=="/dev/null"&&(file.path=nextPath),file.meta.push(raw);continue}const hunkHeader=/^@@ -([0-9]+)(?:,[0-9]+)? \+([0-9]+)(?:,[0-9]+)? @@(.*)$/.exec(raw);if(hunkHeader!==null){oldLine=Number(hunkHeader[1]),newLine=Number(hunkHeader[2]),hunk={header:raw,lines:[]},file.hunks.push(hunk);continue}if(hunk===null){raw!==""&&file.meta.push(raw);continue}if(rendered>=REVIEW_DIFF_LINE_CAP){linesTruncated=!0;continue}rendered+=1,raw.startsWith("+")?(hunk.lines.push({kind:"addition",text:raw.slice(1),oldLine:null,newLine}),newLine+=1):raw.startsWith("-")?(hunk.lines.push({kind:"deletion",text:raw.slice(1),oldLine,newLine:null}),oldLine+=1):raw.startsWith(" ")?(hunk.lines.push({kind:"context",text:raw.slice(1),oldLine,newLine}),oldLine+=1,newLine+=1):hunk.lines.push({kind:"meta",text:raw,oldLine:null,newLine:null})}return{files,linesTruncated}}const diffFileHref=(runId,path)=>`/r/${Math.trunc(runId)}?fragment=diff-file&path=${encodeURIComponent(path)}`;export function followUpsFor(store,evidenceRoot,run,now){if(run.role!=="builder"||run.finishedAt===null||run.headRevision===null)return null;const repo=store.refById(run.taskRef)?.repo??null,tests=store.handle.prepare("SELECT outcome FROM action_ledger WHERE run_id = ? AND action = ? ORDER BY id DESC LIMIT 1").get(run.id,ADD_TESTS_ACTION);return{repo,checks:followUpChecksOf(store,run.id,now,evidenceRoot),testsTask:tests===void 0?null:String(tests.outcome),quick:repo!==null&&liveQuickCommand(store,repo)!==null,full:repo!==null&&store.liveVerifyCommand(repo)!==null}}const FOLLOW_UP_WORDS={waiting:"waiting for a builder",running:"running",passed:"passed",failed:"failed","not-run":"didn't run"};export function receiptStatusOf(view,review=view.review){return evidenceResultStatusOf({runId:view.runId,role:view.role,outcome:view.outcome,verdict:view.verdict,reasons:view.reasons,accepted:view.accepted,recordComplete:view.recordComplete,review,...view.checks===void 0?{}:{checks:view.checks}},view.publication,view.facts.evidenceHealth)}export function plainConclusionOf(conclusion){const prepared=/^Prepared candidate ([0-9a-f]{7,40}) was checked out by the machine; no agent ran\. (The branch already matched it\.|The sealed diff spans this task's base to that candidate\.)/.exec(conclusion);if(prepared===null)return conclusion;const rest=conclusion.slice(prepared[0].length).trim();return`Checked the prepared version ${prepared[1].slice(0,7)}; no agent ran. ${prepared[2].startsWith("The branch")?"The branch already matched it.":"The changes cover everything since the task started."}${rest===""?"":` ${rest}`}`}const CHECK_EXCERPT_LINES=12;function personCheckItems(proof,patchText,shots,runId){const rows=proof.matrix.filter(row=>row.state==="manual-review");if(rows.length===0)return proof.reasons.some(reason=>manualReviewCriterionOf(reason)!==null)?[{id:"you-check",statement:"",words:personCheckWords(null),note:null,excerpts:[],shots:[]}]:[];const diff=patchText===null?null:parseReviewDiff(patchText),excerptOf=(file,cited)=>{const changed=file.hunks.flatMap(hunk=>hunk.lines).filter(line=>line.kind==="addition"||line.kind==="deletion");return{path:file.path,cited,lines:changed.slice(0,CHECK_EXCERPT_LINES).map(line=>({kind:line.kind,line:line.newLine??line.oldLine,text:line.text})),more:Math.max(0,changed.length-CHECK_EXCERPT_LINES)}};return rows.map(row=>{const refs=row.answered??[],paths=refs.filter(one=>one.kind==="changed-path").map(one=>one.ref),files=diff===null?[]:paths.length>0?diff.files.filter(file=>paths.includes(file.path)).map(file=>excerptOf(file,!0)):diff.files.slice(0,1).map(file=>excerptOf(file,!1)),cited=refs.filter(one=>one.kind==="screenshot").map(one=>one.ref),pictures=cited.length>0?shots.filter(shot=>cited.includes(shot.path)):shots,notes=refs.filter(one=>one.kind==="manual-review").map(one=>one.ref.trim()).filter(one=>one!=="");return{id:row.id,statement:row.statement,words:personCheckWords(row.statement),note:notes.length===0?null:notes.join(" "),excerpts:files.filter(one=>one.lines.length>0).slice(0,3),shots:pictures.slice(0,4).map(shot=>({src:`/r/${runId}/evidence/${shot.artifactId}`,href:`/r/${runId}/evidence/${shot.artifactId}`,caption:shot.caption,...shot.sha256===void 0?{}:{image:{run:runId,artifact:shot.artifactId,sha256:shot.sha256}}}))}})}export function hardBlockerOf(assignment){return assignment?.readiness?.blockers.find(one=>one.key==="check-failed"||one.key==="high")?.message??null}export function needActionOf(assignment,status,csrf,returnTo,result){if(assignment===null||status===null||status.headline!=="Needs you"||status.need==null||result!==void 0&&hardBlockerOf(assignment)!==null)return null;const action=assignment.primaryAction,task=taskLinkOf({task:assignment.rootId}),rebuild={href:null,confirm:null,rebuild:{action:`${task}/requeue`}};if(action?.code==="retry-task"&&status.need.key==="rebuild"&&csrf!=="")return{label:status.need.action.label,...rebuild};if(result!==void 0){const exception=result.refuted===!0||(result.exception??!result.humanReview);if((status.need.key==="review-result"||result.refuted===!0)&&!result.accepted&&csrf!=="")return{label:exception?"Accept with exception":"Accept result",href:null,confirm:null,accept:{action:result.action,run:result.run,returnTo,note:exception?"Why is this safe to accept?":null}};const here=(action?.code==="open-result"||action?.code==="inspect-run")&&action.target.runId===result.run;if(here&&csrf!==""&&!result.accepted&&result.humanReview)return{label:"Accept result",href:null,confirm:null,accept:{action:result.action,run:result.run,returnTo,note:null}};if(here&&csrf!==""&&result.rebuildable===!0)return{label:NEEDS.rebuild.action.label,...rebuild};if(status.need.key==="review-result"||here)return null}const confirm=action?.code==="recheck-stopped"&&action.target.runId!==null&&csrf!==""?{action:`${task}/recheck-stopped`,run:action.target.runId,returnTo}:null;return{label:status.need.action.label,href:assignmentActionHref(assignment)??task,confirm}}function conciseOutcomeOf(conclusion){const flat=oneLineOf(conclusion,2e3),sentence=/^[\s\S]*?[.!?](?=\s|$)/.exec(flat)?.[0]??flat;return(sentence.length<=140?sentence:`${sentence.slice(0,140).replace(/\s+\S*$/,"")}…`).trim()}export function runAgentWords(route){if(route==null)return null;const role=route.phase==="plan"?"planner":route.phase==="build"?"builder":route.phase==="repair"?"repair":"reviewer",how=route.chosen==="fallback"?"the approved fallback":route.chosen==="override"?"chosen by an approver":route.chosen==="pinned"?"pinned":route.chosen==="legacy"?"from the approved profile":"recommended";return`${route.provider}${route.model===null?"":` · ${route.model}`} as the ${role} — ${how}`}const EMPTY_AGENT_REPORT=Object.freeze({decisions:[],assumptions:[],notDone:[],risks:[]});function quotedNoteOf(note){const flat=note.replace(/\s+/g," ").trim();return flat.length<=280?flat:`${flat.slice(0,279).trimEnd()}…`}export function completionReceiptData(view,taskId,place,standing=receiptStatusOf(view),assignment=null,headline=!0){const current=assignment?.receipt?.runId===view.runId?assignment:null,status=(current===null?null:assignmentPresentationOf(current))?.status??standing,stored=receiptStatusOf(view,null),inReview=REVIEW_TOKENS.has(status.token),facts=view.facts,shown=view.screenshots.filter(one=>one.problem===null),unavailable=view.screenshots.length-shown.length,diffWords=view.diff===null||"problem"in view.diff?"Change summary unavailable":view.diff.fileCount===0?"No repository changes":`${view.diff.fileCount} file${view.diff.fileCount===1?"":"s"} · +${view.diff.additions} −${view.diff.deletions}`+(view.diff.binaryCount>0?` · ${view.diff.binaryCount} binary`:"")+(view.diff.filesTruncated?" · list shortened":""),criteriaWords=facts.checks===null?"No requirements set":`${facts.checks.passed}/${facts.checks.total} requirements met`,attention=current===null?[...facts.evidenceProblems,...view.caveats]:[],resultHref=status.token==="review-failed"?reviewHref(taskId):place==="chat"?chatResultHref(taskId,view.runId,status.action?.kind==="open-review"?"checks":"summary"):statusActionHref(status,taskId,view.runId,view.publication?.prUrl??null)??`/r/${view.runId}`,rawSummary=view.summary??(view.outcome==="no-change"?"The agent found that no repository change was needed.":"The build finished without a concise handoff."),shortSummary=conciseOutcomeOf(rawSummary);return{runId:view.runId,attributes:{"data-card-kind":"result-receipt",...resultFactsAttributeMap(facts)},heading:receiptHeadingOf(view.outcome,view.publication,view.role),headline,statusToken:status.token,statusTone:status.tone,statusLabel:status.label,statusDetail:status.detail,report:view.report===null?null:view.report.ok?{state:"ok",title:view.report.title,summary:oneLineOf(view.report.summary,240)}:{state:"problem",problem:view.report.problem},screenshots:view.report!==null?[]:shown.slice(0,4).map(shot=>({artifactId:shot.artifactId,caption:shot.caption})),totalScreenshots:view.screenshots.length,unavailableScreenshots:unavailable,summary:shortSummary,fullSummary:view.summary!==null&&view.summary!==conciseOutcomeOf(view.summary)?view.summary:null,primaryHref:resultHref,primaryLabel:status.action?.label??"Open result",publicationFailedNote:view.publication?.state==="failed",caveats:attention.map(plainReasonWords),coverage:view.coverage.length===0?null:{lines:[...view.coverage],secondary:current!==null||view.coverageSecondary},publicationState:facts.publicationState,publicationWords:facts.publicationWords,inReview,criteriaWords,criteriaSub:stored.tone==="problem"?"agent-words":stored.token==="agent-attested"?"agent-unverified":"approved-plan",diffWords,diffSub:facts.head===null?"no commit recorded":`head ${facts.head.slice(0,7)} · ${facts.headSource??""}`,secondaryLink:place==="task"?{href:taskChatHref(taskId),label:"Discuss in chat →"}:{href:`/r/${view.runId}`,label:"Full build record →"},reviewHref:reviewHref(taskId)}}export function resultPanelData(detail,o){const{run,receipt,proof,terminal,handoff}=detail,facts=receipt.facts,current=detail.assignment?.receipt?.runId===run.id?detail.assignment:null,followUps=detail.followUps??null,resultLinks={result:o.hrefFor("summary"),checks:o.hrefFor("checks"),pullRequest:`${taskHref(detail.rootId??detail.taskId)}#merge`,...followUps!==null&&(followUps.quick||followUps.full)&&o.csrf!==""?{runChecks:`${o.hrefFor("checks")}#follow-ups`}:{}},presentation=current==null?null:assignmentPresentationOf(current,{additionalAttention:[...facts.evidenceProblems,...receipt.caveats],...detail.publication===null?{}:{pullRequest:pullRequestFactOf({...detail.publication,lastCheckState:detail.ciFailing?"failing":detail.publication.lastCheckState})},evidence:{damaged:facts.evidenceHealth.damaged,missing:facts.evidenceHealth.missing,shortened:facts.evidenceHealth.shortened},links:resultLinks}),taskStatus=presentation?.taskStatus??null,status=presentation?.status??resultHeadlineOf(receiptStatusOf(receipt)),stored=receiptStatusOf(receipt,null),humanReview=manualReviewOnly(proof===null?null:{...proof,verdict:proof.verdict??""}),need=needActionOf(current,taskStatus,o.csrf,o.returnTo,{accepted:proof?.accepted!=null,humanReview,run:run.id,action:`${taskHref(detail.taskId)}/accept-proof`,refuted:proof?.verdict==="refuted",exception:current?.receipt==null?!humanReview:owedAcceptance(current.receipt,current.readiness?.blockers??[])==="exception",rebuildable:proof?.accepted==null&&proof?.verdict!=="verified"&&proof?.verdict!=="attested"&&!(detail.publication!==null&&["pushed","opened"].includes(detail.publication.state))}),directAssessment=proof?.matrix.some(row=>row.assessment!==void 0)===!0,awaitingGoalReview=directAssessment&&proof?.reasons.length===1&&proof.reasons[0]===GOAL_ASSESSMENT_PENDING,assessmentReasons=directAssessment?new Set(proof.matrix.flatMap(row=>row.review?[`${row.review.author} ${row.review.judgement==="contradicts"?"contradicts":"needs more evidence for"} criterion "${row.id}": ${row.review.note}`]:[])):new Set,physicalReasons=receipt.reasons.filter(reason=>!assessmentReasons.has(reason)),runId=run.id,shots=proof?.screenshots??[],shown=shots.filter(one=>one.problem===null),unavailableShots=shots.filter(one=>one.problem!==null),stat=terminal?.stat??null,statOk=stat!==null&&!("problem"in stat),patch=terminal?.patch??null,patchOk=patch!==null&&!("problem"in patch),lead=resultLeadOf({role:run.role,report:receipt.report!==null,screenshots:shown.length,diff:patchOk&&patch.text.trim()!==""||statOk&&stat.fileCount>0}),tabHref=tab=>o.hrefFor(tab),publication=detail.publication,prUrl=publication===null?null:safePrUrl(publication.prUrl),attention=[],missingVerdictNamed=o.headStatus!==!1&&status.token==="verification-needed"&&receipt.verdict===null&&receipt.reasons.length===0;current==null&&!humanReview&&!awaitingGoalReview&&(!directAssessment||physicalReasons.length>0)&&!missingVerdictNamed&&stored.token!=="evidence-damaged"&&(stored.tone==="problem"||stored.tone==="attention")&&attention.push(stored.token==="check-unreadable"||receipt.verdict==="verified"&&stored.token==="checks-failed"?stored.detail:verificationExplanation(receipt.verdict,physicalReasons)),presentation!==null&&attention.push(...presentation.attention.map(one=>one.detail).filter(d=>!assessmentReasons.has(d))),current==null&&attention.push(...facts.evidenceProblems),detail.outsideTouches.length>0&&attention.push(`${detail.outsideTouches.length} changed file${detail.outsideTouches.length===1?"":"s"} outside the approved paths: ${detail.outsideTouches.join(", ")}.`),current==null&&attention.push(...receipt.caveats.filter(caveat=>!historicalAssessmentReason(caveat)&&!attention.some(problem=>problem.includes(caveat)))),attention.push(...(handoff?.followUps??[]).map(one=>`Follow-up: ${one}`));const automatic=detail.automaticReview??null;if(automatic!==null&&automatic.sentBackAs===null){const reviewed=[...automatic.state==="not-reviewed"?[`Not reviewed: ${automatic.reason??"the automatic review did not finish"}.`]:[],...automatic.high.map(one=>`Review: ${findingWords(one)}`)];for(const line of reviewed)attention.includes(line)||attention.push(line)}publication!==null&&publication.state==="failed"&&taskStatus===null&&attention.push(`Publication failed after ${publication.attempts} attempt${publication.attempts===1?"":"s"}${publication.lastError===null?"":` — ${oneLineOf(publication.lastError,200)}`}. No pull request or merge is recorded.`),detail.ciFailing&&publication!==null&&taskStatus===null&&attention.push(`CI is failing on PR #${publication.prNumber} at the last check.`);const personChecks=proof===null||proof.accepted!==null||detail.landed===!0||detail.assignment?.state==="complete"&&detail.assignment.completion?.person!==void 0?[]:[...proof.matrix.filter(row=>row.state==="manual-review").map(row=>personCheckWords(row.statement)),...proof.matrix.length>0?[]:proof.reasons.filter(reason=>manualReviewCriterionOf(reason)!==null).map(()=>personCheckWords(null))],acceptable=personChecks.length>0&&humanReview&&o.csrf!==""&&(current!=null||detail.assignment==null),youCheck=personChecks.length===0?null:{lines:[...new Set(personChecks)],items:personCheckItems(proof,patchOk?patch.text:null,shown,runId),accept:acceptable&&need?.accept==null?{action:`${taskHref(detail.taskId)}/accept-proof`,run:run.id,returnTo:o.returnTo}:null},conclusion=plainConclusionOf(receipt.summary??(run.outcome==="no-change"?"The agent found that no repository change was needed.":"The build finished without a concise handoff.")),outcome=conciseOutcomeOf(conclusion),report=receipt.report,evidenceSources=[...report!==null?[report.ok?`verified report${report.truncated?" (shortened)":""}`:"report (unverifiable)"]:[],...patch!==null?[patchOk?`saved diff${patch.truncated?" (shortened)":""}`:"diff (can't be checked)"]:[],...proof===null?[]:proof.proofProblem!==null?["agent report (unreadable)"]:proof.proof!==null?["agent report"]:[],...proof?.checkLog!==null&&proof?.checkLog!==void 0?[proof.checkLog.problem!==null?"check log (unverifiable)":`check log${proof.checkLog.truncated?" (shortened)":""}`]:[],...shots.length>0?[`${shown.length} validated screenshot${shown.length===1?"":"s"}${unavailableShots.length>0?`, ${unavailableShots.length} unavailable`:""}`]:[]],agent=runAgentWords(detail.route),tabCounts={summary:"",changes:statOk?stat.fileCount===0?"none":`${stat.fileCount} file${stat.fileCount===1?"":"s"}`:terminal===null?"none":"",checks:""},heading=receiptHeadingOf(run.outcome,receipt.publication,run.role),storedLinkText=(what,truncated)=>truncated?`Download the stored part of the ${what} (shortened at storage — not the full ${what})`:`Download the ${what}`,detailLinks=[];o.place!=="run"&&detailLinks.push({label:"Full build record →",href:`/r/${runId}`}),o.place!=="review"&&detailLinks.push({label:"Open result →",href:reviewHref(detail.taskId)}),o.place!=="chat"&&detailLinks.push({label:"Discuss in chat →",href:taskChatHref(detail.rootId??detail.taskId)}),detailLinks.push({label:"Task overview →",href:taskHref(detail.rootId??detail.taskId)});const summaryData={lead,report:lead!=="report"?null:report===null?{state:"missing"}:report.ok?{state:"ok",title:report.title,artifactId:report.artifactId,truncated:report.truncated,document:report.document,followUps:report.followUps,taskHref:taskHref(detail.rootId??detail.taskId),items:[...report.items],shots:report.shots.map(s=>({file:s.file,artifactId:s.artifactId,caption:s.caption,problem:s.problem}))}:{state:"problem",problem:report.problem},screenshots:lead!=="screenshots"?[]:shown.map(shot=>({artifactId:shot.artifactId,caption:shot.caption,...shot.sha256===void 0?{}:{sha256:shot.sha256},commentable:detail.canAnnotate&&o.csrf!==""&&shot.sha256!==void 0})),unavailableShots:unavailableShots.map(one=>({path:one.path,problem:one.problem??""})),filesLead:lead!=="changes"?null:{paths:detail.files.slice(0,6).map(one=>one.path),more:Math.max(0,detail.files.length-6),changesHref:tabHref("changes")},noChangeNote:lead==="summary"&&run.outcome==="no-change"?`The agent found that no repository change was needed${statOk&&stat.fileCount===0?"; the saved diff is empty":""}.`:null,agentAccount:conclusion===outcome&&(handoff===null||handoff.changes.length===0&&handoff.verification.length===0)&&(proof?.proof==null||proof.proof.caveats.length===0)?null:{conclusion:conclusion!==outcome?conclusion:null,changes:handoff===null?[]:[...handoff.changes],verification:handoff===null?[]:[...handoff.verification],reportNotes:proof?.proof==null?[]:[...proof.proof.caveats]},followUps:automatic===null?[]:automatic.followUps.map((one,index)=>({severity:one.severity==="MEDIUM"?"Medium":"Low",file:one.file,line:one.line,scenario:one.scenario,sendAction:o.csrf===""?null:`${taskHref(detail.taskId)}/follow-through`,pointer:`${automatic.run}:${automatic.high.length+index+1}`})),details:{runId,runner:run.runner??"",provider:run.provider,agent,finishedAt:run.finishedAt,base:facts.base,head:facts.head,headSource:facts.headSource,evidenceSources,publication:{state:facts.publicationState,words:facts.publicationWords,prNumber:publication?.prNumber??null,prUrl,ciState:detail.ciFailing?"failing":publication?.lastCheckState??"none",lastCheckAt:publication?.lastCheckAt??null,ciFailing:detail.ciFailing},links:detailLinks}},parsedDiff=patchOk&&patch.text.trim()!==""?parseReviewDiff(patch.text):null,parsedStructuredDiff=parsedDiff!==null&&parsedDiff.files.some(file=>file.hunks.length>0),diffStats=statOk?new Map(stat.files.map(one=>[one.path,one])):new Map,changesData={noTerminal:terminal===null,scout:run.role==="scout",stat:stat===null?null:statOk?{baseShort:stat.base.slice(0,7),headShort:stat.head.slice(0,7),fileCount:stat.fileCount,additions:stat.additions,deletions:stat.deletions,binaryCount:stat.binaryCount,filesTruncated:stat.filesTruncated}:{problem:stat.problem},outsideTouches:[...detail.outsideTouches],files:detail.files.map(file=>({path:file.path,additions:file.additions,deletions:file.deletions,renamedFrom:file.renamedFrom,anchor:file.anchor,editorHref:detail.editor===null?null:editorFileHref(detail.editor.worktree,file.path),outsideTouches:file.outsideTouches,cited:file.cited,priorityBand:file.priority.band,priorityReasons:[...file.priority.reasons]})),canAnnotate:detail.canAnnotate,hasEditorLinks:detail.editor!==null,diff:terminal===null||patch===null?{kind:"none"}:patchOk?patch.text.trim()===""?{kind:"empty"}:!parsedStructuredDiff||parsedDiff===null?{kind:"raw",text:patch.text,truncated:patch.truncated,downloadHref:`/r/${runId}/evidence/${patch.artifactId}`,downloadLabel:storedLinkText("diff",patch.truncated)}:{kind:"files",files:parsedDiff.files.map((one,fileIndex)=>{const counts=diffStats.get(one.path),isLazy=fileIndex>0&&one.hunks.length>0;return{path:one.path,oldPath:one.oldPath,anchor:detail.fileAnchors.get(one.path)??null,additions:counts?.additions??null,deletions:counts?.deletions??null,lazyHref:isLazy?diffFileHref(runId,one.path):null,hunks:isLazy?[]:one.hunks}}),commentable:detail.canAnnotate,patchTruncated:patch.truncated,linesTruncated:parsedDiff.linesTruncated,downloadHref:`/r/${runId}/evidence/${patch.artifactId}`,downloadLabel:storedLinkText("diff",patch.truncated)}:{kind:"problem",problem:patch.problem}},reviewerFindingData=one=>({severity:one.severity??"note",isProblem:one.severity==="problem",path:one.path,line:one.line,note:one.note,author:one.author,canRequestChange:!isRevisionFeedback(one)&&detail.canAnnotate&&o.csrf!==""}),checkKinds={check:"Checks","changed-path":"Changed files",screenshot:"Screenshots","manual-review":"You check"},releaseCheckBacking=current?.receipt==null?void 0:checkBackingOf(current.receipt.checks),verdictShown=proof===null?void 0:current?.receipt!=null?receiptChecksOf(current.receipt):receipt.checks===void 0?void 0:approvedCheckOf(proof.verdict,proof.reasons,receipt.checks),verdictUnreadNow=proof!==null&&proof.verdict==="verified"&&verdictShown!==void 0&&verdictShown?.status!=="passed"&&!humanReview,covData=proof!==null&&proof.matrix.some(row=>row.review!=null||row.assessment!==void 0)?semanticCoverage(proof.matrix,proof.qualityMode):null,screenshotRequiredFlag=proof!==null&&proof.matrix.some(one=>one.requiredEvidence.includes("screenshot")),checksData={previousAssessment:proof===null?detail.reviewerFindings.map(reviewerFindingData):[],noChangeNoDirect:run.outcome==="no-change"&&!directAssessment,hasProof:proof!==null,verdictLine:proof===null?null:proof.verdict!==null&&!directAssessment?{token:dispatchStatusToken(proof.verdict),words:humanReview?"At completion: Human review required for the requirements below.":verdictUnreadNow?completionWords(proof.verdict,proof.reasons,verdictShown):`At completion: ${verificationExplanation(proof.verdict,proof.reasons)}`,checkNow:verdictUnreadNow?approvedCheckStateOf(verdictShown)??"unreadable":null}:proof.verdict===null&&run.outcome!=="no-change"?{token:"none",words:"No verification result is available for this build.",checkNow:null}:null,acceptedLine:proof?.accepted==null?null:{humanReview,by:proof.accepted.by,at:proof.accepted.at,note:proof.accepted.note},signedCriteriaCount:detail.signedCriteria,matrix:proof===null?[]:proof.matrix.map(row=>{const state=row.state,awaitingAssessment=row.assessment?.evidenceState==="pass"&&row.review===null,confirmed=row.assessment!==void 0&&state==="pass",label=requirementWordOf(row,proof.verdict,releaseCheckBacking),badgeClass=label==="Met"?"badge-done":label==="You check"?"badge-manual-review":"badge-note",detailLines=row.detail.filter(line=>!(row.assessment&&row.review&&line===`${row.review.author} ${row.review.judgement==="contradicts"?"contradicts":"needs more evidence for"} criterion "${row.id}": ${row.review.note}`)&&!(state==="manual-review"&&/^criterion "[^"\n]+" requires manual-review evidence — an operator must accept it before this can verify$/.test(line))),review=row.review,coverage=row.coverage,answered=row.answered??[];return{id:row.id,statement:row.statement,state,label,badgeClass,awaitingAssessment,confirmed,upheldOnly:review?.judgement==="upholds"&&!confirmed,detail:detailLines,review:review===null?null:{judgement:review.judgement,note:review.note,author:review.author},coverage:coverage===void 0?null:{state:coverage.state,gaps:[...coverage.gaps],...coverage.priorSupport===void 0?{}:{priorSupport:coverage.priorSupport},words:coverageStateWords(coverage),...coverage.assets===void 0?{}:{assets:coverage.assets}},requiredLabels:row.requiredEvidence.map(kind=>checkKinds[kind]).join(", ")||"Nothing named",answered:Object.entries(checkKinds).flatMap(([kind,kindLabel])=>{const refs=answered.filter(one=>one.kind===kind);return refs.length===0?[]:[{kindLabel,refs:refs.map(ref=>{const anchor=ref.kind==="changed-path"?detail.fileAnchors.get(ref.ref)??null:null,artifactId=anchor!==null?null:proof.matrixLinks?.get(`${ref.kind}:${ref.ref}`)??(ref.kind==="changed-path"?proof.matrixLinks?.get("changed-path:*"):void 0)??null;return{ref:ref.ref,anchor,artifactId}})}]})}}),semanticCoverage:covData===null?null:{satisfied:covData.satisfied===!0?"satisfied":covData.satisfied===null?"unsettled":"unsatisfied",policy:covData.policy,upheldCount:covData.upheld.length,total:covData.total},reviewConflict:proof!==null&&reviewConflict(proof.matrix,proof.machineVerdict,proof.verdict),repairChain:proof?.repairChain??null,reviewerFindings:proof===null?[]:detail.reviewerFindings.map(reviewerFindingData),proofProblem:proof?.proofProblem??null,checkLog:proof===null?null:proof.checkLog===null?{state:"none",off:current?.receipt?.checks.level==="off"}:proof.checkLog.problem!==null?{state:"damaged",problem:proof.checkLog.problem}:{state:"ok",truncated:proof.checkLog.truncated,bytesStored:proof.checkLog.bytesStored,bytesOriginal:proof.checkLog.bytesOriginal,lines:proof.checkLog.text.split(`
4
- `),downloadHref:`/r/${runId}/evidence/${proof.checkLog.artifactId}`,downloadLabel:storedLinkText("check log",proof.checkLog.truncated)},agentChecks:proof===null?null:{hideWhenEmpty:directAssessment,items:(proof.proof?.checks??[]).map(one=>({command:one.command,exitCode:one.exitCode,summary:one.summary}))},screenshots:proof===null?null:{hideWhenEmpty:directAssessment&&!screenshotRequiredFlag,required:screenshotRequiredFlag,leadIsScreenshots:lead==="screenshots",totalCount:shots.length,shownCount:shown.length,unavailableCount:unavailableShots.length,shown:shown.map(shot=>({artifactId:shot.artifactId,caption:shot.caption,...shot.sha256===void 0?{}:{sha256:shot.sha256},commentable:detail.canAnnotate&&o.csrf!==""&&shot.sha256!==void 0}))},caveats:proof===null?null:{hideWhenEmpty:directAssessment,items:[...receipt.caveats]},followUps:followUps!==null&&run.role==="builder"?(()=>{const canCheck=followUps.quick||followUps.full,batchHow=one=>{const peers=one.batch?.members.filter(member=>member.run!==runId).map(member=>member.task)??[];return one.batch?.mode==="together"&&peers.length>0?` together with ${peers.join(", ")}`:one.batch?.mode==="split"?" on its own after its batch failed":one.batch?.mode==="conflict"?" on its own (it conflicted with another result)":""};return{checks:followUps.checks.map(one=>({state:one.state,text:`${CHECK_LEVEL_WORDS[one.level]} checks ${one.why==="batch"&&one.state==="waiting"?"waiting to check with other results":FOLLOW_UP_WORDS[one.state]}${batchHow(one)}${one.exitCode===null||one.state==="passed"?"":` (exit ${one.exitCode})`}`,batchMode:one.why==="batch"?one.batch?.mode??"waiting":null,commitShort:(one.tested??one.head).slice(0,7),meta:`${one.why==="pull-request"?"for the pull request":one.why==="batch"?"batch check":one.actor}${one.note===null?"":` · ${one.note}`}`,logHref:one.logArtifactId===null?null:`/r/${runId}/evidence/${one.logArtifactId}`})),quick:followUps.quick,full:followUps.full,canAct:canCheck&&o.csrf!=="",action:`/r/${runId}/checks`,returnTo:o.returnTo,testsTask:followUps.testsTask,addTestsAction:followUps.testsTask===null&&o.csrf!==""?`/r/${runId}/add-tests`:null,setupHref:!canCheck&&followUps.repo!==null?`/settings/checks?repo=${encodeURIComponent(followUps.repo)}`:null}})():null,agentOwnAccount:!directAssessment&&handoff!==null?[...handoff.verification]:[],reviewRetry:o.reviewRetry==null||o.reviewRetry.state==="unrequested"?null:{state:o.reviewRetry.state,attempts:o.reviewRetry.attempts.map(one=>({attempt:one.attempt,outcome:one.outcome,runId:one.runId,reason:one.reason}))}},commentData=one=>{const shot=one.image==null?void 0:shots.find(s=>s.artifactId===one.image.artifact&&s.sha256===one.image.sha256&&one.image.run===runId&&s.problem===null),dropAction=one.image!=null&&o.csrf!==""&&(detail.unusableImageNotes??[]).includes(one.id)?`/r/${runId}/comment`:null;return{id:one.id,path:one.path,line:one.line,editorHref:one.path===null||detail.editor===null?null:editorFileHref(detail.editor.worktree,one.path,one.line),note:one.note,author:one.author,createdAt:one.createdAt,image:one.image==null?null:{run:runId,artifact:one.image.artifact,caption:shot===void 0?null:shot.caption,dropAction,dropTab:o.tab,returnTo:o.returnTo}}},requestData=detail.skillTest||detail.landed===!0?null:{runId,comments:detail.comments.map(commentData),reviseFromComments:detail.comments.length>0&&o.csrf!==""&&!detail.canAnnotate?{action:`/r/${runId}/revise`,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),returnTo:o.returnTo}:null,pastComments:(detail.pastComments??[]).map(commentData),revisions:detail.revisions.map(one=>({id:one.id,title:one.title,approved:one.approved,standing:one.standing,tone:one.tone})),availability:o.csrf===""?"signed-out":detail.canAnnotate?"ok":terminal===null?"no-diff":"unverified-diff",chatHref:taskChatHref(detail.rootId??detail.taskId),form:o.csrf!==""&&detail.canAnnotate?{action:`/r/${runId}/comment`,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),recordedKeys:[...detail.comments,...detail.pastComments??[]].filter(one=>one.sourceKey?.startsWith(`review:${o.user}:`)).map(one=>one.sourceKey.slice(`review:${o.user}:`.length)).join(","),noteMaxLength:LIMITS.note,noted:o.noted,buildNowOnSendBack:detail.buildNowOnSendBack===!0,returnTo:o.returnTo,tab:o.tab,requestToken:o.requestToken}:null};return{attributes:{"data-result-panel":"","data-result-place":o.place,"data-result-lead":lead,"data-result-task":detail.rootId??detail.taskId,"data-result-user":o.user,...resultFactsAttributeMap(facts)},back:o.back,failed:o.failed??null,showHeadStatus:o.headStatus!==!1,showPanelAction:o.action!==!1,headVerdict:{hasCurrentOutcome:!(current==null||o.place==="review"&&(current.state==="ready-to-check"||current.state==="complete")),statusToken:status.token,status:taskStatus},heading,outcome,status:taskStatus,reviewHistory:REVIEW_TOKENS.has(status.token)?status.detail:null,attention:attention.filter(one=>!shortenedMaterialReason(one)).map(plainReasonWords),youCheck,requirements:proof===null||proof.verdict==="refuted"?null:requirementsOf(proof.matrix),limits:attention.filter(one=>shortenedMaterialReason(one)),tabs:RESULT_TABS.map(tab=>({key:tab.key,label:tab.key==="checks"&&proof?.matrix.some(row=>row.assessment!==void 0)?"Requirements":tab.label,count:tabCounts[tab.key],href:o.hrefFor(tab.key),active:tab.key===o.tab})),summary:summaryData,changes:changesData,checks:checksData,history:detail.historyData??null,learning:detail.learningData??null,request:requestData,canRequest:detail.canAnnotate&&o.csrf!==""&&detail.landed!==!0,sendBack:detail.skillTest||!detail.canAnnotate||o.csrf===""||detail.landed===!0?null:{action:`/r/${runId}/comment`,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),request:o.requestToken},need,requestQuiet:detail.canAnnotate&&o.csrf!==""&&detail.comments.length===0&&(detail.pastComments?.length??0)===0&&detail.revisions.length===0}}function cockpitStatusOf(view){if(view.run===null||view.detail===null)return view.assignment===null?resultHeadlineOf(resultStatusOf(null,null)):assignmentPresentationOf(view.assignment).status;const receiptStatus=receiptStatusOf(view.detail.receipt);return view.assignment!==null?assignmentStatusOf(assignmentWithEvidence(view.assignment,receiptStatus,view.run.id)):resultHeadlineOf(receiptStatus)}function reviewNextActionOf(view,csrf,back){const run=view.run,detail=view.detail;return run===null||detail===null?{kind:"inspect-task",title:"No build to review",detail:"This task was accepted without a build record.",control:{kind:"link",label:"Open the task",href:taskHref(view.taskId)}}:detail.ciFailing&&csrf!==""?{kind:"draft-repair",title:"CI is failing on its pull request",detail:`Toolroll confirmed the failure. ${SEND_BACK_PUBLISHED}`,control:{kind:"post",action:`/r/${run.id}/draft-repair`,label:"Send back",fields:{}}}:detail.comments.length>0&&csrf!==""?{kind:"revise",title:`${detail.comments.length} note${detail.comments.length===1?"":"s"} ready`,detail:SEND_BACK_UNPUBLISHED,control:{kind:"post",action:`/r/${run.id}/revise`,label:"Send back",fields:{batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest)},returnTo:back??reviewHref(view.taskId)}}:null}export function reviewCockpitDetailData(view,csrf,noted,canRetryReview,tab,user,host={kind:"review"}){const run=view.run,proof=view.detail?.proof??null,accepted=proof?.accepted!==null&&proof?.accepted!==void 0,status=cockpitStatusOf(view),intent=view.intent,intentView=intent===null?null:{approval:intent.approval.approved?`Approved by ${intent.approvedBy??"an approver"}`:intent.approval.reason==="changed"?"Edited after approval. The words below are the current plan, not the approved one.":"Never approved. The result was built without an approved plan.",approvedAt:intent.approval.approved?intent.approval.at??null:null,goal:intent.goal,outOfScope:intent.outOfScope,touches:[...intent.touches],plan:view.plan===null?null:{revision:view.plan.revision,shaShort:view.plan.sha256.slice(0,7),approach:view.plan.approach}},selected={taskId:view.taskId,title:view.title,project:view.repo===null?null:projectName(view.repo),build:run===null?null:run.id,taskHref:taskHref(view.taskId),chatHref:taskChatHref(view.taskId),status:{label:status.label,tone:status.tone,token:status.token},problem:view.detail===null?view.historyProblem:null,next:reviewNextActionOf(view,csrf,host.kind==="task"&&run!==null?`${host.base}&run=${run.id}`:host.kind==="run"&&run!==null?`/r/${run.id}?record=1`:void 0),complete:null,decision:null,checks:null,intent:intentView,noRun:null,panel:null,notes:view.notes.map(one=>({author:one.author,at:one.createdAt,note:one.note})),agentReport:run===null||view.detail===null?null:view.detail.handoff?.report??EMPTY_AGENT_REPORT,youSaid:(view.youSaid??[]).map(one=>({kind:one.kind,author:one.author,you:one.author===user,at:one.at,note:quotedNoteOf(one.note),question:one.question===null?null:quotedNoteOf(one.question)})),efficiency:view.efficiency??null,network:view.network??null,timing:view.timing??null,acts:{primary:null,secondary:null,line:null},runChecks:null,mismatch:null,record:run===null?null:{build:run.id,href:`/r/${run.id}?record=1`,facts:[{label:"Agent",value:[run.provider,run.model].filter(Boolean).join(" · ")},{label:"Builder",value:run.runner},...view.checkRan===void 0||view.checkRan===null?[]:[{label:"Checks",value:view.checkRan}],...run.branch===null?[]:[{label:"Branch",value:run.branch}],...run.finishedAt===null?[]:[{label:"Finished",value:when(run.finishedAt)}],...run.ranMinutes===null?[]:[{label:"Ran",value:`${run.ranMinutes} min`}]]}};if(run===null||view.detail===null)return{...selected,noRun:"This task has no finished build record, so there are no captured changes or checks to review."};const at=(section="summary")=>host.kind==="task"?`${host.base}&run=${run.id}${section==="summary"?"":`&section=${section}`}`:host.kind==="run"?`/r/${run.id}?record=1${section==="summary"?"":`&tab=${section}`}`:taskLinkOf({task:view.taskId,run:run.id,section}),assignment=view.assignment===null?null:assignmentWithEvidence(view.assignment,receiptStatusOf(view.detail.receipt),run.id),saved=assignment?.receipt?.checks,checks=saved===void 0||assignment?.receipt==null?void 0:{...saved,...receiptChecksOf(assignment.receipt),detail:saved.detail},own=taskLinkOf({task:view.taskId,run:run.id}),ownOr=href=>href===own||/^[&#]/.test(href.slice(own.length))&&href.startsWith(own)?href.slice(own.length):null,failure=view.failure==null?null:{line:view.failure.line,evidence:view.failure.evidence,suggestion:view.failure.suggestion,retry:view.failure.retry,link:view.failure.link===null||ownOr(view.failure.link.href)!==null&&!view.failure.link.href.includes("#")?null:host.kind==="task"&&ownOr(view.failure.link.href)?.startsWith("&section=")===!0?{...view.failure.link,href:`${host.base}&run=${run.id}${ownOr(view.failure.link.href)}`}:host.kind==="run"&&ownOr(view.failure.link.href)?.startsWith("&section=")===!0?{...view.failure.link,href:`/r/${run.id}?record=1${ownOr(view.failure.link.href).replace(/^&section=/,"&tab=")}`}:view.failure.link,...view.failure.acceptAnyway==null?{}:{acceptAnyway:{...view.failure.acceptAnyway,returnTo:at()}}},panelData=resultPanelData(view.detail,{...host.kind==="task"&&host.alone===!0&&failure!==null?{failed:{line:failure.line,evidence:failure.evidence,link:failure.link}}:{},place:host.kind==="run"?"run":"review",tab,csrf,user,noted,requestToken:createHash("sha256").update(`${view.taskId}:${run.id}:${user}`).digest("hex").slice(0,32),hrefFor:one=>at(one),returnTo:at(),back:null,reviewRetry:view.reviewRetry,headStatus:!1,action:!1});host.kind==="task"&&(panelData.attributes={...panelData.attributes,"data-result-param":"section"});const hardStop=hardBlockerOf(assignment)??view.detail.completeRefusal??null,blocked=hardStop??cantAcceptYetOf(proof?.verdict??null,proof?.reasons??[],accepted),youCheck=panelData.youCheck,shared=accepted||assignment?.receipt==null?null:owedAcceptance(assignment.receipt,assignment.readiness?.blockers??[]),owed=accepted?null:youCheck?.accept!=null||shared==="person-check"?{note:null}:shared==="exception"||blocked===WORKSPACE_ACCEPT_NEEDS_REASON?{note:"Why is this safe to accept?"}:null,confirm=assignment?.state==="complete"&&assignment.completion!==null&&assignment.completion.person===void 0&&assignment.completion.historical!==!0&&assignment.completion.landed===void 0&&assignment.receipt!==null&&assignment.completion.digest===assignment.receipt.digest&&youCheck!=null,complete=hardStop===null&&(assignment?.state==="ready-to-check"||confirm)&&assignment?.receipt!=null&&canRetryReview&&csrf!==""?{action:`${taskHref(view.taskId)}/complete`,receipt:assignment.receipt.digest,run:run.id,accept:owed,...host.kind!=="review"?{returnTo:at()}:{}}:null,acceptsHere=complete!==null||panelData.need?.accept!=null||youCheck?.accept!=null,matrix=proof===null||proof.proofProblem!==null?[]:proof.matrix,unanswered=accepted||youCheck==null?[]:youCheck.items.length>0?youCheck.items.map(one=>one.statement===""?one.words:one.statement):youCheck.lines,base=acceptsHere?acceptWordsOf({checks:checks===void 0?null:{passed:"passed",failed:"failed",running:"running","not-run":"not-run",off:"off",stale:"unavailable",unreadable:"unavailable"}[approvedCheckStateOf(checks)],unmet:matrix.filter(row=>!["Met","You check",CHECKED_AT_RELEASE].includes(requirementWordOf(row,null,checks===void 0?void 0:checkBackingOf(checks)))).length,action:complete!==null?"complete":"accept",publishing:view.detail?.publishing??"other",proof:proof!==null&&proof.proofProblem===null&&(proof.proof!==null||proof.matrix.length>0)}):null,settled=base===null||blocked===null?base:{...base,label:"Accept",ready:!1},decision=settled===null?null:{sentence:RESULT_DECISION_SENTENCE,...settled,...acceptWithChecksOf(settled,{unanswered,notRight:[]}),base:{label:settled.label,ready:settled.ready,why:settled.why}},followUps=view.detail.followUps??null,checksRunning=checks?.running!=null||(followUps?.checks.some(one=>one.state==="waiting"||one.state==="running")??!1),runChecks=canRetryReview&&csrf!==""&&followUps!==null&&(followUps.full||followUps.quick)&&!checksRunning&&(checks===void 0||(checks.status==="not-run"||checks.status==="unavailable"||checks.status==="failed"&&assignment?.state==="complete")&&checks.release==null)?{action:`/r/${run.id}/checks`,level:followUps.full?"full":"quick",returnTo:at("checks")}:null,need=panelData.need,nextKind=selected.next?.kind,actFacts=failure!==null?{accept:null,runChecks:runChecks!==null,checksRunning,blocked:null,canRequest:!1,need:null,next:null,failed:{retry:failure.retry!==null,acceptAnyway:failure.acceptAnyway!==void 0}}:{accept:settled===null?null:{ready:settled.ready},runChecks:runChecks!==null,checksRunning,blocked,canRequest:panelData.canRequest&&panelData.request!==null,need:need===null||need.accept!=null?null:need.rebuild!=null?"rebuild":need.confirm!==null?"recheck-stopped":null,next:nextKind==="revise"||nextKind==="draft-repair"?nextKind:null,unanswered:settled===null?0:unanswered.length,notRight:0},acts=resultActsOf(actFacts),mismatch=failure!==null||proof===null||accepted||proof.verdict!=="refuted"?null:(()=>{const patch=view.detail?.terminal?.patch??null,files=patch===null||"problem"in patch?[]:parseReviewDiff(patch.text).files,hunkStart=new Map,changes=new Map(files.map(file=>{const shown=file.hunks[0]?.lines.filter(line=>line.newLine!==null&&line.kind!=="meta")??[];shown[0]?.newLine!=null&&hunkStart.set(file.path,shown[0].newLine);const added=shown.filter(line=>line.kind==="addition"),lines=(added.length>0?added:shown).map(line=>line.newLine);return[file.path,lines.length===0?null:{from:Math.min(...lines),to:Math.max(...lines)}]})),changesHref=at("changes"),found=reportMismatchesOf(proof.reasons,proof.proofProblem===null?proof.matrix:[],changes);return proof.proofProblem!==null&&found.push({text:`The saved report can't be read: ${proof.proofProblem}`,path:null,lines:null,inChanges:null,note:null,reason:proof.proofProblem}),found.length===0?null:{headline:evidenceProblemOf(proof.verdict,proof.reasons)==="mismatched"?MISMATCH_HEADLINE:null,rows:found.map(one=>({text:one.text,path:one.path,absent:one.inChanges===!1,lines:one.lines===null?null:one.lines.from===one.lines.to?`line ${one.lines.from}`:`lines ${one.lines.from}–${one.lines.to}`,href:one.path!==null&&one.inChanges===!0?`${changesHref}#${diffFileAnchor(one.path)}${hunkStart.has(one.path)?`-L${hunkStart.get(one.path)}`:""}`:one.note!==null&&(proof.proof?.caveats.length??0)>=one.note?`${at()}#report-note-${one.note}`:null,noteLabel:one.path===null&&one.note!==null?`The report, note ${one.note}`:null})),said:[...new Set([...proof.reasons,...found.map(one=>one.reason)].flatMap(reason=>[reason,plainReasonWords(reason)]))]}})();return{...selected,complete:failure===null?complete:null,decision:failure===null?decision:null,acts,actFacts,runChecks,mismatch,failure,panel:(()=>{const elsewhere=href=>href!==null&&!href.endsWith("#follow-ups")&&!new RegExp(`^/chat\\?task=[^&]+&result=${run.id}(?:&|$)`).test(href),shown=panelData.status===null?null:view.demo===!0?demoChecksOf(panelData.status):panelData.status,missed=proof===null||proof.proofProblem!==null?0:requirementsOf(proof.matrix)?.missed??0,panelStatus=shown===null?null:{...shown,details:shown.details.map(one=>({...one,href:elsewhere(one.href)?one.href:null,action:one.action!==null&&elsewhere(one.action.href)?one.action:null}))};return failure===null?{...panelData,status:panelStatus}:{...panelData,outcome:failure.line,need:null,youCheck:null,status:panelStatus===null?null:{...panelStatus,headline:"Failed",tone:"danger",sentence:failure.line,need:null,details:panelStatus.details.map(one=>one.key!=="requirements"||missed===0?one:{...one,text:`${missed} missed`,mark:"failed",action:null})},attention:panelData.attention.filter(one=>!(proof?.reasons??[]).includes(one)&&!(proof?.matrix??[]).some(row=>row.detail.includes(one)))}})(),...failure===null?{}:{status:{label:"Failed",tone:"problem",token:"failed"}},checks:checks===void 0?null:{detail:checks.detail,problem:checks.status==="failed"||checks.status==="unavailable",logHref:checks.logArtifactId===null?null:`/r/${run.id}/evidence/${checks.logArtifactId}`}}}export function reviewCockpitViewData(data){const{queue,selected,csrf}=data,elevated=queue.filter(one=>one.priority.band<2).length,detailSelected=selected===null?null:reviewCockpitDetailData(selected,csrf,data.noted,data.canRetryReview,data.tab,data.user);return{kind:"result",results:queue.map(row=>{const status=row.assignment==null?null:assignmentPresentationOf(row.assignment).status,reasons=row.priority.reasons;return{title:row.title,href:reviewHref(row.taskId,row.runId),at:row.completedAt,status:status===null?null:{label:status.label,tone:status.tone},notes:[...row.historyProblem?["History unavailable"]:status===null&&reasons.length>0?[reasons[0]]:[],...status!==null&&row.ciFailing?["CI is failing"]:[]],current:selected!==null&&selected.taskId===row.taskId,needsYou:row.priority.band<2}}),attention:elevated,capped:queue.length>=data.queueCap?data.queueCap:null,missing:data.missing===null?null:`No completed task ${data.missing} is in view here — it may not be finished, or it is outside this console's projects.`,beyond:data.beyondQueue&&selected!==null,selected:detailSelected===null?null:data.refusal==null?detailSelected:{...detailSelected,problem:data.refusal}}}
4
+ `),downloadHref:`/r/${runId}/evidence/${proof.checkLog.artifactId}`,downloadLabel:storedLinkText("check log",proof.checkLog.truncated)},agentChecks:proof===null?null:{hideWhenEmpty:directAssessment,items:(proof.proof?.checks??[]).map(one=>({command:one.command,exitCode:one.exitCode,summary:one.summary}))},screenshots:proof===null?null:{hideWhenEmpty:directAssessment&&!screenshotRequiredFlag,required:screenshotRequiredFlag,leadIsScreenshots:lead==="screenshots",totalCount:shots.length,shownCount:shown.length,unavailableCount:unavailableShots.length,shown:shown.map(shot=>({artifactId:shot.artifactId,caption:shot.caption,...shot.sha256===void 0?{}:{sha256:shot.sha256},commentable:detail.canAnnotate&&o.csrf!==""&&shot.sha256!==void 0}))},caveats:proof===null?null:{hideWhenEmpty:directAssessment,items:[...receipt.caveats]},followUps:followUps!==null&&run.role==="builder"?(()=>{const canCheck=followUps.quick||followUps.full,batchHow=one=>{const peers=one.batch?.members.filter(member=>member.run!==runId).map(member=>member.task)??[];return one.batch?.mode==="together"&&peers.length>0?` together with ${peers.join(", ")}`:one.batch?.mode==="split"?" on its own after its batch failed":one.batch?.mode==="conflict"?" on its own (it conflicted with another result)":""};return{checks:followUps.checks.map(one=>({state:one.state,text:`${CHECK_LEVEL_WORDS[one.level]} checks ${one.why==="batch"&&one.state==="waiting"?"waiting to check with other results":FOLLOW_UP_WORDS[one.state]}${batchHow(one)}${one.exitCode===null||one.state==="passed"?"":` (exit ${one.exitCode})`}`,batchMode:one.why==="batch"?one.batch?.mode??"waiting":null,commitShort:(one.tested??one.head).slice(0,7),meta:`${one.why==="pull-request"?"for the pull request":one.why==="batch"?"batch check":one.actor}${one.note===null?"":` · ${one.note}`}`,logHref:one.logArtifactId===null?null:`/r/${runId}/evidence/${one.logArtifactId}`})),quick:followUps.quick,full:followUps.full,canAct:canCheck&&o.csrf!=="",action:`/r/${runId}/checks`,returnTo:o.returnTo,testsTask:followUps.testsTask,addTestsAction:followUps.testsTask===null&&o.csrf!==""?`/r/${runId}/add-tests`:null,setupHref:!canCheck&&followUps.repo!==null?`/settings/checks?repo=${encodeURIComponent(followUps.repo)}`:null}})():null,agentOwnAccount:!directAssessment&&handoff!==null?[...handoff.verification]:[],reviewRetry:o.reviewRetry==null||o.reviewRetry.state==="unrequested"?null:{state:o.reviewRetry.state,attempts:o.reviewRetry.attempts.map(one=>({attempt:one.attempt,outcome:one.outcome,runId:one.runId,reason:one.reason}))}},commentData=one=>{const shot=one.image==null?void 0:shots.find(s=>s.artifactId===one.image.artifact&&s.sha256===one.image.sha256&&one.image.run===runId&&s.problem===null),dropAction=one.image!=null&&o.csrf!==""&&(detail.unusableImageNotes??[]).includes(one.id)?`/r/${runId}/comment`:null;return{id:one.id,path:one.path,line:one.line,editorHref:one.path===null||detail.editor===null?null:editorFileHref(detail.editor.worktree,one.path,one.line),note:one.note,author:one.author,createdAt:one.createdAt,image:one.image==null?null:{run:runId,artifact:one.image.artifact,caption:shot===void 0?null:shot.caption,dropAction,dropTab:o.tab,returnTo:o.returnTo}}},requestData=detail.skillTest||detail.landed===!0?null:{runId,comments:detail.comments.map(commentData),reviseFromComments:detail.comments.length>0&&o.csrf!==""&&!detail.canAnnotate?{action:`/r/${runId}/revise`,buildNow:detail.buildNowOnSendBack===!0,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),returnTo:o.returnTo}:null,pastComments:(detail.pastComments??[]).map(commentData),revisions:detail.revisions.map(one=>({id:one.id,title:one.title,approved:one.approved,standing:one.standing,tone:one.tone})),availability:o.csrf===""?"signed-out":detail.canAnnotate?"ok":terminal===null?"no-diff":"unverified-diff",chatHref:taskChatHref(detail.rootId??detail.taskId),form:o.csrf!==""&&detail.canAnnotate?{action:`/r/${runId}/comment`,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),recordedKeys:[...detail.comments,...detail.pastComments??[]].filter(one=>one.sourceKey?.startsWith(`review:${o.user}:`)).map(one=>one.sourceKey.slice(`review:${o.user}:`.length)).join(","),noteMaxLength:LIMITS.note,noted:o.noted,buildNowOnSendBack:detail.buildNowOnSendBack===!0,returnTo:o.returnTo,tab:o.tab,requestToken:o.requestToken}:null};return{attributes:{"data-result-panel":"","data-result-place":o.place,"data-result-lead":lead,"data-result-task":detail.rootId??detail.taskId,"data-result-user":o.user,...resultFactsAttributeMap(facts)},back:o.back,failed:o.failed??null,showHeadStatus:o.headStatus!==!1,showPanelAction:o.action!==!1,headVerdict:{hasCurrentOutcome:!(current==null||o.place==="review"&&(current.state==="ready-to-check"||current.state==="complete")),statusToken:status.token,status:taskStatus},heading,outcome,status:taskStatus,reviewHistory:REVIEW_TOKENS.has(status.token)?status.detail:null,attention:attention.filter(one=>!shortenedMaterialReason(one)).map(plainReasonWords),youCheck,requirements:proof===null||proof.verdict==="refuted"?null:requirementsOf(proof.matrix),limits:attention.filter(one=>shortenedMaterialReason(one)),tabs:RESULT_TABS.map(tab=>({key:tab.key,label:tab.key==="checks"&&proof?.matrix.some(row=>row.assessment!==void 0)?"Requirements":tab.label,count:tabCounts[tab.key],href:o.hrefFor(tab.key),active:tab.key===o.tab})),summary:summaryData,changes:changesData,checks:checksData,history:detail.historyData??null,learning:detail.learningData??null,request:requestData,canRequest:detail.canAnnotate&&o.csrf!==""&&detail.landed!==!0,sendBack:detail.skillTest||!detail.canAnnotate||o.csrf===""||detail.landed===!0?null:{action:`/r/${runId}/comment`,batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest),request:o.requestToken,buildNow:detail.buildNowOnSendBack===!0},need,requestQuiet:detail.canAnnotate&&o.csrf!==""&&detail.comments.length===0&&(detail.pastComments?.length??0)===0&&detail.revisions.length===0}}function cockpitStatusOf(view){if(view.run===null||view.detail===null)return view.assignment===null?resultHeadlineOf(resultStatusOf(null,null)):assignmentPresentationOf(view.assignment).status;const receiptStatus=receiptStatusOf(view.detail.receipt);return view.assignment!==null?assignmentStatusOf(assignmentWithEvidence(view.assignment,receiptStatus,view.run.id)):resultHeadlineOf(receiptStatus)}function reviewNextActionOf(view,csrf,back){const run=view.run,detail=view.detail;return run===null||detail===null?{kind:"inspect-task",title:"No build to review",detail:"This task was accepted without a build record.",control:{kind:"link",label:"Open the task",href:taskHref(view.taskId)}}:detail.ciFailing&&csrf!==""?{kind:"draft-repair",title:"CI is failing on its pull request",detail:`Toolroll confirmed the failure. ${SEND_BACK_PUBLISHED}`,control:{kind:"post",action:`/r/${run.id}/draft-repair`,label:"Send back",fields:{}}}:detail.comments.length>0&&csrf!==""?{kind:"revise",title:`${detail.comments.length} note${detail.comments.length===1?"":"s"} ready`,detail:SEND_BACK_UNPUBLISHED,control:{kind:"post",action:`/r/${run.id}/revise`,label:"Send back",fields:{batch:revisionBatchOf(detail.comments),source:revisionSourceOf(detail.sourceDigest)},returnTo:back??reviewHref(view.taskId)}}:null}export function reviewCockpitDetailData(view,csrf,noted,canRetryReview,tab,user,host={kind:"review"}){const run=view.run,proof=view.detail?.proof??null,accepted=proof?.accepted!==null&&proof?.accepted!==void 0,status=cockpitStatusOf(view),intent=view.intent,intentView=intent===null?null:{approval:intent.approval.approved?`Approved by ${intent.approvedBy??"an approver"}`:intent.approval.reason==="changed"?"Edited after approval. The words below are the current plan, not the approved one.":"Never approved. The result was built without an approved plan.",approvedAt:intent.approval.approved?intent.approval.at??null:null,goal:intent.goal,outOfScope:intent.outOfScope,touches:[...intent.touches],plan:view.plan===null?null:{revision:view.plan.revision,shaShort:view.plan.sha256.slice(0,7),approach:view.plan.approach}},selected={taskId:view.taskId,title:view.title,project:view.repo===null?null:projectName(view.repo),build:run===null?null:run.id,taskHref:taskHref(view.taskId),chatHref:taskChatHref(view.taskId),status:{label:status.label,tone:status.tone,token:status.token},problem:view.detail===null?view.historyProblem:null,next:reviewNextActionOf(view,csrf,host.kind==="task"&&run!==null?`${host.base}&run=${run.id}`:host.kind==="run"&&run!==null?`/r/${run.id}?record=1`:void 0),complete:null,decision:null,checks:null,intent:intentView,noRun:null,panel:null,notes:view.notes.map(one=>({author:one.author,at:one.createdAt,note:one.note})),agentReport:run===null||view.detail===null?null:view.detail.handoff?.report??EMPTY_AGENT_REPORT,youSaid:(view.youSaid??[]).map(one=>({kind:one.kind,author:one.author,you:one.author===user,at:one.at,note:quotedNoteOf(one.note),question:one.question===null?null:quotedNoteOf(one.question)})),efficiency:view.efficiency??null,network:view.network??null,timing:view.timing??null,acts:{primary:null,secondary:null,line:null},runChecks:null,mismatch:null,record:run===null?null:{build:run.id,href:`/r/${run.id}?record=1`,facts:[{label:"Agent",value:[run.provider,run.model].filter(Boolean).join(" · ")},{label:"Builder",value:run.runner},...view.checkRan===void 0||view.checkRan===null?[]:[{label:"Checks",value:view.checkRan}],...run.branch===null?[]:[{label:"Branch",value:run.branch}],...run.finishedAt===null?[]:[{label:"Finished",value:when(run.finishedAt)}],...run.ranMinutes===null?[]:[{label:"Ran",value:`${run.ranMinutes} min`}]]}};if(run===null||view.detail===null)return{...selected,noRun:"This task has no finished build record, so there are no captured changes or checks to review."};const at=(section="summary")=>host.kind==="task"?`${host.base}&run=${run.id}${section==="summary"?"":`&section=${section}`}`:host.kind==="run"?`/r/${run.id}?record=1${section==="summary"?"":`&tab=${section}`}`:taskLinkOf({task:view.taskId,run:run.id,section}),assignment=view.assignment===null?null:assignmentWithEvidence(view.assignment,receiptStatusOf(view.detail.receipt),run.id),saved=assignment?.receipt?.checks,checks=saved===void 0||assignment?.receipt==null?void 0:{...saved,...receiptChecksOf(assignment.receipt),detail:saved.detail},own=taskLinkOf({task:view.taskId,run:run.id}),ownOr=href=>href===own||/^[&#]/.test(href.slice(own.length))&&href.startsWith(own)?href.slice(own.length):null,failure=view.failure==null?null:{line:view.failure.line,evidence:view.failure.evidence,suggestion:view.failure.suggestion,retry:view.failure.retry,link:view.failure.link===null||ownOr(view.failure.link.href)!==null&&!view.failure.link.href.includes("#")?null:host.kind==="task"&&ownOr(view.failure.link.href)?.startsWith("&section=")===!0?{...view.failure.link,href:`${host.base}&run=${run.id}${ownOr(view.failure.link.href)}`}:host.kind==="run"&&ownOr(view.failure.link.href)?.startsWith("&section=")===!0?{...view.failure.link,href:`/r/${run.id}?record=1${ownOr(view.failure.link.href).replace(/^&section=/,"&tab=")}`}:view.failure.link,...view.failure.acceptAnyway==null?{}:{acceptAnyway:{...view.failure.acceptAnyway,returnTo:at()}}},panelData=resultPanelData(view.detail,{...host.kind==="task"&&host.alone===!0&&failure!==null?{failed:{line:failure.line,evidence:failure.evidence,link:failure.link}}:{},place:host.kind==="run"?"run":"review",tab,csrf,user,noted,requestToken:createHash("sha256").update(`${view.taskId}:${run.id}:${user}`).digest("hex").slice(0,32),hrefFor:one=>at(one),returnTo:at(),back:null,reviewRetry:view.reviewRetry,headStatus:!1,action:!1});host.kind==="task"&&(panelData.attributes={...panelData.attributes,"data-result-param":"section"});const hardStop=hardBlockerOf(assignment)??view.detail.completeRefusal??null,blocked=hardStop??cantAcceptYetOf(proof?.verdict??null,proof?.reasons??[],accepted),youCheck=panelData.youCheck,shared=accepted||assignment?.receipt==null?null:owedAcceptance(assignment.receipt,assignment.readiness?.blockers??[]),owed=accepted?null:youCheck?.accept!=null||shared==="person-check"?{note:null}:shared==="exception"||blocked===WORKSPACE_ACCEPT_NEEDS_REASON?{note:"Why is this safe to accept?"}:null,confirm=assignment?.state==="complete"&&assignment.completion!==null&&assignment.completion.person===void 0&&assignment.completion.historical!==!0&&assignment.completion.landed===void 0&&assignment.receipt!==null&&assignment.completion.digest===assignment.receipt.digest&&youCheck!=null,complete=hardStop===null&&(assignment?.state==="ready-to-check"||confirm)&&assignment?.receipt!=null&&canRetryReview&&csrf!==""?{action:`${taskHref(view.taskId)}/complete`,receipt:assignment.receipt.digest,run:run.id,accept:owed,...host.kind!=="review"?{returnTo:at()}:{}}:null,acceptsHere=complete!==null||panelData.need?.accept!=null||youCheck?.accept!=null,matrix=proof===null||proof.proofProblem!==null?[]:proof.matrix,unanswered=accepted||youCheck==null?[]:youCheck.items.length>0?youCheck.items.map(one=>one.statement===""?one.words:one.statement):youCheck.lines,base=acceptsHere?acceptWordsOf({checks:checks===void 0?null:{passed:"passed",failed:"failed",running:"running","not-run":"not-run",off:"off",stale:"unavailable",unreadable:"unavailable"}[approvedCheckStateOf(checks)],unmet:matrix.filter(row=>!["Met","You check",CHECKED_AT_RELEASE].includes(requirementWordOf(row,null,checks===void 0?void 0:checkBackingOf(checks)))).length,action:complete!==null?"complete":"accept",publishing:view.detail?.publishing??"other",proof:proof!==null&&proof.proofProblem===null&&(proof.proof!==null||proof.matrix.length>0)}):null,settled=base===null||blocked===null?base:{...base,label:"Accept",ready:!1},decision=settled===null?null:{sentence:RESULT_DECISION_SENTENCE,...settled,...acceptWithChecksOf(settled,{unanswered,notRight:[]}),base:{label:settled.label,ready:settled.ready,why:settled.why}},followUps=view.detail.followUps??null,checksRunning=checks?.running!=null||(followUps?.checks.some(one=>one.state==="waiting"||one.state==="running")??!1),runChecks=canRetryReview&&csrf!==""&&followUps!==null&&(followUps.full||followUps.quick)&&!checksRunning&&(checks===void 0||(checks.status==="not-run"||checks.status==="unavailable"||checks.status==="failed"&&assignment?.state==="complete")&&checks.release==null)?{action:`/r/${run.id}/checks`,level:followUps.full?"full":"quick",returnTo:at("checks")}:null,need=panelData.need,nextKind=selected.next?.kind,actFacts=failure!==null?{accept:null,runChecks:runChecks!==null,checksRunning,blocked:null,canRequest:!1,need:null,next:null,failed:{retry:failure.retry!==null,acceptAnyway:failure.acceptAnyway!==void 0}}:{accept:settled===null?null:{ready:settled.ready},runChecks:runChecks!==null,checksRunning,blocked,canRequest:panelData.canRequest&&panelData.request!==null,need:need===null||need.accept!=null?null:need.rebuild!=null?"rebuild":need.confirm!==null?"recheck-stopped":null,next:nextKind==="revise"||nextKind==="draft-repair"?nextKind:null,unanswered:settled===null?0:unanswered.length,notRight:0},acts=resultActsOf(actFacts),mismatch=failure!==null||proof===null||accepted||proof.verdict!=="refuted"?null:(()=>{const patch=view.detail?.terminal?.patch??null,files=patch===null||"problem"in patch?[]:parseReviewDiff(patch.text).files,hunkStart=new Map,changes=new Map(files.map(file=>{const shown=file.hunks[0]?.lines.filter(line=>line.newLine!==null&&line.kind!=="meta")??[];shown[0]?.newLine!=null&&hunkStart.set(file.path,shown[0].newLine);const added=shown.filter(line=>line.kind==="addition"),lines=(added.length>0?added:shown).map(line=>line.newLine);return[file.path,lines.length===0?null:{from:Math.min(...lines),to:Math.max(...lines)}]})),changesHref=at("changes"),found=reportMismatchesOf(proof.reasons,proof.proofProblem===null?proof.matrix:[],changes);return proof.proofProblem!==null&&found.push({text:`The saved report can't be read: ${proof.proofProblem}`,path:null,lines:null,inChanges:null,note:null,reason:proof.proofProblem}),found.length===0?null:{headline:evidenceProblemOf(proof.verdict,proof.reasons)==="mismatched"?MISMATCH_HEADLINE:null,rows:found.map(one=>({text:one.text,path:one.path,absent:one.inChanges===!1,lines:one.lines===null?null:one.lines.from===one.lines.to?`line ${one.lines.from}`:`lines ${one.lines.from}–${one.lines.to}`,href:one.path!==null&&one.inChanges===!0?`${changesHref}#${diffFileAnchor(one.path)}${hunkStart.has(one.path)?`-L${hunkStart.get(one.path)}`:""}`:one.note!==null&&(proof.proof?.caveats.length??0)>=one.note?`${at()}#report-note-${one.note}`:null,noteLabel:one.path===null&&one.note!==null?`The report, note ${one.note}`:null})),said:[...new Set([...proof.reasons,...found.map(one=>one.reason)].flatMap(reason=>[reason,plainReasonWords(reason)]))]}})();return{...selected,complete:failure===null?complete:null,decision:failure===null?decision:null,acts,actFacts,runChecks,mismatch,failure,panel:(()=>{const elsewhere=href=>href!==null&&!href.endsWith("#follow-ups")&&!new RegExp(`^/chat\\?task=[^&]+&result=${run.id}(?:&|$)`).test(href),shown=panelData.status===null?null:view.demo===!0?demoChecksOf(panelData.status):panelData.status,missed=proof===null||proof.proofProblem!==null?0:requirementsOf(proof.matrix)?.missed??0,panelStatus=shown===null?null:{...shown,details:shown.details.map(one=>({...one,href:elsewhere(one.href)?one.href:null,action:one.action!==null&&elsewhere(one.action.href)?one.action:null}))};return failure===null?{...panelData,status:panelStatus}:{...panelData,outcome:failure.line,need:null,youCheck:null,status:panelStatus===null?null:{...panelStatus,headline:"Failed",tone:"danger",sentence:failure.line,need:null,details:panelStatus.details.map(one=>one.key!=="requirements"||missed===0?one:{...one,text:`${missed} missed`,mark:"failed",action:null})},attention:panelData.attention.filter(one=>!(proof?.reasons??[]).includes(one)&&!(proof?.matrix??[]).some(row=>row.detail.includes(one)))}})(),...failure===null?{}:{status:{label:"Failed",tone:"problem",token:"failed"}},checks:checks===void 0?null:{detail:checks.detail,problem:checks.status==="failed"||checks.status==="unavailable",logHref:checks.logArtifactId===null?null:`/r/${run.id}/evidence/${checks.logArtifactId}`}}}export function reviewCockpitViewData(data){const{queue,selected,csrf}=data,elevated=queue.filter(one=>one.priority.band<2).length,detailSelected=selected===null?null:reviewCockpitDetailData(selected,csrf,data.noted,data.canRetryReview,data.tab,data.user);return{kind:"result",results:queue.map(row=>{const status=row.assignment==null?null:assignmentPresentationOf(row.assignment).status,reasons=row.priority.reasons;return{title:row.title,href:reviewHref(row.taskId,row.runId),at:row.completedAt,status:status===null?null:{label:status.label,tone:status.tone},notes:[...row.historyProblem?["History unavailable"]:status===null&&reasons.length>0?[reasons[0]]:[],...status!==null&&row.ciFailing?["CI is failing"]:[]],current:selected!==null&&selected.taskId===row.taskId,needsYou:row.priority.band<2}}),attention:elevated,capped:queue.length>=data.queueCap?data.queueCap:null,missing:data.missing===null?null:`No completed task ${data.missing} is in view here — it may not be finished, or it is outside this console's projects.`,beyond:data.beyondQueue&&selected!==null,selected:detailSelected===null?null:data.refusal==null?detailSelected:{...detailSelected,problem:data.refusal}}}
@@ -1 +1 @@
1
- export function reviewSwitchWords(state){return state.source==="project"?state.on?"on":"off":state.on?"on (hands-off default)":"off (default)"}export function buildReviewOf(store,runId){let row;try{row=store.handle.prepare("SELECT * FROM build_review WHERE run = ?").get(runId)}catch(error){if(/no such table: build_review/.test(String(error)))return null;throw error}if(row===void 0)return null;let findings=[];try{const saved=row.findings_json===null?null:JSON.parse(String(row.findings_json));Array.isArray(saved?.findings)&&(findings=saved.findings)}catch{}return{run:runId,state:String(row.state),reviewerRun:row.reviewer_run===null?null:Number(row.reviewer_run),reason:row.reason===null?null:String(row.reason),high:findings.filter(one=>one.severity==="HIGH"),followUps:findings.filter(one=>one.severity!=="HIGH"),sentBackAs:row.sent_back_as===null?null:String(row.sent_back_as),finishedAt:row.finished_at===null?null:String(row.finished_at)}}export const findingWords=finding=>`${finding.severity} ${finding.file}:${finding.line} — ${finding.scenario}`;function buildReviewHeadline(view){return view===null?null:view.state==="pending"?"Reviewing — an automatic review is reading this result.":view.state==="not-reviewed"?`Not reviewed${view.reason===null?".":`: ${view.reason}`}`:view.sentBackAs!==null?`Sent back as ${view.sentBackAs}: ${view.high.length} high finding${view.high.length===1?"":"s"}.`:view.high.length>0?`Reviewed: ${view.high.length} high finding${view.high.length===1?"":"s"} for you to decide.`:`Reviewed: no high findings${view.followUps.length===0?".":`; ${view.followUps.length} suggested follow-up${view.followUps.length===1?"":"s"}.`}`}export function buildReviewLines(view){const headline=buildReviewHeadline(view);return view===null||headline===null?[]:[` review: ${headline}`,...view.high.map(one=>` ${findingWords(one)}`),...view.followUps.map(one=>` suggested follow-up: ${findingWords(one)}`)]}
1
+ export function reviewSwitchWords(state){return state.source==="project"?state.on?"on":"off":state.source==="hands-off"?"on (hands-off default)":state.on?"on (reviewer default)":"off (default)"}export function buildReviewOf(store,runId){let row;try{row=store.handle.prepare("SELECT * FROM build_review WHERE run = ?").get(runId)}catch(error){if(/no such table: build_review/.test(String(error)))return null;throw error}if(row===void 0)return null;let findings=[];try{const saved=row.findings_json===null?null:JSON.parse(String(row.findings_json));Array.isArray(saved?.findings)&&(findings=saved.findings)}catch{}return{run:runId,state:String(row.state),reviewerRun:row.reviewer_run===null?null:Number(row.reviewer_run),reason:row.reason===null?null:String(row.reason),high:findings.filter(one=>one.severity==="HIGH"),followUps:findings.filter(one=>one.severity!=="HIGH"),sentBackAs:row.sent_back_as===null?null:String(row.sent_back_as),finishedAt:row.finished_at===null?null:String(row.finished_at)}}export const findingWords=finding=>`${finding.severity} ${finding.file}:${finding.line} — ${finding.scenario}`;function buildReviewHeadline(view){return view===null?null:view.state==="pending"?"Reviewing — an automatic review is reading this result.":view.state==="not-reviewed"?`Not reviewed${view.reason===null?".":`: ${view.reason}`}`:view.sentBackAs!==null?`Sent back as ${view.sentBackAs}: ${view.high.length} high finding${view.high.length===1?"":"s"}.`:view.high.length>0?`Reviewed: ${view.high.length} high finding${view.high.length===1?"":"s"} for you to decide.`:`Reviewed: no high findings${view.followUps.length===0?".":`; ${view.followUps.length} suggested follow-up${view.followUps.length===1?"":"s"}.`}`}export function buildReviewLines(view){const headline=buildReviewHeadline(view);return view===null||headline===null?[]:[` review: ${headline}`,...view.high.map(one=>` ${findingWords(one)}`),...view.followUps.map(one=>` suggested follow-up: ${findingWords(one)}`)]}
@@ -1,4 +1,26 @@
1
- import{providerName}from"./provider-auth.js";import{legOf,routeDigestOf,routeFromJson}from"./phase-routing.js";import{deployGateScope,releaseCheckScope}from"./scope.js";import{BUILT_IN}from"./store.js";import{repositoryEcosystems,resolveNetwork}from"./egress.js";const ROLE={plan:"planner",build:"builder",repair:"repair agent",review:"reviewer"},named=one=>`${providerName(one.provider)} ${one.model??"(its default model)"}`,billing=mode=>mode==="api-key"?"API key":mode==="subscription"?"subscription":null;export function networkChangeWords(was,now){if(was==null||now==null)return[];const out=[];if(was.mode!==now.mode)out.push(now.mode==="open"?"builds may now reach any host":"builds now reach only their allowed hosts");else if(now.mode==="allowlist"){const added=now.hosts.filter(one=>!was.hosts.includes(one)),gone=was.hosts.filter(one=>!now.hosts.includes(one));added.length>0&&out.push(`builds may now also reach ${added.join(", ")}`),gone.length>0&&out.push(`builds no longer reach ${gone.join(", ")}`)}return was.loopback!==now.loopback&&out.push(now.loopback==="any"?"builds may now reach this Mac's local services":"builds no longer reach this Mac's local services"),out}const sentence=clauses=>clauses.length===0?"":`${clauses[0].charAt(0).toUpperCase()}${clauses.join("; ").slice(1)}`;export function routeChangeWords(sealed,next,network=[]){const changes=[];for(const phase of["build","plan","repair","review"]){const now=legOf(next.route,phase),was=sealed.route!==null?legOf(sealed.route,phase):phase==="build"&&sealed.profile!=null?{provider:sealed.profile.provider,model:"model"in sealed.profile?sealed.profile.model??null:null}:null;if(was===null){phase==="build"&&changes.push(`The builder is ${named(now)}`);continue}if(was.provider===now.provider&&was.model===now.model)continue;const line=`changes from ${named(was)} to ${named(now)}`;changes.some(one=>one.endsWith(line))||changes.push(`${changes.length===0?"The":"the"} ${ROLE[phase]} ${line}`)}const from=billing(sealed.authMode),to=billing(next.authMode),paid=from!==null&&to!==null&&from!==to?` (${from} → ${to})`:"";return changes.length===0&&network.length===0?"The agents' settings changed since you approved this. Approve to continue.":changes.length===0?`${sentence(network)}. Approve to continue.`:`${changes.join("; ")}${paid}${network.length===0?"":`; ${network.join("; ")}`}. Approve to continue.`}export function proposeNewRoute(store,taskRef,taskId,now){return store.transact(()=>{const before=store.getScope(taskId);if(before===null||deployGateScope(before)||releaseCheckScope(before))return null;const sealedRoute=routeFromJson(before.approvedRouteJson??null),refiled=store.refileScope(taskId,now);if(refiled===null||refiled.profileState==="unresolved")return null;const route=routeFromJson(refiled.proposedRouteJson??null);if(route===null||refiled.approvedDigest===refiled.digest)return null;const lastBilled=store.runsFor(taskRef).find(one=>one.role==="builder")?.authMode??null,billed=store.agentsFor([legOf(route,"build").provider])[0]?.billing??null,words=routeChangeWords({route:sealedRoute,profile:before.approvedProfile??null,authMode:lastBilled},{route,authMode:billed},networkChangeWords(before.approvedProfile?.network,refiled.profile?.network));return store.handle.prepare(`INSERT INTO route_change (task_ref, scope_digest, to_route_digest, words, created_at) VALUES (?, ?, ?, ?, ?)
2
- ON CONFLICT (task_ref) DO UPDATE SET scope_digest = excluded.scope_digest, to_route_digest = excluded.to_route_digest, words = excluded.words, created_at = excluded.created_at`).run(taskRef,refiled.digest,routeDigestOf(route),words,now.toISOString()),{words}})}export function routeChangeOf(store,taskId){const ref=store.lookupRef(taskId);if(ref===null)return null;const row=store.handle.prepare("SELECT scope_digest, to_route_digest, words FROM route_change WHERE task_ref = ?").get(ref.id),scope=store.getScope(taskId);if(row===void 0||scope===null||scope.digest!==row.scope_digest||scope.approvedDigest===scope.digest)return null;const route=routeFromJson(scope.proposedRouteJson??null);return route!==null&&routeDigestOf(route)===row.to_route_digest?String(row.words):null}export function routeLegacyPlans(store,now){const rows=store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task FROM task_scope s JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ? JOIN task t ON t.id = r.external_id
1
+ import{providerName}from"./provider-auth.js";import{isProtectedWork}from"./approval-policy.js";import{exactPinOf,INSTALLATION_SCOPE,resolveRouteCandidates}from"./agentconfig.js";import{legOf,recommendRoute,routeDigestOf,routeFromJson,routeProblems}from"./phase-routing.js";import{liveEarnedRules}from"./route-store.js";import{deployGateScope,releaseCheckScope}from"./scope.js";import{BUILT_IN}from"./store.js";import{FAST_PROJECT_NETWORK_DEFAULT,isOldDefaultProjectNetwork,PROJECT_NETWORK_DEFAULT,projectNetworkFromValue,repositoryEcosystems,resolveNetwork}from"./egress.js";import{ownerMode}from"./owner-mode.js";const ROLE={plan:"planner",build:"builder",repair:"repair agent",review:"reviewer"},named=one=>`${providerName(one.provider)} ${one.model??"(its default model)"}`,billing=mode=>mode==="api-key"?"API key":mode==="subscription"?"subscription":null;export function networkChangeWords(was,now){if(was==null||now==null)return[];const out=[];if(was.mode!==now.mode)out.push(now.mode==="open"?"builds may now reach any host":"builds now reach only their allowed hosts");else if(now.mode==="allowlist"){const added=now.hosts.filter(one=>!was.hosts.includes(one)),gone=was.hosts.filter(one=>!now.hosts.includes(one));added.length>0&&out.push(`builds may now also reach ${added.join(", ")}`),gone.length>0&&out.push(`builds no longer reach ${gone.join(", ")}`)}return was.loopback!==now.loopback&&out.push(now.loopback==="any"?"builds may now reach this Mac's local services":"builds no longer reach this Mac's local services"),out}const sentence=clauses=>clauses.length===0?"":`${clauses[0].charAt(0).toUpperCase()}${clauses.join("; ").slice(1)}`;export function routeChangeWords(sealed,next,network=[]){const changes=[];for(const phase of["build","plan","repair","review"]){const now=legOf(next.route,phase),was=sealed.route!==null?legOf(sealed.route,phase):phase==="build"&&sealed.profile!=null?{provider:sealed.profile.provider,model:"model"in sealed.profile?sealed.profile.model??null:null}:null;if(was===null){phase==="build"&&changes.push(`The builder is ${named(now)}`);continue}if(was.provider===now.provider&&was.model===now.model)continue;const line=`changes from ${named(was)} to ${named(now)}`;changes.some(one=>one.endsWith(line))||changes.push(`${changes.length===0?"The":"the"} ${ROLE[phase]} ${line}`)}const from=billing(sealed.authMode),to=billing(next.authMode),paid=from!==null&&to!==null&&from!==to?` (${from} → ${to})`:"";return changes.length===0&&network.length===0?"The agents' settings changed since you approved this. Approve to continue.":changes.length===0?`${sentence(network)}. Approve to continue.`:`${changes.join("; ")}${paid}${network.length===0?"":`; ${network.join("; ")}`}. Approve to continue.`}function taskIsArchived(store,taskRef){return store.handle.prepare("SELECT 1 AS hit FROM task_archive WHERE task_ref = ? LIMIT 1").get(taskRef)!==void 0}function taskApprovedAndStarted(store,taskRef,approvedDigest){return store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND role = 'builder' AND scope_digest = ? LIMIT 1").get(taskRef,approvedDigest)!==void 0}export function proposeNewRoute(store,taskRef,taskId,now,options={}){return store.transact(()=>{const task=store.getTask(taskId),ref=store.refForId(taskRef),allowedStates=options.states??["queued","failed"];if(task===null||ref===null||ref.externalId!==taskId||!allowedStates.includes(task.state)||taskIsArchived(store,taskRef)||taskHasActiveAttempt(store,taskRef,now.toISOString()))return null;const before=store.getScope(taskId);if(before===null||deployGateScope(before)||releaseCheckScope(before))return null;const wasApproved=before.approvedDigest!==null&&before.approvedDigest===before.digest;if(options.onlyUnclaimed===!0&&wasApproved&&taskApprovedAndStarted(store,taskRef,before.approvedDigest))return null;const sealedRoute=routeFromJson(before.approvedRouteJson??null),currentRoute=wasApproved?sealedRoute??routeFromJson(before.proposedRouteJson??null):routeFromJson(before.proposedRouteJson??null),wordsBaseRoute=sealedRoute??currentRoute;store.handle.exec("SAVEPOINT propose_new_route");const rollback=()=>(store.handle.exec("ROLLBACK TO propose_new_route"),store.handle.exec("RELEASE propose_new_route"),null);try{const refiled=store.refileScope(taskId,now);if(refiled===null||refiled.profileState==="unresolved")return rollback();const route=routeFromJson(refiled.proposedRouteJson??null);if(route===null||wasApproved&&refiled.approvedDigest===refiled.digest||currentRoute!==null&&routeDigestOf(currentRoute)===routeDigestOf(route)&&before.digest===refiled.digest)return rollback();if(options.changedPhases!==void 0){if(currentRoute===null)return rollback();let touched=!1;for(const phase of options.changedPhases){const prevLeg=legOf(currentRoute,phase),nextLeg=legOf(route,phase);if(!(nextLeg.chosen==="pinned"||nextLeg.chosen==="override")&&(prevLeg.provider!==nextLeg.provider||prevLeg.model!==nextLeg.model)){touched=!0;break}}if(!touched)return rollback()}!wasApproved&&refiled.approvedDigest===refiled.digest&&store.handle.prepare("UPDATE task_scope SET approved_at = NULL, approved_by = NULL, approved_digest = NULL WHERE task_id = ?").run(taskId);const lastBilled=store.runsFor(taskRef).find(one=>one.role==="builder")?.authMode??null,billed=store.agentsFor([legOf(route,"build").provider])[0]?.billing??null,words=routeChangeWords({route:wordsBaseRoute,profile:before.approvedProfile??null,authMode:lastBilled},{route,authMode:billed},networkChangeWords(before.approvedProfile?.network,refiled.profile?.network));store.handle.prepare(`INSERT INTO route_change (task_ref, scope_digest, to_route_digest, words, created_at) VALUES (?, ?, ?, ?, ?)
2
+ ON CONFLICT (task_ref) DO UPDATE SET scope_digest = excluded.scope_digest, to_route_digest = excluded.to_route_digest, words = excluded.words, created_at = excluded.created_at`).run(taskRef,refiled.digest,routeDigestOf(route),words,now.toISOString());const plannerChanged=currentRoute!==null&&(legOf(currentRoute,"plan").provider!==legOf(route,"plan").provider||legOf(currentRoute,"plan").model!==legOf(route,"plan").model);let replanned=!1;return options.replanIfPlannerChanged!==!1&&plannerChanged&&ref.plan==="drafted"&&(replanned=store.restartPlanning(taskRef,now)),store.handle.exec("RELEASE propose_new_route"),{words,wasApproved,replanned,route}}catch(error){throw store.handle.exec("ROLLBACK TO propose_new_route"),store.handle.exec("RELEASE propose_new_route"),error}})}export function routeChangeOf(store,taskId){const ref=store.lookupRef(taskId);if(ref===null)return null;const row=store.handle.prepare("SELECT scope_digest, to_route_digest, words FROM route_change WHERE task_ref = ?").get(ref.id),scope=store.getScope(taskId);if(row===void 0||scope===null||scope.digest!==row.scope_digest||scope.approvedDigest===scope.digest)return null;const route=routeFromJson(scope.proposedRouteJson??null);return route!==null&&routeDigestOf(route)===row.to_route_digest?String(row.words):null}export function routeLegacyPlans(store,now){const rows=store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task FROM task_scope s JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ? JOIN task t ON t.id = r.external_id
3
3
  WHERE s.route_era IS NULL AND t.state = 'queued' AND (s.approved_digest IS NULL OR s.approved_digest <> s.digest) LIMIT 20`).all(BUILT_IN);let routed=0;for(const row of rows)proposeNewRoute(store,Number(row.ref),String(row.task),now)!==null&&routed++;return routed}export function proposeNetworkChanges(store,repo,now){const rows=store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task FROM task_scope s JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ?
4
- JOIN task t ON t.id = r.external_id WHERE r.repo = ? AND t.state IN ('queued', 'failed') AND s.approved_digest = s.digest`).all(BUILT_IN,repo);if(rows.length===0)return 0;const project=store.projectNetwork(repo),ecosystems=repositoryEcosystems(repo);let proposed=0;for(const row of rows){const sealed=store.getScope(String(row.task))?.approvedProfile;sealed!=null&&networkChangeWords(sealed.network,resolveNetwork(sealed.provider,project,ecosystems)).length!==0&&proposeNewRoute(store,Number(row.ref),String(row.task),now)!==null&&proposed++}return proposed}
4
+ JOIN task t ON t.id = r.external_id WHERE r.repo = ? AND t.state IN ('queued', 'failed') AND s.approved_digest = s.digest`).all(BUILT_IN,repo);if(rows.length===0)return 0;const project=store.projectNetwork(repo),ecosystems=repositoryEcosystems(repo);let proposed=0;for(const row of rows){const sealed=store.getScope(String(row.task))?.approvedProfile;sealed!=null&&networkChangeWords(sealed.network,resolveNetwork(sealed.provider,project,ecosystems,sealed.model)).length!==0&&proposeNewRoute(store,Number(row.ref),String(row.task),now)!==null&&proposed++}return proposed}export const FAST_NETWORK_MIGRATION_ACTION="fast mode network migration";function taskHasActiveAttempt(store,taskRef,nowIso){return store.handle.prepare("SELECT 1 AS hit FROM claim WHERE task_ref = ? AND released_at IS NULL AND expires_at > ? LIMIT 1").get(taskRef,nowIso)!==void 0?!0:store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND (finished_at IS NULL OR outcome IS NULL) LIMIT 1").get(taskRef)!==void 0}const ALL_PHASES=["plan","build","repair","review"];function affectedPhasesOf(slots){if(slots===void 0)return new Set(ALL_PHASES);const out=new Set;for(const slot of slots)out.add(slot.phase),slot.phase==="build"&&out.add("repair"),slot.phase==="plan"&&out.add("review");return out}export function eligibleModelChangeTasks(store,scope,now,options={}){const nowIso=now.toISOString(),phases=affectedPhasesOf(options.changedSlots);if(phases.size===0)return[];const rows=scope===INSTALLATION_SCOPE?store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task, r.repo AS repo, t.title AS title
5
+ FROM task_scope s
6
+ JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ?
7
+ JOIN task t ON t.id = r.external_id
8
+ WHERE t.state = 'queued'
9
+ AND NOT EXISTS (SELECT 1 FROM task_archive a WHERE a.task_ref = r.id)
10
+ ORDER BY r.id`).all(BUILT_IN):store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task, r.repo AS repo, t.title AS title
11
+ FROM task_scope s
12
+ JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ?
13
+ JOIN task t ON t.id = r.external_id
14
+ WHERE r.repo = ? AND t.state = 'queued'
15
+ AND NOT EXISTS (SELECT 1 FROM task_archive a WHERE a.task_ref = r.id)
16
+ ORDER BY r.id`).all(BUILT_IN,scope),headroom=store.planHeadroom(now),out=[];for(const row of rows){const taskRef=Number(row.ref),taskId=String(row.task),title=String(row.title),repo=row.repo==null?null:String(row.repo);if(taskHasActiveAttempt(store,taskRef,nowIso))continue;const taskScope=store.getScope(taskId);if(taskScope===null||deployGateScope(taskScope)||releaseCheckScope(taskScope))continue;const wasApproved=taskScope.approvedDigest!==null&&taskScope.approvedDigest===taskScope.digest;if(wasApproved&&taskApprovedAndStarted(store,taskRef,taskScope.approvedDigest))continue;const currentRoute=wasApproved?routeFromJson(taskScope.approvedRouteJson??taskScope.proposedRouteJson??null):routeFromJson(taskScope.proposedRouteJson??null);if(currentRoute===null)continue;const ref=store.refForId(taskRef);if(ref===null)continue;const overrides=ref.routeOverrides??[];if(overrides===null)continue;const buildPin=exactPinOf(ref.agentProvider??null,ref.agentModel??null,"build"),planPin=exactPinOf(ref.planProvider??null,ref.planModel??null,"plan");if(!buildPin.ok||!planPin.ok)continue;const candidates=resolveRouteCandidates(store,repo,{plan:planPin.pin,build:buildPin.pin});if(!candidates.ok)continue;const rules=repo===null?[]:liveEarnedRules(store,repo),protectedWork=repo!==null&&isProtectedWork(store.approvalRules(repo),taskScope.touches),nextRoute=recommendRoute({qualityMode:taskScope.qualityMode??"default",evidence:[...new Set(taskScope.acceptance.flatMap(one=>one.evidence))],publication:store.publicationAuthorityOf(repo,now),candidates:candidates.candidates,overrides,pins:{plan:planPin.pin,build:buildPin.pin},size:ref.sizing??null,headroom,earned:rules.length===0?null:{rules,release:!1,protected:protectedWork}});if(routeProblems(nextRoute).length>0)continue;const changedPhases=[];for(const phase of phases){const prevLeg=legOf(currentRoute,phase),nextLeg=legOf(nextRoute,phase);nextLeg.chosen==="pinned"||nextLeg.chosen==="override"||(prevLeg.provider!==nextLeg.provider||prevLeg.model!==nextLeg.model)&&changedPhases.push(phase)}if(changedPhases.length===0)continue;const plannerChanged=changedPhases.includes("plan");out.push({taskRef,taskId,title,repo,wasApproved,wouldReplan:plannerChanged&&ref.plan==="drafted",changedPhases,nextRoute})}return out}export function rerouteAgentLabel(items){const targets=new Set;for(const item of items){const primary=item.changedPhases?.includes("build")?"build":item.changedPhases?.includes("plan")?"plan":item.changedPhases?.[0]??"build",leg=legOf(item.route,primary);targets.add(named(leg))}return targets.size===1?[...targets][0]:"the updated agents"}export function rerouteReplyWords(result){const n=result.moved.length;if(n===0)return null;const base=`${n} waiting task${n===1?"":"s"} moved to ${result.agentLabel}; ${n===1?"it needs":"they need"} your approval again.`;return result.replanned===0?base:`${base} ${result.replanned} completed plan draft${result.replanned===1?"":"s"} will be re-planned.`}export function rerouteWaitingTasks(store,scope,now,options={}){const phases=options.changedSlots===void 0?void 0:affectedPhasesOf(options.changedSlots);return store.transact(()=>{const candidates=eligibleModelChangeTasks(store,scope,now,options),moved=[],labelInputs=[];let replanned=0;for(const candidate of candidates){const res=proposeNewRoute(store,candidate.taskRef,candidate.taskId,now,{states:["queued"],onlyUnclaimed:!0,...phases===void 0?{}:{changedPhases:phases},replanIfPlannerChanged:!0});res!==null&&(res.replanned&&replanned++,moved.push({taskId:candidate.taskId,title:candidate.title,wasApproved:res.wasApproved,replanned:res.replanned,words:res.words,route:res.route}),labelInputs.push({changedPhases:candidate.changedPhases,route:res.route}))}return{moved,replanned,agentLabel:rerouteAgentLabel(labelInputs)}})}function refileEligibleNetworkScopes(store,repo,now){const nowIso=now.toISOString(),project=store.projectNetwork(repo),ecosystems=repositoryEcosystems(repo),rows=store.handle.prepare(`SELECT r.id AS ref, r.external_id AS task, s.digest AS digest, s.approved_digest AS approved_digest
17
+ FROM task_scope s
18
+ JOIN task_ref r ON r.external_id = s.task_id AND r.backend = ?
19
+ JOIN task t ON t.id = r.external_id
20
+ WHERE r.repo = ? AND t.state IN ('queued', 'failed')`).all(BUILT_IN,repo);let rescopedApproved=0,rescopedUnapproved=0;for(const row of rows){const taskRef=Number(row.ref),taskId=String(row.task);if(taskHasActiveAttempt(store,taskRef,nowIso))continue;const scope=store.getScope(taskId);if(scope===null||deployGateScope(scope)||releaseCheckScope(scope))continue;if(row.approved_digest!=null&&String(row.approved_digest)===String(row.digest)){const sealed=scope.approvedProfile;if(sealed==null||networkChangeWords(sealed.network,resolveNetwork(sealed.provider,project,ecosystems,sealed.model)).length===0)continue;proposeNewRoute(store,taskRef,taskId,now)!==null&&(rescopedApproved+=1)}else{const proposed=scope.profile;if(!(proposed==null||networkChangeWords(proposed.network,resolveNetwork(proposed.provider,project,ecosystems,proposed.model)).length>0))continue;store.refileScope(taskId,now)!==null&&(rescopedUnapproved+=1)}}return{rescopedApproved,rescopedUnapproved}}export function migrateFastModeNetworks(store,by="system",now=new Date){return store.transact(()=>{if(ownerMode(store,now)!=="fast")return{ran:!1,migrated:[],rescopedApproved:0,rescopedUnapproved:0};if(store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE repo IS NULL AND task_id IS NULL AND action = ? AND outcome = 'done' LIMIT 1").get(FAST_NETWORK_MIGRATION_ACTION)!==void 0)return{ran:!1,migrated:[],rescopedApproved:0,rescopedUnapproved:0};const savedRows=store.handle.prepare("SELECT repo, network_json, recovery_network_json FROM project_network").all(),savedByRepo=new Map;for(const r of savedRows)savedByRepo.set(String(r.repo),{networkJson:String(r.network_json),recoveryJson:r.recovery_network_json==null?null:String(r.recovery_network_json)});const repos=[...new Set([...store.knownRepos(),...savedByRepo.keys()])].sort(),fastJson=JSON.stringify(FAST_PROJECT_NETWORK_DEFAULT),oldDefaultJson=JSON.stringify(PROJECT_NETWORK_DEFAULT),stamp=now.toISOString(),migrated=[];let rescopedApproved=0,rescopedUnapproved=0;for(const repo of repos){const existing=savedByRepo.get(repo);let shouldMigrate=!1,recoveryJson=oldDefaultJson;if(existing===void 0)shouldMigrate=!0;else{let parsed=null;try{parsed=JSON.parse(existing.networkJson)}catch{parsed=null}const net=projectNetworkFromValue(parsed);net!==null&&isOldDefaultProjectNetwork(net)&&(shouldMigrate=!0,recoveryJson=existing.networkJson)}if(!shouldMigrate)continue;store.handle.prepare(`INSERT INTO project_network (repo, network_json, recovery_network_json, updated_at, updated_by)
21
+ VALUES (?, ?, ?, ?, ?)
22
+ ON CONFLICT (repo) DO UPDATE SET
23
+ network_json = excluded.network_json,
24
+ recovery_network_json = COALESCE(project_network.recovery_network_json, excluded.recovery_network_json),
25
+ updated_at = excluded.updated_at,
26
+ updated_by = excluded.updated_by`).run(repo,fastJson,recoveryJson,stamp,by),store.recordAction({at:stamp,actor:by,repo,taskId:null,runId:null,action:"policy changed",outcome:"network",source:"policy",detail:"allowlist no-local → open"}),migrated.push(repo);const rescoped=refileEligibleNetworkScopes(store,repo,now);rescopedApproved+=rescoped.rescopedApproved,rescopedUnapproved+=rescoped.rescopedUnapproved}return store.recordAction({at:stamp,actor:by,repo:null,taskId:null,runId:null,action:FAST_NETWORK_MIGRATION_ACTION,outcome:"done",source:"policy",detail:JSON.stringify({migrated,rescopedApproved,rescopedUnapproved})}),{ran:!0,migrated,rescopedApproved,rescopedUnapproved}})}
@@ -1,7 +1,7 @@
1
- import{execFileSync}from"node:child_process";import{existsSync,readdirSync,readlinkSync,realpathSync}from"node:fs";import{basename,sep}from"node:path";import{ownedProcessCount,runOwnerTag}from"./exec.js";import{localWitnessSql}from"./store.js";import{sleep as defaultSleep}from"./sleep.js";export const STOP_GRACE_MS=1e4;const BIRTH_SLACK_MS=2e3;export function processCensus(now=Date.now()){if(process.platform==="win32")return[];const text=execFileSync("/bin/ps",["-axo","pid=,ppid=,pgid=,etime=,tty=,comm="],{encoding:"utf8",timeout:5e3,maxBuffer:16*1024*1024});return parseCensus(text,now)}export function parseCensus(text,now){const rows=[];for(const line of text.split(`
1
+ import{execFileSync}from"node:child_process";import{existsSync,readdirSync,readlinkSync,realpathSync}from"node:fs";import{basename,sep}from"node:path";import{ownedProcessCount,runOwnerTag}from"./exec.js";import{withoutLeadTokenEnv}from"./names.js";import{localWitnessSql}from"./store.js";import{sleep as defaultSleep}from"./sleep.js";export const STOP_GRACE_MS=1e4;const BIRTH_SLACK_MS=2e3;export function processCensus(now=Date.now()){if(process.platform==="win32")return[];const text=execFileSync("/bin/ps",["-axo","pid=,ppid=,pgid=,etime=,tty=,comm="],{encoding:"utf8",timeout:5e3,maxBuffer:16*1024*1024,env:withoutLeadTokenEnv(process.env)});return parseCensus(text,now)}export function parseCensus(text,now){const rows=[];for(const line of text.split(`
2
2
  `)){const match=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s+(\S+)\s+(.*)$/.exec(line);if(match===null)continue;const[,pid,ppid,pgid,days,hours,minutes,seconds,tty,comm]=match,age=((Number(days??0)*24+Number(hours??0))*60+Number(minutes))*60+Number(seconds);rows.push({pid:Number(pid),ppid:Number(ppid),pgid:Number(pgid),bornAt:now-age*1e3,name:basename(comm.trim())||"?",terminal:!/^(\?+|-)$/.test(tty)})}return rows}export function protectedProcesses(census,self=process.pid){const byPid=new Map(census.map(row=>[row.pid,row])),pids=new Set([1,self,process.ppid]);for(let at=byPid.get(self),hops=0;at!==void 0&&hops<64&&(pids.add(at.pid),!(at.ppid<=1));at=byPid.get(at.ppid),hops++);const groups=new Set;for(const pid of pids){const row=byPid.get(pid);row!==void 0&&groups.add(row.pgid)}return{pids,groups}}export function closeoutTargets(census,witnesses,guard){const byPid=new Map(census.map(row=>[row.pid,row])),groups=new Set,pids=new Set;for(const one of witnesses){const now=byPid.get(one.pid),same=now!==void 0&&now.bornAt<=one.observedAt+BIRTH_SLACK_MS;same&&pids.add(one.pid),one.group&&(same||now===void 0)&&groups.add(one.pid)}return census.filter(row=>(pids.has(row.pid)||groups.has(row.pgid))&&!guard.pids.has(row.pid)&&!guard.groups.has(row.pgid))}export async function stopProcesses(targets,options={}){if(targets.length===0)return{stopped:[],killed:[]};const graceMs=options.graceMs??STOP_GRACE_MS,census=options.census??(()=>processCensus()),signal=options.signal??((pid,name)=>process.kill(pid,name)),sleep=options.sleep??defaultSleep,send=(rows,name)=>{for(const row of rows)try{signal(row.pid,name)}catch(error){if(error.code!=="ESRCH"&&error.code!=="EPERM")throw error}},remaining=()=>{let rows;try{rows=census()}catch{return[...targets]}const alive=new Map(rows.map(row=>[row.pid,row]));return targets.filter(one=>{const now=alive.get(one.pid);return now!==void 0&&Math.abs(now.bornAt-one.bornAt)<=BIRTH_SLACK_MS})};send(targets,"SIGTERM");const deadline=Date.now()+graceMs;let left=remaining();for(;left.length>0&&Date.now()<deadline;)await sleep(Math.min(250,Math.max(0,deadline-Date.now()))),left=remaining();return left.length>0&&send(left,"SIGKILL"),{stopped:[...targets],killed:left}}export function stoppedWords(done,graceMs=STOP_GRACE_MS){const names=done.stopped.map(one=>`${one.name} (${one.pid})`).join(", "),groups=new Set(done.stopped.map(one=>one.pgid)).size,killed=done.killed.length===0?"":`; ${done.killed.length} needed SIGKILL after ${Number((graceMs/1e3).toFixed(1))} s`;return`${done.stopped.length} process${done.stopped.length===1?"":"es"} in ${groups} group${groups===1?"":"s"}: ${names}${killed}`}export async function closeOutRuns(store,clock,options={}){if(process.platform==="win32")return[];const db=store.handle,local=localWitnessSql(db,"p"),mine=localWitnessSql(db),runs=db.prepare(`SELECT DISTINCT p.run AS run FROM run_process p JOIN run r ON r.id = p.run JOIN task_ref t ON t.id = r.task_ref
3
3
  WHERE p.exited_at IS NULL AND p.pid IS NOT NULL AND p.containment IS NULL AND p.container IS NULL AND ${local.sql}
4
4
  AND r.outcome IS NOT NULL${options.repo===void 0?"":" AND t.repo = ?"} ORDER BY p.run`).all(...local.params,...options.repo===void 0?[]:[options.repo]).map(row=>Number(row.run)),out=[];if(runs.length===0)return out;let census=null;for(const runId of runs){if(store.recordRunProcessExits(runId,clock()),ownedProcessCount(runOwnerTag(store,runId))>0)continue;const witnesses=db.prepare(`SELECT pid, process_group, observed_at FROM run_process
5
- WHERE run = ? AND exited_at IS NULL AND pid IS NOT NULL AND containment IS NULL AND container IS NULL AND ${mine.sql}`).all(runId,...mine.params).map(row=>({pid:Number(row.pid),group:Number(row.process_group)===1,observedAt:Date.parse(String(row.observed_at))})).filter(one=>Number.isFinite(one.observedAt));if(witnesses.length===0)continue;try{census??=(options.census??(()=>processCensus()))()}catch{return out}const targets=closeoutTargets(census,witnesses,protectedProcesses(census));if(targets.length===0)continue;const done=await stopProcesses(targets,options);census=null;const run=store.getRun(runId),ref=run===null?null:store.refById(run.taskRef);store.recordAction({at:clock().toISOString(),actor:options.actor??"worker",repo:ref?.repo??null,taskId:ref?.externalId??null,runId,action:"run processes stopped",outcome:"stopped",source:"work",detail:`run #${runId} ended (${run?.outcome??"?"}); stopped ${stoppedWords(done,options.graceMs)}`}),store.recordRunProcessExits(runId,clock()),out.push({runId,done})}return store.settleQuiescentStops(clock()),out}export function processesIn(paths){const found=new Map;if(paths.length===0||process.platform==="win32")return found;const roots=paths.map(path=>{let real=path;try{real=realpathSync(path)}catch{}return{path,real}}),note=(pid2,cwd)=>{for(const one of roots)[one.path,one.real].some(root=>cwd===root||cwd.startsWith(root+sep))&&found.set(one.path,[...found.get(one.path)??[],pid2])};if(process.platform==="linux"&&existsSync("/proc")){for(const name of readdirSync("/proc"))if(/^\d+$/.test(name))try{note(Number(name),readlinkSync(`/proc/${name}/cwd`))}catch{}return found}let text="";try{text=execFileSync("lsof",["-nP","-d","cwd","-Fpn"],{encoding:"utf8",timeout:2e4,maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}catch(error){text=String(error.stdout??"")}let pid=0;for(const line of text.split(`
5
+ WHERE run = ? AND exited_at IS NULL AND pid IS NOT NULL AND containment IS NULL AND container IS NULL AND ${mine.sql}`).all(runId,...mine.params).map(row=>({pid:Number(row.pid),group:Number(row.process_group)===1,observedAt:Date.parse(String(row.observed_at))})).filter(one=>Number.isFinite(one.observedAt));if(witnesses.length===0)continue;try{census??=(options.census??(()=>processCensus()))()}catch{return out}const targets=closeoutTargets(census,witnesses,protectedProcesses(census));if(targets.length===0)continue;const done=await stopProcesses(targets,options);census=null;const run=store.getRun(runId),ref=run===null?null:store.refById(run.taskRef);store.recordAction({at:clock().toISOString(),actor:options.actor??"worker",repo:ref?.repo??null,taskId:ref?.externalId??null,runId,action:"run processes stopped",outcome:"stopped",source:"work",detail:`run #${runId} ended (${run?.outcome??"?"}); stopped ${stoppedWords(done,options.graceMs)}`}),store.recordRunProcessExits(runId,clock()),out.push({runId,done})}return store.settleQuiescentStops(clock()),out}export function processesIn(paths){const found=new Map;if(paths.length===0||process.platform==="win32")return found;const roots=paths.map(path=>{let real=path;try{real=realpathSync(path)}catch{}return{path,real}}),note=(pid2,cwd)=>{for(const one of roots)[one.path,one.real].some(root=>cwd===root||cwd.startsWith(root+sep))&&found.set(one.path,[...found.get(one.path)??[],pid2])};if(process.platform==="linux"&&existsSync("/proc")){for(const name of readdirSync("/proc"))if(/^\d+$/.test(name))try{note(Number(name),readlinkSync(`/proc/${name}/cwd`))}catch{}return found}let text="";try{text=execFileSync("lsof",["-nP","-d","cwd","-Fpn"],{encoding:"utf8",timeout:2e4,maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],env:withoutLeadTokenEnv(process.env)})}catch(error){text=String(error.stdout??"")}let pid=0;for(const line of text.split(`
6
6
  `))line.startsWith("p")?pid=Number(line.slice(1)):line.startsWith("n")&&pid>0&&note(pid,line.slice(1));return found}export function checkoutTargets(census,inside,roots,guard){const byPid=new Map(census.map(row=>[row.pid,row])),fromRun=row=>{for(let at=row,hops=0;at!==void 0&&at.pid>1&&hops<64;at=byPid.get(at.ppid),hops++)if(roots.has(at.pid))return!0;return!1},verdict=new Map,left=row=>{const known=verdict.get(row.pid);if(known!==void 0)return known;verdict.set(row.pid,!1);const parent=byPid.get(row.ppid),ours=inside.has(row.pid)&&!row.terminal&&!guard.pids.has(row.pid)&&!guard.groups.has(row.pgid)&&(row.ppid===1||fromRun(row)||parent!==void 0&&left(parent));return verdict.set(row.pid,ours),ours};return census.filter(left)}function finishedRunProcesses(store,census){const byPid=new Map(census.map(row=>[row.pid,row])),roots=new Set,local=localWitnessSql(store.handle,"p"),rows=store.handle.prepare(`SELECT p.pid AS pid, p.observed_at AS observed_at FROM run_process p JOIN run r ON r.id = p.run
7
7
  WHERE p.exited_at IS NULL AND p.pid IS NOT NULL AND ${local.sql} AND r.outcome IS NOT NULL`).all(...local.params);for(const row of rows){const now=byPid.get(Number(row.pid)),observedAt=Date.parse(String(row.observed_at));now!==void 0&&Number.isFinite(observedAt)&&now.bornAt<=observedAt+BIRTH_SLACK_MS&&roots.add(now.pid)}return roots}const closed=new Set;export async function closeOutCheckouts(store,clock,finished,options={}){const fresh=finished.filter(one=>!closed.has(`${one.row.path}\0${one.finishedAt}`)&&existsSync(one.row.path)&&one.row.runner===null),out=[];if(fresh.length===0||process.platform==="win32")return out;const inside=(options.find??processesIn)(fresh.map(one=>one.row.path));let census=null;for(const one of fresh){closed.add(`${one.row.path}\0${one.finishedAt}`);const pids=new Set(inside.get(one.row.path)??[]);if(pids.size===0)continue;try{census??=(options.census??(()=>processCensus()))()}catch{return out}const targets=checkoutTargets(census,pids,finishedRunProcesses(store,census),protectedProcesses(census));if(targets.length===0)continue;const done=await stopProcesses(targets,options);census=null,store.recordAction({at:clock().toISOString(),actor:options.actor??"worker",repo:one.row.repo,taskId:one.taskId,runId:null,action:"checkout processes stopped",outcome:"stopped",source:"work",detail:`${basename(one.row.path)}: its task finished; stopped ${stoppedWords(done,options.graceMs)}`}),out.push({path:one.row.path,done})}return out}
package/dist/runner.js CHANGED
@@ -1,4 +1,4 @@
1
- import{mintSecret}from"./secret-mint.js";import{isAcpProvider}from"./acp-agents.js";import{verifyLaunch}from"./acp-attest.js";import{inspectAcpAgent,inspectionWords}from"./acp-inspect.js";import{createHash,timingSafeEqual}from"node:crypto";import{resolve}from"node:path";import{canonicalProject}from"./project.js";import{lifecycleOf,reportLifecycle,reviveWatchLease,watchLeaseRow}from"./store.js";import{ALL_CREDENTIAL_ENV,PROVIDER_IDS,inspectionOf}from"./provider.js";import{attestationOf,versionInRange}from"./attest.js";import{IDENTITY_FAILED_PROBE,LOGIN_PROBE,PATH_PROBE}from"./phase-routing.js";import{homedir}from"node:os";import{readAuthMode}from"./keys.js";import{signInFacts}from"./provider-connection.js";import{updateAdmissionPaused}from"./update-gate.js";export function canonicalRepos(repos){return repos.map(repo=>canonicalProject(repo)??resolve(repo))}export const RUNNER_TOKEN_MS=365*864e5,DEFAULT_LIVENESS_MS=6e4,RUNNER_HEARTBEAT_MS=15e3;export{MAX_WATCH_LEASE_MS}from"./store.js";export function register(store,options){const{name,host,capacity=1,repos=[],agents=[],now,newToken=mintToken,mutation={}}=options,token=newToken(),reclaimed=store.getRunner(name)===null?null:{runner:name,claims:store.releaseClaimsOf(name,now),worktrees:store.releaseWorktreesOf(name,now)},proposed={name,host,capacity,repos:canonicalRepos(repos),agents:[...agents],registeredAt:now.toISOString(),heartbeatAt:now.toISOString(),retiredAt:null},runner=store.saveRunner(proposed,hashToken(token),mutation);return reportLifecycle(store,workerComponent(name),"started",runner.registeredAt,now),{runner,token,reclaimed:reclaimed!==null&&(reclaimed.claims.length>0||reclaimed.worktrees.length>0)?reclaimed:null}}export function authenticate(store,name,token){const found=store.getRunner(name);return found===null?{ok:!1,reason:"unknown"}:found.runner.retiredAt!==null?{ok:!1,reason:"retired"}:Date.now()-Date.parse(found.runner.registeredAt)>RUNNER_TOKEN_MS?{ok:!1,reason:"expired"}:sameDigest(found.credentialHash,hashToken(token))?{ok:!0,runner:found.runner}:{ok:!1,reason:"bad-token"}}export function heartbeat(store,name,token,now){return store.transact(()=>{const auth=authenticate(store,name,token);return auth.ok?(store.touchRunner(name,now),{ok:!0,runner:{...auth.runner,heartbeatAt:now.toISOString()}}):auth})}export function addRunnerReposAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.name,args.token);if(!auth.ok)return auth;const repos=[...new Set([...auth.runner.repos,...canonicalRepos(args.repos)])].sort(),bound=store.bindRunnerRepos(args.name,repos,now);return bound.ok?(store.touchRunner(args.name,now),{ok:!0,runner:{...auth.runner,repos:bound.repos,heartbeatAt:now.toISOString()}}):{ok:!1,reason:bound.reason}})}export function removeRunnerRepoAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.name,args.token);if(!auth.ok)return auth;const bound=store.bindRunnerRepos(args.name,auth.runner.repos.filter(one=>one!==args.repo),now);return bound.ok?{ok:!0,runner:{...auth.runner,repos:bound.repos}}:{ok:!1,reason:bound.reason}})}export const RUNNER_NAME_MAX=60,RUNNER_CAPACITY_MAX=64;export function parseRunnerCapacity(value,{allowZero=!1}={}){const capacity=Number(value.trim());return value.trim()!==""&&Number.isInteger(capacity)&&capacity>=(allowZero?0:1)&&capacity<=RUNNER_CAPACITY_MAX?capacity:null}export function validRunnerName(name){if(name===""||name.length>RUNNER_NAME_MAX)return!1;for(const char of name){const code=char.codePointAt(0)??0;if(code<32||code===127)return!1}return!0}export function normalizeRunnerName(raw){const collapsed=raw.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return(collapsed===""?"worker":collapsed).slice(0,RUNNER_NAME_MAX)}export function registerRunnerIfIdle(store,options){const{name,now,previousGone,...registration}=options;return store.transact(()=>{let existing=store.getRunner(name),signedOff=null;const blocked=existing!==null&&(existing.runner.retiredAt===null&&isAlive(existing.runner,now)||store.liveWatchLeaseOf(name,now)!==null),drain=existing===null?null:drainOf(store,existing.runner,now);if(blocked&&existing!==null&&previousGone!==void 0){const proof=previousGone(existing);proof.gone&&(store.retireRunner(name,now),store.expireWatchLeasesOf(name,now),store.recordAction({at:now.toISOString(),actor:"toolroll up",repo:null,taskId:null,runId:null,action:"worker signed off",outcome:"processes proved gone",source:"policy",detail:proof.detail}),signedOff=proof.detail,existing=store.getRunner(name))}if(existing!==null&&drain!==null&&(isAlive(existing.runner,now)||store.liveWatchLeaseOf(name,now)!==null))return{ok:!1,reason:"runner-draining",until:drain.until,detail:`Toolroll is restarting (draining): ${name} is still stopping (scheduled by ${drain.until})`};if(existing!==null&&existing.runner.retiredAt===null&&isAlive(existing.runner,now))return{ok:!1,reason:"runner-alive",detail:`${name} heartbeated ${existing.runner.heartbeatAt} — it looks alive`};const lease=store.liveWatchLeaseOf(name,now);if(lease!==null)return{ok:!1,reason:"watch-live",detail:`${name} holds a live watch lease on ${lease.repo} until ${lease.until}`};const recoveredRuns=existing===null?0:store.recoverRunnerWork(name,now).runs.length;return{ok:!0,...register(store,{...registration,name,now,capacity:options.capacity??existing?.runner.capacity??1}),recoveredRuns,signedOff}})}export function acquireWatchLeaseAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.runner,args.token);if(!auth.ok)return{ok:!1,reason:auth.reason};if(!auth.runner.repos.includes(canonicalProject(args.repo)??resolve(args.repo)))return{ok:!1,reason:"unauthorized-repo"};const got=store.acquireWatchLease(args.runner,args.repo,args.owner,args.ttlMs,now);if(!got.ok)return{ok:!1,reason:"watch-busy",holder:got.holder,until:got.until};const recovered=got.superseded===null?0:store.recoverIncarnation(args.runner,got.superseded,now);return{ok:!0,generation:got.generation,superseded:got.superseded,recovered}})}export function heartbeatWatchLeaseAuthed(store,args,now){return store.transact(()=>{if(!authenticate(store,args.runner,args.token).ok)return!1;const renewed=store.heartbeatWatchLease(args.runner,args.repo,args.owner,args.ttlMs,now);return renewed&&store.touchRunner(args.runner,now),renewed})}export function retireRunnerIfCurrent(store,name,token,now){return store.transact(()=>{const auth=authenticate(store,name,token);return auth.ok?(store.retireRunner(name,now),store.expireWatchLeasesOf(name,now),reportLifecycle(store,workerComponent(name),"stopped",auth.runner.registeredAt,now),{ok:!0}):{ok:!1,reason:auth.reason}})}export function isAlive(runner,now,livenessMs=DEFAULT_LIVENESS_MS){if(runner.retiredAt!==null)return!1;const last=Date.parse(runner.heartbeatAt);return Number.isNaN(last)?!1:now.getTime()-last<livenessMs}export function deadRunners(store,now,livenessMs=DEFAULT_LIVENESS_MS){return store.listRunners().filter(runner=>!isAlive(runner,now,livenessMs))}export function recoveredAnything(one){return one.claims.length>0||one.worktrees.length>0||one.runs.length>0||one.requeued.length>0}export function recoverDead(store,now,livenessMs=DEFAULT_LIVENESS_MS){const recovered=[];for(const candidate of deadRunners(store,now,livenessMs)){const recovery=store.transact(()=>{const fresh=store.getRunner(candidate.name);if(fresh===null||isAlive(fresh.runner,now,livenessMs))return null;const requeued=[],claims=store.releaseClaimsOf(candidate.name,now,requeued),worktrees=store.releaseWorktreesOf(candidate.name,now),settled=store.recoverRunnerWork(candidate.name,now);return{runner:candidate.name,claims,worktrees,runs:settled.runs,requeued:[...new Set([...requeued,...settled.requeued])].filter(id=>store.getTask(id)?.state==="queued")}});recovery!==null&&recovered.push(recovery)}return recovered}function mintToken(){return mintSecret(32)}export function hashToken(token){return createHash("sha256").update(token,"utf8").digest("hex")}function sameDigest(left,right){const a=Buffer.from(left,"utf8"),b=Buffer.from(right,"utf8");return a.length===b.length&&timingSafeEqual(a,b)}const READINESS_PROBE_TIMEOUT_MS=5e3;export async function observeProviderReadiness(probe,env=process.env,providers=PROVIDER_IDS,acpChecked,claudeMode=()=>readAuthMode("claude",homedir())){return Promise.all(providers.map(async provider=>{if(isAcpProvider(provider)){const checked=acpChecked?.(provider)??null;if(checked!==null){const verified=verifyLaunch(checked.launch);return verified.ok?{provider,state:"ready",reason:`${checked.agent.name} ${checked.agent.version}, checked ${checked.recordedAt.slice(0,10)}`,probe:"version"}:{provider,state:"unavailable",reason:`${verified.problem}`,probe:"version"}}const seen=inspectAcpAgent(provider,env);return seen.found?{provider,state:"unavailable",reason:`${inspectionWords(seen)}; not checked on this computer — run \`toolroll agents check ${provider}\``,probe:"version"}:{provider,state:"unavailable",reason:inspectionWords(seen),probe:"version"}}const facts=inspectionOf(provider),version=await probe(facts.binary,["--version"],{timeoutMs:READINESS_PROBE_TIMEOUT_MS,omitEnv:ALL_CREDENTIAL_ENV});if(version.notFound)return{provider,state:"unavailable",reason:`\`${facts.binary}\` is not installed on this runner's PATH`,probe:PATH_PROBE};if(version.timedOut||version.code!==0)return{provider,state:"unavailable",reason:`\`${facts.binary} --version\` ${version.timedOut?"timed out":`exited ${version.code}`}`,probe:"version"};const installed=version.stdout.trim().split(`
2
- `)[0]??"",range=attestationOf(provider);if(range!==null&&!versionInRange(installed,range))return{provider,state:"unavailable",reason:`installed ${facts.binary} ${installed||"(unversioned)"} is outside this build's attested range ${range.floor}–${range.ceiling}`,probe:"version"};if(facts.requiresEnv!==null&&(env[facts.requiresEnv]??"")==="")return{provider,state:"unavailable",reason:`${facts.requiresEnv} is absent from this runner's environment`,probe:"key"};if(facts.requiresEnv!==null)return{provider,state:"ready",reason:`installed (${installed}); ${facts.requiresEnv} present (presence, not authorization)`,probe:"key"};if(facts.identityProbe!==null){const identity=await probe(facts.binary,[...facts.identityProbe],{timeoutMs:READINESS_PROBE_TIMEOUT_MS,omitEnv:ALL_CREDENTIAL_ENV}),asked=`\`${facts.binary} ${facts.identityProbe.join(" ")}\``;if(!identity.timedOut&&identity.code===1&&/not logged in/i.test(`${identity.stdout}
1
+ import{mintSecret}from"./secret-mint.js";import{isAcpProvider}from"./acp-agents.js";import{piSignIns}from"./pi-build.js";import{verifyLaunch}from"./acp-attest.js";import{inspectionWords,resolveAcpAgentForRunner}from"./acp-inspect.js";import{createHash,timingSafeEqual}from"node:crypto";import{resolve}from"node:path";import{canonicalProject}from"./project.js";import{lifecycleOf,reportLifecycle,reviveWatchLease,watchLeaseRow}from"./store.js";import{ALL_CREDENTIAL_ENV,PROVIDER_IDS,inspectionOf}from"./provider.js";import{attestationOf,versionInRange}from"./attest.js";import{IDENTITY_FAILED_PROBE,LOGIN_PROBE,PATH_PROBE}from"./phase-routing.js";import{homedir}from"node:os";import{readAuthMode}from"./keys.js";import{signInFacts}from"./provider-connection.js";import{updateAdmissionPaused}from"./update-gate.js";export function canonicalRepos(repos){return repos.map(repo=>canonicalProject(repo)??resolve(repo))}export const RUNNER_TOKEN_MS=365*864e5,DEFAULT_LIVENESS_MS=6e4,RUNNER_HEARTBEAT_MS=15e3;export{MAX_WATCH_LEASE_MS}from"./store.js";export function register(store,options){const{name,host,capacity=1,repos=[],agents=[],now,newToken=mintToken,mutation={}}=options,token=newToken(),reclaimed=store.getRunner(name)===null?null:{runner:name,claims:store.releaseClaimsOf(name,now),worktrees:store.releaseWorktreesOf(name,now)},proposed={name,host,capacity,repos:canonicalRepos(repos),agents:[...agents],registeredAt:now.toISOString(),heartbeatAt:now.toISOString(),retiredAt:null},runner=store.saveRunner(proposed,hashToken(token),mutation);return reportLifecycle(store,workerComponent(name),"started",runner.registeredAt,now),{runner,token,reclaimed:reclaimed!==null&&(reclaimed.claims.length>0||reclaimed.worktrees.length>0)?reclaimed:null}}export function authenticate(store,name,token){const found=store.getRunner(name);return found===null?{ok:!1,reason:"unknown"}:found.runner.retiredAt!==null?{ok:!1,reason:"retired"}:Date.now()-Date.parse(found.runner.registeredAt)>RUNNER_TOKEN_MS?{ok:!1,reason:"expired"}:sameDigest(found.credentialHash,hashToken(token))?{ok:!0,runner:found.runner}:{ok:!1,reason:"bad-token"}}export function heartbeat(store,name,token,now){return store.transact(()=>{const auth=authenticate(store,name,token);return auth.ok?(store.touchRunner(name,now),{ok:!0,runner:{...auth.runner,heartbeatAt:now.toISOString()}}):auth})}export function addRunnerReposAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.name,args.token);if(!auth.ok)return auth;const repos=[...new Set([...auth.runner.repos,...canonicalRepos(args.repos)])].sort(),bound=store.bindRunnerRepos(args.name,repos,now);return bound.ok?(store.touchRunner(args.name,now),{ok:!0,runner:{...auth.runner,repos:bound.repos,heartbeatAt:now.toISOString()}}):{ok:!1,reason:bound.reason}})}export function removeRunnerRepoAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.name,args.token);if(!auth.ok)return auth;const bound=store.bindRunnerRepos(args.name,auth.runner.repos.filter(one=>one!==args.repo),now);return bound.ok?{ok:!0,runner:{...auth.runner,repos:bound.repos}}:{ok:!1,reason:bound.reason}})}export const RUNNER_NAME_MAX=60,RUNNER_CAPACITY_MAX=64;export function parseRunnerCapacity(value,{allowZero=!1}={}){const capacity=Number(value.trim());return value.trim()!==""&&Number.isInteger(capacity)&&capacity>=(allowZero?0:1)&&capacity<=RUNNER_CAPACITY_MAX?capacity:null}export function validRunnerName(name){if(name===""||name.length>RUNNER_NAME_MAX)return!1;for(const char of name){const code=char.codePointAt(0)??0;if(code<32||code===127)return!1}return!0}export function normalizeRunnerName(raw){const collapsed=raw.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return(collapsed===""?"worker":collapsed).slice(0,RUNNER_NAME_MAX)}export function registerRunnerIfIdle(store,options){const{name,now,previousGone,...registration}=options;return store.transact(()=>{let existing=store.getRunner(name),signedOff=null;const blocked=existing!==null&&(existing.runner.retiredAt===null&&isAlive(existing.runner,now)||store.liveWatchLeaseOf(name,now)!==null),drain=existing===null?null:drainOf(store,existing.runner,now);if(blocked&&existing!==null&&previousGone!==void 0){const proof=previousGone(existing);proof.gone&&(store.retireRunner(name,now),store.expireWatchLeasesOf(name,now),store.recordAction({at:now.toISOString(),actor:"toolroll up",repo:null,taskId:null,runId:null,action:"worker signed off",outcome:"processes proved gone",source:"policy",detail:proof.detail}),signedOff=proof.detail,existing=store.getRunner(name))}if(existing!==null&&drain!==null&&(isAlive(existing.runner,now)||store.liveWatchLeaseOf(name,now)!==null))return{ok:!1,reason:"runner-draining",until:drain.until,detail:`Toolroll is restarting (draining): ${name} is still stopping (scheduled by ${drain.until})`};if(existing!==null&&existing.runner.retiredAt===null&&isAlive(existing.runner,now))return{ok:!1,reason:"runner-alive",detail:`${name} heartbeated ${existing.runner.heartbeatAt} — it looks alive`};const lease=store.liveWatchLeaseOf(name,now);if(lease!==null)return{ok:!1,reason:"watch-live",detail:`${name} holds a live watch lease on ${lease.repo} until ${lease.until}`};const recoveredRuns=existing===null?0:store.recoverRunnerWork(name,now).runs.length;return{ok:!0,...register(store,{...registration,name,now,capacity:options.capacity??existing?.runner.capacity??1}),recoveredRuns,signedOff}})}export function acquireWatchLeaseAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.runner,args.token);if(!auth.ok)return{ok:!1,reason:auth.reason};if(!auth.runner.repos.includes(canonicalProject(args.repo)??resolve(args.repo)))return{ok:!1,reason:"unauthorized-repo"};const got=store.acquireWatchLease(args.runner,args.repo,args.owner,args.ttlMs,now);if(!got.ok)return{ok:!1,reason:"watch-busy",holder:got.holder,until:got.until};const recovered=got.superseded===null?0:store.recoverIncarnation(args.runner,got.superseded,now);return{ok:!0,generation:got.generation,superseded:got.superseded,recovered}})}export function heartbeatWatchLeaseAuthed(store,args,now){return store.transact(()=>{if(!authenticate(store,args.runner,args.token).ok)return!1;const renewed=store.heartbeatWatchLease(args.runner,args.repo,args.owner,args.ttlMs,now);return renewed&&store.touchRunner(args.runner,now),renewed})}export function retireRunnerIfCurrent(store,name,token,now){return store.transact(()=>{const auth=authenticate(store,name,token);return auth.ok?(store.retireRunner(name,now),store.expireWatchLeasesOf(name,now),reportLifecycle(store,workerComponent(name),"stopped",auth.runner.registeredAt,now),{ok:!0}):{ok:!1,reason:auth.reason}})}export function isAlive(runner,now,livenessMs=DEFAULT_LIVENESS_MS){if(runner.retiredAt!==null)return!1;const last=Date.parse(runner.heartbeatAt);return Number.isNaN(last)?!1:now.getTime()-last<livenessMs}export function deadRunners(store,now,livenessMs=DEFAULT_LIVENESS_MS){return store.listRunners().filter(runner=>!isAlive(runner,now,livenessMs))}export function recoveredAnything(one){return one.claims.length>0||one.worktrees.length>0||one.runs.length>0||one.requeued.length>0}export function recoverDead(store,now,livenessMs=DEFAULT_LIVENESS_MS){const recovered=[];for(const candidate of deadRunners(store,now,livenessMs)){const recovery=store.transact(()=>{const fresh=store.getRunner(candidate.name);if(fresh===null||isAlive(fresh.runner,now,livenessMs))return null;const requeued=[],claims=store.releaseClaimsOf(candidate.name,now,requeued),worktrees=store.releaseWorktreesOf(candidate.name,now),settled=store.recoverRunnerWork(candidate.name,now);return{runner:candidate.name,claims,worktrees,runs:settled.runs,requeued:[...new Set([...requeued,...settled.requeued])].filter(id=>store.getTask(id)?.state==="queued")}});recovery!==null&&recovered.push(recovery)}return recovered}function mintToken(){return mintSecret(32)}export function hashToken(token){return createHash("sha256").update(token,"utf8").digest("hex")}function sameDigest(left,right){const a=Buffer.from(left,"utf8"),b=Buffer.from(right,"utf8");return a.length===b.length&&timingSafeEqual(a,b)}const READINESS_PROBE_TIMEOUT_MS=5e3;export async function observeProviderReadiness(probe,env=process.env,providers=PROVIDER_IDS,acpChecked,claudeMode=()=>readAuthMode("claude",homedir())){return Promise.all(providers.map(async provider=>{if(isAcpProvider(provider)){const checked=acpChecked?.(provider)??null;if(checked!==null){const verified=verifyLaunch(checked.launch);return verified.ok?{provider,state:"ready",reason:`${checked.agent.name} ${checked.agent.version}, checked ${checked.recordedAt.slice(0,10)}`,probe:"version"}:{provider,state:"unavailable",reason:`${verified.problem}`,probe:"version"}}const seen=resolveAcpAgentForRunner(provider,{env});return seen.found?{provider,state:"unavailable",reason:`${inspectionWords(seen)}; not checked on this computer — run \`toolroll agents check ${provider}\``,probe:"version"}:{provider,state:"unavailable",reason:inspectionWords(seen),probe:PATH_PROBE}}const facts=inspectionOf(provider),version=await probe(facts.binary,["--version"],{timeoutMs:READINESS_PROBE_TIMEOUT_MS,omitEnv:ALL_CREDENTIAL_ENV});if(version.notFound)return{provider,state:"unavailable",reason:`\`${facts.binary}\` is not installed on this runner's PATH`,probe:PATH_PROBE};if(version.timedOut||version.code!==0)return{provider,state:"unavailable",reason:`\`${facts.binary} --version\` ${version.timedOut?"timed out":`exited ${version.code}`}`,probe:"version"};const installed=version.stdout.trim().split(`
2
+ `)[0]??"",range=attestationOf(provider);if(range!==null&&!versionInRange(installed,range))return{provider,state:"unavailable",reason:`installed ${facts.binary} ${installed||"(unversioned)"} is outside this build's attested range ${range.floor}–${range.ceiling}`,probe:"version"};if(facts.requiresEnv!==null&&(env[facts.requiresEnv]??"")==="")return{provider,state:"unavailable",reason:`${facts.requiresEnv} is absent from this runner's environment`,probe:"key"};if(facts.requiresEnv!==null)return{provider,state:"ready",reason:`installed (${installed}); ${facts.requiresEnv} present (presence, not authorization)`,probe:"key"};if(provider==="pi"){const signIns=piSignIns(homedir());return signIns===null?{provider,state:"unavailable",reason:"Pi's sign-ins file (~/.pi/agent/auth.json) can't be read",probe:"identity"}:signIns===0?{provider,state:"unavailable",reason:"Pi isn't signed in to any model service — run `pi`, then /login",probe:"identity"}:{provider,state:"ready",reason:`installed (${installed}); signed in to ${signIns===1?"one model service":`${signIns} model services`}`,probe:"identity"}}if(facts.identityProbe!==null){const identity=await probe(facts.binary,[...facts.identityProbe],{timeoutMs:READINESS_PROBE_TIMEOUT_MS,omitEnv:ALL_CREDENTIAL_ENV}),asked=`\`${facts.binary} ${facts.identityProbe.join(" ")}\``;if(!identity.timedOut&&identity.code===1&&/not logged in/i.test(`${identity.stdout}
3
3
  ${identity.stderr}`))return{provider,state:"unavailable",reason:`${asked} says not logged in`,probe:"identity"};if(identity.code!==0)return{provider,state:"unavailable",reason:`${asked} ${identity.timedOut?"timed out":`exited ${identity.code}`}`,probe:IDENTITY_FAILED_PROBE};const who=identity.stdout.trim().split(`
4
4
  `)[0]??"";return{provider,state:"ready",reason:`installed (${installed}); ${who===""?"logged in":who}`,probe:"identity"}}if(provider==="claude"&&claudeMode()==="subscription"){const status=await probe(facts.binary,["auth","status","--json"],{timeoutMs:READINESS_PROBE_TIMEOUT_MS,omitEnv:ALL_CREDENTIAL_ENV});if(signInFacts("claude",status).state==="signed-out")return{provider,state:"unavailable",reason:"`claude auth status` says not logged in",probe:LOGIN_PROBE}}return{provider,state:"unknown",reason:`installed (${installed}); no non-spending login check exists — a real run is the proof`,probe:"version"}}))}export function reportProviderReadinessAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.name,args.token);return auth.ok&&store.recordProviderReadiness(args.name,args.observations,now),auth})}export const workerComponent=name=>`worker:${name}`;export function drainRunnerIfCurrent(store,name,token,now,until){return store.transact(()=>{const auth=authenticate(store,name,token);return auth.ok?reportLifecycle(store,workerComponent(name),"draining",auth.runner.registeredAt,now,{drainUntil:until}):!1})}export function drainOf(store,runner,now){const row=lifecycleOf(store,workerComponent(runner.name));return row===null||row.holder!==runner.registeredAt?null:row.state==="stopped"?{until:row.changedAt,ended:!0}:row.state!=="draining"||row.drainUntil===null?null:{until:row.drainUntil,ended:Date.parse(row.drainUntil)<=now.getTime()}}export function renewWatchLeaseAuthed(store,args,now){return store.transact(()=>{const auth=authenticate(store,args.runner,args.token);if(!auth.ok)return{ok:!1,reason:auth.reason};if(store.heartbeatWatchLease(args.runner,args.repo,args.owner,args.ttlMs,now))return store.touchRunner(args.runner,now),{ok:!0,lateMs:0};const row=watchLeaseRow(store,args.runner,args.repo);return row===null?{ok:!1,reason:"missing"}:row.owner!==args.owner?{ok:!1,reason:"taken"}:boundTo(auth.runner,args.repo)?updateAdmissionPaused(store.raw())||drainOf(store,auth.runner,now)!==null?{ok:!1,reason:"paused"}:reviveWatchLease(store,args.runner,args.repo,args.owner,row.generation,args.ttlMs,now)?(store.touchRunner(args.runner,now),{ok:!0,lateMs:Math.max(0,now.getTime()-Date.parse(row.expiresAt))}):{ok:!1,reason:"taken"}:{ok:!1,reason:"unbound"}})}function boundTo(runner,repo){if(runner.repos.includes(repo))return!0;try{return runner.repos.includes(canonicalProject(repo)??resolve(repo))}catch{return!1}}