@uniqbit/mate-core 0.20.0 → 0.21.1

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 (287) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-capability-plugins/companion-mentions/hooks/register.ts +1 -1
  3. package/claude-plugin/hooks/hooks.json +10 -1
  4. package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
  5. package/opencode-plugin/src/server.ts +9 -2
  6. package/package.json +2 -1
  7. package/src/cli/commands/artifact/delivery/environment.ts +28 -8
  8. package/src/cli/commands/artifact/delivery/link.ts +28 -9
  9. package/src/cli/commands/artifact/delivery/output.ts +7 -0
  10. package/src/cli/commands/companion/update.ts +2 -19
  11. package/src/cli/commands/factory/factory.ts +11 -1
  12. package/src/cli/commands/install.ts +47 -36
  13. package/src/cli/commands/launch/claude.ts +2 -0
  14. package/src/cli/commands/launch/shared.ts +33 -6
  15. package/src/cli/commands/plugin/install.ts +27 -11
  16. package/src/cli/commands/report/index.ts +180 -184
  17. package/src/cli/commands/report/markdown.ts +67 -72
  18. package/src/cli/commands/shared/companion-selection.ts +3 -1
  19. package/src/cli/commands/studio/access.ts +6 -14
  20. package/src/cli/commands/studio/areas.ts +112 -33
  21. package/src/cli/commands/studio/companion-add.ts +87 -0
  22. package/src/cli/commands/studio/companion-removal.ts +15 -8
  23. package/src/cli/commands/studio/factory-credential.ts +1 -15
  24. package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
  25. package/src/cli/commands/studio/factory-relay.ts +18 -0
  26. package/src/cli/commands/studio/graph-model.ts +61 -0
  27. package/src/cli/commands/studio/graph.ts +336 -0
  28. package/src/cli/commands/studio/index.ts +4 -4
  29. package/src/cli/commands/studio/payload.ts +42 -15
  30. package/src/cli/commands/studio/repository-add.ts +116 -0
  31. package/src/cli/commands/studio/routes.ts +6 -0
  32. package/src/cli/commands/studio/selection.ts +12 -3
  33. package/src/cli/commands/studio/server.ts +127 -5
  34. package/src/cli/commands/studio/services.ts +40 -0
  35. package/src/cli/commands/studio/terminal.ts +45 -3
  36. package/src/cli/commands/studio/views/vault/markdown-tree.ts +84 -3
  37. package/src/cli/commands/studio/workset-session.ts +47 -14
  38. package/src/cli/commands/unwrap.ts +3 -0
  39. package/src/cli/commands/update.ts +2 -0
  40. package/src/cli/commands/vscode/release-vsix.json +4 -0
  41. package/src/cli/commands/vscode/setup.ts +71 -13
  42. package/src/cli/commands/vscode/vsix.ts +48 -7
  43. package/src/cli/commands/working/cleanup.ts +40 -8
  44. package/src/cli/commands/working/worktree.ts +176 -35
  45. package/src/cli/main.ts +17 -2
  46. package/src/cli/usage.ts +1 -1
  47. package/src/hooks/rtk-worktree-git.ts +48 -0
  48. package/src/hooks/validate-artifact-path.ts +38 -7
  49. package/src/lib/delivery/branch-template.ts +122 -0
  50. package/src/lib/delivery/branches.ts +21 -16
  51. package/src/lib/delivery/checkout.ts +102 -0
  52. package/src/lib/delivery/environment.ts +2 -0
  53. package/src/lib/delivery/merge-git.ts +13 -1
  54. package/src/lib/delivery/record-delivery.ts +83 -29
  55. package/src/lib/delivery/record.ts +15 -3
  56. package/src/lib/delivery/resolve-branch.ts +157 -110
  57. package/src/lib/factory/attach-client.ts +11 -1
  58. package/src/lib/factory/broker.ts +37 -40
  59. package/src/lib/factory/client.ts +22 -1
  60. package/src/lib/factory/clone-url.ts +39 -0
  61. package/src/lib/factory/command.ts +21 -5
  62. package/src/lib/factory/git-auth.ts +61 -0
  63. package/src/lib/factory/git-credential-store.ts +181 -0
  64. package/src/lib/factory/ids.ts +12 -2
  65. package/src/lib/factory/outcomes/actions.ts +20 -4
  66. package/src/lib/factory/outcomes/index.ts +77 -11
  67. package/src/lib/factory/outcomes/lifecycle.ts +9 -2
  68. package/src/lib/factory/outcomes/sessions.ts +23 -1
  69. package/src/lib/factory/prepare.ts +9 -3
  70. package/src/lib/factory/runner/scheduler.ts +96 -14
  71. package/src/lib/factory/runner/workflow.ts +5 -1
  72. package/src/lib/factory/runtime.ts +143 -43
  73. package/src/lib/orchestrator/companion-hub.ts +6 -1
  74. package/src/lib/orchestrator/engine-floor.ts +48 -0
  75. package/src/lib/orchestrator/launcher.ts +34 -1
  76. package/src/lib/orchestrator/projection-claude-commands.ts +2 -2
  77. package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
  78. package/src/lib/orchestrator/projection-claude-links.ts +32 -8
  79. package/src/lib/orchestrator/projection-claude-skills.ts +2 -2
  80. package/src/lib/orchestrator/projection-entries.ts +22 -18
  81. package/src/lib/orchestrator/projection-opencode-copies.ts +65 -21
  82. package/src/lib/orchestrator/projection-runtime-documents.ts +66 -43
  83. package/src/lib/orchestrator/projection-types.ts +28 -1
  84. package/src/lib/orchestrator/refresh-working-claude-links.ts +3 -1
  85. package/src/lib/orchestrator/session-prepare.ts +6 -1
  86. package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
  87. package/src/lib/orchestrator/types.ts +4 -0
  88. package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
  89. package/src/lib/orchestrator/working-repo-projection.ts +24 -4
  90. package/src/lib/orchestrator/wrap-pass.ts +1 -0
  91. package/src/lib/public-npm.ts +95 -50
  92. package/src/lib/session-state.ts +72 -2
  93. package/src/lib/update-checker.ts +7 -1
  94. package/src/lib/usage/aggregate.ts +202 -0
  95. package/src/lib/usage/cache.ts +87 -0
  96. package/src/lib/usage/claude-pricing.ts +71 -0
  97. package/src/lib/usage/claude.ts +189 -0
  98. package/src/lib/usage/collect.ts +56 -0
  99. package/src/lib/usage/opencode.ts +188 -0
  100. package/src/lib/usage/records.ts +80 -0
  101. package/src/lib/usage/rtk-database.ts +72 -0
  102. package/src/lib/usage/savings.ts +209 -0
  103. package/src/lib/usage/scope.ts +182 -0
  104. package/src/lib/usage/source.ts +102 -0
  105. package/src/lib/usage/types.ts +143 -0
  106. package/src/lib/usage/window.ts +37 -0
  107. package/src/lib/workset/factory-local.ts +157 -0
  108. package/src/lib/workset/record.ts +25 -11
  109. package/src/lib/workset/repositories.ts +118 -25
  110. package/src/lib/workset/worktree-include.ts +161 -0
  111. package/src/lib/workset/worktree-index.ts +6 -2
  112. package/src/lib/workset/worktree.ts +591 -101
  113. package/src/opencode/companion-hooks.ts +46 -8
  114. package/src/opencode/companion-policy.ts +18 -5
  115. package/src/opencode/enter-worktree.ts +254 -6
  116. package/src/opencode/session-register.ts +2 -2
  117. package/src/runtime/claude-bg-isolation.ts +138 -0
  118. package/src/runtime/companion-git.ts +10 -2
  119. package/src/runtime/companion-guidance.ts +17 -4
  120. package/src/runtime/current-branch.ts +16 -2
  121. package/src/runtime/entered-worktree.ts +24 -0
  122. package/src/runtime/git-tracked.ts +60 -0
  123. package/src/runtime/repo-destination.ts +72 -0
  124. package/src/runtime/repo-local.ts +25 -3
  125. package/src/runtime/rtk-git-guard.ts +66 -0
  126. package/src/runtime/runtime-document-manifest.ts +229 -19
  127. package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
  128. package/src/runtime/secret-guard.ts +9 -2
  129. package/src/runtime/secret-policy-weakening.ts +122 -0
  130. package/src/runtime/serving-claude-wrap.ts +15 -2
  131. package/src/runtime/umbrella-folder.ts +56 -0
  132. package/src/runtime/wrap-state.ts +5 -13
  133. package/src/studio.ts +37 -0
  134. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +61 -6
  135. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +8 -4
  136. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +9 -5
  137. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +5 -4
  138. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +10 -4
  139. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +5 -1
  140. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +61 -6
  141. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +8 -4
  142. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +9 -5
  143. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +5 -4
  144. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +10 -4
  145. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +5 -1
  146. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +307 -42
  147. package/src/tools/setup/capabilities/rtk.ts +93 -1
  148. package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
  149. package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
  150. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -4
  151. package/src/tools/setup/dynamic-plugins/install.ts +24 -22
  152. package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
  153. package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
  154. package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
  155. package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
  156. package/src/tools/setup/mate.ts +3 -3
  157. package/src/tools/setup/plugins/gitignore.ts +15 -9
  158. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  159. package/src/tools/setup/providers/claude.ts +25 -3
  160. package/src/tools/setup/utils.ts +4 -2
  161. package/src/tools/setup/working-repo-cleanup.ts +2 -2
  162. package/src/tools/setup/working-repo-local-state.ts +2 -0
  163. package/src/tools/setup.ts +25 -14
  164. package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
  165. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
  166. package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
  167. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
  168. package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
  169. package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
  170. package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
  171. package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
  172. package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
  173. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
  174. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
  175. package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
  176. package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
  177. package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
  178. package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
  179. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  180. package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
  181. package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
  182. package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
  183. package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
  184. package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
  185. package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
  186. package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
  187. package/studio-dist/client/assets/select-CnaMd617.js +1 -0
  188. package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
  189. package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
  190. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
  191. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
  192. package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
  193. package/studio-dist/client/assets/store-Dw34catY.js +1 -0
  194. package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
  195. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
  196. package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
  197. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
  198. package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
  199. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  200. package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
  201. package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
  202. package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
  203. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
  204. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +102 -35
  205. package/studio-dist/server/assets/{actions-Bvgj9eb8.js → actions-DYSv-9VV.js} +10 -4
  206. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
  207. package/studio-dist/server/assets/{button-CIJqAhni.js → button-CgOIVdmD.js} +13 -1702
  208. package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
  209. package/studio-dist/server/assets/{companion-view-DISASvdJ.js → companion-view-BKVXD3TO.js} +3 -3
  210. package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
  211. package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
  212. package/studio-dist/server/assets/{factory-DUTa0eDs.js → factory-C7Ybg0xG.js} +1256 -353
  213. package/studio-dist/server/assets/{factory-DGPmNGbo.js → factory-Df5uAHjb.js} +53 -6
  214. package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
  215. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  216. package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
  217. package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
  218. package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
  219. package/studio-dist/server/assets/graph-CSje3029.js +801 -0
  220. package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
  221. package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
  222. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  223. package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
  224. package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
  225. package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
  226. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  227. package/studio-dist/server/assets/{markdown-view-Bn7xPdks.js → markdown-view-BR8dJ7aR.js} +28 -9
  228. package/studio-dist/server/assets/{panel-3Jmn4awF.js → panel-BR_t9iMM.js} +4 -4
  229. package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
  230. package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
  231. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  232. package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
  233. package/studio-dist/server/assets/{reports-D6YMqhnO.js → reports-CQ9qQ1-n.js} +9 -10
  234. package/studio-dist/server/assets/{reports-C06RXVE2.js → reports-dYDEoBeq.js} +3 -3
  235. package/studio-dist/server/assets/{router-C8MGqlAY.js → router-DkRHNTpE.js} +787 -2862
  236. package/studio-dist/server/assets/{routes-BcFgvqf7.js → routes-B6GfOew4.js} +22 -171
  237. package/studio-dist/server/assets/{search-JAKurDNh.js → search-BJnWLfkG.js} +21 -2
  238. package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
  239. package/studio-dist/server/assets/{shell-DS3wUexh.js → shell-Hq-hXgnT.js} +6 -5
  240. package/studio-dist/server/assets/{skills-BEnOxiDl.js → skills-B7nEuVbx.js} +9 -8
  241. package/studio-dist/server/assets/{skills-CtrBAtX3.js → skills-B_YYL7q8.js} +3 -3
  242. package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
  243. package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
  244. package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
  245. package/studio-dist/server/assets/{steps-Dq_CwY_s.js → steps-D56DApvK.js} +1 -1
  246. package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
  247. package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
  248. package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
  249. package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
  250. package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
  251. package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
  252. package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
  253. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-M2GBs8s3.js → useSelector-DUmCUXAs.js} +4 -668
  254. package/studio-dist/server/assets/{vault-Fvxt2Tzl.js → vault-BDuIUq0F.js} +8 -5
  255. package/studio-dist/server/assets/{vault-BmWnryh3.js → vault-BVLp6zu3.js} +3 -3
  256. package/studio-dist/server/assets/{views-BgYa-za2.js → views-flRUr21z.js} +4 -4
  257. package/studio-dist/server/assets/{warnings-DzR6fyZh.js → warnings-CDy9pdgL.js} +3 -2
  258. package/studio-dist/server/assets/{delivery-path-C29fBynY.js → workflow-D9GKI2EV.js} +132 -106
  259. package/studio-dist/server/server.js +582 -8
  260. package/src/cli/commands/report/collector.ts +0 -288
  261. package/studio-dist/client/assets/app-CdPiFv59.css +0 -2
  262. package/studio-dist/client/assets/button-BIIHE0EQ.js +0 -3
  263. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +0 -1
  264. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +0 -1
  265. package/studio-dist/client/assets/factory-BZy0E8ty.js +0 -4
  266. package/studio-dist/client/assets/index-B3wkMzjA.js +0 -40
  267. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +0 -1
  268. package/studio-dist/client/assets/panel-CbajlC3p.js +0 -1
  269. package/studio-dist/client/assets/prepaint-CwSrpdFA.js +0 -27
  270. package/studio-dist/client/assets/react-CN2GSx7x.js +0 -1
  271. package/studio-dist/client/assets/reports-DllhYQ5_.js +0 -1
  272. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  273. package/studio-dist/client/assets/routes-COm-G3mK.js +0 -1
  274. package/studio-dist/client/assets/skills-DmWAy-jZ.js +0 -1
  275. package/studio-dist/client/assets/specs-BG3Wi3ln.js +0 -1
  276. package/studio-dist/client/assets/steps-DFsH3Neu.js +0 -1
  277. package/studio-dist/client/assets/vault-B2q1nBY5.js +0 -1
  278. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +0 -1
  279. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +0 -1
  280. package/studio-dist/server/assets/companions-BYbHWKOZ.js +0 -15
  281. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
  282. package/studio-dist/server/assets/prepaint-DJfTQ_VH.js +0 -45
  283. package/studio-dist/server/assets/react-Ce6dj15C.js +0 -46
  284. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
  285. package/studio-dist/server/assets/specs-C8rv34-5.js +0 -211
  286. package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
  287. package/studio-dist/server/assets/workflow-liRYecHk.js +0 -73
@@ -56,8 +56,10 @@ export interface RunnerOptions {
56
56
  rankFor?: (id: string) => Promise<number | null>;
57
57
  /** The Workset's identity for prompts the runner builds itself. */
58
58
  recordFor?: (id: string) => Promise<Pick<WorksetRecord, "id" | "title"> | undefined>;
59
- /** Whether a person works on the Workset in a live session; pickup and Return to automation wait for it. */
59
+ /** Whether a person works on the Workset in a live session; pickup waits for it. */
60
60
  sessionLive?: (id: string) => boolean;
61
+ /** Ends the person's live session for Return to automation; without it, Return waits for it. */
62
+ endSession?: (id: string) => Promise<void>;
61
63
  /** Told once a Workset's run has ended, whatever its outcome; pickup hangs off this. */
62
64
  onSettled?: (id: string) => void;
63
65
  setTimer?: (callback: () => void, ms: number) => unknown;
@@ -67,6 +69,9 @@ export interface RunnerOptions {
67
69
  /** How often runs waiting for a Workset container slot try again, besides settles and session ends. */
68
70
  export const SLOT_RETRY_MS = 30_000;
69
71
 
72
+ /** How long Delete waits for a cancelled run to end before it gives up. */
73
+ export const STOP_WAIT_MS = 30_000;
74
+
70
75
  function isSlotBusy(error: unknown): boolean {
71
76
  return error instanceof FactoryError && error.code === "busy";
72
77
  }
@@ -171,35 +176,42 @@ export class FactoryRunner {
171
176
 
172
177
  /**
173
178
  * Starts the stage pickup chose unless the Outcome is busy, not idle or with a person; true
174
- * when it was requested. Under the Workset's lock, so it never races Return to automation.
179
+ * when it was requested. Under the Workset's lock, so it never races Return to automation
180
+ * or `park`; `pickable` re-checks there that the Outcome still wants the stage.
175
181
  */
176
- pickUp(id: string, stage: RunnableStage): Promise<boolean> {
182
+ pickUp(id: string, stage: RunnableStage, pickable?: () => Promise<boolean>): Promise<boolean> {
177
183
  return this.locks.run(id, async () => {
178
184
  if (this.isActive(id) || this.options.sessionLive?.(id)) return false;
179
185
  const { execution, control } = await this.options.runs.facts(id);
180
186
  // A person has the conversation; only Return to automation continues it.
181
187
  if (execution.state !== "idle" || control.mode !== "automatic") return false;
188
+ if (pickable && !(await pickable())) return false;
182
189
  await this.request(id, stage);
183
190
  return true;
184
191
  });
185
192
  }
186
193
 
187
194
  /**
188
- * Return to automation, refused while the Outcome's session is live: links the changes the
189
- * person proposed, logs task progress and hands control back, then starts the stage the
190
- * factory would start by itself, told that a person worked in the conversation. One step
191
- * under the Workset's lock, so no pickup starts that stage in between. A waiting question
192
- * stays waiting; failed and later stages wait for a person. On failure the person keeps
193
- * control, with the reason recorded.
195
+ * Return to automation: ends the person's live session while they hold control (refused
196
+ * when it cannot), links the changes the person proposed, logs task progress and hands
197
+ * control back, then starts the stage the factory would start by itself, told that a person
198
+ * worked in the conversation. One step under the Workset's lock, so no pickup starts that
199
+ * stage in between. A waiting question stays waiting; failed and later stages wait for a
200
+ * person. On failure the person keeps control, with the reason recorded.
194
201
  */
195
202
  returnToAutomation(id: string): Promise<void> {
196
203
  return this.locks.run(id, async () => {
197
- if (this.options.sessionLive?.(id)) {
198
- throw new StageError(
199
- "exit Claude in the Outcome's terminal first, then return to automation",
200
- );
204
+ const { runs, endSession, sessionLive } = this.options;
205
+ if (sessionLive?.(id)) {
206
+ // Only a person in control closes the session; a takeover still waiting is refused below.
207
+ const { control } = await runs.facts(id);
208
+ if (endSession && control.mode === "manual") await endSession(id);
209
+ if (sessionLive(id)) {
210
+ throw new StageError(
211
+ "exit Claude in the Outcome's terminal first, then return to automation",
212
+ );
213
+ }
201
214
  }
202
- const { runs } = this.options;
203
215
  const { companionPath } = this.options.depsFor(id);
204
216
  const log = (text: string) => void this.live.log(id, text);
205
217
  const returned = await runs.control.giveBack(id, async (changesBefore) => {
@@ -251,6 +263,28 @@ export class FactoryRunner {
251
263
  if (request) request.rank = (await this.options.rankFor?.(id)) ?? null;
252
264
  }
253
265
 
266
+ /**
267
+ * Later, under the Workset's lock: `refusal` is checked before anything changes, then a
268
+ * queued request is dropped and `unstart` runs. A pickup runs wholly before or after.
269
+ * `refusal` is told whether a run is running, which its facts may not show yet.
270
+ */
271
+ park(
272
+ id: string,
273
+ refusal: (running: boolean) => Promise<string | null>,
274
+ unstart: () => Promise<unknown>,
275
+ ): Promise<void> {
276
+ return this.locks.run(id, async () => {
277
+ const refuse = async () => {
278
+ const reason = await refusal(this.active.has(id));
279
+ if (reason) throw new StageError(reason);
280
+ };
281
+ await refuse();
282
+ // The queued request may have started while the check read.
283
+ if (!(await this.dequeue(id)) && this.active.has(id)) await refuse();
284
+ await unstart();
285
+ });
286
+ }
287
+
254
288
  /** Drops a queued request, leaving the Workset idle; a running one is left to finish. */
255
289
  async dequeue(id: string): Promise<boolean> {
256
290
  const queued = this.queue.findIndex((request) => request.id === id);
@@ -272,6 +306,54 @@ export class FactoryRunner {
272
306
  controller.abort(new StageError("cancelled"));
273
307
  }
274
308
 
309
+ /**
310
+ * Cancels a queued or running run and waits until it has ended; no run, nothing to do.
311
+ * `refusal` is checked and the run cancelled under the Workset's lock, so a refused caller
312
+ * cancels nothing. The wait is outside it: a settling run takes the lock to hand over.
313
+ */
314
+ async stop(id: string, refusal: () => Promise<string | null> = async () => null): Promise<void> {
315
+ const cancelled = await this.locks.run(id, async () => {
316
+ const reason = await refusal();
317
+ if (reason) throw new StageError(reason);
318
+ if (!this.isActive(id)) return false;
319
+ try {
320
+ await this.cancel(id);
321
+ } catch (error) {
322
+ // The run may have ended on its own between the check and the cancel.
323
+ if (this.isActive(id)) throw error;
324
+ }
325
+ return true;
326
+ });
327
+ if (!cancelled) return;
328
+ const clearTimer =
329
+ this.options.clearTimer ??
330
+ ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
331
+ let timer: unknown;
332
+ const timedOut = new Promise<false>((resolve) => {
333
+ timer = this.setTimer(() => resolve(false), STOP_WAIT_MS);
334
+ });
335
+ const ended = await Promise.race([this.idle(id).then(() => true), timedOut]);
336
+ clearTimer(timer);
337
+ if (!ended) throw new StageError(`the run of Workset ${id} did not stop; try again`);
338
+ }
339
+
340
+ /**
341
+ * Delete, under the Workset's lock so no pickup starts a run meanwhile: `refusal` is
342
+ * re-checked and a run that started again refuses, then `remove` runs.
343
+ */
344
+ discard(
345
+ id: string,
346
+ refusal: () => Promise<string | null>,
347
+ remove: () => Promise<unknown>,
348
+ ): Promise<void> {
349
+ return this.locks.run(id, async () => {
350
+ const reason = await refusal();
351
+ if (reason) throw new StageError(reason);
352
+ if (this.isActive(id)) throw new StageError(`Workset ${id} started a run again; try again`);
353
+ await remove();
354
+ });
355
+ }
356
+
275
357
  /**
276
358
  * Runs waiting for a Workset container slot try again; called when a run settles, a
277
359
  * session ends, and on a timer while any waits.
@@ -488,7 +488,11 @@ export async function applyStage(
488
488
  await commitWork(deps, id, applyMessage(pending, id));
489
489
  const clone = path.join(deps.stateDir, "repos", repoKey(repository));
490
490
  check(
491
- await deps.run("git", ["-C", clone, "push", "origin", branch], deps.companionPath),
491
+ await deps.run(
492
+ "git",
493
+ ["-C", clone, "push", "--end-of-options", "origin", branch],
494
+ deps.companionPath,
495
+ ),
492
496
  `pushing ${branch}`,
493
497
  );
494
498
  deps.log(`\npushed ${branch}\n`);
@@ -1,14 +1,15 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import {
4
- listRefsWith,
5
- newBranchBase,
6
- resolveDeliveryBranch,
7
- worktreeAddArgs,
8
- } from "../delivery/resolve-branch";
3
+ import { parseRemote } from "../delivery/forge";
4
+ import { deliveryCheckout } from "../delivery/checkout";
5
+ import { newBranchBase, resolveDeliveryBranch, worktreeAddArgs } from "../delivery/resolve-branch";
9
6
  import { resolveWorksetBranch } from "../workset/record";
10
7
 
11
- import { type CommandResult, type CommandRunner, runCommand } from "./command";
8
+ import { type CommandOptions, type CommandResult, type CommandRunner, runCommand } from "./command";
9
+ import { checkedCloneUrl } from "./clone-url";
10
+ import { authFailureMessage, gitAuthEnv, isAuthFailure, scrubToken } from "./git-auth";
11
+ import type { GitCredentials } from "./git-credential-store";
12
+ import type { AgentCredential } from "./credential-store";
12
13
  import { KeyedSerial } from "./keyed-serial";
13
14
  import { readWorktreeBranch } from "./worktree-branch";
14
15
  import {
@@ -27,11 +28,12 @@ import {
27
28
 
28
29
  /**
29
30
  * The Workset runtime: one unprivileged Sysbox container per Workset, with its
30
- * own worktree on `workset/<workset>`, driven through the inner Docker daemon.
31
+ * own worktree on its Delivery Branch (default `workset/<workset>`), driven through
32
+ * the inner Docker daemon.
31
33
  *
32
34
  * Runs inside the factory broker, which alone holds the inner socket. Callers
33
35
  * name a Workset, a repository and a command; image, mounts, runtime and
34
- * flags are fixed here. Git runs as the unprivileged user so clones and
36
+ * flags and the Docker client environment are fixed here. Git runs as the unprivileged user so clones and
35
37
  * worktrees keep the uid the Workset containers share.
36
38
  */
37
39
 
@@ -42,6 +44,8 @@ export interface WorksetInfo {
42
44
  repository: string | null;
43
45
  branch: string;
44
46
  state: WorksetState;
47
+ /** What resolving a new worktree's Delivery Branch reported, e.g. a dependency not inherited. */
48
+ warnings?: string[];
45
49
  }
46
50
 
47
51
  export interface SpawnRequest {
@@ -61,8 +65,6 @@ export type MemorySize = "agent" | "build";
61
65
  export interface ExecRequest {
62
66
  id: string;
63
67
  command: string[];
64
- /** Per-command environment; values reach only this command. */
65
- env?: Record<string, string>;
66
68
  /** Working directory relative to the worktree. */
67
69
  cwd?: string;
68
70
  /** Standard input for the command, closed after it is written. */
@@ -88,6 +90,8 @@ export interface RuntimeOptions {
88
90
  user: string;
89
91
  /** Companions must resolve inside this directory. */
90
92
  companionsDir: string;
93
+ /** The Git tokens a clone or fetch of a remote may use; none when unset. */
94
+ gitCredentials?: GitCredentials;
91
95
  /** Unset leaves containers unlimited. */
92
96
  limits?: WorksetLimits;
93
97
  /** How many Workset containers may run at once; unset caps nothing. */
@@ -126,6 +130,10 @@ export function assertSessionMarker(session: unknown): asserts session is string
126
130
  }
127
131
  }
128
132
  const STOP_SECONDS = "10";
133
+ /** A companion clone that takes longer is abandoned. */
134
+ const CLONE_TIMEOUT_MS = 180_000;
135
+ /** A reachability check that takes longer fails. */
136
+ const REMOTE_CHECK_TIMEOUT_MS = 60_000;
129
137
  /**
130
138
  * How long after its last activity a container is safe from making room: an AFK turn
131
139
  * spawns its container, then attaches its bridge a moment later.
@@ -232,25 +240,109 @@ export class WorksetRuntime {
232
240
  return path.join(this.options.stateDir, "worktrees", id);
233
241
  }
234
242
 
235
- private docker(args: string[], env?: Record<string, string>): Promise<CommandResult> {
236
- return this.run("docker", args, { env: { ...this.dockerEnv(), ...env } });
243
+ private docker(args: string[]): Promise<CommandResult> {
244
+ return this.run("docker", args, { env: this.dockerEnv() });
237
245
  }
238
246
 
239
- private git(args: string[]): Promise<CommandResult> {
247
+ /**
248
+ * `remote` names the URL the command talks to: its matching token reaches this one command
249
+ * through its environment, output is scrubbed of it, and a refusal is reported as one.
250
+ */
251
+ private async git(
252
+ args: string[],
253
+ options: Pick<CommandOptions, "env" | "stdin" | "timeoutMs"> & { remote?: string } = {},
254
+ ): Promise<CommandResult> {
255
+ const { remote, ...commandOptions } = options;
256
+ const token =
257
+ remote === undefined ? null : (this.options.gitCredentials?.forUrl(remote) ?? null);
258
+ const auth = remote === undefined ? {} : gitAuthEnv(this.options.stateDir, token);
259
+ // A configured helper would answer before askpass and store the token it was handed.
260
+ const helpers = token === null ? [] : ["-c", "credential.helper="];
240
261
  // `ext::` would run a command named by the remote URL.
241
- return this.run("git", ["-c", "protocol.ext.allow=never", ...args], {
262
+ const result = await this.run("git", ["-c", "protocol.ext.allow=never", ...helpers, ...args], {
263
+ ...commandOptions,
264
+ env: { ...commandOptions.env, ...auth },
242
265
  asUser: this.options.user,
243
266
  });
267
+ const scrubbed = {
268
+ ...result,
269
+ stdout: scrubToken(result.stdout, token),
270
+ stderr: scrubToken(result.stderr, token),
271
+ };
272
+ if (remote !== undefined && result.status !== 0 && isAuthFailure(scrubbed.stderr)) {
273
+ return { ...scrubbed, authFailure: authFailureMessage(remote) } as CommandResult;
274
+ }
275
+ return scrubbed;
244
276
  }
245
277
 
246
278
  private async must(result: Promise<CommandResult>, what: string): Promise<CommandResult> {
247
279
  const done = await result;
248
280
  if (done.status !== 0) {
281
+ const refusal = (done as CommandResult & { authFailure?: string }).authFailure;
282
+ if (refusal) throw new FactoryError(`${what} failed: ${refusal}`, "auth");
249
283
  throw new FactoryError(`${what} failed: ${(done.stderr || done.stdout).trim()}`);
250
284
  }
251
285
  return done;
252
286
  }
253
287
 
288
+ /**
289
+ * Clones a companion into the companions directory as the unprivileged user, with the stored
290
+ * token for its URL. The folder is named after the repository and derived here, never taken
291
+ * from a caller. A checkout of the same repository already there is reported, not cloned again.
292
+ */
293
+ cloneCompanion(url: unknown): Promise<{ path: string; existing: boolean }> {
294
+ const remote = checkedCloneUrl(url);
295
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(remote.name)) {
296
+ throw new FactoryError(`${remote.name} cannot name a folder in the companions directory`);
297
+ }
298
+ const target = path.join(this.options.companionsDir, remote.name);
299
+ return this.chains.run(`companion:${remote.name}`, async () => {
300
+ if (this.exists(target)) {
301
+ if (!this.exists(path.join(target, ".git"))) {
302
+ throw new FactoryError(`${target} exists and is not a Git checkout`);
303
+ }
304
+ const origin = (
305
+ await this.git(["-C", target, "remote", "get-url", "origin"])
306
+ ).stdout.trim();
307
+ const there = origin ? parseRemote(origin) : null;
308
+ if (there?.host === remote.host && `${there.owner}/${there.repo}` === remote.identity) {
309
+ return { path: target, existing: true };
310
+ }
311
+ throw new FactoryError(
312
+ `${target} already holds a different repository; remove it or add that one by its folder`,
313
+ );
314
+ }
315
+ try {
316
+ await this.must(
317
+ this.git(["clone", "--", remote.url, target], {
318
+ remote: remote.url,
319
+ timeoutMs: CLONE_TIMEOUT_MS,
320
+ }),
321
+ `cloning ${remote.identity}`,
322
+ );
323
+ } catch (error) {
324
+ fs.rmSync(target, { recursive: true, force: true });
325
+ throw error;
326
+ }
327
+ return { path: target, existing: false };
328
+ });
329
+ }
330
+
331
+ /**
332
+ * Whether a remote answers, with the stored token for its URL: `git ls-remote` on its HEAD, as
333
+ * the unprivileged user. A refusal for authentication carries the `auth` code.
334
+ */
335
+ async checkRemote(url: unknown): Promise<void> {
336
+ const remote = checkedCloneUrl(url);
337
+ await this.must(
338
+ this.git(["ls-remote", "--", remote.url, "HEAD"], {
339
+ remote: remote.url,
340
+ timeoutMs: REMOTE_CHECK_TIMEOUT_MS,
341
+ }),
342
+ `reaching ${remote.identity}`,
343
+ );
344
+ }
345
+
254
346
  /** Factory mode is the inner daemon answering with Sysbox registered. */
255
347
  async assertAvailable(): Promise<void> {
256
348
  if (this.ready) return;
@@ -342,18 +434,19 @@ export class WorksetRuntime {
342
434
 
343
435
  if (!this.exists(path.join(repoDir, ".git"))) {
344
436
  await this.must(
345
- this.git(["clone", "--", request.remoteUrl, repoDir]),
437
+ this.git(["clone", "--", request.remoteUrl, repoDir], { remote: request.remoteUrl }),
346
438
  `cloning ${request.repository}`,
347
439
  );
348
440
  } else {
349
441
  await this.must(
350
- this.git(["-C", repoDir, "fetch", "--prune", "origin"]),
442
+ this.git(["-C", repoDir, "fetch", "--prune", "origin"], { remote: request.remoteUrl }),
351
443
  `fetching ${request.repository}`,
352
444
  );
353
445
  }
354
446
 
355
- const branch =
356
- existingBranch ?? (await this.createWorktree(request, companion, repoDir, worktree));
447
+ const { branch, warnings } = existingBranch
448
+ ? { branch: existingBranch, warnings: [] }
449
+ : await this.createWorktree(request, companion, repoDir, worktree);
357
450
 
358
451
  const size = request.size ?? "build";
359
452
  let state = await this.containerState(request.id);
@@ -422,38 +515,50 @@ export class WorksetRuntime {
422
515
  );
423
516
  }
424
517
  this.touch(request.id);
425
- return { id: request.id, repository: request.repository, branch, state: "running" };
518
+ return {
519
+ id: request.id,
520
+ repository: request.repository,
521
+ branch,
522
+ state: "running",
523
+ ...(warnings.length > 0 ? { warnings } : {}),
524
+ };
426
525
  }
427
526
 
428
- /** Puts a new worktree on the resolved Delivery Branch; call after fetching `repoDir`. */
527
+ /**
528
+ * Puts a new worktree on the resolved Delivery Branch; call after fetching `repoDir`. The
529
+ * branch is resolved and merges are probed in the factory's clone, as its user.
530
+ */
429
531
  private async createWorktree(
430
532
  request: SpawnRequest,
431
533
  companion: string,
432
534
  repoDir: string,
433
535
  worktree: string,
434
- ): Promise<string> {
435
- const hasRef = async (ref: string) =>
436
- (await this.git(["-C", repoDir, "rev-parse", "--verify", "--quiet", ref])).status === 0;
437
- const resolution = await resolveDeliveryBranch({
536
+ ): Promise<{ branch: string; warnings: string[] }> {
537
+ const checkout = deliveryCheckout(repoDir, async (args, { input, timeoutMs }) => {
538
+ const result = await this.git(["-C", repoDir, ...args], {
539
+ // Only the additions: a whole environment would replace the user's HOME with the broker's.
540
+ env: { GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" },
541
+ ...(input !== undefined ? { stdin: new TextEncoder().encode(input) } : {}),
542
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
543
+ });
544
+ return { code: result.status, stdout: result.stdout, stderr: result.stderr };
545
+ });
546
+ // An invalid template counts as the default; link reports it.
547
+ const resolution = await resolveDeliveryBranch(checkout, {
438
548
  companionPath: companion,
439
549
  repository: request.repository,
440
- hasRef,
441
- listRefs: listRefsWith(async (args) => {
442
- const listed = await this.git(["-C", repoDir, ...args]);
443
- return listed.status === 0 ? listed.stdout : null;
444
- }),
445
550
  worksetId: request.id,
446
551
  });
447
552
  const { branch, source } = resolution;
448
553
  if (branch === null || source === null) {
449
554
  throw new FactoryError(resolution.diagnostics.join("\n"));
450
555
  }
451
- const base = source === "new" ? await newBranchBase(hasRef) : undefined;
556
+ const base = source === "new" ? await newBranchBase(checkout.hasRef) : undefined;
452
557
  await this.must(
453
558
  this.git(["-C", repoDir, ...worktreeAddArgs({ branch, source }, worktree, base)]),
454
559
  `creating the worktree for ${request.id}`,
455
560
  );
456
- return branch;
561
+ return { branch, warnings: resolution.diagnostics };
457
562
  }
458
563
 
459
564
  private memoryOf(size: MemorySize): string | undefined {
@@ -733,7 +838,7 @@ export class WorksetRuntime {
733
838
  });
734
839
  }
735
840
 
736
- async exec(request: ExecRequest): Promise<CommandResult> {
841
+ async exec(request: ExecRequest, credential?: AgentCredential): Promise<CommandResult> {
737
842
  assertWorksetId(request.id);
738
843
  assertCommand(request.command, "exec");
739
844
  const worktree = this.worktree(request.id);
@@ -741,14 +846,6 @@ export class WorksetRuntime {
741
846
  if (cwd !== worktree && !cwd.startsWith(`${worktree}${path.sep}`)) {
742
847
  throw new FactoryError(`exec's working directory ${request.cwd} is outside the worktree`);
743
848
  }
744
- const env = request.env ?? {};
745
- for (const name of Object.keys(env)) {
746
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
747
- throw new FactoryError(
748
- `exec's environment variable name ${JSON.stringify(name)} is invalid`,
749
- );
750
- }
751
- }
752
849
  // Counted before waiting, so an idle stop queued meanwhile sees it busy.
753
850
  const done = this.track(request.id, "commands");
754
851
  try {
@@ -765,12 +862,15 @@ export class WorksetRuntime {
765
862
  this.options.user,
766
863
  "--workdir",
767
864
  cwd,
768
- ...Object.keys(env).flatMap((name) => ["--env", name]),
865
+ ...(credential ? ["--env", credential.name] : []),
769
866
  containerName(request.id),
770
867
  ...request.command,
771
868
  ],
772
869
  {
773
- env: { ...this.dockerEnv(), ...env },
870
+ env: {
871
+ ...(credential ? { [credential.name]: credential.value } : {}),
872
+ ...this.dockerEnv(),
873
+ },
774
874
  ...(request.stdin ? { stdin: request.stdin } : {}),
775
875
  },
776
876
  );
@@ -14,6 +14,7 @@ import {
14
14
  type PluginInstallResult,
15
15
  } from "../../tools/setup/dynamic-plugins/install";
16
16
  import { hydrateDynamicPlugins } from "../../tools/setup/dynamic-plugins/hydrate";
17
+ import { dynamicPluginsWorkspaceRoot } from "../../tools/setup/dynamic-plugins/paths";
17
18
  import { applySetupCompatibilities } from "../../tools/setup";
18
19
  import { findRepoLocalRegistryFile } from "./repository-link";
19
20
  import { companionGit, describeGitFailure, type CompanionGit } from "../../runtime/companion-git";
@@ -350,7 +351,11 @@ export async function updateHubPlugins(
350
351
  const resolvedHubPath = path.resolve(hubPath);
351
352
  const results =
352
353
  declarations.length > 0
353
- ? await installDeclaredPlugins(resolvedHubPath, declarations, deps.installDeps)
354
+ ? await installDeclaredPlugins(
355
+ dynamicPluginsWorkspaceRoot(resolvedHubPath),
356
+ declarations,
357
+ deps.installDeps,
358
+ )
354
359
  : [];
355
360
  if (declarations.length > 0) {
356
361
  await (deps.hydrate ?? hydrateDynamicPlugins)({ companionPath: resolvedHubPath });
@@ -0,0 +1,48 @@
1
+ import path from "node:path";
2
+
3
+ import semver from "semver";
4
+
5
+ import { FRAMEWORK_NAME } from "../../framework";
6
+ import { YamlFileStore } from "./yaml-file-store";
7
+
8
+ /**
9
+ * Raw view of `framework.yaml`: `ConfigStore.load()` merges defaults, so saving
10
+ * its result would add keys the companion never declared.
11
+ */
12
+ class RawFrameworkConfigStore extends YamlFileStore<Record<string, unknown>> {
13
+ protected onMissing(): Promise<Record<string, unknown>> {
14
+ return Promise.resolve({});
15
+ }
16
+ }
17
+
18
+ function rawStore(companionPath: string): RawFrameworkConfigStore {
19
+ return new RawFrameworkConfigStore(
20
+ path.join(companionPath, `.${FRAMEWORK_NAME}`, "config", "framework.yaml"),
21
+ );
22
+ }
23
+
24
+ /** Sets `engines.mate` to `range`. Returns true when the file was rewritten. */
25
+ export async function writeEngineFloor(companionPath: string, range: string): Promise<boolean> {
26
+ const store = rawStore(companionPath);
27
+ const raw = (await store.load()) ?? {};
28
+ const engines = (raw.engines ?? {}) as Record<string, string>;
29
+ if (engines[FRAMEWORK_NAME] === range) return false;
30
+ await store.save({ ...raw, engines: { ...engines, [FRAMEWORK_NAME]: range } });
31
+ return true;
32
+ }
33
+
34
+ /**
35
+ * Raises `engines.mate` to `>=version` when it is absent or admits a lower
36
+ * version; a floor already at or above it, or a range that does not parse,
37
+ * is left alone. Returns true when the file was rewritten.
38
+ */
39
+ export async function raiseEngineFloor(companionPath: string, version: string): Promise<boolean> {
40
+ const raw = (await rawStore(companionPath).load()) ?? {};
41
+ const current = ((raw.engines ?? {}) as Record<string, unknown>)[FRAMEWORK_NAME];
42
+ if (typeof current === "string") {
43
+ if (semver.validRange(current) === null) return false;
44
+ const lowest = semver.minVersion(current);
45
+ if (lowest && semver.gte(lowest, version)) return false;
46
+ }
47
+ return writeEngineFloor(companionPath, `>=${version}`);
48
+ }
@@ -1,5 +1,11 @@
1
1
  // oxlint-disable no-underscore-dangle
2
2
  import { FRAMEWORK_NAME } from "../../framework";
3
+ import { companionGit, GIT_QUERY_TIMEOUT_MS } from "../../runtime/companion-git";
4
+ import { companionFrameworkConfigPath, resolveSecretPolicy } from "../../runtime/policy";
5
+ import {
6
+ secretPolicyOfConfigText,
7
+ secretPolicyWeakenings,
8
+ } from "../../runtime/secret-policy-weakening";
3
9
  import type { AdapterContext, LaunchAdapter } from "./adapters/base";
4
10
  import { ClaudeAdapter } from "./adapters/claude";
5
11
  import { OpenCodeAdapter } from "./adapters/opencode";
@@ -41,8 +47,34 @@ interface ResolvedLaunchState {
41
47
 
42
48
  export const launcherDeps = {
43
49
  prepareSession,
50
+ /** The companion's `HEAD` version of `framework.yaml`; null when Git cannot answer. Local only. */
51
+ readCommittedFrameworkConfig: async (companionPath: string): Promise<string | null> => {
52
+ const git = companionGit(companionPath, {
53
+ prompt: "never",
54
+ commandCapMs: GIT_QUERY_TIMEOUT_MS,
55
+ });
56
+ const shown = await git.run(["show", `HEAD:./.${FRAMEWORK_NAME}/config/framework.yaml`]);
57
+ return shown.status === 0 ? shown.stdout : null;
58
+ },
44
59
  };
45
60
 
61
+ /**
62
+ * Warns, never blocks, when the working tree's secret policy is weaker than the
63
+ * committed one: a shell edit the guard does not see shows up at the next launch.
64
+ */
65
+ async function warnOnLoosenedSecretPolicy(companionPath: string): Promise<void> {
66
+ const committedText = await launcherDeps
67
+ .readCommittedFrameworkConfig(companionPath)
68
+ .catch(() => null);
69
+ const committed = committedText === null ? null : secretPolicyOfConfigText(committedText);
70
+ if (!committed) return;
71
+ const weakenings = secretPolicyWeakenings(committed, resolveSecretPolicy(companionPath));
72
+ if (weakenings.length === 0) return;
73
+ console.error(
74
+ `${FRAMEWORK_NAME}: warning: ${companionFrameworkConfigPath(companionPath)} loosens the committed secret policy (${weakenings.join("; ")}); only the user should loosen it.`,
75
+ );
76
+ }
77
+
46
78
  /** The wrap notice is informational: `process.stderr.write`, since Bun renders `console.error` red. */
47
79
  function report(result: PrepareResult): void {
48
80
  const wrapped = result.steps.find((step) => step.step === "working-target");
@@ -100,8 +132,9 @@ export class FrameworkLauncher {
100
132
  config: state.config,
101
133
  skipGit: state.skipGit,
102
134
  });
103
- report(prepared);
135
+ if (!request.quiet) report(prepared);
104
136
  if (!prepared.ok) throw state.adapter.launchFailure(prepared);
137
+ await warnOnLoosenedSecretPolicy(state.companionPath);
105
138
  const adapterContext = await state.adapter.planLaunch(this.makeAdapterContext(state), prepared);
106
139
  await state.adapter.validateLaunch(adapterContext);
107
140
 
@@ -24,13 +24,13 @@ export function reconcileWorkingRepoClaudeCommandLinks(
24
24
  companionPath: string | null,
25
25
  enabled: boolean,
26
26
  registeredCompanionPaths: string[] = [],
27
- ): Promise<"written" | "current"> {
27
+ ): ReturnType<typeof reconcileClaudeLinks> {
28
28
  return reconcileClaudeLinks(COMMANDS, repoPath, companionPath, enabled, registeredCompanionPaths);
29
29
  }
30
30
 
31
31
  export function removeWorkingRepoClaudeCommandLinks(
32
32
  repoPath: string,
33
33
  registeredCompanionPaths: string[] = [],
34
- ): Promise<"removed" | "absent"> {
34
+ ): ReturnType<typeof removeClaudeLinks> {
35
35
  return removeClaudeLinks(COMMANDS, repoPath, registeredCompanionPaths);
36
36
  }