@uniqbit/mate-core 1.0.0-canary.3 → 1.0.0-canary.6

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 (483) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-capability-plugins/companion-mentions/hooks/register.ts +1 -1
  3. package/claude-plugin/hooks/hooks.json +61 -1
  4. package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
  5. package/claude-plugin/hooks/session-attention.mjs +10 -0
  6. package/claude-plugin/hooks/session-end.mjs +9 -0
  7. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  8. package/claude-plugin/hooks/workflow-turn.mjs +68 -0
  9. package/opencode-plugin/src/companion.ts +6 -0
  10. package/opencode-plugin/src/server.ts +46 -4
  11. package/package.json +5 -2
  12. package/src/cli/commands/artifact/apply-context.ts +1 -0
  13. package/src/cli/commands/artifact/artifact.ts +16 -0
  14. package/src/cli/commands/artifact/delivery/archive.ts +37 -112
  15. package/src/cli/commands/artifact/delivery/branch-flags.ts +19 -1
  16. package/src/cli/commands/artifact/delivery/environment.ts +32 -72
  17. package/src/cli/commands/artifact/delivery/link.ts +69 -33
  18. package/src/cli/commands/artifact/delivery/output.ts +34 -5
  19. package/src/cli/commands/artifact/delivery/resolve.ts +101 -0
  20. package/src/cli/commands/artifact/delivery/submit.ts +164 -0
  21. package/src/cli/commands/artifact/delivery/take.ts +45 -0
  22. package/src/cli/commands/artifact/extract-repo-name.ts +1 -1
  23. package/src/cli/commands/artifact/finish/command.ts +455 -43
  24. package/src/cli/commands/artifact/finish/engine.ts +79 -61
  25. package/src/cli/commands/artifact/finish/finisher.ts +5 -12
  26. package/src/cli/commands/artifact/finish/git.ts +9 -10
  27. package/src/cli/commands/artifact/finish/openspec.ts +22 -177
  28. package/src/cli/commands/artifact/finish/secret-scan.ts +5 -43
  29. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +57 -7
  30. package/src/cli/commands/artifact/pending/command.ts +119 -6
  31. package/src/cli/commands/artifact/pending/discovery.ts +7 -11
  32. package/src/cli/commands/artifact/project/command.ts +60 -0
  33. package/src/cli/commands/companion/companion.ts +1 -1
  34. package/src/cli/commands/companion/link.ts +36 -4
  35. package/src/cli/commands/companion/list.ts +70 -14
  36. package/src/cli/commands/companion/open.ts +40 -12
  37. package/src/cli/commands/companion/sync.ts +18 -0
  38. package/src/cli/commands/companion/update.ts +4 -19
  39. package/src/cli/commands/doctor.ts +122 -0
  40. package/src/cli/commands/install.ts +48 -36
  41. package/src/cli/commands/launch/claude.ts +2 -0
  42. package/src/cli/commands/launch/shared.ts +33 -6
  43. package/src/cli/commands/plugin/install.ts +27 -11
  44. package/src/cli/commands/report/index.ts +180 -184
  45. package/src/cli/commands/report/markdown.ts +67 -72
  46. package/src/cli/commands/session/prepare.ts +32 -4
  47. package/src/cli/commands/session/registry.ts +90 -0
  48. package/src/cli/commands/shared/companion-selection.ts +3 -1
  49. package/src/cli/commands/studio/access.ts +6 -14
  50. package/src/cli/commands/studio/areas.ts +112 -33
  51. package/src/cli/commands/studio/companion-add.ts +72 -0
  52. package/src/cli/commands/studio/companion-removal.ts +86 -0
  53. package/src/cli/commands/studio/graph-model.ts +61 -0
  54. package/src/cli/commands/studio/graph.ts +336 -0
  55. package/src/cli/commands/studio/index.ts +4 -4
  56. package/src/{lib/factory/outcomes/sessions.ts → cli/commands/studio/live-sessions.ts} +26 -2
  57. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  58. package/src/cli/commands/studio/payload.ts +223 -30
  59. package/src/cli/commands/studio/reports.ts +19 -18
  60. package/src/cli/commands/studio/routes.ts +5 -18
  61. package/src/cli/commands/studio/selection.ts +12 -5
  62. package/src/cli/commands/studio/server.ts +321 -198
  63. package/src/cli/commands/studio/service-host.ts +266 -0
  64. package/src/cli/commands/studio/services.ts +54 -16
  65. package/src/cli/commands/studio/skill-files.ts +133 -0
  66. package/src/cli/commands/studio/studio-app.ts +1 -0
  67. package/src/cli/commands/studio/terminal.ts +45 -3
  68. package/src/cli/commands/studio/vault.ts +259 -84
  69. package/src/cli/commands/studio/views/model.ts +1 -14
  70. package/src/cli/commands/studio/views/vault/markdown-tree.ts +343 -10
  71. package/src/cli/commands/unwrap.ts +11 -0
  72. package/src/cli/commands/update.ts +28 -8
  73. package/src/cli/commands/vscode/release-vsix.json +4 -0
  74. package/src/cli/commands/vscode/setup.ts +213 -0
  75. package/src/cli/commands/vscode/vsix.ts +114 -0
  76. package/src/cli/commands/workflow/workflow.ts +516 -0
  77. package/src/cli/commands/working/cleanup.ts +73 -17
  78. package/src/cli/commands/working/worktree.ts +227 -36
  79. package/src/cli/commands/wrap.ts +33 -7
  80. package/src/cli/main.ts +48 -12
  81. package/src/cli/repo-list-table.tsx +73 -37
  82. package/src/cli/usage.ts +25 -9
  83. package/src/factory-host.ts +69 -0
  84. package/src/hooks/companion-instructions.ts +35 -16
  85. package/src/hooks/hook-io.ts +18 -1
  86. package/src/hooks/rtk-worktree-git.ts +48 -0
  87. package/src/hooks/session-banner.ts +30 -3
  88. package/src/hooks/session-end.ts +10 -0
  89. package/src/hooks/session-guidance.ts +10 -6
  90. package/src/hooks/session-prepare.ts +47 -31
  91. package/src/hooks/session-register.ts +199 -0
  92. package/src/hooks/tokensave-route.ts +7 -3
  93. package/src/hooks/validate-artifact-path.ts +53 -14
  94. package/src/hooks/workflow-turn.ts +219 -0
  95. package/src/lib/apply-context/fingerprint.ts +2 -1
  96. package/src/lib/apply-context/protocol.ts +2 -2
  97. package/src/lib/artifact-trailer.ts +27 -0
  98. package/src/lib/change-layout.ts +83 -38
  99. package/src/lib/delivery/branch-template.ts +114 -0
  100. package/src/lib/delivery/branches.ts +34 -14
  101. package/src/lib/delivery/checkout.ts +103 -0
  102. package/src/lib/delivery/environment.ts +131 -7
  103. package/src/lib/delivery/merge-git.ts +282 -26
  104. package/src/lib/delivery/overlap.ts +68 -16
  105. package/src/lib/delivery/record-delivery.ts +253 -57
  106. package/src/lib/delivery/record.ts +229 -53
  107. package/src/lib/delivery/refresh.ts +222 -141
  108. package/src/lib/delivery/remote.ts +66 -0
  109. package/src/lib/delivery/repository-access.ts +19 -60
  110. package/src/lib/delivery/resolve-branch.ts +318 -50
  111. package/src/lib/delivery/stages.ts +83 -50
  112. package/src/lib/delivery/staging/apply-chain.ts +164 -0
  113. package/src/lib/delivery/staging/artifact-type.ts +101 -0
  114. package/src/lib/delivery/staging/declared-type.ts +277 -0
  115. package/src/lib/delivery/staging/naming.ts +64 -0
  116. package/src/lib/delivery/staging/openspec-type.ts +135 -0
  117. package/src/lib/delivery/staging/pending-edit.ts +291 -0
  118. package/src/lib/delivery/staging/pending.ts +780 -0
  119. package/src/lib/delivery/staging/project.ts +373 -0
  120. package/src/lib/delivery/staging/publish.ts +1024 -0
  121. package/src/lib/delivery/staging/refs.ts +258 -0
  122. package/src/lib/delivery/staging/registry.ts +73 -0
  123. package/src/lib/delivery/staging/replay.ts +308 -0
  124. package/src/lib/delivery/staging/requirement-blocks.ts +10 -0
  125. package/src/lib/delivery/staging/resolve.ts +264 -0
  126. package/src/lib/delivery/staging/settle-linked.ts +290 -0
  127. package/src/lib/delivery/staging/submit.ts +929 -0
  128. package/src/lib/delivery/staging/worktree.ts +130 -0
  129. package/src/lib/delivery/submit-change.ts +443 -0
  130. package/src/lib/git-key.ts +15 -0
  131. package/src/lib/install.ts +2 -0
  132. package/src/lib/opencode-server.ts +238 -0
  133. package/src/lib/openspec-canonical-frontmatter.ts +159 -0
  134. package/src/lib/orchestrator/adapters/base.ts +31 -20
  135. package/src/lib/orchestrator/adapters/claude.ts +162 -4
  136. package/src/lib/orchestrator/adapters/opencode.ts +55 -2
  137. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  138. package/src/lib/orchestrator/companion-git-sync.ts +152 -16
  139. package/src/lib/orchestrator/companion-hub.ts +6 -1
  140. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  141. package/src/lib/orchestrator/editor.ts +2 -2
  142. package/src/lib/orchestrator/engine-floor.ts +48 -0
  143. package/src/lib/orchestrator/framework-context.ts +41 -15
  144. package/src/lib/orchestrator/global-config-store.ts +11 -0
  145. package/src/lib/orchestrator/launcher.ts +49 -3
  146. package/src/lib/orchestrator/projection-claude-commands.ts +2 -2
  147. package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
  148. package/src/lib/orchestrator/projection-claude-links.ts +83 -11
  149. package/src/lib/orchestrator/projection-claude-skills.ts +30 -4
  150. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  151. package/src/lib/orchestrator/projection-entries.ts +22 -18
  152. package/src/lib/orchestrator/projection-opencode-copies.ts +65 -21
  153. package/src/lib/orchestrator/projection-runtime-documents.ts +66 -43
  154. package/src/lib/orchestrator/projection-types.ts +28 -1
  155. package/src/lib/orchestrator/refresh-working-claude-links.ts +4 -1
  156. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  157. package/src/lib/orchestrator/repository-link.ts +216 -57
  158. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  159. package/src/lib/orchestrator/session-context-link.ts +11 -5
  160. package/src/lib/orchestrator/session-prepare.ts +53 -8
  161. package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
  162. package/src/lib/orchestrator/types.ts +9 -0
  163. package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
  164. package/src/lib/orchestrator/working-repo-projection.ts +24 -4
  165. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  166. package/src/lib/orchestrator/wrap-pass.ts +1 -0
  167. package/src/lib/prebuilt-workspace-prepare.ts +2 -1
  168. package/src/lib/prebuilt-workspace.ts +1 -0
  169. package/src/lib/public-npm.ts +105 -43
  170. package/src/lib/session-attribution.ts +52 -0
  171. package/src/lib/session-state.ts +356 -0
  172. package/src/lib/session-stop.ts +64 -0
  173. package/src/lib/update-checker.ts +7 -1
  174. package/src/lib/usage/aggregate.ts +202 -0
  175. package/src/lib/usage/cache.ts +87 -0
  176. package/src/lib/usage/claude-pricing.ts +71 -0
  177. package/src/lib/usage/claude.ts +189 -0
  178. package/src/lib/usage/collect.ts +56 -0
  179. package/src/lib/usage/opencode.ts +188 -0
  180. package/src/lib/usage/records.ts +80 -0
  181. package/src/lib/usage/rtk-database.ts +72 -0
  182. package/src/lib/usage/savings.ts +209 -0
  183. package/src/lib/usage/scope.ts +182 -0
  184. package/src/lib/usage/source.ts +102 -0
  185. package/src/lib/usage/types.ts +143 -0
  186. package/src/lib/usage/window.ts +37 -0
  187. package/src/lib/workflow/declaration.ts +6 -0
  188. package/src/lib/workflow/handoff.ts +90 -0
  189. package/src/lib/workflow/hook-trust.ts +108 -0
  190. package/src/lib/workflow/position.ts +524 -0
  191. package/src/lib/workflow/report.ts +79 -0
  192. package/src/lib/workflow/work.ts +106 -0
  193. package/src/lib/workset/factory-local.ts +157 -0
  194. package/src/lib/workset/record.ts +45 -11
  195. package/src/lib/workset/repositories.ts +118 -25
  196. package/src/lib/workset/stage.ts +4 -2
  197. package/src/lib/workset/stages.ts +64 -4
  198. package/src/lib/workset/worktree-include.ts +161 -0
  199. package/src/lib/workset/worktree-index.ts +6 -2
  200. package/src/lib/workset/worktree.ts +665 -89
  201. package/src/opencode/background-server.ts +145 -0
  202. package/src/opencode/companion-hooks.ts +55 -14
  203. package/src/opencode/companion-policy.ts +20 -7
  204. package/src/opencode/enter-worktree.ts +254 -6
  205. package/src/opencode/projected-guidance.ts +7 -3
  206. package/src/opencode/session-register.ts +176 -0
  207. package/src/opencode/turn-hook.ts +241 -0
  208. package/src/playbooks/companion-guidance.ts +6 -3
  209. package/src/plugin-api.ts +42 -0
  210. package/src/runtime/artifact-trailers.ts +63 -0
  211. package/src/runtime/claude-bg-isolation.ts +138 -0
  212. package/src/runtime/claude-delivery-plan.ts +14 -3
  213. package/src/runtime/claude-hook-group.ts +2 -0
  214. package/src/runtime/companion-git-state.ts +155 -10
  215. package/src/runtime/companion-git.ts +96 -13
  216. package/src/runtime/companion-guidance.ts +107 -8
  217. package/src/runtime/companion-instructions.ts +1 -1
  218. package/src/runtime/companion-sync.ts +109 -21
  219. package/src/runtime/current-branch.ts +24 -0
  220. package/src/runtime/entered-worktree.ts +24 -0
  221. package/src/runtime/env-names.ts +2 -2
  222. package/src/runtime/env.ts +16 -9
  223. package/src/runtime/forge-remote.ts +48 -0
  224. package/src/runtime/git-layout.ts +185 -24
  225. package/src/runtime/git-tracked.ts +60 -0
  226. package/src/runtime/json-fields.ts +8 -0
  227. package/src/runtime/launch-env-guard.ts +65 -0
  228. package/src/runtime/opencode-server-record.ts +136 -0
  229. package/src/runtime/pending-records.ts +533 -0
  230. package/src/runtime/projected-guidance.ts +6 -2
  231. package/src/runtime/projection.ts +40 -6
  232. package/src/runtime/publication-secret-scan.ts +45 -0
  233. package/src/runtime/repo-destination.ts +72 -0
  234. package/src/runtime/repo-local.ts +29 -2
  235. package/src/runtime/rtk-git-guard.ts +66 -0
  236. package/src/runtime/runtime-document-manifest.ts +229 -19
  237. package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
  238. package/src/runtime/secret-guard.ts +9 -2
  239. package/src/runtime/secret-patterns.ts +3 -2
  240. package/src/runtime/secret-policy-weakening.ts +122 -0
  241. package/src/runtime/serving-claude-wrap.ts +41 -0
  242. package/src/runtime/session-context.ts +4 -3
  243. package/src/runtime/session-registry.ts +434 -0
  244. package/src/runtime/skill-prefix.ts +75 -0
  245. package/src/runtime/submitted-arrivals.ts +547 -0
  246. package/src/runtime/tokensave-route.ts +10 -5
  247. package/src/runtime/turn-state.d.mts +14 -0
  248. package/src/runtime/turn-state.mjs +93 -0
  249. package/src/runtime/umbrella-children.ts +52 -0
  250. package/src/runtime/umbrella-folder.ts +84 -0
  251. package/src/runtime/workflow/change-folders.ts +66 -0
  252. package/src/runtime/workflow/declaration.ts +720 -0
  253. package/src/runtime/workflow/globs.ts +85 -0
  254. package/src/runtime/workflow/next-handoff-process.ts +98 -0
  255. package/src/runtime/workflow/turn.ts +309 -0
  256. package/src/runtime/workflow/workflow.ts +262 -0
  257. package/src/runtime/wrap-state.ts +36 -13
  258. package/src/studio.ts +73 -19
  259. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/schema.yaml +3 -3
  260. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/design.md +1 -1
  261. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/proposal.md +1 -1
  262. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/tasks.md +1 -1
  263. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +3 -3
  264. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +147 -46
  265. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +1 -1
  266. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +7 -75
  267. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +13 -7
  268. package/src/templates/mate-skills/agents/mate-domain-modeling/SKILL.md +10 -0
  269. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +46 -14
  270. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +51 -38
  271. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +14 -10
  272. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +1 -1
  273. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +113 -87
  274. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +111 -100
  275. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +11 -5
  276. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +16 -6
  277. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +114 -0
  278. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +147 -46
  279. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +1 -1
  280. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +7 -75
  281. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +13 -7
  282. package/src/templates/mate-skills/claude/mate-domain-modeling/SKILL.md +10 -0
  283. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +46 -14
  284. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +51 -38
  285. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +14 -10
  286. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +1 -1
  287. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +113 -87
  288. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +111 -100
  289. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +11 -5
  290. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +16 -6
  291. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +114 -0
  292. package/src/templates/mate-skills/openspec-references.ts +3 -2
  293. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +1301 -154
  294. package/src/tools/setup/capabilities/openspec.ts +54 -15
  295. package/src/tools/setup/capabilities/rtk.ts +98 -5
  296. package/src/tools/setup/capabilities/tokensave.ts +3 -2
  297. package/src/tools/setup/dynamic-plugins/api.ts +38 -0
  298. package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
  299. package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
  300. package/src/tools/setup/dynamic-plugins/host.ts +2 -32
  301. package/src/tools/setup/dynamic-plugins/hydrate.ts +8 -7
  302. package/src/tools/setup/dynamic-plugins/install.ts +24 -22
  303. package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
  304. package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
  305. package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
  306. package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
  307. package/src/tools/setup/engine.ts +20 -1
  308. package/src/tools/setup/mate.ts +5 -3
  309. package/src/tools/setup/package-managers/bun.ts +8 -8
  310. package/src/tools/setup/plugin.ts +9 -1
  311. package/src/tools/setup/plugins/gitignore.ts +15 -9
  312. package/src/tools/setup/plugins/guidance.ts +4 -2
  313. package/src/tools/setup/providers/claude-plugin-hooks.ts +56 -0
  314. package/src/tools/setup/providers/claude.ts +64 -7
  315. package/src/tools/setup/service-registry.ts +69 -0
  316. package/src/tools/setup/service.ts +233 -0
  317. package/src/tools/setup/utils.ts +28 -5
  318. package/src/tools/setup/working-repo-cleanup.ts +2 -2
  319. package/src/tools/setup/working-repo-local-state.ts +2 -0
  320. package/src/tools/setup.ts +25 -14
  321. package/studio-dist/client/assets/app-BFVyWHGo.css +2 -0
  322. package/studio-dist/client/assets/button-D6LrRkOG.js +1 -0
  323. package/studio-dist/client/assets/combobox-Dk2MMZWE.js +1 -0
  324. package/studio-dist/client/assets/companion-view-BVaZNtiI.js +1 -0
  325. package/studio-dist/client/assets/fields-D_FYhxQr.js +1 -0
  326. package/studio-dist/client/assets/getting-started-ByWRg7hC.js +1 -0
  327. package/studio-dist/client/assets/getting-started-DZSjYC-b.js +1 -0
  328. package/studio-dist/client/assets/getting-started._topic-C6OyQ4G6.js +1 -0
  329. package/studio-dist/client/assets/getting-started.index-BkmPHdEm.js +1 -0
  330. package/studio-dist/client/assets/graph-7jm2XzyL.js +2 -0
  331. package/studio-dist/client/assets/graph-canvas-DDuzsNSx.js +3242 -0
  332. package/studio-dist/client/assets/guides-D9VTjWXP.js +1 -0
  333. package/studio-dist/client/assets/index-BBmFpG4y.js +40 -0
  334. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  335. package/studio-dist/client/assets/markdown-view-RL5YvfZg.js +1 -0
  336. package/studio-dist/client/assets/panel-B8F8sOKQ.js +1 -0
  337. package/studio-dist/client/assets/plugins._service._view-CynxTbMx.js +1 -0
  338. package/studio-dist/client/assets/queries-axYk2u9L.js +1 -0
  339. package/studio-dist/client/assets/react-r45OnJCw.js +27 -0
  340. package/studio-dist/client/assets/reports-BCAyXh6p.js +1 -0
  341. package/studio-dist/client/assets/routes-BFPqq89E.js +1 -0
  342. package/studio-dist/client/assets/skills-DTks_uBx.js +1 -0
  343. package/studio-dist/client/assets/specs-DU1kqcp5.js +1 -0
  344. package/studio-dist/client/assets/specs-view-omrd_5P3.js +1 -0
  345. package/studio-dist/client/assets/steps-DhIFuAZy.js +1 -0
  346. package/studio-dist/client/assets/store-DJ5cncKA.js +1 -0
  347. package/studio-dist/client/assets/studio-BR9j15J0.js +100 -0
  348. package/studio-dist/client/assets/studio-queries-CFP_yTpr.js +2 -0
  349. package/studio-dist/client/assets/usage-CHmwtkoM.js +55 -0
  350. package/studio-dist/client/assets/useBaseQuery-BlC-AZ35.js +1 -0
  351. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  352. package/studio-dist/client/assets/vault-DRg8MScm.js +1 -0
  353. package/studio-dist/client/assets/warnings-UHFy6HAp.js +1 -0
  354. package/studio-dist/client/assets/workflow-Bv9vSfVV.js +1 -0
  355. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-DAbZ6fzY.js +106 -0
  356. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +86 -31
  357. package/studio-dist/server/assets/button-BfoNadNR.js +8193 -0
  358. package/studio-dist/server/assets/combobox-oxUI6r4V.js +2089 -0
  359. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DHUjPpA0.js} +13 -7
  360. package/studio-dist/server/assets/companions-kBrJZAd6.js +31 -0
  361. package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
  362. package/studio-dist/server/assets/fields-BD_c65T1.js +1190 -0
  363. package/studio-dist/server/assets/getting-started-7P0oyWaM.js +67 -0
  364. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  365. package/studio-dist/server/assets/getting-started._topic-B1mV0kGz.js +13 -0
  366. package/studio-dist/server/assets/getting-started.index-CeGtvUsm.js +13 -0
  367. package/studio-dist/server/assets/graph-BWtmJOH2.js +16 -0
  368. package/studio-dist/server/assets/graph-DSDVEELZ.js +801 -0
  369. package/studio-dist/server/assets/graph-canvas-CID9Nksc.js +21066 -0
  370. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  371. package/studio-dist/server/assets/guides-BLJenHwQ.js +5 -0
  372. package/studio-dist/server/assets/guides-Bm3RbUB-.js +13 -0
  373. package/studio-dist/server/assets/guides.server-rHHqRuzV.js +66 -0
  374. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  375. package/studio-dist/server/assets/markdown-view-D3v9x-cM.js +105 -0
  376. package/studio-dist/server/assets/panel-yqOl5GMU.js +169 -0
  377. package/studio-dist/server/assets/plugins._service._view-DwqJX7s9.js +92 -0
  378. package/studio-dist/server/assets/queries-DYmGrhNO.js +32 -0
  379. package/studio-dist/server/assets/react-BO0uMhpm.js +89 -0
  380. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  381. package/studio-dist/server/assets/reports-7yaPz7aP.js +147 -0
  382. package/studio-dist/server/assets/reports-C4Y_Jd-x.js +18 -0
  383. package/studio-dist/server/assets/router-Dnoq5auE.js +12844 -0
  384. package/studio-dist/server/assets/routes-Cok4p3mK.js +768 -0
  385. package/studio-dist/server/assets/{search-JAKurDNh.js → search-DUK7Jl6f.js} +21 -2
  386. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DNVXedgE.js} +16 -6
  387. package/studio-dist/server/assets/skills-D8qdXSku.js +267 -0
  388. package/studio-dist/server/assets/skills-pKmuAs0F.js +28 -0
  389. package/studio-dist/server/assets/specs-DeHYUNFp.js +51 -0
  390. package/studio-dist/server/assets/specs-view-BGn-5Ik_.js +425 -0
  391. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  392. package/studio-dist/server/assets/steps-CV7Yk7L7.js +224 -0
  393. package/studio-dist/server/assets/store-CWDGIp6x.js +280 -0
  394. package/studio-dist/server/assets/studio-CB94np48.js +10437 -0
  395. package/studio-dist/server/assets/studio-queries-BqZGBE70.js +1335 -0
  396. package/studio-dist/server/assets/usage-M6Gi6Km7.js +25584 -0
  397. package/studio-dist/server/assets/usage-j5jR9gX9.js +24 -0
  398. package/studio-dist/server/assets/{studio-queries-CLnP9kGu.js → useBaseQuery-Tv_QJt9r.js} +4 -1318
  399. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → useSelector-DUmCUXAs.js} +4 -498
  400. package/studio-dist/server/assets/vault-PqVmssmW.js +1035 -0
  401. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-lBlvSyD4.js} +19 -4
  402. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-CsFp1i1G.js} +10 -9
  403. package/studio-dist/server/assets/warnings-BDs34j_m.js +24 -0
  404. package/studio-dist/server/assets/workflow-T0eEldsa.js +687 -0
  405. package/studio-dist/server/server.js +429 -9
  406. package/src/cli/commands/factory/factory.ts +0 -301
  407. package/src/cli/commands/report/collector.ts +0 -288
  408. package/src/cli/commands/studio/factory-credential.ts +0 -49
  409. package/src/cli/commands/studio/workset-session.ts +0 -131
  410. package/src/lib/delivery/archive-change.ts +0 -166
  411. package/src/lib/delivery/forge.ts +0 -279
  412. package/src/lib/delivery/token.ts +0 -24
  413. package/src/lib/factory/attach-client.ts +0 -113
  414. package/src/lib/factory/attach.ts +0 -178
  415. package/src/lib/factory/broker.ts +0 -190
  416. package/src/lib/factory/bun-commands.ts +0 -39
  417. package/src/lib/factory/client.ts +0 -92
  418. package/src/lib/factory/command.ts +0 -61
  419. package/src/lib/factory/credential-store.ts +0 -153
  420. package/src/lib/factory/frames.ts +0 -77
  421. package/src/lib/factory/ids.ts +0 -58
  422. package/src/lib/factory/outcomes/actions.ts +0 -114
  423. package/src/lib/factory/outcomes/index.ts +0 -381
  424. package/src/lib/factory/outcomes/lifecycle.ts +0 -205
  425. package/src/lib/factory/outcomes/runs.ts +0 -81
  426. package/src/lib/factory/prepare.ts +0 -49
  427. package/src/lib/factory/pty.ts +0 -103
  428. package/src/lib/factory/runner/companion-context.ts +0 -178
  429. package/src/lib/factory/runner/control.ts +0 -92
  430. package/src/lib/factory/runner/harness-agent.ts +0 -250
  431. package/src/lib/factory/runner/live.ts +0 -159
  432. package/src/lib/factory/runner/questions.ts +0 -22
  433. package/src/lib/factory/runner/rank.ts +0 -26
  434. package/src/lib/factory/runner/run-policy.ts +0 -12
  435. package/src/lib/factory/runner/run.ts +0 -199
  436. package/src/lib/factory/runner/scheduler.ts +0 -416
  437. package/src/lib/factory/runner/state.ts +0 -233
  438. package/src/lib/factory/runner/workflow.ts +0 -542
  439. package/src/lib/factory/runtime.ts +0 -972
  440. package/src/lib/factory/sandbox.ts +0 -292
  441. package/src/lib/factory/worktree-branch.ts +0 -17
  442. package/src/templates/capabilities/openspec-cap/mate-v1/templates/explore-brief.md +0 -25
  443. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  444. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  445. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  446. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  447. package/studio-dist/client/assets/prepaint-CD5OpmTM.js +0 -24
  448. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  449. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  450. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  451. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  452. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  453. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  454. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  455. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  456. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  457. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  458. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  459. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  460. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  461. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  462. package/studio-dist/server/assets/actions-Bvgj9eb8.js +0 -54
  463. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
  464. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  465. package/studio-dist/server/assets/factory-D6xnjedJ.js +0 -2385
  466. package/studio-dist/server/assets/factory-DT3UzHlh.js +0 -68
  467. package/studio-dist/server/assets/prepaint-BMke0fo1.js +0 -41
  468. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  469. package/studio-dist/server/assets/react-COs0LHn-.js +0 -51
  470. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  471. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  472. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
  473. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  474. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  475. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  476. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  477. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  478. package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
  479. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  480. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  481. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
  482. /package/src/lib/{factory/keyed-serial.ts → keyed-serial.ts} +0 -0
  483. /package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/spec.md +0 -0
@@ -0,0 +1,1024 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { ARTIFACT_TRAILER, INBOX_TRAILER, TRANSACTION_TRAILER } from "../../artifact-trailer";
6
+ import type { RunOpenSpec } from "../../openspec-cli";
7
+ import {
8
+ companionGit,
9
+ describeGitFailure,
10
+ isTransientRemoteFailure,
11
+ LITERAL_PATHSPECS,
12
+ nulPaths,
13
+ type CompanionGit,
14
+ type GitResult,
15
+ type NetworkGitResult,
16
+ } from "../../../runtime/companion-git";
17
+ import { adoptUpstream } from "../../../runtime/companion-sync";
18
+ import { errorMessage } from "../../../runtime/error-message";
19
+ import { inboxText } from "../../../runtime/pending-records";
20
+ import {
21
+ scanPublication,
22
+ type PublicationSecretScan,
23
+ } from "../../../runtime/publication-secret-scan";
24
+ import type { SecretFinding } from "../../../runtime/secret-scan";
25
+ import {
26
+ isCommitId,
27
+ readDeliveryRecord,
28
+ readDeliveryState,
29
+ writeDeliveryRecord,
30
+ type DeliveryBlock,
31
+ type DeliveryRecord,
32
+ } from "../record";
33
+ import {
34
+ applyChain,
35
+ describeFailure,
36
+ failurePaths,
37
+ failureRemedy,
38
+ isChainFailure,
39
+ type ChainFailure,
40
+ } from "./apply-chain";
41
+ import { artifactTrailerValue, sourceDir, type ArtifactType } from "./artifact-type";
42
+ import { isDeliveryGroup } from "./naming";
43
+ import {
44
+ deliveryHold,
45
+ deltaBase,
46
+ groupsOf,
47
+ isOthersAnswer,
48
+ mergeClaims,
49
+ publicationOrder,
50
+ publishedAs,
51
+ submittedAt,
52
+ unpublishedDependencies,
53
+ type MergeClaim,
54
+ type SubmittedChange,
55
+ } from "./pending";
56
+ import { commitToPending } from "./pending-edit";
57
+ import {
58
+ anchorsAt,
59
+ defaultRef,
60
+ fetchPendingBranches,
61
+ fetchStaging,
62
+ INBOX_BRANCH,
63
+ isPushNotPermitted,
64
+ isRejectedPush,
65
+ pendingPlace,
66
+ pendingRef,
67
+ pushPending,
68
+ recordsAt,
69
+ stagingRemote,
70
+ transactionsAt,
71
+ type StagingRemote,
72
+ } from "./refs";
73
+ import { defaultArtifactType } from "./registry";
74
+ import { capabilitySpecPath } from "./replay";
75
+ import { withTemporaryWorktree, WITHOUT_HOOKS } from "./worktree";
76
+
77
+ /** Bound on one publication, every fetch, apply and push included. */
78
+ const PUBLICATION_BUDGET_MS = 180_000;
79
+
80
+ /**
81
+ * - `held`: a delivery is not merged (`reason: unmerged`), a change depends on an unpublished
82
+ * change of another group that could not publish (`reason: dependency-unpublished`), or, with
83
+ * `ownAnswersOnly`, a merge was answered by someone else (`reason: unconfirmed-merge`)
84
+ * - `awaiting-publisher`: ready, but the remote refused this user's push to the default branch
85
+ * - `deferred`: the remote stayed unreachable; nothing was published
86
+ */
87
+ export type PublicationStatus =
88
+ | "ok"
89
+ | "held"
90
+ | "conflict"
91
+ | "error"
92
+ | "deferred"
93
+ | "awaiting-publisher";
94
+
95
+ /** A requirement changed since its delta was written, with the texts to resolve it from. */
96
+ export interface PublicationConflict {
97
+ change: string;
98
+ capability: string;
99
+ requirement: string;
100
+ /** The requirement as the delta was written against it. */
101
+ base: string;
102
+ /** The change's version; null when it removes the requirement or only renames it. */
103
+ ours: string | null;
104
+ /** The default branch's version; null when removed there. */
105
+ theirs: string | null;
106
+ }
107
+
108
+ export interface PublicationResult {
109
+ status: PublicationStatus;
110
+ /** The Delivery Group, once known. */
111
+ group: string | null;
112
+ /** Its submitted changes, in publication order. */
113
+ changes: string[];
114
+ /** The records they became, on `ok`. */
115
+ records: string[];
116
+ /** The commit pushed to the default branch. */
117
+ commit?: string;
118
+ /** Published by an earlier run or a teammate; at most the inbox was emptied. */
119
+ alreadyPublished?: boolean;
120
+ reason?: "unmerged" | "dependency-unpublished" | "unconfirmed-merge";
121
+ /** `dependency-unpublished`: the changes of other groups it waits for. */
122
+ heldBy?: string[];
123
+ /** The final merge results the group's changes record and who recorded each. */
124
+ merges?: PublishedClaim[];
125
+ /** Groups its changes depend on, published first in this run. */
126
+ dependencies?: PublicationResult[];
127
+ conflictedPaths: string[];
128
+ warnings: string[];
129
+ conflict?: PublicationConflict;
130
+ /** The conflict is recorded as `blocked` in the change's Delivery Record on the pending branch. */
131
+ blocked?: boolean;
132
+ secretFindings?: SecretFinding[];
133
+ message: string;
134
+ }
135
+
136
+ /** A {@link MergeClaim} of one change of the group. */
137
+ export interface PublishedClaim extends MergeClaim {
138
+ change: string;
139
+ }
140
+
141
+ export interface PublishDeps {
142
+ git?: (cwd: string) => CompanionGit;
143
+ /**
144
+ * Records the user's answers or a refresh into the Delivery Records of `changes` in `dir`, a
145
+ * checkout of the pending branch; returns a refusal message or null.
146
+ */
147
+ settle?: (dir: string, changes: string[]) => Promise<string | null>;
148
+ /** Settles a dependency's group published in the same run; never the user's answer. */
149
+ settleDependency?: (dir: string, changes: string[]) => Promise<string | null>;
150
+ scan?: (root: string, paths: string[], policyPath: string) => Promise<PublicationSecretScan>;
151
+ /** Applies each change on the default branch; the bundled CLI by default. */
152
+ runOpenSpec?: RunOpenSpec;
153
+ artifactType?: ArtifactType;
154
+ newTransaction?: () => string;
155
+ /** The remote was just fetched; the first attempt reuses its refs. */
156
+ fresh?: boolean;
157
+ /** Publish the groups of unpublished dependencies first; true by default. */
158
+ withDependencies?: boolean;
159
+ /**
160
+ * Hold a group back (`reason: unconfirmed-merge`) while a merge it rests on was answered by
161
+ * someone else and found by no checkout: an unattended run takes nobody's word for it.
162
+ */
163
+ ownAnswersOnly?: boolean;
164
+ /** The time a block is first recorded at. */
165
+ now?: () => Date;
166
+ tmpRoot?: string;
167
+ /** Home of Mate's local companion state; `HOME` by default. */
168
+ stateHome?: string;
169
+ }
170
+
171
+ const defaultGit = (cwd: string): CompanionGit =>
172
+ companionGit(cwd, { prompt: "never", budgetMs: PUBLICATION_BUDGET_MS });
173
+
174
+ const absolute = (dir: string, relative: string): string => path.join(dir, ...relative.split("/"));
175
+
176
+ const head = async (git: CompanionGit, ref = "HEAD"): Promise<string> =>
177
+ (await git.run(["rev-parse", "--verify", "-q", `${ref}^{commit}`])).stdout.trim();
178
+
179
+ /** What one publication run works with. */
180
+ interface Run {
181
+ companionPath: string;
182
+ type: ArtifactType;
183
+ gitFor: (cwd: string) => CompanionGit;
184
+ remote: StagingRemote;
185
+ transaction: string;
186
+ deps: PublishDeps;
187
+ }
188
+
189
+ function worktreeOptions(run: Run) {
190
+ return {
191
+ git: run.gitFor,
192
+ types: [run.type],
193
+ ...(run.deps.tmpRoot ? { tmpRoot: run.deps.tmpRoot } : {}),
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Publishes a Delivery Group of submitted changes from any machine, once every delivery in it
199
+ * is merged: in a temporary worktree of the fetched default branch its changes are applied in
200
+ * `dependsOn` order, then submit order (stale check, the type's `apply`, `validate`), committed
201
+ * once with a `Mate-Artifact` trailer per change and a `Mate-Transaction` trailer,
202
+ * secret-scanned and pushed without force, rebuilt once on a rejected push. The group's
203
+ * folders then leave the inbox in a second push. `target` is a Delivery Group or a submitted change.
204
+ * The companion checkout then fast-forwards to the published commit when nothing blocks it.
205
+ * Never throws.
206
+ */
207
+ export async function publishSubmitted(
208
+ companionPath: string,
209
+ target: string,
210
+ deps: PublishDeps = {},
211
+ ): Promise<PublicationResult> {
212
+ try {
213
+ return await publishOnce(companionPath, target, deps, []);
214
+ } catch (error) {
215
+ return {
216
+ ...emptyResult(null),
217
+ message: `mate: publishing ${target} failed; nothing was published. ${errorMessage(error)}`,
218
+ };
219
+ }
220
+ }
221
+
222
+ function emptyResult(group: string | null): PublicationResult {
223
+ return {
224
+ status: "error",
225
+ group,
226
+ changes: [],
227
+ records: [],
228
+ conflictedPaths: [],
229
+ warnings: [],
230
+ message: "",
231
+ };
232
+ }
233
+
234
+ async function publishOnce(
235
+ companionPath: string,
236
+ target: string,
237
+ deps: PublishDeps,
238
+ visiting: readonly string[],
239
+ ): Promise<PublicationResult> {
240
+ const gitFor = deps.git ?? defaultGit;
241
+ const git = gitFor(companionPath);
242
+ const configured = await stagingRemote(git);
243
+ if (!configured) {
244
+ return { ...emptyResult(null), message: "mate: the companion has no upstream to publish to." };
245
+ }
246
+ const type = deps.artifactType ?? defaultArtifactType(deps.runOpenSpec);
247
+ const transaction = (deps.newTransaction ?? randomUUID)();
248
+
249
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
250
+ let remote = configured;
251
+ if (attempt > 1 || !deps.fresh) {
252
+ // oxlint-disable-next-line no-await-in-loop -- each attempt starts from a fresh fetch
253
+ const fetched = await fetchPendingBranches(git, configured);
254
+ if ("error" in fetched) {
255
+ return {
256
+ ...emptyResult(null),
257
+ status: fetched.transient ? "deferred" : "error",
258
+ message: `mate: ${fetched.error}; nothing was published.`,
259
+ };
260
+ }
261
+ remote = fetched;
262
+ }
263
+ const run: Run = { companionPath, type, gitFor, remote, transaction, deps };
264
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
265
+ const submitted = await submittedAt(git, pendingRef(remote), type, deps.tmpRoot);
266
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
267
+ const resolved = await resolveTarget(run, git, target, submitted);
268
+ if ("result" in resolved) return resolved.result;
269
+ const { group } = resolved;
270
+ const base = { ...emptyResult(group), changes: resolved.members.map((change) => change.name) };
271
+
272
+ if (resolved.members.length === 0) {
273
+ // oxlint-disable-next-line no-await-in-loop -- returns
274
+ const cleared = await clearInbox(run, group, resolved.inbox);
275
+ return {
276
+ ...base,
277
+ status: "ok",
278
+ alreadyPublished: true,
279
+ ...(cleared ? { warnings: [cleared] } : {}),
280
+ message: `${group} is already published on ${remote.defaultBranch}; nothing to do.`,
281
+ };
282
+ }
283
+
284
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
285
+ const dependencies = await publishDependencies(run, resolved, submitted, visiting);
286
+ if (dependencies && "held" in dependencies) return { ...base, ...dependencies.held };
287
+ if (dependencies) {
288
+ // The dependencies changed both branches; publish this group on their result.
289
+ // oxlint-disable-next-line no-await-in-loop -- returns
290
+ const own = await publishOnce(companionPath, group, { ...deps, fresh: false }, [
291
+ ...visiting,
292
+ group,
293
+ ]);
294
+ return { ...own, dependencies: [...dependencies.published, ...(own.dependencies ?? [])] };
295
+ }
296
+
297
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
298
+ const settled = await settleGroup(run, base, resolved.members);
299
+ if (settled === "retry") continue;
300
+ if (!("deliveries" in settled)) return settled;
301
+
302
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
303
+ const merges = await claimsOf(run, resolved.members, settled);
304
+ const answered = merges.filter(isOthersAnswer);
305
+ if (deps.ownAnswersOnly && answered.length > 0) {
306
+ // What a refresh just found is kept for the publication by name.
307
+ if (settled.changed) {
308
+ // oxlint-disable-next-line no-await-in-loop -- returns
309
+ await recordOnPending(run, group, resolved.members, settled.deliveries, null);
310
+ }
311
+ return {
312
+ ...base,
313
+ status: "held",
314
+ reason: "unconfirmed-merge",
315
+ merges,
316
+ message: `mate: ${group} is held back: ${describeClaims(answered)}. Publish ${group} by name to accept that.`,
317
+ };
318
+ }
319
+
320
+ // oxlint-disable-next-line no-await-in-loop -- same attempt
321
+ const outcome = await withTemporaryWorktree(
322
+ companionPath,
323
+ defaultRef(remote),
324
+ (dir) =>
325
+ publishIn(run, {
326
+ dir,
327
+ work: gitFor(dir),
328
+ base,
329
+ members: resolved.members,
330
+ pendingCommit: settled.commit,
331
+ deliveries: settled.deliveries,
332
+ }),
333
+ worktreeOptions(run),
334
+ );
335
+ if (outcome === "retry") continue;
336
+ // oxlint-disable-next-line no-await-in-loop -- returns
337
+ const result = await finish(run, outcome, resolved, settled);
338
+ if (merges.length === 0) return result;
339
+ const note =
340
+ result.status === "ok" && answered.length > 0
341
+ ? ` It rests on ${describeClaims(answered)}.`
342
+ : "";
343
+ return { ...result, merges, message: `${result.message}${note}` };
344
+ }
345
+ return {
346
+ ...emptyResult(null),
347
+ status: "conflict",
348
+ message: `mate: the remote moved twice while publishing ${target}; publish again.`,
349
+ };
350
+ }
351
+
352
+ /** The merge claims of `members`, as their settled records read. */
353
+ async function claimsOf(
354
+ run: Run,
355
+ members: readonly SubmittedChange[],
356
+ settled: Settled,
357
+ ): Promise<PublishedClaim[]> {
358
+ const git = run.gitFor(run.companionPath);
359
+ const claims = await Promise.all(
360
+ members.map((change) =>
361
+ mergeClaims(
362
+ git,
363
+ settled.commit,
364
+ change.path,
365
+ settled.records.get(change.name) ?? null,
366
+ run.type,
367
+ ),
368
+ ),
369
+ );
370
+ return members.flatMap((change, index) =>
371
+ claims[index]!.map((claim) => ({ change: change.name, ...claim })),
372
+ );
373
+ }
374
+
375
+ /** Whose answers `claims` are, for a message. */
376
+ function describeClaims(claims: readonly PublishedClaim[]): string {
377
+ return claims
378
+ .map(
379
+ (claim) =>
380
+ `${claim.change} is ${claim.state} in ${inboxText(claim.repository)} by the answer of ${claim.recordedBy ? inboxText(claim.recordedBy) : "someone else"}, which no checkout checked`,
381
+ )
382
+ .join("; ");
383
+ }
384
+
385
+ /** Records the block or the settlement a publication left behind, and empties the inbox. */
386
+ async function finish(
387
+ run: Run,
388
+ outcome: Outcome,
389
+ { members, inbox }: ResolvedTarget,
390
+ settled: Settled,
391
+ ): Promise<PublicationResult> {
392
+ const group = outcome.group!;
393
+ if (outcome.status === "ok") {
394
+ const cleared = await clearInbox(run, group, inbox);
395
+ // The checkout takes the published commit: its specs and archives are current at once.
396
+ await adoptUpstream(run.companionPath, run.remote.defaultBranch, {
397
+ homeDir: run.deps.stateHome,
398
+ });
399
+ return cleared ? { ...outcome, warnings: [...outcome.warnings, cleared] } : outcome;
400
+ }
401
+ const block =
402
+ outcome.status === "conflict" && outcome.blocker
403
+ ? { ...outcome.blocker, paths: outcome.conflictedPaths }
404
+ : null;
405
+ // Answers given for a group that did not publish are kept for the next attempt.
406
+ const deliveries = settled.changed ? settled.deliveries : new Map<string, string>();
407
+ if (!block && deliveries.size === 0) return strip(outcome);
408
+ const recorded = await recordOnPending(run, group, members, deliveries, block);
409
+ if (recorded.failure) {
410
+ return strip({ ...outcome, warnings: [...outcome.warnings, recorded.failure] });
411
+ }
412
+ return strip({ ...outcome, ...(block ? { blocked: true } : {}) });
413
+ }
414
+
415
+ /** The result without the internal blocker. */
416
+ function strip(result: PublicationResult & { blocker?: unknown }): PublicationResult {
417
+ const { blocker: _blocker, ...rest } = result;
418
+ return rest;
419
+ }
420
+
421
+ interface ResolvedTarget {
422
+ group: string;
423
+ /** Its submitted changes not yet published, in publication order. */
424
+ members: SubmittedChange[];
425
+ /** Every change of it the inbox holds, published ones included. */
426
+ inbox: string[];
427
+ }
428
+
429
+ /** The Delivery Group `target` names, or the result that ends the run. */
430
+ async function resolveTarget(
431
+ run: Run,
432
+ git: CompanionGit,
433
+ target: string,
434
+ submitted: readonly SubmittedChange[],
435
+ ): Promise<ResolvedTarget | { result: PublicationResult }> {
436
+ const { type, remote } = run;
437
+ const named = isDeliveryGroup(target)
438
+ ? target
439
+ : submitted.find((change) => change.name === target)?.group;
440
+ if (!named) {
441
+ const published = (await anchorsAt(git, defaultRef(remote), type)).some(
442
+ (id) => type.recordName(id) === target,
443
+ );
444
+ return {
445
+ result: {
446
+ ...emptyResult(null),
447
+ ...(published ? { status: "ok", alreadyPublished: true } : {}),
448
+ message: published
449
+ ? `${target} is already published on ${remote.defaultBranch}; nothing to do.`
450
+ : isDeliveryGroup(target)
451
+ ? `mate: no Delivery Group ${target} with submitted changes on ${pendingPlace(remote)}.`
452
+ : `mate: ${target} is not submitted. Submit it first with \`mate artifact submit ${target}\`.`,
453
+ },
454
+ };
455
+ }
456
+ const group = groupsOf(submitted).find((entry) => entry.group === named);
457
+ if (!group) {
458
+ return {
459
+ result: {
460
+ ...emptyResult(named),
461
+ message: `mate: no Delivery Group ${named} with submitted changes on ${pendingPlace(remote)}.`,
462
+ },
463
+ };
464
+ }
465
+ // An earlier publication the inbox was not emptied after: only taken out of the inbox.
466
+ const records = await recordsAt(git, defaultRef(remote), type);
467
+ const published = await Promise.all(
468
+ group.changes.map((change) =>
469
+ publishedAs(git, defaultRef(remote), pendingRef(remote), type, change.name, records),
470
+ ),
471
+ );
472
+ return {
473
+ group: named,
474
+ members: group.changes.filter((_, index) => published[index] === null),
475
+ inbox: group.changes.map((change) => change.name),
476
+ };
477
+ }
478
+
479
+ /**
480
+ * Publishes the groups of the unpublished dependencies first; null when there are none. A
481
+ * dependency that does not publish holds this group back.
482
+ */
483
+ async function publishDependencies(
484
+ run: Run,
485
+ resolved: ResolvedTarget,
486
+ submitted: readonly SubmittedChange[],
487
+ visiting: readonly string[],
488
+ ): Promise<{ held: Partial<PublicationResult> } | { published: PublicationResult[] } | null> {
489
+ const { remote, type } = run;
490
+ const git = run.gitFor(run.companionPath);
491
+ const depended = unpublishedDependencies(
492
+ { group: resolved.group, changes: resolved.members },
493
+ submitted,
494
+ );
495
+ // Published, but the inbox was not emptied yet: no longer waited for.
496
+ const records = depended.length > 0 ? await recordsAt(git, defaultRef(remote), type) : [];
497
+ const archived = await Promise.all(
498
+ depended.map((change) =>
499
+ publishedAs(git, defaultRef(remote), pendingRef(remote), type, change.name, records),
500
+ ),
501
+ );
502
+ const waiting = depended.filter((_, index) => archived[index] === null);
503
+ if (waiting.length === 0) return null;
504
+ const heldBy = waiting.map((change) => change.name);
505
+ const held = (detail: string, dependencies: PublicationResult[] = []) => ({
506
+ held: {
507
+ status: "held" as const,
508
+ reason: "dependency-unpublished" as const,
509
+ heldBy,
510
+ ...(dependencies.length > 0 ? { dependencies } : {}),
511
+ message: `mate: ${resolved.group} is held back: it depends on ${heldBy.join(", ")}, ${detail}. Publish it once those are published.`,
512
+ },
513
+ });
514
+ const groups = [...new Set(waiting.map((change) => change.group))];
515
+ if (
516
+ run.deps.withDependencies === false ||
517
+ visiting.includes(resolved.group) ||
518
+ groups.some((group) => visiting.includes(group))
519
+ ) {
520
+ return held("not published yet");
521
+ }
522
+ const published: PublicationResult[] = [];
523
+ for (const group of groups) {
524
+ // oxlint-disable-next-line no-await-in-loop -- dependencies publish one after another
525
+ const result = await publishOnce(
526
+ run.companionPath,
527
+ group,
528
+ {
529
+ ...run.deps,
530
+ fresh: false,
531
+ newTransaction: randomUUID,
532
+ settle: run.deps.settleDependency,
533
+ },
534
+ [...visiting, resolved.group],
535
+ );
536
+ published.push(result);
537
+ if (result.status !== "ok")
538
+ return held(`which could not publish (${result.status})`, published);
539
+ }
540
+ return { published };
541
+ }
542
+
543
+ /** A group ready to publish, with its settled Delivery Records by change. */
544
+ interface Settled {
545
+ deliveries: ReadonlyMap<string, string>;
546
+ /** The same records, parsed; a change without a readable one is left out. */
547
+ records: ReadonlyMap<string, DeliveryRecord>;
548
+ /** Settlement changed a record; kept on the pending branch if the publication fails. */
549
+ changed: boolean;
550
+ /** The pending-branch commit the records were read from. */
551
+ commit: string;
552
+ }
553
+
554
+ /**
555
+ * Settles the group's deliveries in a worktree of the pending branch and reads them. A group
556
+ * held back gets its answers pushed to the pending branch; a publishable one hands them to the
557
+ * publication, which publishes them with the changes.
558
+ */
559
+ async function settleGroup(
560
+ run: Run,
561
+ base: PublicationResult,
562
+ members: readonly SubmittedChange[],
563
+ ): Promise<Settled | PublicationResult | "retry"> {
564
+ const { type, remote, deps } = run;
565
+ const names = members.map((change) => change.name);
566
+ return withTemporaryWorktree(
567
+ run.companionPath,
568
+ pendingRef(remote),
569
+ async (dir): Promise<Settled | PublicationResult | "retry"> => {
570
+ const work = run.gitFor(dir);
571
+ const companion = run.gitFor(run.companionPath);
572
+ // The commit the worktree checked for links; a fetch may move the ref meanwhile.
573
+ const commit = await head(work);
574
+ if (deps.settle) {
575
+ const refusal = await deps.settle(dir, names);
576
+ if (refusal) return { ...base, message: refusal };
577
+ }
578
+ const held: string[] = [];
579
+ const deliveries = new Map<string, string>();
580
+ const records = new Map<string, DeliveryRecord>();
581
+ for (const change of members) {
582
+ const folder = sourceDir(dir, type, change.name);
583
+ // oxlint-disable-next-line no-await-in-loop -- a handful of changes per group
584
+ const delivery = await readDeliveryState(folder);
585
+ const hold = deliveryHold({ ...change, delivery });
586
+ if (hold) held.push(hold);
587
+ if (delivery.record) records.set(change.name, delivery.record);
588
+ const file = path.join(folder, type.deliveryFile);
589
+ // oxlint-disable-next-line no-await-in-loop -- same change
590
+ const text = await fs.readFile(file, "utf8").catch(() => null);
591
+ if (text !== null) deliveries.set(change.name, text);
592
+ }
593
+ await work.run([
594
+ ...LITERAL_PATHSPECS,
595
+ "add",
596
+ "-f",
597
+ "-A",
598
+ "--",
599
+ ...members.map((change) => change.path),
600
+ ]);
601
+ const changed = (await work.run(["diff", "--cached", "--quiet"])).status !== 0;
602
+ if (held.length === 0) return { deliveries, records, changed, commit };
603
+ if (changed) {
604
+ const findings = await stagedSecrets(run, work, dir);
605
+ if (findings.length > 0) {
606
+ return {
607
+ ...base,
608
+ secretFindings: findings,
609
+ message: `mate: refusing to record the delivery of ${base.group}: it contains secrets. Nothing was pushed or published.`,
610
+ };
611
+ }
612
+ const pushed = await commitAndPush(
613
+ work,
614
+ remote,
615
+ `chore(${type.name}): record delivery of ${base.group}`,
616
+ `${run.transaction}-record`,
617
+ );
618
+ // A cut-off push may still have been accepted; the trailer settles it. Fetched from the
619
+ // companion checkout: in this worktree a relative `core.hooksPath` names inbox content.
620
+ const recorded =
621
+ pushed.status === 0 ||
622
+ ("transport" in pushed &&
623
+ !isRejectedPush(pushed) &&
624
+ (await fetchStaging(companion, remote)).status === 0 &&
625
+ (await transactionsAt(companion, pendingRef(remote))).includes(
626
+ `${run.transaction}-record`,
627
+ ));
628
+ if (!recorded) {
629
+ // The remote moved: rebuilt on a fresh fetch, or a conflict after the last attempt.
630
+ if ("transport" in pushed && isRejectedPush(pushed)) return "retry";
631
+ return {
632
+ ...base,
633
+ status:
634
+ "transport" in pushed && isTransientRemoteFailure(pushed) ? "deferred" : "error",
635
+ message: `mate: recording the delivery of ${base.group} on ${pendingPlace(remote)} failed; nothing was published. ${describeGitFailure(pushed)}`,
636
+ };
637
+ }
638
+ }
639
+ return {
640
+ ...base,
641
+ status: "held",
642
+ reason: "unmerged",
643
+ message: `mate: ${base.group} is held back: ${held.join(", ")}. Publish it once every delivery is merged.`,
644
+ };
645
+ },
646
+ worktreeOptions(run),
647
+ );
648
+ }
649
+
650
+ /** Secret findings in the files staged in `work` at `dir`; none when the policy skips the scan. */
651
+ async function stagedSecrets(run: Run, work: CompanionGit, dir: string): Promise<SecretFinding[]> {
652
+ const staged = await work.run(["diff", "--cached", "--name-only", "--diff-filter=d", "-z"]);
653
+ const scanned = await (run.deps.scan ?? scanPublication)(
654
+ dir,
655
+ nulPaths(staged.stdout),
656
+ run.companionPath,
657
+ );
658
+ return scanned.skipped ? [] : scanned.findings;
659
+ }
660
+
661
+ async function commitAndPush(
662
+ work: CompanionGit,
663
+ remote: StagingRemote,
664
+ subject: string,
665
+ transaction: string,
666
+ ): Promise<GitResult | NetworkGitResult> {
667
+ const committed = await work.run([
668
+ ...WITHOUT_HOOKS,
669
+ "commit",
670
+ "-q",
671
+ "-m",
672
+ subject,
673
+ "-m",
674
+ `${TRANSACTION_TRAILER}: ${transaction}`,
675
+ ]);
676
+ return committed.status === 0 ? pushPending(work, remote) : committed;
677
+ }
678
+
679
+ interface PublishIn {
680
+ dir: string;
681
+ work: CompanionGit;
682
+ base: PublicationResult;
683
+ members: readonly SubmittedChange[];
684
+ /** The pending-branch commit the changes are read from, as {@link settleGroup} checked it. */
685
+ pendingCommit: string;
686
+ deliveries: ReadonlyMap<string, string>;
687
+ }
688
+
689
+ type Outcome = PublicationResult & {
690
+ blocker?: { change: string | null; reason: string; tip: string };
691
+ };
692
+
693
+ /** Applies, commits, scans and pushes the group on the checked-out default tip. */
694
+ async function publishIn(run: Run, input: PublishIn): Promise<Outcome | "retry"> {
695
+ const { type, remote, transaction } = run;
696
+ const { dir, work, base, members, pendingCommit } = input;
697
+ const start = await head(work);
698
+ const paths = members.map((change) => change.path);
699
+ // A folder committed while active goes first: a file the submitted one dropped must not stay.
700
+ await work.run([...LITERAL_PATHSPECS, "rm", "-r", "-q", "--ignore-unmatch", "--", ...paths]);
701
+ // Without hooks: `post-checkout` would run on a teammate's pending tree.
702
+ const read = await work.run([
703
+ ...WITHOUT_HOOKS,
704
+ ...LITERAL_PATHSPECS,
705
+ "checkout",
706
+ "-q",
707
+ pendingCommit,
708
+ "--",
709
+ ...paths,
710
+ ]);
711
+ if (read.status !== 0) {
712
+ return {
713
+ ...base,
714
+ message: `mate: reading ${base.group} from the inbox failed; nothing was published. ${describeGitFailure(read)}`,
715
+ };
716
+ }
717
+ for (const change of members) {
718
+ const folder = absolute(dir, change.path);
719
+ const settled = input.deliveries.get(change.name);
720
+ // oxlint-disable-next-line no-await-in-loop -- a handful of changes per group
721
+ if (settled !== undefined) await fs.writeFile(path.join(folder, type.deliveryFile), settled);
722
+ // Publication clears a block; the published record never carries one.
723
+ // oxlint-disable-next-line no-await-in-loop -- same change
724
+ const record = await readDeliveryRecord(folder).catch(() => null);
725
+ if (record?.blocked) {
726
+ delete record.blocked;
727
+ // oxlint-disable-next-line no-await-in-loop -- same change
728
+ await writeDeliveryRecord(folder, record);
729
+ }
730
+ }
731
+ const git = run.gitFor(run.companionPath);
732
+ const bases = await Promise.all(
733
+ members.map((change) => deltaBase(git, defaultRef(remote), pendingCommit, change, type)),
734
+ );
735
+ // Without a base nothing can be found stale: a part changed since would be overwritten unseen.
736
+ const undated = members.find((change, index) => !bases[index] && change.touches.length > 0);
737
+ if (undated) {
738
+ return {
739
+ ...base,
740
+ status: "conflict",
741
+ message: `mate: ${base.group} cannot be published: the commit ${undated.name} was written against is unknown, so what changed on ${remote.defaultBranch} since cannot be checked. Nothing was published. Submit ${undated.name} again with \`mate artifact submit ${undated.name}\`, then publish again.`,
742
+ };
743
+ }
744
+ const applied = await applyChain({
745
+ type,
746
+ work,
747
+ dir,
748
+ members: members.map((change, index) => ({ name: change.name, base: bases[index] ?? null })),
749
+ ref: pendingCommit,
750
+ start,
751
+ });
752
+ if (isChainFailure(applied)) return chainConflict(run, base, applied, start);
753
+
754
+ const scanned = await (run.deps.scan ?? scanPublication)(dir, applied.changed, run.companionPath);
755
+ if (!scanned.skipped && scanned.findings.length > 0) {
756
+ return {
757
+ ...base,
758
+ secretFindings: scanned.findings,
759
+ message: `mate: refusing to publish ${base.group}: it contains secrets. Nothing was pushed.`,
760
+ };
761
+ }
762
+ // Without the companion's hooks, as every commit made in a temporary worktree: one written
763
+ // for the checkout would abort the publication.
764
+ const committed = await work.run([
765
+ ...WITHOUT_HOOKS,
766
+ "commit",
767
+ "-q",
768
+ "-m",
769
+ `chore(${type.name}): publish ${base.group}`,
770
+ "-m",
771
+ [
772
+ ...applied.records.map(
773
+ (record) => `${ARTIFACT_TRAILER}: ${artifactTrailerValue(type, record)}`,
774
+ ),
775
+ // Without an archive, how a later submission of the same name is told apart.
776
+ ...(type.archiveRoot === undefined ? [`${INBOX_TRAILER}: ${pendingCommit}`] : []),
777
+ `${TRANSACTION_TRAILER}: ${transaction}`,
778
+ ].join("\n"),
779
+ ]);
780
+ if (committed.status !== 0) {
781
+ return {
782
+ ...base,
783
+ message: `mate: committing ${base.group} on ${remote.defaultBranch} failed; nothing was published. ${describeGitFailure(committed)}`,
784
+ };
785
+ }
786
+ const commit = await head(work);
787
+ const pushed = await work.push(
788
+ [remote.remote, `HEAD:refs/heads/${remote.defaultBranch}`],
789
+ WITHOUT_HOOKS,
790
+ );
791
+ if (pushed.status !== 0) {
792
+ // The remote moved: rebuilt on a fresh fetch, or a conflict after the last attempt.
793
+ if (isRejectedPush(pushed)) return "retry";
794
+ if (isPushNotPermitted(pushed)) {
795
+ return {
796
+ ...base,
797
+ status: "awaiting-publisher",
798
+ message: `${base.group} is ready, but the companion refused your push to ${remote.defaultBranch}. Someone with push rights publishes it; its changes stay submitted.`,
799
+ };
800
+ }
801
+ // A cut-off push may still have been accepted; the trailer settles it. Fetched from the
802
+ // companion checkout, so no hook path resolves inside this worktree.
803
+ const accepted =
804
+ (await fetchStaging(git, remote)).status === 0 &&
805
+ (await transactionsAt(git, defaultRef(remote))).includes(transaction);
806
+ if (!accepted) {
807
+ return {
808
+ ...base,
809
+ status: isTransientRemoteFailure(pushed) ? "deferred" : "error",
810
+ message: `mate: pushing ${remote.defaultBranch} failed; nothing was published. ${describeGitFailure(pushed)}`,
811
+ };
812
+ }
813
+ }
814
+ return {
815
+ ...base,
816
+ status: "ok",
817
+ records: applied.records,
818
+ commit,
819
+ message: `Published ${base.group} (${applied.records.join(", ")}) to ${remote.defaultBranch}.`,
820
+ };
821
+ }
822
+
823
+ /** A chain that cannot be applied on default tip `tip`, as a conflict that published nothing. */
824
+ function chainConflict(
825
+ run: Run,
826
+ base: PublicationResult,
827
+ failure: ChainFailure,
828
+ tip: string,
829
+ ): Outcome {
830
+ const reason = describeFailure(failure, run.remote.defaultBranch);
831
+ const versions = failure.kind === "stale" ? failure.failure.versions : undefined;
832
+ return {
833
+ ...base,
834
+ status: "conflict",
835
+ conflictedPaths: failurePaths(failure, capabilitySpecPath),
836
+ blocker: { change: failure.change, reason, tip },
837
+ ...(failure.kind === "stale" && versions
838
+ ? {
839
+ conflict: {
840
+ change: failure.change,
841
+ capability: failure.failure.capability,
842
+ requirement: failure.failure.requirement,
843
+ ...versions,
844
+ },
845
+ }
846
+ : {}),
847
+ message: `mate: ${base.group} cannot be published: ${reason}. Nothing was published and the submitted changes are unchanged. ${failureRemedy(failure)}`,
848
+ };
849
+ }
850
+
851
+ /**
852
+ * Commits `edit` to the pending branch the run fetched from; `edit` returns the paths it touched.
853
+ * Best effort: returns the failure, or null when done or not needed.
854
+ */
855
+ async function editPendingBranch(
856
+ run: Run,
857
+ subject: string,
858
+ transaction: string,
859
+ edit: (work: CompanionGit, dir: string) => Promise<string[]>,
860
+ ): Promise<string | null> {
861
+ const result = await commitToPending<string>(
862
+ {
863
+ companionPath: run.companionPath,
864
+ subject,
865
+ remote: run.remote,
866
+ transaction,
867
+ edit: async (dir) => {
868
+ try {
869
+ return await edit(run.gitFor(dir), dir);
870
+ } catch (error) {
871
+ // Runs after the publication's outcome is settled; it must not turn into a failed one.
872
+ return {
873
+ stop: describeGitFailure({ status: 1, stdout: "", stderr: errorMessage(error) }),
874
+ };
875
+ }
876
+ },
877
+ },
878
+ {
879
+ git: run.gitFor,
880
+ artifactType: run.type,
881
+ ...(run.deps.scan ? { scan: run.deps.scan } : {}),
882
+ ...(run.deps.tmpRoot ? { tmpRoot: run.deps.tmpRoot } : {}),
883
+ },
884
+ );
885
+ if (result.status === "stopped") return result.value ?? null;
886
+ if (result.status !== "failed") return null;
887
+ if (result.reason === "secret") {
888
+ const files = [...new Set(result.secretFindings.map((finding) => finding.path))];
889
+ return `it contains secrets at ${files.join(", ")}`;
890
+ }
891
+ return "git" in result ? describeGitFailure(result.git) : result.detail;
892
+ }
893
+
894
+ /**
895
+ * Takes the published changes of `group` out of the inbox: those of `names`, its changes there,
896
+ * the default branch holds an archive of. Both branches are read fresh, and only those folders,
897
+ * so a later publication resumes an interrupted one. Returns a warning when they stay.
898
+ */
899
+ async function clearInbox(
900
+ run: Run,
901
+ group: string,
902
+ names: readonly string[],
903
+ ): Promise<string | null> {
904
+ const { type, remote } = run;
905
+ const failure = await editPendingBranch(
906
+ run,
907
+ `chore(${type.name}): clear published ${group}`,
908
+ `${run.transaction}-clear`,
909
+ async (work) => {
910
+ const present = await submittedAt(work, "HEAD", type, run.deps.tmpRoot, names);
911
+ const records = present.length > 0 ? await recordsAt(work, defaultRef(remote), type) : [];
912
+ const published = await Promise.all(
913
+ present.map((change) =>
914
+ publishedAs(work, defaultRef(remote), "HEAD", type, change.name, records),
915
+ ),
916
+ );
917
+ const paths = present.filter((_, index) => published[index] !== null).map((c) => c.path);
918
+ if (paths.length === 0) return [];
919
+ const removed = await work.run([
920
+ ...LITERAL_PATHSPECS,
921
+ "rm",
922
+ "-r",
923
+ "-q",
924
+ "--ignore-unmatch",
925
+ "--",
926
+ ...paths,
927
+ ]);
928
+ if (removed.status !== 0) throw new Error(describeGitFailure(removed));
929
+ return paths;
930
+ },
931
+ );
932
+ return failure === null
933
+ ? null
934
+ : `${group} is published, but its changes stay in the inbox ${INBOX_BRANCH} (${failure}); the next publication of the group takes them out.`;
935
+ }
936
+
937
+ /** True when `a` and `b` name the same block, whenever and on whichever tip it was seen. */
938
+ function sameBlock(a: DeliveryBlock, b: Pick<DeliveryBlock, "reason" | "paths">): boolean {
939
+ return a.reason === b.reason && a.paths.join("\n") === b.paths.join("\n");
940
+ }
941
+
942
+ /**
943
+ * Keeps a group's settled Delivery Records and its block on the pending branch: `block` goes into
944
+ * the record of the change that caused it, or of every member when none is known, unless the
945
+ * same block is recorded already for the same default tip; a block seen again keeps its `since`.
946
+ * Committed only when something changed.
947
+ */
948
+ async function recordOnPending(
949
+ run: Run,
950
+ group: string,
951
+ members: readonly SubmittedChange[],
952
+ deliveries: ReadonlyMap<string, string>,
953
+ block: { change: string | null; reason: string; paths: string[]; tip: string } | null,
954
+ ): Promise<{ failure: string | null }> {
955
+ const { type, remote } = run;
956
+ const failure = await editPendingBranch(
957
+ run,
958
+ block
959
+ ? `chore(${type.name}): block ${group}`
960
+ : `chore(${type.name}): record delivery of ${group}`,
961
+ `${run.transaction}-${block ? "block" : "record"}`,
962
+ async (_work, dir) => {
963
+ const paths: string[] = [];
964
+ const tip = block && isCommitId(block.tip) ? block.tip : undefined;
965
+ for (const change of members) {
966
+ const folder = sourceDir(dir, type, change.name);
967
+ // oxlint-disable-next-line no-await-in-loop -- a handful of changes per group
968
+ if (!(await fs.stat(folder).catch(() => null))) continue;
969
+ paths.push(change.path);
970
+ const settled = deliveries.get(change.name);
971
+ if (settled !== undefined) {
972
+ // oxlint-disable-next-line no-await-in-loop -- same change
973
+ await fs.writeFile(path.join(folder, type.deliveryFile), settled);
974
+ }
975
+ if (!block || (block.change !== null && block.change !== change.name)) continue;
976
+ // oxlint-disable-next-line no-await-in-loop -- same change
977
+ const record = await readDeliveryRecord(folder).catch(() => null);
978
+ if (!record) continue;
979
+ const known = record.blocked && sameBlock(record.blocked, block) ? record.blocked : null;
980
+ if (known && known.tip === tip) continue;
981
+ const since = known?.since ?? (run.deps.now ?? (() => new Date()))().toISOString();
982
+ // oxlint-disable-next-line no-await-in-loop -- same change
983
+ await writeDeliveryRecord(folder, {
984
+ ...record,
985
+ blocked: { reason: block.reason, paths: block.paths, since, ...(tip ? { tip } : {}) },
986
+ });
987
+ }
988
+ return paths;
989
+ },
990
+ );
991
+ return {
992
+ failure:
993
+ failure === null
994
+ ? null
995
+ : `recording ${block ? `${group} as blocked` : `the delivery of ${group}`} on ${pendingPlace(remote)} failed (${failure}).`,
996
+ };
997
+ }
998
+
999
+ export interface PublicationQueue {
1000
+ /** The Delivery Groups `publish --all` publishes, dependencies first. */
1001
+ groups: string[];
1002
+ /** The remote was fetched for it; false when the groups come from the last fetched refs. */
1003
+ fresh: boolean;
1004
+ }
1005
+
1006
+ /** The Delivery Groups `publish --all` publishes, dependencies first. */
1007
+ export async function publicationQueue(
1008
+ companionPath: string,
1009
+ deps: Pick<PublishDeps, "git" | "artifactType" | "tmpRoot"> = {},
1010
+ ): Promise<PublicationQueue> {
1011
+ const type = deps.artifactType ?? defaultArtifactType();
1012
+ const git = (deps.git ?? defaultGit)(companionPath);
1013
+ const configured = await stagingRemote(git);
1014
+ if (!configured) return { groups: [], fresh: false };
1015
+ // A failed fetch leaves the last fetched refs; each publication then fetches for itself.
1016
+ const fetched = await fetchPendingBranches(git, configured);
1017
+ const fresh = !("error" in fetched);
1018
+ const remote = "error" in fetched ? configured : fetched;
1019
+ const submitted = await submittedAt(git, pendingRef(remote), type, deps.tmpRoot);
1020
+ return {
1021
+ groups: publicationOrder(groupsOf(submitted), submitted).map((group) => group.group),
1022
+ fresh,
1023
+ };
1024
+ }