@uniqbit/mate-core 1.0.0-canary.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +5 -4
  3. package/src/cli/commands/artifact/delivery/link.ts +1 -1
  4. package/src/cli/commands/artifact/delivery/output.ts +10 -1
  5. package/src/cli/commands/artifact/delivery/resolve.ts +3 -2
  6. package/src/cli/commands/artifact/delivery/submit.ts +9 -4
  7. package/src/cli/commands/artifact/delivery/take.ts +12 -9
  8. package/src/cli/commands/artifact/finish/command.ts +16 -14
  9. package/src/cli/commands/artifact/finish/engine.ts +8 -8
  10. package/src/cli/commands/artifact/project/command.ts +2 -3
  11. package/src/cli/commands/companion/hub.ts +11 -6
  12. package/src/cli/commands/companion/link.ts +173 -46
  13. package/src/cli/commands/report/contract.ts +0 -17
  14. package/src/cli/commands/studio/access.ts +4 -0
  15. package/src/cli/commands/studio/actions.ts +35 -2
  16. package/src/cli/commands/studio/mcp-manager.ts +162 -0
  17. package/src/cli/commands/studio/routes.ts +12 -0
  18. package/src/cli/commands/studio/selection.ts +44 -11
  19. package/src/cli/commands/studio/server.ts +246 -2
  20. package/src/cli/commands/studio/services.ts +26 -0
  21. package/src/cli/commands/studio/terminal-launch.ts +21 -4
  22. package/src/cli/commands/studio/terminal.ts +3 -14
  23. package/src/cli/commands/studio/work-requests.ts +9 -0
  24. package/src/cli/commands/studio/work.ts +473 -0
  25. package/src/cli/commands/vscode/release-vsix.json +2 -2
  26. package/src/cli/commands/working/cleanup.ts +1 -18
  27. package/src/cli/companion-link-wizard.tsx +158 -91
  28. package/src/cli/usage.ts +1 -1
  29. package/src/lib/agent-credential.ts +131 -0
  30. package/src/lib/credential-kinds.ts +7 -0
  31. package/src/lib/delivery/merge-git.ts +16 -0
  32. package/src/lib/delivery/record-delivery.ts +12 -6
  33. package/src/lib/delivery/record.ts +5 -0
  34. package/src/lib/delivery/refresh.ts +34 -6
  35. package/src/lib/delivery/staging/refs.ts +9 -4
  36. package/src/lib/delivery/staging/submit.ts +81 -22
  37. package/src/lib/mcp-manager/resolve.ts +27 -9
  38. package/src/lib/mcp-manager/store.ts +35 -11
  39. package/src/lib/mcp-manager/types.ts +14 -0
  40. package/src/lib/mcp-manager/validate.ts +6 -10
  41. package/src/lib/opencode-server.ts +2 -17
  42. package/src/lib/orchestrator/repo-local-store.ts +14 -0
  43. package/src/lib/orchestrator/repository-link.ts +80 -52
  44. package/src/lib/orchestrator/root-context.ts +17 -1
  45. package/src/lib/studio-chat/agent.ts +139 -0
  46. package/src/lib/studio-chat/companion-context.ts +136 -0
  47. package/src/lib/studio-chat/credential.ts +79 -0
  48. package/src/lib/studio-chat/harness-chat-agent.ts +334 -0
  49. package/src/lib/studio-chat/host-sandbox.ts +578 -0
  50. package/src/lib/studio-chat/prepare-bridges.ts +95 -0
  51. package/src/lib/studio-chat/session.ts +15 -0
  52. package/src/lib/studio-chat/turns.ts +112 -0
  53. package/src/lib/workset/claims.ts +85 -0
  54. package/src/lib/workset/execution.ts +71 -0
  55. package/src/lib/workset/git-transaction.ts +74 -0
  56. package/src/lib/workset/groups.ts +176 -0
  57. package/src/lib/workset/inventory.ts +196 -0
  58. package/src/lib/workset/projection.ts +237 -0
  59. package/src/lib/workset/record.ts +101 -36
  60. package/src/lib/workset/repositories.ts +24 -0
  61. package/src/lib/workset/sharing.ts +951 -0
  62. package/src/lib/workset/stages.ts +50 -14
  63. package/src/lib/workset/transactions.ts +158 -0
  64. package/src/runtime/companion-git-state.ts +1 -0
  65. package/src/runtime/companion-guidance.ts +2 -2
  66. package/src/runtime/forge-remote.ts +6 -0
  67. package/src/runtime/host-process.ts +28 -0
  68. package/src/runtime/secret-guard.ts +18 -1
  69. package/src/runtime/secret-patterns.ts +4 -3
  70. package/src/runtime/submitted-arrivals.ts +28 -2
  71. package/src/runtime/write-atomic.ts +2 -2
  72. package/src/studio.ts +52 -8
  73. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +1 -1
  74. package/src/templates/capabilities/openspec-cap/mate-full/templates/proposal.md +1 -1
  75. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +3 -2
  76. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +5 -3
  77. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +3 -2
  78. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +5 -3
  79. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +12 -12
  80. package/src/tools/setup/capabilities/mcp-manager.ts +1 -2
  81. package/src/tools/setup/dynamic-plugins/declarations.ts +0 -26
  82. package/src/tools/setup/plugins/gitignore.ts +1 -0
  83. package/src/tools/setup/providers/claude-format.ts +1 -5
  84. package/src/tools/setup/providers/claude.ts +28 -3
  85. package/src/tools/setup/providers/opencode.ts +7 -18
  86. package/src/tools/setup/providers/relative-path-warnings.ts +26 -0
  87. package/studio-dist/THIRD-PARTY-NOTICES.md +297 -0
  88. package/studio-dist/client/THIRD-PARTY-LICENSES.md +4294 -0
  89. package/studio-dist/client/assets/DialogTitle-DOhjDa7H.js +1 -0
  90. package/studio-dist/client/assets/app-CG3vCgyA.css +2 -0
  91. package/studio-dist/client/assets/bundle-mjs-CdK3cBzO.js +1 -0
  92. package/studio-dist/client/assets/button-upSzkd-q.js +1 -0
  93. package/studio-dist/client/assets/chat-DbaMXb8H.js +157 -0
  94. package/studio-dist/client/assets/cn-BCnYnarL.js +1 -0
  95. package/studio-dist/client/assets/combobox-cP9OsRf2.js +1 -0
  96. package/studio-dist/client/assets/{companion-view-C1F0_jbt.js → companion-view-B54_Lj0S.js} +1 -1
  97. package/studio-dist/client/assets/fields-DNZ4a89M.js +1 -0
  98. package/studio-dist/client/assets/friction-DgEimeDB.js +1 -0
  99. package/studio-dist/client/assets/getting-started-BTfYCt5s.js +1 -0
  100. package/studio-dist/client/assets/{getting-started-BN4aTpsz.js → getting-started-CAszmdDJ.js} +1 -1
  101. package/studio-dist/client/assets/getting-started._topic-CHJMf0pa.js +1 -0
  102. package/studio-dist/client/assets/getting-started.index-MR6HftWs.js +1 -0
  103. package/studio-dist/client/assets/{graph-canvas-Be5qgdDt.js → graph-canvas-BdNk2F9O.js} +1 -1
  104. package/studio-dist/client/assets/graph-hRijsC89.js +2 -0
  105. package/studio-dist/client/assets/guides-CwFnh08E.js +1 -0
  106. package/studio-dist/client/assets/highlighted-body-JLMTFACH-BcroQey-.js +1 -0
  107. package/studio-dist/client/assets/index-D5oGyvG8.js +41 -0
  108. package/studio-dist/client/assets/{markdown-view-dku7MGPn.js → markdown-view-CJ8JsLb7.js} +1 -1
  109. package/studio-dist/client/assets/marked.esm-vFuq1cCd.js +65 -0
  110. package/studio-dist/client/assets/mcp-BE9M-bkO.js +4 -0
  111. package/studio-dist/client/assets/mermaid-WFAXDIZX-BjSsakrn.js +1 -0
  112. package/studio-dist/client/assets/panel-CDQ6Lryw.js +1 -0
  113. package/studio-dist/client/assets/plugins._service._view-DRVPUAWN.js +1 -0
  114. package/studio-dist/client/assets/{prepaint-BkoDSw5X.js → prepaint-sD_LlrDN.js} +1 -1
  115. package/studio-dist/client/assets/{queries-CMvC2OkU.js → queries-COL925ML.js} +1 -1
  116. package/studio-dist/client/assets/react-dom-K3Hp2Cdj.js +1 -0
  117. package/studio-dist/client/assets/{react-BYUSgtBs.js → react-h2xQ_NSp.js} +1 -1
  118. package/studio-dist/client/assets/reports-BClsojkb.js +1 -0
  119. package/studio-dist/client/assets/routes-CJQ2MAej.js +1 -0
  120. package/studio-dist/client/assets/search-DhWdEiKT.js +1 -0
  121. package/studio-dist/client/assets/select-B2FsN9FY.js +1 -0
  122. package/studio-dist/client/assets/skills-SoUHk77W.js +1 -0
  123. package/studio-dist/client/assets/{specs-Bqd1ajyD.js → specs-C_tZnAvF.js} +1 -1
  124. package/studio-dist/client/assets/specs-view-C6t3Y5IT.js +1 -0
  125. package/studio-dist/client/assets/steps-CF3-Zpmh.js +1 -0
  126. package/studio-dist/client/assets/{store-BYnEU33C.js → store-pY9gU4uS.js} +1 -1
  127. package/studio-dist/client/assets/studio-X7bnFrRe.js +36 -0
  128. package/studio-dist/client/assets/studio-queries-CKtAnIKP.js +2 -0
  129. package/studio-dist/client/assets/usage-BaaqUpTG.js +55 -0
  130. package/studio-dist/client/assets/useAnchoredPopupScrollLock-BspHR7Wt.js +1 -0
  131. package/studio-dist/client/assets/useBlocker-BQOfcu_f.js +1 -0
  132. package/studio-dist/client/assets/useMutation-DKeEoP5S.js +1 -0
  133. package/studio-dist/client/assets/useOpenInteractionType-CtaZCaFT.js +1 -0
  134. package/studio-dist/client/assets/usePopupHandleStore-Bc7Q4bnF.js +1 -0
  135. package/studio-dist/client/assets/vault-sAPFUnPN.js +1 -0
  136. package/studio-dist/client/assets/{warnings-Cnw99ugO.js → warnings-D7YY1HSG.js} +1 -1
  137. package/studio-dist/client/assets/work-BZek_LGB.js +5 -0
  138. package/studio-dist/client/assets/workflow-N5boHXFz.js +1 -0
  139. package/studio-dist/server/THIRD-PARTY-LICENSES.md +4371 -0
  140. package/studio-dist/server/assets/DialogTitle-DnKSl2V0.js +421 -0
  141. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-CS3QRY4Q.js → __23tanstack-start-server-fn-resolver-Bli9bpSB.js} +38 -18
  142. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +91 -59
  143. package/studio-dist/server/assets/{actions-D8erOphH.js → actions-CHEFA1i9.js} +33 -1
  144. package/studio-dist/server/assets/{cn-DWFJaP_9.js → bundle-mjs-Ot6dQ8Pq.js} +1 -2056
  145. package/studio-dist/server/assets/{button-Ct_WeYLc.js → button-BqA1urbl.js} +14 -7
  146. package/studio-dist/server/assets/chat-zl332Tvu.js +49486 -0
  147. package/studio-dist/server/assets/cn-B0fl6NWK.js +2057 -0
  148. package/studio-dist/server/assets/{combobox-17vO5Uz8.js → combobox-iTjvPCtS.js} +7 -6
  149. package/studio-dist/server/assets/{companion-view-JkxnGLlp.js → companion-view-DIQ6AFIY.js} +2 -2
  150. package/studio-dist/server/assets/{companions-YNLsbnch.js → companions-aVwjRL8j.js} +1 -1
  151. package/studio-dist/server/assets/{fields-VytPpqBq.js → fields-BMap2_Ju.js} +10 -3
  152. package/studio-dist/server/assets/{friction-BW86PCPM.js → friction-BER50hoD.js} +2 -2
  153. package/studio-dist/server/assets/{friction-B6osqFSm.js → friction-BPs9KWdq.js} +8 -8
  154. package/studio-dist/server/assets/{getting-started-CFHSeX5h.js → getting-started-DGfRVmZ_.js} +2 -2
  155. package/studio-dist/server/assets/{getting-started._topic-BK2eU6AS.js → getting-started._topic-BgrBA4Vj.js} +2 -2
  156. package/studio-dist/server/assets/{getting-started.index-DZLuXnNO.js → getting-started.index-BaFfQ9Mn.js} +2 -2
  157. package/studio-dist/server/assets/{graph-BJVZBevL.js → graph-Cgzlrv3P.js} +8 -8
  158. package/studio-dist/server/assets/{graph-DGZHV-Ek.js → graph-DODpuOy_.js} +1 -1
  159. package/studio-dist/server/assets/{graph-canvas-lrNT6jbl.js → graph-canvas-DW_zU1nA.js} +2 -2
  160. package/studio-dist/server/assets/{guides-_G8Vucsk.js → guides-CA_EMG7E.js} +1 -1
  161. package/studio-dist/server/assets/{guides-CEwLOZb9.js → guides-D0SpoD32.js} +1 -1
  162. package/studio-dist/server/assets/{guides.server-ZWFKX2XJ.js → guides.server-DJjQuy03.js} +1 -1
  163. package/studio-dist/server/assets/highlighted-body-JLMTFACH-BeHllu-r.js +41 -0
  164. package/studio-dist/server/assets/{markdown-view-Bmjghg_Z.js → markdown-view-CvVBGMZV.js} +1 -1
  165. package/studio-dist/server/assets/mcp-BU0fLYyJ.js +1103 -0
  166. package/studio-dist/server/assets/mcp-manager-D9YctTQe.js +50 -0
  167. package/studio-dist/server/assets/mermaid-WFAXDIZX-B1yDN6vG.js +1 -0
  168. package/studio-dist/server/assets/{panel-DvRjyil3.js → panel-D1K6Bsux.js} +4 -32
  169. package/studio-dist/server/assets/{plugins._service._view-B32LzraG.js → plugins._service._view-DdO1nELF.js} +4 -4
  170. package/studio-dist/server/assets/{prepaint-BEHwKl51.js → prepaint-BB3dwSmz.js} +1 -1
  171. package/studio-dist/server/assets/{queries-D6Vq0AuZ.js → queries-BwiDxQy5.js} +1 -1
  172. package/studio-dist/server/assets/{react-CiBZPDs8.js → react-B2cLiz-i.js} +1 -1
  173. package/studio-dist/server/assets/{reports-Dn92pLap.js → reports-9Pr7Bz6o.js} +7 -7
  174. package/studio-dist/server/assets/{reports-DDaH5k0H.js → reports-Cc9M3phM.js} +1 -1
  175. package/studio-dist/server/assets/{router-Bjf4S9tO.js → router-DcWe0J7Y.js} +827 -548
  176. package/studio-dist/server/assets/{routes-B4sNiE0X.js → routes-BEXxl0py.js} +8 -8
  177. package/studio-dist/server/assets/{search-DKeJRvg8.js → search-bltT7gwy.js} +39 -7
  178. package/studio-dist/server/assets/{select-CVHYL7oR.js → select-CZvHgGCi.js} +7 -6
  179. package/studio-dist/server/assets/{shell-BxbYYaAk.js → shell-BQ0vMKXN.js} +13 -4
  180. package/studio-dist/server/assets/{skills-Bj8eOgzR.js → skills-Be_52h0i.js} +1 -1
  181. package/studio-dist/server/assets/{skills-B4-0qpqN.js → skills-BpGGUl6L.js} +8 -8
  182. package/studio-dist/server/assets/{specs-rfMug6qW.js → specs-CCGgXE-V.js} +5 -5
  183. package/studio-dist/server/assets/{specs-view-qi1SE1Sl.js → specs-view-DtL5JxYM.js} +12 -11
  184. package/studio-dist/server/assets/{steps-rger6HJc.js → steps-BWFSO6dM.js} +1 -1
  185. package/studio-dist/server/assets/{store-Dg9T7oWs.js → store-X7yLPp7v.js} +1 -1
  186. package/studio-dist/server/assets/{studio-queries-CeFfmIuM.js → studio-queries-ur1ygXi3.js} +117 -13
  187. package/studio-dist/server/assets/{studio-D79JzDLc.js → studio-qzH-UETC.js} +209 -180
  188. package/studio-dist/server/assets/{usage-Dw_UQFX-.js → usage-C1o0DLzS.js} +1 -1
  189. package/studio-dist/server/assets/{usage-BJgYWRCX.js → usage-DWbSPrPD.js} +10 -9
  190. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-ciS_sEq3.js → useAnchoredPopupScrollLock-DLDmv6kM.js} +4 -135
  191. package/studio-dist/server/assets/useBlocker-CQtANHK8.js +111 -0
  192. package/studio-dist/server/assets/{useMutation-DnWK0PhO.js → useMutation-NjlA8oFY.js} +2 -2
  193. package/studio-dist/server/assets/useOpenInteractionType-CZYscfOb.js +136 -0
  194. package/studio-dist/server/assets/usePopupHandleStore-DEEXJYv0.js +26 -0
  195. package/studio-dist/server/assets/{vault-BzarssiL.js → vault-B_kfi1h-.js} +1 -1
  196. package/studio-dist/server/assets/{vault-CvlrLd2H.js → vault-dL79JlKH.js} +8 -115
  197. package/studio-dist/server/assets/{views-CAxwKHMK.js → views-BSGH56lb.js} +3 -3
  198. package/studio-dist/server/assets/{warnings-BpVCugHm.js → warnings-DtUVPV-k.js} +2 -2
  199. package/studio-dist/server/assets/work-D789VXGH.js +110 -0
  200. package/studio-dist/server/assets/work-DsCEfhmK.js +3817 -0
  201. package/studio-dist/server/assets/work-requests-BLhOmQFO.js +11 -0
  202. package/studio-dist/server/assets/{workflow-BdrzcCt8.js → workflow-BOZ2sRYg.js} +9 -9
  203. package/studio-dist/server/server.js +3 -3
  204. package/wrappers/bin/openspec +87 -2
  205. package/studio-dist/client/assets/app-ggXJ_QVh.css +0 -2
  206. package/studio-dist/client/assets/button-C9SQW3kI.js +0 -1
  207. package/studio-dist/client/assets/cn-DC80MJV0.js +0 -1
  208. package/studio-dist/client/assets/combobox-D7mKYCBb.js +0 -1
  209. package/studio-dist/client/assets/fields-CEep8IFT.js +0 -1
  210. package/studio-dist/client/assets/friction-D9dBU7WN.js +0 -1
  211. package/studio-dist/client/assets/getting-started-BDyGvHhc.js +0 -1
  212. package/studio-dist/client/assets/getting-started._topic-B9ajbF4o.js +0 -1
  213. package/studio-dist/client/assets/getting-started.index-CYiBPtb7.js +0 -1
  214. package/studio-dist/client/assets/graph-ah7ZXfTa.js +0 -2
  215. package/studio-dist/client/assets/guides-CsL0660B.js +0 -1
  216. package/studio-dist/client/assets/index-zmRH87D4.js +0 -40
  217. package/studio-dist/client/assets/panel-COgk0vP5.js +0 -1
  218. package/studio-dist/client/assets/plugins._service._view-Cn3WBHab.js +0 -1
  219. package/studio-dist/client/assets/reports-C_AqLBYH.js +0 -1
  220. package/studio-dist/client/assets/routes-BokQmHtC.js +0 -1
  221. package/studio-dist/client/assets/search-DxidNK2M.js +0 -1
  222. package/studio-dist/client/assets/select-CYFCbHUd.js +0 -1
  223. package/studio-dist/client/assets/skills-R3vttWHM.js +0 -1
  224. package/studio-dist/client/assets/specs-view-znqFPx9p.js +0 -1
  225. package/studio-dist/client/assets/steps-tVDWn7j6.js +0 -1
  226. package/studio-dist/client/assets/studio-ndtFcS2Y.js +0 -100
  227. package/studio-dist/client/assets/studio-queries-CkUSByy7.js +0 -2
  228. package/studio-dist/client/assets/usage-Kuhr8dSl.js +0 -55
  229. package/studio-dist/client/assets/useAnchoredPopupScrollLock-dc_kP4Go.js +0 -1
  230. package/studio-dist/client/assets/useMutation-CqtM9COw.js +0 -1
  231. package/studio-dist/client/assets/vault-CSP8kwRg.js +0 -1
  232. package/studio-dist/client/assets/workflow-BPJAmmZi.js +0 -1
@@ -21,7 +21,9 @@ export type AnswerReason =
21
21
  /** The repository has no checkout linked on this machine. */
22
22
  | "no-checkout"
23
23
  /** The branch is gone from the remote and its content is on no default-branch commit. */
24
- | "branch-deleted";
24
+ | "branch-deleted"
25
+ /** The unpushed branch never moved from the default-branch commit it was created at. */
26
+ | "empty-branch";
25
27
 
26
28
  export interface BranchOutcome {
27
29
  repository: string;
@@ -172,6 +174,23 @@ async function unpushedHead(
172
174
  return (await git.localTip(branch)) === head ? true : undefined;
173
175
  }
174
176
 
177
+ async function hasNoCommitsOfItsOwn(
178
+ git: MergeGit,
179
+ branch: string,
180
+ head: string,
181
+ local: { tip: string | null; unpushed: boolean },
182
+ ): Promise<boolean> {
183
+ if (local.tip !== head) return false;
184
+ if ((await git.neverAdvanced(branch, head)) !== true) return false;
185
+ return local.unpushed || (await unpushedHead(git, branch, head)) === true;
186
+ }
187
+
188
+ function answerReasonOf(evidence: LocalMergeEvidence, deleted: boolean): AnswerReason {
189
+ if (evidence.empty) return "empty-branch";
190
+ if (evidence.suggestion) return "likely-merged";
191
+ return deleted ? "branch-deleted" : "not-on-default";
192
+ }
193
+
175
194
  async function lookup(
176
195
  repository: string,
177
196
  branch: string,
@@ -226,16 +245,18 @@ async function lookup(
226
245
  : {};
227
246
  return { ...base, ...withFetch, ...found, result: "merged", needsAnswer: false, provenance };
228
247
  }
229
- const suggestion = evidence.suggestion;
248
+ const { suggestion } = evidence;
249
+ const neverPushed = fetch?.branchDeleted === true && (recorded.unpushed || unpushed === true);
250
+ const reportedFetch = neverPushed ? { fetch: { ok: true, branchUnpushed: true } } : withFetch;
230
251
  // Without a fetch a missing `origin/<branch>` is no evidence of deletion.
231
- const deleted = fetch?.branchDeleted === true && evidence.uncontained;
252
+ const deleted = fetch?.branchDeleted === true && !neverPushed && evidence.uncontained;
232
253
  return {
233
254
  ...base,
234
- ...withFetch,
255
+ ...reportedFetch,
235
256
  ...found,
236
257
  result: "unknown",
237
258
  needsAnswer: true,
238
- answerReason: suggestion ? "likely-merged" : deleted ? "branch-deleted" : "not-on-default",
259
+ answerReason: answerReasonOf(evidence, deleted),
239
260
  ...(suggestion ? { suggestion } : {}),
240
261
  fetchedAt,
241
262
  };
@@ -297,6 +318,8 @@ export interface LocalMergeEvidence {
297
318
  suggestion: PatchMatch | null;
298
319
  /** Containment ran and found no default-branch commit holding the head. */
299
320
  uncontained: boolean;
321
+ /** The unpushed head is on the default branch and its branch never moved from it. */
322
+ empty?: boolean;
300
323
  }
301
324
 
302
325
  /**
@@ -320,9 +343,10 @@ export async function localMergeEvidence(
320
343
  ? recordedHead
321
344
  : null;
322
345
  let head = live ?? recorded ?? known.fallback ?? null;
346
+ const localTip = head ? await git.localTip(branch) : null;
323
347
  if (live) {
324
348
  // Unpushed work: the remote tip alone would settle a merge of the branch's earlier commits.
325
- for (const candidate of [await git.localTip(branch), recorded]) {
349
+ for (const candidate of [localTip, recorded]) {
326
350
  // oxlint-disable-next-line no-await-in-loop -- the second candidate is compared to the first
327
351
  if (candidate && (await git.aheadOf(head!, candidate))) head = candidate;
328
352
  }
@@ -330,6 +354,10 @@ export async function localMergeEvidence(
330
354
  const unsettled = { live, head, merged: false, uncontained: false };
331
355
  if (!head) return { ...unsettled, suggestion: null };
332
356
  if (await git.isAncestor(head, defaultBranch)) {
357
+ const local = { tip: localTip, unpushed: known.unpushed === true };
358
+ if (await hasNoCommitsOfItsOwn(git, branch, head, local)) {
359
+ return { ...unsettled, empty: true, suggestion: null };
360
+ }
333
361
  // A fast-forward and a branch without commits of its own look the same: only a merge
334
362
  // commit settles by itself, and a check Git could not run settles nothing.
335
363
  if ((await git.onFirstParent(head, defaultBranch)) === false) {
@@ -126,12 +126,17 @@ export function pushPending(git: CompanionGit, remote: StagingRemote): Promise<N
126
126
  }
127
127
 
128
128
  /**
129
- * A push the remote refused because the branch moved since the fetch, or because a concurrent
130
- * push created it first.
129
+ * A lock failure counts only as the remote's rejection: locally it hits the tracking ref after
130
+ * an accepted push.
131
131
  */
132
132
  export function isRejectedPush(result: NetworkGitResult): boolean {
133
- return /\[rejected\]|non-fast-forward|fetch first|stale info|reference already exists/i.test(
134
- result.stderr,
133
+ return (
134
+ /\[rejected\]|non-fast-forward|fetch first|stale info|reference already exists/i.test(
135
+ result.stderr,
136
+ ) ||
137
+ /\[remote rejected\][^\n]*\((cannot lock ref|failed to update ref|incorrect old value)/i.test(
138
+ result.stderr,
139
+ )
135
140
  );
136
141
  }
137
142
 
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import fs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
 
@@ -19,7 +20,14 @@ import {
19
20
  import { errorMessage } from "../../../runtime/error-message";
20
21
  import { isSubmittedName } from "../../../runtime/pending-records";
21
22
  import { isWithin } from "../../../runtime/physical-path";
22
- import { contentDigest, folderDigest, ownFiles } from "../../../runtime/submitted-arrivals";
23
+ import {
24
+ contentDigest,
25
+ emptyFolderKeepingClaim,
26
+ folderDigest,
27
+ OWNER_FILE,
28
+ ownFiles,
29
+ sharedDigestAt,
30
+ } from "../../../runtime/submitted-arrivals";
23
31
  import type { PublicationSecretScan } from "../../../runtime/publication-secret-scan";
24
32
  import type { SecretFinding } from "../../../runtime/secret-scan";
25
33
  import {
@@ -28,6 +36,7 @@ import {
28
36
  isCommitId,
29
37
  readDeliveryRecord,
30
38
  readOrUnlinkedRecord,
39
+ submissionStateOf,
31
40
  upsertDelivery,
32
41
  withoutStage,
33
42
  writeDeliveryRecord,
@@ -497,12 +506,13 @@ async function pushGroup(
497
506
  for (const [index, name] of names.entries()) {
498
507
  const folder = sourcePathOf(type, name);
499
508
  const files: [string, Buffer][] = [];
509
+ let claim: Buffer | null = null;
500
510
  for (const file of listed[index]!) {
501
- files.push([
502
- path.posix.relative(folder, file),
503
- // oxlint-disable-next-line no-await-in-loop -- one file at a time
504
- await readSubmittable(companionPath, folder, file),
505
- ]);
511
+ const relative = path.posix.relative(folder, file);
512
+ // oxlint-disable-next-line no-await-in-loop -- one file at a time
513
+ const content = await readSubmittable(companionPath, folder, file);
514
+ if (relative === OWNER_FILE) claim = content;
515
+ else files.push([relative, content]);
506
516
  }
507
517
  // oxlint-disable-next-line no-await-in-loop -- one folder at a time
508
518
  const theirs = await pendingContent(work, dir, folder);
@@ -517,7 +527,7 @@ async function pushGroup(
517
527
  // A blocked change submitted again by name may accept its conflict, even unchanged.
518
528
  if (unchanged && !blocked) continue;
519
529
  const mine = submitted[folder]?.content;
520
- const here = contentOnly(files);
530
+ const here = contentOnly(claim ? [...files, [OWNER_FILE, claim]] : files);
521
531
  // Never submitted or taken here: only the same content may be pushed over it.
522
532
  if (mine === undefined && theirs !== here) {
523
533
  throw new Error(
@@ -555,7 +565,7 @@ async function pushGroup(
555
565
  }
556
566
  records.set(name, record);
557
567
  // oxlint-disable-next-line no-await-in-loop -- one folder at a time
558
- await fs.rm(within(dir, folder), { recursive: true, force: true });
568
+ await emptyFolderKeepingClaim(within(dir, folder));
559
569
  const copied: [string, Buffer][] = [];
560
570
  for (const [relative, read] of files) {
561
571
  const target = within(dir, `${folder}/${relative}`);
@@ -598,7 +608,11 @@ async function pushGroup(
598
608
  [DELIVERY_FILE, written],
599
609
  );
600
610
  }
601
- digests.set(name, { digest: contentDigest(copied), content: contentOnly(copied) });
611
+ digests.set(name, {
612
+ digest: contentDigest(claim ? [...copied, [OWNER_FILE, claim]] : copied),
613
+ // oxlint-disable-next-line no-await-in-loop -- one folder at a time
614
+ content: (await pendingContent(work, dir, folder)) ?? contentOnly(copied),
615
+ });
602
616
  staged.push(folder);
603
617
  }
604
618
  return staged;
@@ -959,12 +973,6 @@ export interface TakeResult {
959
973
  message: string;
960
974
  }
961
975
 
962
- /**
963
- * Takes submitted change `name` into the checkout: writes its folder as the fetched pending
964
- * branch has it, untracked, and records it as submitted from this checkout, so an edit is
965
- * submitted again like one of the checkout's own and the folder gives way once its archive
966
- * arrives. Refused while the checkout holds a folder of that name; nothing is pushed.
967
- */
968
976
  export async function takeSubmitted(
969
977
  companionPath: string,
970
978
  name: string,
@@ -981,10 +989,15 @@ export async function takeSubmitted(
981
989
  if (!isChangeName(name)) return refused("missing", `mate: "${name}" is no change name.`);
982
990
  const relative = sourcePathOf(type, name);
983
991
  const dir = sourceDir(companionPath, type, name);
984
- if (await pathIsDirectory(dir)) {
985
- return refused("exists", `mate: ${relative} is in this checkout already; nothing was taken.`);
986
- }
987
992
  const git = (deps.git ?? defaultGit)(companionPath);
993
+ const exists = await pathIsDirectory(dir);
994
+ const kept = exists ? await replaceRefusal(git, companionPath, relative, deps) : null;
995
+ if (kept) {
996
+ return refused(
997
+ "exists",
998
+ `mate: ${relative} is in this checkout already and ${kept}; nothing was taken.`,
999
+ );
1000
+ }
988
1001
  const remote = await stagingRemote(git);
989
1002
  if (!remote) return refused("no-remote", "mate: the companion has no upstream.");
990
1003
  const fetched = await fetchPendingBranches(git, remote);
@@ -993,11 +1006,15 @@ export async function takeSubmitted(
993
1006
  const tip = (
994
1007
  await git.run(["rev-parse", "--verify", "-q", `${pendingRef(remote)}^{commit}`])
995
1008
  ).stdout.trim();
996
- const record = isCommitId(tip)
1009
+ const held =
1010
+ isCommitId(tip) &&
1011
+ (await git.run(["cat-file", "-e", "--end-of-options", `${tip}:${relative}`])).status === 0;
1012
+ const record = held
997
1013
  ? await git.run(["show", "--end-of-options", `${tip}:${relative}/${DELIVERY_FILE}`])
998
1014
  : null;
999
- if (record?.status !== 0 || !/^state:\s*submitted\s*$/m.test(record.stdout)) {
1000
- return refused("missing", `mate: ${name} is not submitted on ${pendingPlace(remote)}.`);
1015
+ const state = submissionStateOf(record?.status === 0 ? record.stdout : null);
1016
+ if (!held || state === "dropped") {
1017
+ return refused("missing", `mate: ${name} is not on ${pendingPlace(remote)}.`);
1001
1018
  }
1002
1019
  // Anyone may push the inbox: a link there must not reach the checkout, where it is followed.
1003
1020
  const linked = await linkedContentPaths(git, tip, [relative]);
@@ -1009,6 +1026,14 @@ export async function takeSubmitted(
1009
1026
  : `mate: ${pendingPlace(remote)} holds a symbolic link or submodule at ${linked.join(", ")}; Mate does not take it.`,
1010
1027
  );
1011
1028
  }
1029
+ let backup: string | null = null;
1030
+ if (exists) {
1031
+ if (await replaceRefusal(git, companionPath, relative, deps)) {
1032
+ return refused("exists", `mate: ${relative} changed while taking it; nothing was taken.`);
1033
+ }
1034
+ backup = path.join(path.dirname(dir), `.${name}.take-${randomBytes(4).toString("hex")}`);
1035
+ await fs.rename(dir, backup);
1036
+ }
1012
1037
  // The work tree only: the index stays as it is, so the folder is untracked like a submitted one.
1013
1038
  const written = await git.run([
1014
1039
  ...LITERAL_PATHSPECS,
@@ -1021,11 +1046,13 @@ export async function takeSubmitted(
1021
1046
  const files = written.status === 0 ? await ownFiles(git, companionPath, relative) : null;
1022
1047
  if (!files || files.length === 0) {
1023
1048
  await fs.rm(dir, { recursive: true, force: true });
1049
+ if (backup) await fs.rename(backup, dir);
1024
1050
  return refused(
1025
1051
  "failed",
1026
1052
  `mate: writing ${relative} failed; nothing was taken. ${describeGitFailure(written)}`,
1027
1053
  );
1028
1054
  }
1055
+ if (backup) await fs.rm(backup, { recursive: true, force: true });
1029
1056
  updateSubmittedFolders(
1030
1057
  companionPath,
1031
1058
  {
@@ -1035,16 +1062,48 @@ export async function takeSubmitted(
1035
1062
  dir,
1036
1063
  files.filter((file) => file !== DELIVERY_FILE),
1037
1064
  ),
1065
+ shared: await sharedDigestAt(git, tip, relative),
1038
1066
  submittedAt: (deps.now?.() ?? new Date()).toISOString(),
1039
1067
  },
1040
1068
  },
1041
1069
  [],
1042
1070
  deps.stateHome,
1043
1071
  );
1072
+ const next =
1073
+ state === "submitted"
1074
+ ? `Edit it, then submit it again with \`mate artifact submit ${name}\`.`
1075
+ : `Continue it, then submit it with \`mate artifact submit ${name}\` once it is done.`;
1044
1076
  return {
1045
1077
  change: name,
1046
1078
  status: "taken",
1047
1079
  path: relative,
1048
- message: `Took ${name} into ${relative} as ${pendingPlace(remote)} has it. Edit it, then submit it again with \`mate artifact submit ${name}\`.`,
1080
+ message: `Took ${name} into ${relative} as ${pendingPlace(remote)} has it. ${next}`,
1049
1081
  };
1050
1082
  }
1083
+
1084
+ /** Why a take must not replace the folder `relative`; null when a take loses nothing. */
1085
+ async function replaceRefusal(
1086
+ git: CompanionGit,
1087
+ companionPath: string,
1088
+ relative: string,
1089
+ deps: Pick<SubmitDeps, "stateHome">,
1090
+ ): Promise<string | null> {
1091
+ const recorded = readSubmittedFolders(companionPath, deps.stateHome)[relative];
1092
+ const files = recorded ? await ownFiles(git, companionPath, relative) : null;
1093
+ const dir = path.join(companionPath, ...relative.split("/"));
1094
+ if (!recorded || !files || (await folderDigest(dir, files)) !== recorded.digest) {
1095
+ return "changed since this checkout last pushed or took it";
1096
+ }
1097
+ const known = new Set(
1098
+ files.flatMap((file) => {
1099
+ const parts = file.split("/");
1100
+ return parts.map((_, index) => parts.slice(0, index + 1).join("/"));
1101
+ }),
1102
+ );
1103
+ const stray = (await fs.readdir(dir, { recursive: true }))
1104
+ .map((entry) => entry.split(path.sep).join("/"))
1105
+ .find((entry) => !known.has(entry));
1106
+ return stray === undefined
1107
+ ? null
1108
+ : `holds ${stray}, which Git ignores or Mate does not take, and a take would delete it`;
1109
+ }
@@ -1,11 +1,12 @@
1
1
  import { audienceEntry, normalizeBaseAudience } from "../../tools/setup/dynamic-plugins/audiences";
2
- import type {
3
- McpManagerAudienceSelection,
4
- McpManagerConfig,
5
- McpManagerSelection,
6
- ResolvedMcpServer,
2
+ import {
3
+ type McpManagerAudienceSelection,
4
+ type McpManagerConfig,
5
+ type McpManagerSelection,
6
+ parseHeaderRef,
7
+ type ResolvedMcpServer,
7
8
  } from "./types";
8
- import { isRecord, parseHeaderRef } from "./validate";
9
+ import { isRecord } from "./validate";
9
10
 
10
11
  function members(section: McpManagerConfig, groups: string[] | undefined): string[] {
11
12
  return (groups ?? []).flatMap((group) => section.groups?.[group] ?? []);
@@ -25,13 +26,17 @@ export interface MissingMcpVariable {
25
26
  }
26
27
 
27
28
  /** Variables a server reads: its `env` names and the one each header references. */
28
- function serverVariables(server: ResolvedMcpServer["server"]): string[] {
29
+ export function serverVariables(server: ResolvedMcpServer["server"]): string[] {
29
30
  const headers = "headers" in server ? Object.values(server.headers ?? {}) : [];
30
31
  const fromHeaders = headers.flatMap((value) => parseHeaderRef(value)?.variable ?? []);
31
32
  return [...new Set([...(server.env ?? []), ...fromHeaders])];
32
33
  }
33
34
 
34
- /** Checks presence only; a value never leaves `env`. */
35
+ /** Unset and empty both count as missing. Checks presence only; a value never leaves `env`. */
36
+ export function isVariableSet(env: Record<string, string | undefined>, variable: string): boolean {
37
+ return Boolean(env[variable]);
38
+ }
39
+
35
40
  export function missingMcpVariables(
36
41
  raw: unknown,
37
42
  audience: string | null,
@@ -39,7 +44,7 @@ export function missingMcpVariables(
39
44
  ): MissingMcpVariable[] {
40
45
  return resolveMcpServers(raw, audience).flatMap(({ name, server }) =>
41
46
  serverVariables(server)
42
- .filter((variable) => !env[variable])
47
+ .filter((variable) => !isVariableSet(env, variable))
43
48
  .map((variable) => ({ server: name, variable })),
44
49
  );
45
50
  }
@@ -68,3 +73,16 @@ export function resolveMcpServers(raw: unknown, audience: string | null): Resolv
68
73
  .toSorted()
69
74
  .map((name) => ({ name, server: section.servers![name] }));
70
75
  }
76
+
77
+ /** Effective server names for the base set and for each of `audiences`. */
78
+ export function effectiveSets(
79
+ raw: unknown,
80
+ audiences: readonly string[],
81
+ ): { base: string[]; audiences: Record<string, string[]> } {
82
+ const names = (audience: string | null) =>
83
+ resolveMcpServers(raw, audience).map((server) => server.name);
84
+ return {
85
+ base: names(null),
86
+ audiences: Object.fromEntries(audiences.map((audience) => [audience, names(audience)])),
87
+ };
88
+ }
@@ -1,7 +1,8 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import { isDeepStrictEqual } from "node:util";
3
4
 
4
- import { parseDocument } from "yaml";
5
+ import { type Document, isCollection, isMap, isNode, isScalar, parseDocument } from "yaml";
5
6
 
6
7
  import { FRAMEWORK_NAME } from "../../framework";
7
8
  import { companionFrameworkConfigPath } from "../../runtime/policy";
@@ -9,7 +10,7 @@ import { writeAtomic } from "../../runtime/write-atomic";
9
10
  import { BASE_AUDIENCE, declaredAudiences } from "../../tools/setup/dynamic-plugins/audiences";
10
11
  import { parseFrameworkConfig } from "../orchestrator/config-store";
11
12
  import { ConfigError, type FrameworkConfig } from "../orchestrator/types";
12
- import { resolveMcpServers } from "./resolve";
13
+ import { effectiveSets } from "./resolve";
13
14
  import type { McpManagerAudienceSelection, McpManagerConfig } from "./types";
14
15
  import { mcpManagerEngineRange } from "./validate";
15
16
 
@@ -46,21 +47,43 @@ function tokenOf(text: string): string {
46
47
 
47
48
  function snapshotOf(config: FrameworkConfig, token: string): McpManagerSnapshot {
48
49
  const names = declaredAudiences(config);
49
- const effective = (audience: string | null) =>
50
- resolveMcpServers(config, audience).map((server) => server.name);
51
50
  return {
52
51
  catalog: config.mcpManager ?? null,
53
52
  audiences: Object.fromEntries(
54
53
  names.map((name) => [name, config.audiences?.[name]?.mcpManager ?? {}]),
55
54
  ),
56
- effective: {
57
- base: effective(null),
58
- audiences: Object.fromEntries(names.map((name) => [name, effective(name)])),
59
- },
55
+ effective: effectiveSets(config, names),
60
56
  token,
61
57
  };
62
58
  }
63
59
 
60
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
61
+ typeof value === "object" && value !== null && !Array.isArray(value);
62
+
63
+ /**
64
+ * Sets `value` at `path`, rewriting only the entries that differ, so untouched
65
+ * entries keep their comments and flow or block style.
66
+ */
67
+ function mergeIn(document: Document, path: readonly string[], value: unknown): void {
68
+ const held: unknown = document.getIn(path, true);
69
+ if (isNode(held) && isDeepStrictEqual(held.toJS(document), value)) return;
70
+ if (isMap(held) && isPlainObject(value)) {
71
+ const removed = held.items.filter(
72
+ ({ key }) => !Object.hasOwn(value, String(isScalar(key) ? key.value : key)),
73
+ );
74
+ for (const { key } of removed) held.delete(key);
75
+ for (const [key, child] of Object.entries(value)) mergeIn(document, [...path, key], child);
76
+ return;
77
+ }
78
+ const node = document.createNode(value);
79
+ if (isCollection(held) && isCollection(node)) node.flow = held.flow;
80
+ if (isNode(held)) {
81
+ node.commentBefore = held.commentBefore;
82
+ node.comment = held.comment;
83
+ }
84
+ document.setIn(path, node);
85
+ }
86
+
64
87
  async function readText(companionPath: string): Promise<string> {
65
88
  return fs.readFile(companionFrameworkConfigPath(companionPath), "utf8");
66
89
  }
@@ -87,7 +110,7 @@ export async function writeMcpManager(
87
110
 
88
111
  const document = parseDocument(text);
89
112
  if (patch.catalog === null) document.delete("mcpManager");
90
- else if (patch.catalog !== undefined) document.set("mcpManager", patch.catalog);
113
+ else if (patch.catalog !== undefined) mergeIn(document, ["mcpManager"], patch.catalog);
91
114
  for (const [audience, selection] of Object.entries(patch.audiences ?? {})) {
92
115
  if (audience === BASE_AUDIENCE) {
93
116
  throw new ConfigError(
@@ -95,7 +118,7 @@ export async function writeMcpManager(
95
118
  );
96
119
  }
97
120
  if (selection === null) document.deleteIn(["audiences", audience, "mcpManager"]);
98
- else document.setIn(["audiences", audience, "mcpManager"], selection);
121
+ else mergeIn(document, ["audiences", audience, "mcpManager"], selection);
99
122
  }
100
123
 
101
124
  const raw = document.toJS() as Record<string, unknown>;
@@ -103,7 +126,8 @@ export async function writeMcpManager(
103
126
  const raised = mcpManagerEngineRange(raw);
104
127
  if (raised !== null) document.setIn(["engines", FRAMEWORK_NAME], raised);
105
128
 
106
- const next = document.toString();
129
+ // No folding, so a long flow entry the save left alone stays on its line.
130
+ const next = document.toString({ lineWidth: 0 });
107
131
  await writeAtomic(companionFrameworkConfigPath(companionPath), next);
108
132
  return snapshotOf(config, tokenOf(next));
109
133
  }
@@ -2,6 +2,9 @@
2
2
  export const MCP_MANAGER_TRANSPORTS = ["http", "sse"] as const;
3
3
  export type McpManagerTransport = (typeof MCP_MANAGER_TRANSPORTS)[number];
4
4
 
5
+ /** Scheme prefixes a header may put before its `${NAME}` reference. */
6
+ export const MCP_MANAGER_HEADER_PREFIXES = ["Bearer ", "Basic ", "Token "] as const;
7
+
5
8
  /** Fields every declared server shares. Holds variable names, never values. */
6
9
  interface McpManagerServerBase {
7
10
  /** Environment variable names the server reads, rendered as runtime references. */
@@ -51,6 +54,17 @@ export interface McpManagerHeaderRef {
51
54
  variable: string;
52
55
  }
53
56
 
57
+ const HEADER_VALUE_PATTERN = new RegExp(
58
+ `^(${MCP_MANAGER_HEADER_PREFIXES.join("|")})?\\$\\{([A-Z_][A-Z0-9_]*)\\}$`,
59
+ );
60
+
61
+ /** `${NAME}` with an optional known scheme prefix, or null for anything else. */
62
+ export function parseHeaderRef(value: unknown): McpManagerHeaderRef | null {
63
+ if (typeof value !== "string") return null;
64
+ const match = HEADER_VALUE_PATTERN.exec(value);
65
+ return match ? { prefix: match[1] ?? "", variable: match[2]! } : null;
66
+ }
67
+
54
68
  /** One server of an effective set, ready to become an MCP descriptor. */
55
69
  export interface ResolvedMcpServer {
56
70
  name: string;
@@ -1,16 +1,19 @@
1
1
  import { raisedEngineRange } from "../orchestrator/engine-floor";
2
2
  import { ConfigError } from "../orchestrator/types";
3
- import { MCP_MANAGER_TRANSPORTS, type McpManagerConfig, type McpManagerHeaderRef } from "./types";
3
+ import {
4
+ MCP_MANAGER_HEADER_PREFIXES,
5
+ MCP_MANAGER_TRANSPORTS,
6
+ type McpManagerConfig,
7
+ parseHeaderRef,
8
+ } from "./types";
4
9
 
5
10
  /** First Mate release that reads `mcpManager`; the `engines.mate` floor a save sets. */
6
11
  export const MCP_MANAGER_VERSION = "1.0.0-canary.9";
7
12
 
8
13
  export const MCP_MANAGER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
9
14
  export const MCP_MANAGER_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
10
- export const MCP_MANAGER_HEADER_PREFIXES = ["Bearer ", "Basic ", "Token "] as const;
11
15
 
12
16
  const HEADER_NAME_PATTERN = /^[A-Za-z0-9-]+$/;
13
- const HEADER_VALUE_PATTERN = /^(Bearer |Basic |Token )?\$\{([A-Z_][A-Z0-9_]*)\}$/;
14
17
 
15
18
  const SECTION_KEYS = ["servers", "groups", "enabled"] as const;
16
19
  const STDIO_KEYS = ["command", "args", "env"] as const;
@@ -34,13 +37,6 @@ function checkKeys(where: string, value: Record<string, unknown>, allowed: reado
34
37
  }
35
38
  }
36
39
 
37
- /** `${NAME}` with an optional known scheme prefix, or null for anything else. */
38
- export function parseHeaderRef(value: unknown): McpManagerHeaderRef | null {
39
- if (typeof value !== "string") return null;
40
- const match = HEADER_VALUE_PATTERN.exec(value);
41
- return match ? { prefix: match[1] ?? "", variable: match[2] } : null;
42
- }
43
-
44
40
  function validateEnv(where: string, env: unknown): void {
45
41
  if (!Array.isArray(env)) {
46
42
  fail(
@@ -3,7 +3,6 @@ import { execFileSync, spawn } from "node:child_process";
3
3
  import crypto from "node:crypto";
4
4
  import fsSync from "node:fs";
5
5
  import fs from "node:fs/promises";
6
- import net from "node:net";
7
6
 
8
7
  import {
9
8
  activeSessions,
@@ -17,6 +16,7 @@ import {
17
16
  readServerRecord,
18
17
  serverFileBase,
19
18
  } from "../runtime/opencode-server-record";
19
+ import { freeLoopbackPort } from "../runtime/host-process";
20
20
  import { withLock } from "../runtime/session-registry";
21
21
  import { writeAtomic } from "../runtime/write-atomic";
22
22
 
@@ -62,21 +62,6 @@ function startServe({ cwd, env, port, log }: Parameters<ServerDeps["start"]>[0])
62
62
  }
63
63
  }
64
64
 
65
- function freePort(): Promise<number> {
66
- return new Promise((resolve, reject) => {
67
- const probe = net.createServer();
68
- probe.once("error", reject);
69
- probe.listen(0, "127.0.0.1", () => {
70
- const address = probe.address();
71
- probe.close(() =>
72
- typeof address === "object" && address
73
- ? resolve(address.port)
74
- : reject(new Error("no free port")),
75
- );
76
- });
77
- });
78
- }
79
-
80
65
  function commandOf(pid: number): string | null {
81
66
  try {
82
67
  return execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }).trim();
@@ -91,7 +76,7 @@ const isOpenCodeServe = (command: string | null) => /\bopencode\b.*\bserve\b/.te
91
76
  export const defaultServerDeps: ServerDeps = {
92
77
  dir: openCodeServersDir(),
93
78
  start: startServe,
94
- freePort,
79
+ freePort: freeLoopbackPort,
95
80
  fetch,
96
81
  alive: processAlive,
97
82
  command: commandOf,
@@ -94,3 +94,17 @@ export async function upsertRepoLocalCompanionPointer(
94
94
 
95
95
  await saveRepoLocalRegistry(repoPath, registry);
96
96
  }
97
+
98
+ /** Drops the pointer to `companionPath` from `repoPath`'s own registry; writes nothing when none matches. */
99
+ export async function removeRepoLocalCompanionPointer(
100
+ repoPath: string,
101
+ companionPath: string,
102
+ ): Promise<void> {
103
+ const resolvedCompanionPath = path.resolve(companionPath);
104
+ const registry = await loadRepoLocalRegistry(repoPath);
105
+ const companions = registry.companions.filter(
106
+ (pointer) => path.resolve(pointer.path) !== resolvedCompanionPath,
107
+ );
108
+ if (companions.length === registry.companions.length) return;
109
+ await saveRepoLocalRegistry(repoPath, { ...registry, companions });
110
+ }