@uniqbit/mate-core 1.0.0-canary.8 → 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 (244) 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/doctor.ts +17 -0
  14. package/src/cli/commands/report/contract.ts +0 -17
  15. package/src/cli/commands/studio/access.ts +4 -0
  16. package/src/cli/commands/studio/actions.ts +35 -2
  17. package/src/cli/commands/studio/mcp-manager.ts +162 -0
  18. package/src/cli/commands/studio/routes.ts +12 -0
  19. package/src/cli/commands/studio/selection.ts +44 -11
  20. package/src/cli/commands/studio/server.ts +246 -2
  21. package/src/cli/commands/studio/services.ts +26 -0
  22. package/src/cli/commands/studio/terminal-launch.ts +21 -4
  23. package/src/cli/commands/studio/terminal.ts +3 -14
  24. package/src/cli/commands/studio/work-requests.ts +9 -0
  25. package/src/cli/commands/studio/work.ts +473 -0
  26. package/src/cli/commands/vscode/release-vsix.json +2 -2
  27. package/src/cli/commands/working/cleanup.ts +1 -18
  28. package/src/cli/companion-link-wizard.tsx +158 -91
  29. package/src/cli/usage.ts +1 -1
  30. package/src/create-mate.ts +4 -1
  31. package/src/lib/agent-credential.ts +131 -0
  32. package/src/lib/credential-kinds.ts +7 -0
  33. package/src/lib/delivery/merge-git.ts +16 -0
  34. package/src/lib/delivery/record-delivery.ts +12 -6
  35. package/src/lib/delivery/record.ts +5 -0
  36. package/src/lib/delivery/refresh.ts +34 -6
  37. package/src/lib/delivery/staging/refs.ts +9 -4
  38. package/src/lib/delivery/staging/submit.ts +81 -22
  39. package/src/lib/mcp-manager/resolve.ts +88 -0
  40. package/src/lib/mcp-manager/store.ts +133 -0
  41. package/src/lib/mcp-manager/types.ts +72 -0
  42. package/src/lib/mcp-manager/validate.ts +242 -0
  43. package/src/lib/opencode-server.ts +2 -17
  44. package/src/lib/orchestrator/config-store.ts +30 -7
  45. package/src/lib/orchestrator/engine-floor.ts +16 -4
  46. package/src/lib/orchestrator/engine-guard.ts +7 -1
  47. package/src/lib/orchestrator/repo-local-store.ts +14 -0
  48. package/src/lib/orchestrator/repository-link.ts +80 -52
  49. package/src/lib/orchestrator/root-context.ts +17 -1
  50. package/src/lib/orchestrator/types.ts +4 -0
  51. package/src/lib/studio-chat/agent.ts +139 -0
  52. package/src/lib/studio-chat/companion-context.ts +136 -0
  53. package/src/lib/studio-chat/credential.ts +79 -0
  54. package/src/lib/studio-chat/harness-chat-agent.ts +334 -0
  55. package/src/lib/studio-chat/host-sandbox.ts +578 -0
  56. package/src/lib/studio-chat/prepare-bridges.ts +95 -0
  57. package/src/lib/studio-chat/session.ts +15 -0
  58. package/src/lib/studio-chat/turns.ts +112 -0
  59. package/src/lib/workset/claims.ts +85 -0
  60. package/src/lib/workset/execution.ts +71 -0
  61. package/src/lib/workset/git-transaction.ts +74 -0
  62. package/src/lib/workset/groups.ts +176 -0
  63. package/src/lib/workset/inventory.ts +196 -0
  64. package/src/lib/workset/projection.ts +237 -0
  65. package/src/lib/workset/record.ts +101 -36
  66. package/src/lib/workset/repositories.ts +24 -0
  67. package/src/lib/workset/sharing.ts +951 -0
  68. package/src/lib/workset/stages.ts +50 -14
  69. package/src/lib/workset/transactions.ts +158 -0
  70. package/src/runtime/companion-git-state.ts +1 -0
  71. package/src/runtime/companion-guidance.ts +2 -2
  72. package/src/runtime/forge-remote.ts +6 -0
  73. package/src/runtime/host-process.ts +28 -0
  74. package/src/runtime/secret-guard.ts +18 -1
  75. package/src/runtime/secret-patterns.ts +4 -3
  76. package/src/runtime/submitted-arrivals.ts +28 -2
  77. package/src/runtime/workflow/turn.ts +14 -12
  78. package/src/runtime/write-atomic.ts +2 -2
  79. package/src/studio.ts +61 -0
  80. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +1 -1
  81. package/src/templates/capabilities/openspec-cap/mate-full/templates/proposal.md +1 -1
  82. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +3 -2
  83. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +5 -3
  84. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +3 -2
  85. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +5 -3
  86. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +12 -12
  87. package/src/tools/setup/capabilities/mcp-manager.ts +73 -0
  88. package/src/tools/setup/context-services.ts +35 -6
  89. package/src/tools/setup/dynamic-plugins/audiences.ts +3 -2
  90. package/src/tools/setup/dynamic-plugins/declarations.ts +0 -26
  91. package/src/tools/setup/engine.ts +55 -3
  92. package/src/tools/setup/plugin.ts +14 -0
  93. package/src/tools/setup/plugins/gitignore.ts +1 -0
  94. package/src/tools/setup/providers/claude-format.ts +40 -7
  95. package/src/tools/setup/providers/claude.ts +38 -3
  96. package/src/tools/setup/providers/opencode-format.ts +13 -3
  97. package/src/tools/setup/providers/opencode.ts +7 -18
  98. package/src/tools/setup/providers/relative-path-warnings.ts +26 -0
  99. package/studio-dist/THIRD-PARTY-NOTICES.md +297 -0
  100. package/studio-dist/client/THIRD-PARTY-LICENSES.md +4294 -0
  101. package/studio-dist/client/assets/DialogTitle-DOhjDa7H.js +1 -0
  102. package/studio-dist/client/assets/app-CG3vCgyA.css +2 -0
  103. package/studio-dist/client/assets/bundle-mjs-CdK3cBzO.js +1 -0
  104. package/studio-dist/client/assets/button-upSzkd-q.js +1 -0
  105. package/studio-dist/client/assets/chat-DbaMXb8H.js +157 -0
  106. package/studio-dist/client/assets/cn-BCnYnarL.js +1 -0
  107. package/studio-dist/client/assets/combobox-cP9OsRf2.js +1 -0
  108. package/studio-dist/client/assets/{companion-view-C_N237bf.js → companion-view-B54_Lj0S.js} +1 -1
  109. package/studio-dist/client/assets/fields-DNZ4a89M.js +1 -0
  110. package/studio-dist/client/assets/friction-DgEimeDB.js +1 -0
  111. package/studio-dist/client/assets/getting-started-BTfYCt5s.js +1 -0
  112. package/studio-dist/client/assets/{getting-started-djaQeWlu.js → getting-started-CAszmdDJ.js} +1 -1
  113. package/studio-dist/client/assets/getting-started._topic-CHJMf0pa.js +1 -0
  114. package/studio-dist/client/assets/getting-started.index-MR6HftWs.js +1 -0
  115. package/studio-dist/client/assets/{graph-canvas-ySGKMhmk.js → graph-canvas-BdNk2F9O.js} +1 -1
  116. package/studio-dist/client/assets/graph-hRijsC89.js +2 -0
  117. package/studio-dist/client/assets/guides-CwFnh08E.js +1 -0
  118. package/studio-dist/client/assets/highlighted-body-JLMTFACH-BcroQey-.js +1 -0
  119. package/studio-dist/client/assets/index-D5oGyvG8.js +41 -0
  120. package/studio-dist/client/assets/{markdown-view-jMiaBTSO.js → markdown-view-CJ8JsLb7.js} +1 -1
  121. package/studio-dist/client/assets/marked.esm-vFuq1cCd.js +65 -0
  122. package/studio-dist/client/assets/mcp-BE9M-bkO.js +4 -0
  123. package/studio-dist/client/assets/mermaid-WFAXDIZX-BjSsakrn.js +1 -0
  124. package/studio-dist/client/assets/panel-CDQ6Lryw.js +1 -0
  125. package/studio-dist/client/assets/plugins._service._view-DRVPUAWN.js +1 -0
  126. package/studio-dist/client/assets/{prepaint-CKsXyJOR.js → prepaint-sD_LlrDN.js} +1 -1
  127. package/studio-dist/client/assets/{queries-Dfp5deWj.js → queries-COL925ML.js} +1 -1
  128. package/studio-dist/client/assets/react-dom-K3Hp2Cdj.js +1 -0
  129. package/studio-dist/client/assets/{react-BYUSgtBs.js → react-h2xQ_NSp.js} +1 -1
  130. package/studio-dist/client/assets/reports-BClsojkb.js +1 -0
  131. package/studio-dist/client/assets/routes-CJQ2MAej.js +1 -0
  132. package/studio-dist/client/assets/search-DhWdEiKT.js +1 -0
  133. package/studio-dist/client/assets/select-B2FsN9FY.js +1 -0
  134. package/studio-dist/client/assets/skills-SoUHk77W.js +1 -0
  135. package/studio-dist/client/assets/{specs-BrCOjOch.js → specs-C_tZnAvF.js} +1 -1
  136. package/studio-dist/client/assets/specs-view-C6t3Y5IT.js +1 -0
  137. package/studio-dist/client/assets/steps-CF3-Zpmh.js +1 -0
  138. package/studio-dist/client/assets/{store-C3vJq8Wj.js → store-pY9gU4uS.js} +1 -1
  139. package/studio-dist/client/assets/studio-X7bnFrRe.js +36 -0
  140. package/studio-dist/client/assets/studio-queries-CKtAnIKP.js +2 -0
  141. package/studio-dist/client/assets/usage-BaaqUpTG.js +55 -0
  142. package/studio-dist/client/assets/useAnchoredPopupScrollLock-BspHR7Wt.js +1 -0
  143. package/studio-dist/client/assets/useBlocker-BQOfcu_f.js +1 -0
  144. package/studio-dist/client/assets/useMutation-DKeEoP5S.js +1 -0
  145. package/studio-dist/client/assets/useOpenInteractionType-CtaZCaFT.js +1 -0
  146. package/studio-dist/client/assets/usePopupHandleStore-Bc7Q4bnF.js +1 -0
  147. package/studio-dist/client/assets/vault-sAPFUnPN.js +1 -0
  148. package/studio-dist/client/assets/{warnings-CqOOGlPD.js → warnings-D7YY1HSG.js} +1 -1
  149. package/studio-dist/client/assets/work-BZek_LGB.js +5 -0
  150. package/studio-dist/client/assets/workflow-N5boHXFz.js +1 -0
  151. package/studio-dist/server/THIRD-PARTY-LICENSES.md +4371 -0
  152. package/studio-dist/server/assets/DialogTitle-DnKSl2V0.js +421 -0
  153. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-gVfW5vIV.js → __23tanstack-start-server-fn-resolver-Bli9bpSB.js} +38 -18
  154. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +91 -59
  155. package/studio-dist/server/assets/{actions-D8erOphH.js → actions-CHEFA1i9.js} +33 -1
  156. package/studio-dist/server/assets/{cn-FXJAM0KO.js → bundle-mjs-Ot6dQ8Pq.js} +1 -2056
  157. package/studio-dist/server/assets/{button-D6bvrFmm.js → button-BqA1urbl.js} +14 -7
  158. package/studio-dist/server/assets/chat-zl332Tvu.js +49486 -0
  159. package/studio-dist/server/assets/cn-B0fl6NWK.js +2057 -0
  160. package/studio-dist/server/assets/{combobox-D2MbYV1O.js → combobox-iTjvPCtS.js} +7 -6
  161. package/studio-dist/server/assets/{companion-view-Mf1ANbMb.js → companion-view-DIQ6AFIY.js} +2 -2
  162. package/studio-dist/server/assets/{companions-Dr6IpNAb.js → companions-aVwjRL8j.js} +1 -1
  163. package/studio-dist/server/assets/{fields-B4mAPETz.js → fields-BMap2_Ju.js} +10 -3
  164. package/studio-dist/server/assets/{friction-CWOTjpCV.js → friction-BER50hoD.js} +2 -2
  165. package/studio-dist/server/assets/{friction-9a5S1m7U.js → friction-BPs9KWdq.js} +8 -8
  166. package/studio-dist/server/assets/{getting-started-RU6tYU2Q.js → getting-started-DGfRVmZ_.js} +2 -2
  167. package/studio-dist/server/assets/{getting-started._topic-C02HGrC6.js → getting-started._topic-BgrBA4Vj.js} +2 -2
  168. package/studio-dist/server/assets/{getting-started.index-EzLRosbb.js → getting-started.index-BaFfQ9Mn.js} +2 -2
  169. package/studio-dist/server/assets/{graph-CZ2H9Fzr.js → graph-Cgzlrv3P.js} +8 -8
  170. package/studio-dist/server/assets/{graph-B11ITte0.js → graph-DODpuOy_.js} +1 -1
  171. package/studio-dist/server/assets/{graph-canvas-rP5TT14Z.js → graph-canvas-DW_zU1nA.js} +2 -2
  172. package/studio-dist/server/assets/{guides-BGftp4wf.js → guides-CA_EMG7E.js} +1 -1
  173. package/studio-dist/server/assets/{guides-B8HdeK_C.js → guides-D0SpoD32.js} +1 -1
  174. package/studio-dist/server/assets/{guides.server-DqFQAStf.js → guides.server-DJjQuy03.js} +1 -1
  175. package/studio-dist/server/assets/highlighted-body-JLMTFACH-BeHllu-r.js +41 -0
  176. package/studio-dist/server/assets/{markdown-view-CArpV-CS.js → markdown-view-CvVBGMZV.js} +1 -1
  177. package/studio-dist/server/assets/mcp-BU0fLYyJ.js +1103 -0
  178. package/studio-dist/server/assets/mcp-manager-D9YctTQe.js +50 -0
  179. package/studio-dist/server/assets/mermaid-WFAXDIZX-B1yDN6vG.js +1 -0
  180. package/studio-dist/server/assets/{panel-DR0iq46J.js → panel-D1K6Bsux.js} +4 -32
  181. package/studio-dist/server/assets/{plugins._service._view-n7u2k5dF.js → plugins._service._view-DdO1nELF.js} +4 -4
  182. package/studio-dist/server/assets/{prepaint-B28ClcPN.js → prepaint-BB3dwSmz.js} +1 -1
  183. package/studio-dist/server/assets/{queries-D-yVP9i0.js → queries-BwiDxQy5.js} +1 -1
  184. package/studio-dist/server/assets/{react-CiBZPDs8.js → react-B2cLiz-i.js} +1 -1
  185. package/studio-dist/server/assets/{reports-C2SmTgqh.js → reports-9Pr7Bz6o.js} +7 -7
  186. package/studio-dist/server/assets/{reports-B9k98oE6.js → reports-Cc9M3phM.js} +1 -1
  187. package/studio-dist/server/assets/{router-CPt0TAk_.js → router-DcWe0J7Y.js} +827 -548
  188. package/studio-dist/server/assets/{routes-CwH8LEy2.js → routes-BEXxl0py.js} +8 -8
  189. package/studio-dist/server/assets/{search-b-yQesv3.js → search-bltT7gwy.js} +39 -7
  190. package/studio-dist/server/assets/{select-C3i6TTX-.js → select-CZvHgGCi.js} +7 -6
  191. package/studio-dist/server/assets/{shell-CagqZZMZ.js → shell-BQ0vMKXN.js} +13 -4
  192. package/studio-dist/server/assets/{skills-DGg0mWDM.js → skills-Be_52h0i.js} +1 -1
  193. package/studio-dist/server/assets/{skills-C21Mg_8-.js → skills-BpGGUl6L.js} +8 -8
  194. package/studio-dist/server/assets/{specs-DetoMiaB.js → specs-CCGgXE-V.js} +5 -5
  195. package/studio-dist/server/assets/{specs-view-CmbfLDwN.js → specs-view-DtL5JxYM.js} +12 -11
  196. package/studio-dist/server/assets/{steps-D1tYAyWZ.js → steps-BWFSO6dM.js} +1 -1
  197. package/studio-dist/server/assets/{store-aC-I6f6o.js → store-X7yLPp7v.js} +1 -1
  198. package/studio-dist/server/assets/{studio-queries-Dqf-3nzj.js → studio-queries-ur1ygXi3.js} +117 -13
  199. package/studio-dist/server/assets/{studio-qRvQjRpz.js → studio-qzH-UETC.js} +1555 -179
  200. package/studio-dist/server/assets/{usage-Cwle9-xY.js → usage-C1o0DLzS.js} +1 -1
  201. package/studio-dist/server/assets/{usage-CS4CBK9D.js → usage-DWbSPrPD.js} +10 -9
  202. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-BjMNgXv9.js → useAnchoredPopupScrollLock-DLDmv6kM.js} +4 -135
  203. package/studio-dist/server/assets/useBlocker-CQtANHK8.js +111 -0
  204. package/studio-dist/server/assets/{useMutation-DpBIuWXt.js → useMutation-NjlA8oFY.js} +2 -2
  205. package/studio-dist/server/assets/useOpenInteractionType-CZYscfOb.js +136 -0
  206. package/studio-dist/server/assets/usePopupHandleStore-DEEXJYv0.js +26 -0
  207. package/studio-dist/server/assets/{vault-CEBBRLMb.js → vault-B_kfi1h-.js} +1 -1
  208. package/studio-dist/server/assets/{vault-DVQidlId.js → vault-dL79JlKH.js} +8 -115
  209. package/studio-dist/server/assets/{views-UgO0Qz_g.js → views-BSGH56lb.js} +3 -3
  210. package/studio-dist/server/assets/{warnings-C7hgXpdk.js → warnings-DtUVPV-k.js} +2 -2
  211. package/studio-dist/server/assets/work-D789VXGH.js +110 -0
  212. package/studio-dist/server/assets/work-DsCEfhmK.js +3817 -0
  213. package/studio-dist/server/assets/work-requests-BLhOmQFO.js +11 -0
  214. package/studio-dist/server/assets/{workflow-6dZZ1ofw.js → workflow-BOZ2sRYg.js} +9 -9
  215. package/studio-dist/server/server.js +3 -3
  216. package/wrappers/bin/openspec +87 -2
  217. package/studio-dist/client/assets/app-ggXJ_QVh.css +0 -2
  218. package/studio-dist/client/assets/button-amJ3g5oD.js +0 -1
  219. package/studio-dist/client/assets/cn-BQPKiwI4.js +0 -1
  220. package/studio-dist/client/assets/combobox-CJ7aGFid.js +0 -1
  221. package/studio-dist/client/assets/fields-BAiGkJ5N.js +0 -1
  222. package/studio-dist/client/assets/friction-DqOU59v7.js +0 -1
  223. package/studio-dist/client/assets/getting-started-yp42dj5S.js +0 -1
  224. package/studio-dist/client/assets/getting-started._topic-C9zVXz_m.js +0 -1
  225. package/studio-dist/client/assets/getting-started.index-DWbDKICP.js +0 -1
  226. package/studio-dist/client/assets/graph-BYaD_5Bq.js +0 -2
  227. package/studio-dist/client/assets/guides-D6T6W_jV.js +0 -1
  228. package/studio-dist/client/assets/index-Qx7reRPD.js +0 -40
  229. package/studio-dist/client/assets/panel-C4bf_h2W.js +0 -1
  230. package/studio-dist/client/assets/plugins._service._view-y6f2FDAB.js +0 -1
  231. package/studio-dist/client/assets/reports-JFSwSueq.js +0 -1
  232. package/studio-dist/client/assets/routes-BdOWSgzK.js +0 -1
  233. package/studio-dist/client/assets/search-CXosfvYh.js +0 -1
  234. package/studio-dist/client/assets/select-BHYYWPhK.js +0 -1
  235. package/studio-dist/client/assets/skills-Bo9FLsBd.js +0 -1
  236. package/studio-dist/client/assets/specs-view-CdE2rlli.js +0 -1
  237. package/studio-dist/client/assets/steps-CKUno4lh.js +0 -1
  238. package/studio-dist/client/assets/studio-0ueISxwP.js +0 -100
  239. package/studio-dist/client/assets/studio-queries-BflKt9va.js +0 -2
  240. package/studio-dist/client/assets/usage-BLsLy0nN.js +0 -55
  241. package/studio-dist/client/assets/useAnchoredPopupScrollLock-DC7f8GOp.js +0 -1
  242. package/studio-dist/client/assets/useMutation-uJUrejsi.js +0 -1
  243. package/studio-dist/client/assets/vault-BB1B_OhR.js +0 -1
  244. package/studio-dist/client/assets/workflow-BFzmI-06.js +0 -1
@@ -0,0 +1,951 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { parse } from "yaml";
6
+
7
+ import {
8
+ type CompanionGit,
9
+ companionGit,
10
+ LITERAL_PATHSPECS,
11
+ nulPaths,
12
+ } from "../../runtime/companion-git";
13
+ import {
14
+ readSubmittedFolders,
15
+ type SubmittedFolder,
16
+ updateSubmittedFolders,
17
+ } from "../../runtime/companion-git-state";
18
+ import { withPathLock } from "../../runtime/companion-lock";
19
+ import { resolveSecretPolicy } from "../../runtime/policy";
20
+ import type { PublicationSecretScan } from "../../runtime/publication-secret-scan";
21
+ import { matchesSecretPattern, type SecretPolicy } from "../../runtime/secret-patterns";
22
+ import {
23
+ blobsAt,
24
+ contentDigest,
25
+ emptyFolderKeepingClaim,
26
+ folderDigest,
27
+ ownFiles,
28
+ sharedDigest,
29
+ sharedDigestAt,
30
+ } from "../../runtime/submitted-arrivals";
31
+ import { isMateSchema, SCHEMA_ARTIFACTS, type MateSchema } from "../delivery/stages";
32
+ import { submissionStateOf } from "../delivery/record";
33
+ import { recordDir, sourceDir, type ArtifactType } from "../delivery/staging/artifact-type";
34
+ import {
35
+ commitToPending,
36
+ type PendingCommitDeps,
37
+ type PendingCommitFailure,
38
+ } from "../delivery/staging/pending-edit";
39
+ import {
40
+ anchorsAt,
41
+ defaultRef,
42
+ fetchPendingBranches,
43
+ pendingPlace,
44
+ pendingRef,
45
+ stagingRemote,
46
+ type StagingRemote,
47
+ } from "../delivery/staging/refs";
48
+ import { defaultArtifactType } from "../delivery/staging/registry";
49
+ import {
50
+ claimAs,
51
+ type Operator,
52
+ OWNER_FILE,
53
+ type OwnerRead,
54
+ parseOwner,
55
+ serializeOwner,
56
+ } from "./claims";
57
+ import {
58
+ configuredOperator,
59
+ fetchedAt,
60
+ type GitFailure,
61
+ hashFiles,
62
+ isGitBacked,
63
+ refCommit,
64
+ workGit,
65
+ } from "./git-transaction";
66
+ import {
67
+ type ChangeLinks,
68
+ branchesFrom,
69
+ dependsOnFrom,
70
+ deriveGroups,
71
+ LINK_ARTIFACTS,
72
+ readFolderLinks,
73
+ readOptional,
74
+ } from "./groups";
75
+ import {
76
+ activeMembers,
77
+ implicitRecord,
78
+ type InventoryWorkset,
79
+ refuseSharedIds,
80
+ worksetIdDiagnostics,
81
+ } from "./inventory";
82
+ import { type SharingFacts, type SyncState, unsynced } from "./projection";
83
+
84
+ const WORK_LOCK = "work";
85
+
86
+ export interface WorkGitDeps {
87
+ git?: (cwd: string) => CompanionGit;
88
+ artifactType?: ArtifactType;
89
+ scan?: (root: string, paths: string[], policyPath: string) => Promise<PublicationSecretScan>;
90
+ stateHome?: string;
91
+ tmpRoot?: string;
92
+ }
93
+
94
+ const PENDING_BUDGET_MS = 120_000;
95
+
96
+ export const pendingGit = (cwd: string): CompanionGit =>
97
+ companionGit(cwd, { prompt: "never", budgetMs: PENDING_BUDGET_MS });
98
+
99
+ export function pendingCommitDeps(
100
+ gitFor: (cwd: string) => CompanionGit,
101
+ type: ArtifactType,
102
+ deps: WorkGitDeps,
103
+ ): PendingCommitDeps {
104
+ return {
105
+ git: gitFor,
106
+ artifactType: type,
107
+ ...(deps.scan ? { scan: deps.scan } : {}),
108
+ ...(deps.tmpRoot ? { tmpRoot: deps.tmpRoot } : {}),
109
+ };
110
+ }
111
+
112
+ export function folderOf(type: ArtifactType, name: string): string {
113
+ return `${type.source}/${name}`;
114
+ }
115
+
116
+ export interface SharedBranch {
117
+ remote: string;
118
+ branch: string;
119
+ trackingRef: string;
120
+ defaultRef: string;
121
+ }
122
+
123
+ export interface TeamStatus {
124
+ shared: SharedBranch | null;
125
+ tip: string | null;
126
+ fetchedAt?: string;
127
+ failure?: GitFailure;
128
+ stale: boolean;
129
+ }
130
+
131
+ export interface RemoteChange {
132
+ files: Map<string, string>;
133
+ links: ChangeLinks;
134
+ owner: OwnerRead;
135
+ state: "active" | "submitted";
136
+ }
137
+
138
+ export interface RemoteBacklog {
139
+ status: TeamStatus;
140
+ changes: Map<string, RemoteChange>;
141
+ archived: Set<string>;
142
+ }
143
+
144
+ function emptyBacklog(status: TeamStatus): RemoteBacklog {
145
+ return { status, changes: new Map(), archived: new Set() };
146
+ }
147
+
148
+ function sharedOf(remote: StagingRemote): SharedBranch {
149
+ return {
150
+ remote: remote.remote,
151
+ branch: remote.pendingBranch,
152
+ trackingRef: pendingRef(remote),
153
+ defaultRef: defaultRef(remote),
154
+ };
155
+ }
156
+
157
+ const NO_UPSTREAM: GitFailure = { message: "the companion has no upstream to share with" };
158
+
159
+ const NOT_GIT: GitFailure = { message: "the companion is not a Git repository" };
160
+
161
+ async function teamRemote(
162
+ git: CompanionGit,
163
+ ): Promise<{ remote: StagingRemote; shared: SharedBranch } | { failure: GitFailure }> {
164
+ if (!(await isGitBacked(git))) return { failure: NOT_GIT };
165
+ const remote = await stagingRemote(git);
166
+ return remote ? { remote, shared: sharedOf(remote) } : { failure: NO_UPSTREAM };
167
+ }
168
+
169
+ export async function readTeamBacklog(
170
+ companionPath: string,
171
+ lastFailure?: GitFailure,
172
+ type: ArtifactType = defaultArtifactType(),
173
+ ): Promise<RemoteBacklog> {
174
+ const git = workGit(companionPath);
175
+ const team = await teamRemote(git);
176
+ if ("failure" in team) {
177
+ return emptyBacklog({ shared: null, tip: null, failure: team.failure, stale: true });
178
+ }
179
+ const { shared } = team;
180
+ const [tip, published, at] = await Promise.all([
181
+ refCommit(git, shared.trackingRef),
182
+ refCommit(git, shared.defaultRef),
183
+ fetchedAt(git, shared.trackingRef),
184
+ ]);
185
+ const status: TeamStatus = {
186
+ shared,
187
+ tip,
188
+ ...(at ? { fetchedAt: at } : {}),
189
+ ...(lastFailure ? { failure: lastFailure } : {}),
190
+ stale: !!lastFailure || (!tip && !published),
191
+ };
192
+ const backlog = emptyBacklog(status);
193
+ if (published) {
194
+ backlog.archived = new Set(
195
+ (await anchorsAt(git, published, type)).map((id) => type.recordName(id)),
196
+ );
197
+ }
198
+ if (!tip) return backlog;
199
+ const files = new Map<string, Map<string, string>>();
200
+ for (const [file, blob] of await blobsAt(git, tip, type.source)) {
201
+ const slash = file.indexOf("/");
202
+ if (slash < 0) continue;
203
+ const name = file.slice(0, slash);
204
+ if (folderOf(type, name) === type.archiveRoot) continue;
205
+ const entry = files.get(name) ?? new Map<string, string>();
206
+ entry.set(file.slice(slash + 1), blob);
207
+ files.set(name, entry);
208
+ }
209
+ const wanted = [...LINK_ARTIFACTS, type.deliveryFile, OWNER_FILE];
210
+ const contents =
211
+ (await git.readBlobs(
212
+ [...files.values()].flatMap((blobs) =>
213
+ wanted.flatMap((file) => (blobs.has(file) ? [blobs.get(file)!] : [])),
214
+ ),
215
+ )) ?? new Map<string, string>();
216
+ for (const [name, blobs] of files) {
217
+ const read = (file: string) => contents.get(blobs.get(file) ?? "") ?? null;
218
+ const delivery = read(type.deliveryFile);
219
+ const state = submissionStateOf(delivery);
220
+ if (state === "dropped") continue;
221
+ backlog.changes.set(name, {
222
+ files: blobs,
223
+ links: {
224
+ name,
225
+ dependsOn: dependsOnFrom(LINK_ARTIFACTS.map(read)),
226
+ branches: branchesFrom(delivery),
227
+ },
228
+ owner: parseOwner(read(OWNER_FILE)),
229
+ state,
230
+ });
231
+ }
232
+ return backlog;
233
+ }
234
+
235
+ export async function refreshTeam(
236
+ companionPath: string,
237
+ ): Promise<{ ok: true } | { failure: GitFailure }> {
238
+ const git = workGit(companionPath);
239
+ const team = await teamRemote(git);
240
+ if ("failure" in team) return team;
241
+ const fetched = await fetchPendingBranches(git, team.remote);
242
+ return "error" in fetched ? { failure: { message: fetched.error } } : { ok: true };
243
+ }
244
+
245
+ const SHARE_SECRET_NAMES =
246
+ /(^|\/)(\.env(\..*)?|\.npmrc|\.netrc|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|credentials(\.\w+)?)$|\.(pem|key|p12|pfx)$/i;
247
+
248
+ function looksSecret(relative: string, policy: SecretPolicy): boolean {
249
+ if (matchesSecretPattern(relative, policy.allow)) return false;
250
+ return SHARE_SECRET_NAMES.test(relative) || matchesSecretPattern(relative, policy.deny);
251
+ }
252
+
253
+ export interface ChangeFiles {
254
+ files: string[];
255
+ excluded: { path: string; reason: string }[];
256
+ refusals: string[];
257
+ }
258
+
259
+ async function walkFiles(root: string, prefix = ""): Promise<string[]> {
260
+ const found: string[] = [];
261
+ const entries = await fs.readdir(path.join(root, prefix), { withFileTypes: true });
262
+ for (const entry of entries) {
263
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
264
+ // oxlint-disable-next-line no-await-in-loop -- bounded change folder, walked in order
265
+ if (entry.isDirectory()) found.push(...(await walkFiles(root, relative)));
266
+ else found.push(relative);
267
+ }
268
+ return found;
269
+ }
270
+
271
+ export async function changeFiles(
272
+ companionPath: string,
273
+ change: string,
274
+ type: ArtifactType = defaultArtifactType(),
275
+ ): Promise<ChangeFiles> {
276
+ const result: ChangeFiles = { files: [], excluded: [], refusals: [] };
277
+ const folder = folderOf(type, change);
278
+ const root = sourceDir(companionPath, type, change);
279
+ const rootStat = await fs.lstat(root).catch(() => null);
280
+ if (!rootStat) return result;
281
+ if (!rootStat.isDirectory()) {
282
+ result.refusals.push(`${folder} is not a regular directory`);
283
+ return result;
284
+ }
285
+ const git = workGit(companionPath);
286
+ const secrets = resolveSecretPolicy(companionPath);
287
+ const listed = await git.run([
288
+ ...LITERAL_PATHSPECS,
289
+ "ls-files",
290
+ "-z",
291
+ "--cached",
292
+ "--others",
293
+ "--exclude-standard",
294
+ "--",
295
+ `${folder}/`,
296
+ ]);
297
+ if (listed.status !== 0 && (await isGitBacked(git))) {
298
+ result.refusals.push(`Git could not list ${folder}`);
299
+ return result;
300
+ }
301
+ const relatives =
302
+ listed.status === 0
303
+ ? nulPaths(listed.stdout).map((file) => file.slice(folder.length + 1))
304
+ : await walkFiles(root);
305
+ for (const relative of [...new Set(relatives)].toSorted()) {
306
+ const companionRelative = `${folder}/${relative.replace(/\/$/, "")}`;
307
+ if (relative.endsWith("/")) {
308
+ result.refusals.push(`${companionRelative} is a nested Git repository`);
309
+ continue;
310
+ }
311
+ // oxlint-disable-next-line no-await-in-loop -- a handful of files per change
312
+ const stat = await fs.lstat(path.join(root, ...relative.split("/"))).catch(() => null);
313
+ if (!stat) continue;
314
+ if (stat.isSymbolicLink()) {
315
+ result.refusals.push(`${companionRelative} is a symbolic link`);
316
+ } else if (!stat.isFile()) {
317
+ result.refusals.push(`${companionRelative} is not a regular file`);
318
+ } else if (looksSecret(relative, secrets)) {
319
+ result.refusals.push(`${companionRelative} looks like a secret and is never shared`);
320
+ } else if (relative === OWNER_FILE) {
321
+ result.excluded.push({
322
+ path: companionRelative,
323
+ reason: "changed only by Claim and Release",
324
+ });
325
+ } else {
326
+ result.files.push(companionRelative);
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+
332
+ function remoteDigest(backlog: RemoteBacklog, member: string): string {
333
+ return sharedDigest(backlog.changes.get(member)?.files ?? []);
334
+ }
335
+
336
+ async function localShared(
337
+ git: CompanionGit,
338
+ companionPath: string,
339
+ type: ArtifactType,
340
+ member: string,
341
+ ): Promise<[string, string][]> {
342
+ const listed = await changeFiles(companionPath, member, type);
343
+ const blobs = await hashFiles(git, companionPath, listed.files);
344
+ const prefix = `${folderOf(type, member)}/`;
345
+ return listed.files.map((file): [string, string] => [
346
+ file.slice(prefix.length),
347
+ blobs.get(file) ?? "",
348
+ ]);
349
+ }
350
+
351
+ function memberSync(local: string, remote: string, recorded: string | undefined): SyncState {
352
+ if (local === remote) return "in-sync";
353
+ if (recorded === remote) return "ahead";
354
+ if (recorded === local) return "behind";
355
+ return "diverged";
356
+ }
357
+
358
+ function combine(states: readonly SyncState[]): SyncState {
359
+ if (states.includes("diverged")) return "diverged";
360
+ const ahead = states.includes("ahead");
361
+ const behind = states.includes("behind");
362
+ if (ahead && behind) return "diverged";
363
+ if (ahead) return "ahead";
364
+ return behind ? "behind" : "in-sync";
365
+ }
366
+
367
+ export async function compareWorkset(
368
+ companionPath: string,
369
+ entry: InventoryWorkset,
370
+ backlog: RemoteBacklog,
371
+ deps: Pick<WorkGitDeps, "artifactType" | "stateHome"> & {
372
+ recorded?: Record<string, SubmittedFolder>;
373
+ } = {},
374
+ ): Promise<SharingFacts> {
375
+ const type = deps.artifactType ?? defaultArtifactType();
376
+ const members = activeMembers(entry);
377
+ const shared = members.filter((member) => backlog.changes.has(member));
378
+ const stale = backlog.status.stale;
379
+ if (shared.length === 0) {
380
+ const unknown = !backlog.status.tip && !!backlog.status.failure && !!backlog.status.shared;
381
+ return {
382
+ presence: unknown ? "unknown" : "local",
383
+ missingMembers: [],
384
+ sync: "in-sync",
385
+ stale,
386
+ remoteOnly: false,
387
+ };
388
+ }
389
+ const git = workGit(companionPath);
390
+ const recorded = deps.recorded ?? readSubmittedFolders(companionPath, deps.stateHome);
391
+ const locals = await Promise.all(
392
+ shared.map(async (member) => ({
393
+ member,
394
+ local: await localShared(git, companionPath, type, member),
395
+ })),
396
+ );
397
+ const states: SyncState[] = [];
398
+ let localFiles = 0;
399
+ for (const { member, local } of locals) {
400
+ if (local.length === 0) continue;
401
+ localFiles += local.length;
402
+ states.push(
403
+ memberSync(
404
+ sharedDigest(local),
405
+ remoteDigest(backlog, member),
406
+ recorded[folderOf(type, member)]?.shared,
407
+ ),
408
+ );
409
+ }
410
+ const missing = members.filter((member) => !backlog.changes.has(member));
411
+ return {
412
+ presence: missing.length > 0 ? "partial" : "shared",
413
+ missingMembers: missing,
414
+ sync: combine(states),
415
+ stale,
416
+ remoteOnly: localFiles === 0,
417
+ };
418
+ }
419
+
420
+ export interface SharePreview {
421
+ workset: string;
422
+ members: string[];
423
+ files: { path: string; blob: string }[];
424
+ excluded: { path: string; reason: string }[];
425
+ externalDependencies: string[];
426
+ included: string[];
427
+ target: { remote: string; branch: string };
428
+ problems: string[];
429
+ hash: string;
430
+ }
431
+
432
+ export type PreviewResult = { preview: SharePreview } | { refusal: string };
433
+
434
+ async function readSchema(changeDir: string): Promise<MateSchema | null> {
435
+ try {
436
+ const document = parse(await fs.readFile(path.join(changeDir, ".openspec.yaml"), "utf8")) as {
437
+ schema?: unknown;
438
+ } | null;
439
+ const schema = document?.schema;
440
+ return typeof schema === "string" && isMateSchema(schema) ? schema : null;
441
+ } catch {
442
+ return null;
443
+ }
444
+ }
445
+
446
+ const ARTIFACT_FILE: Record<string, (files: string[], prefix: string) => boolean> = {
447
+ proposal: (files, prefix) => files.includes(`${prefix}/proposal.md`),
448
+ design: (files, prefix) => files.includes(`${prefix}/design.md`),
449
+ tasks: (files, prefix) => files.includes(`${prefix}/tasks.md`),
450
+ specs: (files, prefix) => files.some((file) => file.startsWith(`${prefix}/specs/`)),
451
+ };
452
+
453
+ export async function planProblems(
454
+ companionPath: string,
455
+ members: readonly string[],
456
+ type: ArtifactType = defaultArtifactType(),
457
+ known: ReadonlyMap<string, ChangeFiles> = new Map(),
458
+ ): Promise<string[]> {
459
+ const problems: string[] = [];
460
+ const openspec = type.name === defaultArtifactType().name;
461
+ for (const change of members) {
462
+ const prefix = folderOf(type, change);
463
+ // oxlint-disable-next-line no-await-in-loop -- few members per Workset
464
+ const [schema, listed] = await Promise.all([
465
+ readSchema(sourceDir(companionPath, type, change)),
466
+ known.get(change) ?? changeFiles(companionPath, change, type),
467
+ ]);
468
+ problems.push(...listed.refusals);
469
+ if (!openspec) {
470
+ // oxlint-disable-next-line no-await-in-loop -- same change
471
+ const refused = await type.check(companionPath, change);
472
+ if (refused) problems.push(`${change}: ${refused}`);
473
+ continue;
474
+ }
475
+ if (!schema) {
476
+ problems.push(`${change} names no known schema in .openspec.yaml`);
477
+ continue;
478
+ }
479
+ for (const artifact of SCHEMA_ARTIFACTS[schema]) {
480
+ if (!ARTIFACT_FILE[artifact]?.(listed.files, prefix)) {
481
+ problems.push(`${change} lacks its ${artifact} artifact`);
482
+ }
483
+ }
484
+ }
485
+ return problems;
486
+ }
487
+
488
+ async function localArchived(
489
+ companionPath: string,
490
+ name: string,
491
+ type: ArtifactType,
492
+ ): Promise<boolean> {
493
+ const dir = recordDir(companionPath, type);
494
+ if (dir === null) return false;
495
+ const entries = await fs.readdir(dir).catch(() => [] as string[]);
496
+ return entries.some((id) => type.isRecordId(id) && type.recordName(id) === name);
497
+ }
498
+
499
+ async function localDependsOn(
500
+ companionPath: string,
501
+ change: string,
502
+ type: ArtifactType,
503
+ ): Promise<readonly string[]> {
504
+ return (await readFolderLinks(sourceDir(companionPath, type, change), change)).dependsOn;
505
+ }
506
+
507
+ function contentHash(value: unknown): string {
508
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
509
+ }
510
+
511
+ export interface PreviewOptions {
512
+ include?: readonly string[];
513
+ artifactType?: ArtifactType;
514
+ }
515
+
516
+ export async function previewShare(
517
+ companionPath: string,
518
+ entry: InventoryWorkset,
519
+ backlog: RemoteBacklog,
520
+ options: PreviewOptions = {},
521
+ ): Promise<PreviewResult> {
522
+ const type = options.artifactType ?? defaultArtifactType();
523
+ if (!entry.actionable) {
524
+ return { refusal: entry.diagnostics[0] ?? "this Workset cannot be shared" };
525
+ }
526
+ const shared = backlog.status.shared;
527
+ if (!shared) {
528
+ return { refusal: backlog.status.failure?.message ?? "the companion has no shared branch" };
529
+ }
530
+ const members = activeMembers(entry);
531
+ if (members.length === 0) {
532
+ return { refusal: "Scratchpad ideas are not shared; propose the change first" };
533
+ }
534
+
535
+ const excluded: SharePreview["excluded"] = [];
536
+ const files: string[] = [];
537
+ const included = [...new Set(options.include ?? [])].filter((name) => !members.includes(name));
538
+ const changes = [...members, ...included];
539
+ const listedFor = new Map<string, ChangeFiles>();
540
+ for (const change of changes) {
541
+ // oxlint-disable-next-line no-await-in-loop -- few members per Workset
542
+ const delivery = await readOptional(
543
+ path.join(sourceDir(companionPath, type, change), type.deliveryFile),
544
+ );
545
+ if (submissionStateOf(delivery) === "dropped") {
546
+ return {
547
+ refusal: `${change} was dropped and is not shared; \`mate artifact submit ${change}\` submits it again once it is done`,
548
+ };
549
+ }
550
+ // oxlint-disable-next-line no-await-in-loop -- same change
551
+ const listed = await changeFiles(companionPath, change, type);
552
+ if (listed.refusals.length > 0) return { refusal: listed.refusals.join("; ") };
553
+ if (listed.files.length === 0) return { refusal: `${change} has no files to share` };
554
+ excluded.push(...listed.excluded);
555
+ files.push(...listed.files);
556
+ listedFor.set(change, listed);
557
+ }
558
+ const problems = await planProblems(companionPath, changes, type, listedFor);
559
+ const external: string[] = [];
560
+ for (const change of changes) {
561
+ // oxlint-disable-next-line no-await-in-loop -- few members per Workset
562
+ for (const dependency of await localDependsOn(companionPath, change, type)) {
563
+ if (changes.includes(dependency)) continue;
564
+ if (backlog.archived.has(dependency) || backlog.changes.has(dependency)) continue;
565
+ // oxlint-disable-next-line no-await-in-loop -- rare
566
+ if (await localArchived(companionPath, dependency, type)) continue;
567
+ external.push(dependency);
568
+ }
569
+ }
570
+ const blobs = await hashFiles(workGit(companionPath), companionPath, files);
571
+ const fileList = files
572
+ .map((file) => ({ path: file, blob: blobs.get(file) ?? "" }))
573
+ .toSorted((a, b) => a.path.localeCompare(b.path));
574
+ const target = { remote: shared.remote, branch: shared.branch };
575
+ const hash = contentHash({
576
+ workset: entry.id,
577
+ members,
578
+ included,
579
+ files: fileList,
580
+ remote: changes.map((change) => [change, remoteDigest(backlog, change)]),
581
+ target,
582
+ });
583
+ return {
584
+ preview: {
585
+ workset: entry.id,
586
+ members,
587
+ files: fileList,
588
+ excluded,
589
+ externalDependencies: [...new Set(external)],
590
+ included,
591
+ target,
592
+ problems,
593
+ hash,
594
+ },
595
+ };
596
+ }
597
+
598
+ export interface InboxChange {
599
+ links: ChangeLinks;
600
+ owner: OwnerRead;
601
+ submitted: boolean;
602
+ }
603
+
604
+ export async function inboxChanges(
605
+ dir: string,
606
+ type: ArtifactType,
607
+ ): Promise<Map<string, InboxChange>> {
608
+ const root = path.join(dir, ...type.source.split("/"));
609
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []);
610
+ const changes = new Map<string, InboxChange>();
611
+ await Promise.all(
612
+ entries
613
+ .filter((entry) => entry.isDirectory() && folderOf(type, entry.name) !== type.archiveRoot)
614
+ .map(async ({ name }) => {
615
+ const folder = path.join(root, name);
616
+ const [links, owner, delivery] = await Promise.all([
617
+ readFolderLinks(folder, name),
618
+ readOptional(path.join(folder, OWNER_FILE)),
619
+ readOptional(path.join(folder, type.deliveryFile)),
620
+ ]);
621
+ const state = submissionStateOf(delivery);
622
+ if (state === "dropped") return;
623
+ changes.set(name, { links, owner: parseOwner(owner), submitted: state === "submitted" });
624
+ }),
625
+ );
626
+ return changes;
627
+ }
628
+
629
+ export function joinedInboxGroup(
630
+ inbox: ReadonlyMap<string, InboxChange>,
631
+ names: readonly string[],
632
+ ): string[] | null {
633
+ const groups = deriveGroups(
634
+ [...inbox.values()].filter((change) => !change.submitted).map((change) => change.links),
635
+ );
636
+ const joined = new Set<string>();
637
+ for (const name of names) {
638
+ const group = groups.find((candidate) => candidate.members.includes(name));
639
+ if (!group) return null;
640
+ for (const member of group.members) joined.add(member);
641
+ }
642
+ return [...joined];
643
+ }
644
+
645
+ export function claimGroupOf(entry: InventoryWorkset, backlog: RemoteBacklog): string[] {
646
+ const active = activeMembers(entry);
647
+ const inbox = new Map(
648
+ [...backlog.changes].map(([name, change]) => [
649
+ name,
650
+ { links: change.links, owner: change.owner, submitted: change.state === "submitted" },
651
+ ]),
652
+ );
653
+ return joinedInboxGroup(inbox, active) ?? active;
654
+ }
655
+
656
+ export async function withWorkLock<T>(
657
+ companionPath: string,
658
+ run: () => Promise<T>,
659
+ ): Promise<T | { status: "refused"; reason: string }> {
660
+ const locked = await withPathLock(WORK_LOCK, companionPath, { timeoutMs: 15_000 }, run);
661
+ return locked.acquired
662
+ ? locked.value
663
+ : { status: "refused", reason: "another Work operation is running on this companion" };
664
+ }
665
+
666
+ export type TransactionFailure =
667
+ | { status: "stale"; reason: string }
668
+ | { status: "refused"; reason: string }
669
+ | { status: "failed"; failure: GitFailure };
670
+
671
+ export function transactionFailure(result: PendingCommitFailure): TransactionFailure {
672
+ switch (result.reason) {
673
+ case "no-remote":
674
+ return { status: "refused", reason: NO_UPSTREAM.message };
675
+ case "secret":
676
+ return {
677
+ status: "refused",
678
+ reason: `a file looks like it holds a secret: ${result.secretFindings
679
+ .map((finding) => `${finding.path}:${finding.line} (${finding.ruleId})`)
680
+ .join(", ")}`,
681
+ };
682
+ case "conflict":
683
+ return { status: "stale", reason: `${result.detail}; refresh and confirm again` };
684
+ default:
685
+ return { status: "failed", failure: { message: result.detail } };
686
+ }
687
+ }
688
+
689
+ export async function pendingContent(
690
+ dir: string,
691
+ folder: string,
692
+ type: ArtifactType,
693
+ git: CompanionGit,
694
+ ): Promise<string | null> {
695
+ const files = await ownFiles(git, dir, folder);
696
+ if (!files || files.length === 0) return null;
697
+ return folderDigest(
698
+ path.join(dir, ...folder.split("/")),
699
+ files.filter((file) => file !== type.deliveryFile),
700
+ );
701
+ }
702
+
703
+ export function recordPendingContent(
704
+ companionPath: string,
705
+ contents: ReadonlyMap<string, string>,
706
+ stateHome?: string,
707
+ ): void {
708
+ const recorded = readSubmittedFolders(companionPath, stateHome);
709
+ const updates: Record<string, SubmittedFolder> = {};
710
+ for (const [folder, content] of contents) {
711
+ const entry = recorded[folder];
712
+ if (entry) updates[folder] = { ...entry, content };
713
+ }
714
+ if (Object.keys(updates).length > 0)
715
+ updateSubmittedFolders(companionPath, updates, [], stateHome);
716
+ }
717
+
718
+ export type ShareOutcome = { status: "shared"; commit: string } | TransactionFailure;
719
+
720
+ export interface ShareRequest {
721
+ hash: string;
722
+ include?: readonly string[];
723
+ transactionId: string;
724
+ }
725
+
726
+ export interface ShareDeps extends WorkGitDeps {
727
+ inventoryEntry: (backlog: RemoteBacklog) => Promise<InventoryWorkset | undefined>;
728
+ now?: () => Date;
729
+ }
730
+
731
+ type ShareStop = Exclude<ShareOutcome, { status: "shared" }>;
732
+
733
+ export async function confirmShare(
734
+ companionPath: string,
735
+ request: ShareRequest,
736
+ deps: ShareDeps,
737
+ ): Promise<ShareOutcome> {
738
+ const type = deps.artifactType ?? defaultArtifactType();
739
+ return withWorkLock(companionPath, async (): Promise<ShareOutcome> => {
740
+ const refreshed = await refreshTeam(companionPath);
741
+ if ("failure" in refreshed) return { status: "failed", failure: refreshed.failure };
742
+ const backlog = await readTeamBacklog(companionPath, undefined, type);
743
+ const entry = await deps.inventoryEntry(backlog);
744
+ if (!entry) return { status: "stale", reason: "the Workset no longer exists locally" };
745
+ const previewed = await previewShare(companionPath, entry, backlog, {
746
+ include: request.include,
747
+ artifactType: type,
748
+ });
749
+ if ("refusal" in previewed) return { status: "refused", reason: previewed.refusal };
750
+ const { preview } = previewed;
751
+ if (preview.hash !== request.hash) {
752
+ return {
753
+ status: "stale",
754
+ reason: "the proposal or its shared version changed; review a new preview",
755
+ };
756
+ }
757
+ if (preview.problems.length > 0) {
758
+ return { status: "refused", reason: preview.problems.join("; ") };
759
+ }
760
+ if (preview.externalDependencies.length > 0) {
761
+ return {
762
+ status: "refused",
763
+ reason: `depends on unshared active ${preview.externalDependencies.join(", ")}; include them or share them first`,
764
+ };
765
+ }
766
+ const behind = unsynced(await compareWorkset(companionPath, entry, backlog, deps));
767
+ if (behind) return { status: "refused", reason: behind };
768
+ const operator = await configuredOperator(workGit(companionPath));
769
+ const owners = [...preview.members, ...preview.included].flatMap((change) => {
770
+ const remote = backlog.changes.get(change);
771
+ return remote ? [remote.owner] : [];
772
+ });
773
+ const claimed = claimedByOther(owners, operator);
774
+ if (claimed) return { status: "refused", reason: claimed };
775
+ return pushShare(companionPath, request, preview, backlog, type, deps, operator);
776
+ });
777
+ }
778
+
779
+ function claimedByOther(owners: readonly OwnerRead[], operator: Operator | null): string | null {
780
+ const claim = claimAs(
781
+ owners.filter((owner) => owner.status !== "absent"),
782
+ operator,
783
+ );
784
+ if (claim.kind === "conflict") return claim.diagnostic;
785
+ return claim.kind === "other" ? `claimed by ${claim.label}` : null;
786
+ }
787
+
788
+ async function pushShare(
789
+ companionPath: string,
790
+ request: ShareRequest,
791
+ preview: SharePreview,
792
+ backlog: RemoteBacklog,
793
+ type: ArtifactType,
794
+ deps: ShareDeps,
795
+ operator: Operator | null,
796
+ ): Promise<ShareOutcome> {
797
+ const gitFor = deps.git ?? pendingGit;
798
+ const changes = [...preview.members, ...preview.included];
799
+ const bytes = new Map<string, Buffer>();
800
+ for (const file of preview.files) {
801
+ // oxlint-disable-next-line no-await-in-loop -- a handful of files
802
+ bytes.set(file.path, await fs.readFile(path.join(companionPath, ...file.path.split("/"))));
803
+ }
804
+ const current = await hashFiles(
805
+ workGit(companionPath),
806
+ companionPath,
807
+ preview.files.map((file) => file.path),
808
+ );
809
+ const changed = preview.files.find((file) => current.get(file.path) !== file.blob);
810
+ if (changed) {
811
+ return {
812
+ status: "stale",
813
+ reason: `${changed.path} changed while sharing; review a new preview`,
814
+ };
815
+ }
816
+ const confirmed = new Map(changes.map((change) => [change, remoteDigest(backlog, change)]));
817
+ const folderDigests = new Map<string, string>();
818
+ for (const change of changes) {
819
+ const folder = folderOf(type, change);
820
+ // oxlint-disable-next-line no-await-in-loop -- few members per Workset
821
+ const own = await ownFiles(workGit(companionPath), companionPath, folder);
822
+ if (!own) continue;
823
+ // oxlint-disable-next-line no-await-in-loop -- same folder
824
+ const digest = await folderDigest(sourceDir(companionPath, type, change), own);
825
+ folderDigests.set(folder, digest);
826
+ }
827
+ const recorded = new Map<string, SubmittedFolder>();
828
+ const extra = new Map<string, string>();
829
+ const filesIn = (folder: string) =>
830
+ preview.files.filter((file) => file.path.startsWith(`${folder}/`));
831
+ const pushedOf = (folder: string): [string, Buffer][] =>
832
+ filesIn(folder).map((file) => [file.path.slice(folder.length + 1), bytes.get(file.path)!]);
833
+ const submittedAt = (deps.now?.() ?? new Date()).toISOString();
834
+ const result = await commitToPending<ShareStop>(
835
+ {
836
+ companionPath,
837
+ subject: `chore(${type.name}): share ${preview.workset}`,
838
+ transaction: request.transactionId,
839
+ edit: async (dir, remote) => {
840
+ recorded.clear();
841
+ extra.clear();
842
+ const work = gitFor(dir);
843
+ const folders: string[] = [];
844
+ const blobsOf = new Map<string, [string, string][]>();
845
+ for (const change of changes) {
846
+ const folder = folderOf(type, change);
847
+ const target = sourceDir(dir, type, change);
848
+ // oxlint-disable-next-line no-await-in-loop -- one folder at a time
849
+ const delivery = await readOptional(path.join(target, type.deliveryFile));
850
+ const unlisted = submissionStateOf(delivery) === "dropped";
851
+ // oxlint-disable-next-line no-await-in-loop -- same folder
852
+ const theirs = unlisted ? sharedDigest([]) : await sharedDigestAt(work, "HEAD", folder);
853
+ if (theirs !== confirmed.get(change)) {
854
+ return {
855
+ stop: {
856
+ status: "stale",
857
+ reason: `${change} changed on ${pendingPlace(remote)} since the preview; review a new preview`,
858
+ },
859
+ };
860
+ }
861
+ // oxlint-disable-next-line no-await-in-loop -- same folder
862
+ await emptyFolderKeepingClaim(target);
863
+ // oxlint-disable-next-line no-await-in-loop -- same folder
864
+ if (unlisted) await fs.rm(path.join(target, OWNER_FILE), { force: true });
865
+ const blobs: [string, string][] = [];
866
+ for (const file of filesIn(folder)) {
867
+ const relative = file.path.slice(folder.length + 1);
868
+ const content = bytes.get(file.path)!;
869
+ const written = path.join(target, ...relative.split("/"));
870
+ // oxlint-disable-next-line no-await-in-loop -- one file at a time
871
+ await fs.mkdir(path.dirname(written), { recursive: true });
872
+ // oxlint-disable-next-line no-await-in-loop -- same file
873
+ await fs.writeFile(written, content);
874
+ blobs.push([relative, file.blob]);
875
+ }
876
+ blobsOf.set(change, blobs);
877
+ folders.push(folder);
878
+ }
879
+ const inbox = await inboxChanges(dir, type);
880
+ const joined = joinedInboxGroup(inbox, changes) ?? changes;
881
+ const owners = joined.map(
882
+ (name) => inbox.get(name)?.owner ?? { status: "absent" as const },
883
+ );
884
+ const claimed = claimedByOther(owners, operator);
885
+ if (claimed) return { stop: { status: "refused", reason: claimed } };
886
+ const extend = operator && owners.some((owner) => owner.status === "owned");
887
+ for (const [index, name] of joined.entries()) {
888
+ const folder = folderOf(type, name);
889
+ if (extend && owners[index]!.status === "absent") {
890
+ // oxlint-disable-next-line no-await-in-loop -- one small file per member
891
+ await fs.writeFile(
892
+ path.join(sourceDir(dir, type, name), OWNER_FILE),
893
+ serializeOwner(operator),
894
+ "utf8",
895
+ );
896
+ if (!changes.includes(name)) folders.push(`${folder}/${OWNER_FILE}`);
897
+ }
898
+ // oxlint-disable-next-line no-await-in-loop -- same member
899
+ const content = await pendingContent(dir, folder, type, work);
900
+ const memberBlobs = blobsOf.get(name);
901
+ if (!memberBlobs) {
902
+ if (content) extra.set(folder, content);
903
+ continue;
904
+ }
905
+ recorded.set(folder, {
906
+ digest: folderDigests.get(folder) ?? contentDigest(pushedOf(folder)),
907
+ ...(content ? { content } : {}),
908
+ shared: sharedDigest(memberBlobs),
909
+ submittedAt,
910
+ });
911
+ }
912
+ return folders;
913
+ },
914
+ },
915
+ pendingCommitDeps(gitFor, type, deps),
916
+ );
917
+ if (result.status === "failed") return transactionFailure(result);
918
+ if (result.status === "stopped") {
919
+ return result.value ?? { status: "refused", reason: "the share was stopped" };
920
+ }
921
+ updateSubmittedFolders(companionPath, Object.fromEntries(recorded), [], deps.stateHome);
922
+ recordPendingContent(companionPath, extra, deps.stateHome);
923
+ if (result.status === "unchanged") {
924
+ const tip = await refCommit(workGit(companionPath), pendingRef(result.remote));
925
+ return { status: "shared", commit: tip ?? "" };
926
+ }
927
+ return { status: "shared", commit: result.commit };
928
+ }
929
+
930
+ export function remoteOnlyEntries(
931
+ backlog: RemoteBacklog,
932
+ localChanges: ReadonlySet<string>,
933
+ ): InventoryWorkset[] {
934
+ const remote = [...backlog.changes.values()]
935
+ .map((change) => change.links)
936
+ .filter((links) => !localChanges.has(links.name));
937
+ return refuseSharedIds(
938
+ deriveGroups(remote).map((group) => {
939
+ const diagnostics = [...group.diagnostics, ...worksetIdDiagnostics(group.id)];
940
+ return {
941
+ id: group.id,
942
+ implicit: true,
943
+ record: implicitRecord(group.id, group.members, []),
944
+ members: group.members.map((name) => ({ name, kind: "active" as const })),
945
+ branches: [],
946
+ diagnostics,
947
+ actionable: diagnostics.length === 0,
948
+ };
949
+ }),
950
+ );
951
+ }