@uniqbit/mate-core 1.0.0-canary.0 → 1.0.0-canary.2

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 (325) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
  2. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
  3. package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
  4. package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
  5. package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
  6. package/claude-plugin/hooks/hooks.json +10 -1
  7. package/claude-plugin/hooks/tokensave-route.mjs +52 -0
  8. package/opencode-plugin/src/server.ts +4 -0
  9. package/opencode-plugin/src/tui.tsx +2 -0
  10. package/opencode-plugin/tui.tsx +2 -0
  11. package/package.json +45 -16
  12. package/src/brand/terminal.ts +5 -0
  13. package/src/cli/commands/artifact/apply-context.ts +275 -0
  14. package/src/cli/commands/artifact/artifact.ts +4 -0
  15. package/src/cli/commands/artifact/delivery/archive.ts +13 -5
  16. package/src/cli/commands/artifact/delivery/environment.ts +36 -13
  17. package/src/cli/commands/artifact/delivery/link.ts +35 -15
  18. package/src/cli/commands/artifact/delivery/output.ts +31 -0
  19. package/src/cli/commands/artifact/finish/command.ts +50 -5
  20. package/src/cli/commands/artifact/finish/engine.ts +44 -11
  21. package/src/cli/commands/artifact/finish/git.ts +132 -19
  22. package/src/cli/commands/artifact/finish/openspec.ts +6 -1
  23. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
  24. package/src/cli/commands/cap/index-cmd.ts +64 -15
  25. package/src/cli/commands/cap/tokensave.ts +7 -5
  26. package/src/cli/commands/companion/link.ts +14 -1
  27. package/src/cli/commands/companion/open.ts +16 -11
  28. package/src/cli/commands/companion/sync.ts +10 -0
  29. package/src/cli/commands/companion/tui.ts +17 -7
  30. package/src/cli/commands/companion/update.ts +74 -12
  31. package/src/cli/commands/doctor.ts +20 -5
  32. package/src/cli/commands/factory/factory.ts +301 -0
  33. package/src/cli/commands/install.ts +133 -9
  34. package/src/cli/commands/launch/shared.ts +16 -11
  35. package/src/cli/commands/report/index.ts +20 -1
  36. package/src/cli/commands/session/context.ts +102 -0
  37. package/src/cli/commands/setup.ts +44 -10
  38. package/src/cli/commands/studio/factory-credential.ts +49 -0
  39. package/src/cli/commands/studio/index.ts +29 -2
  40. package/src/cli/commands/studio/payload.ts +249 -15
  41. package/src/cli/commands/studio/routes.ts +41 -8
  42. package/src/cli/commands/studio/selection.ts +142 -16
  43. package/src/cli/commands/studio/server.ts +403 -364
  44. package/src/cli/commands/studio/services.ts +60 -0
  45. package/src/cli/commands/studio/studio-app.ts +67 -0
  46. package/src/cli/commands/studio/terminal-assets.ts +21 -33
  47. package/src/cli/commands/studio/terminal.ts +85 -15
  48. package/src/cli/commands/studio/views/model.ts +18 -0
  49. package/src/cli/commands/studio/views/vault/markdown-tree.ts +267 -0
  50. package/src/cli/commands/studio/views/vault/view.ts +185 -0
  51. package/src/cli/commands/studio/workset-session.ts +131 -0
  52. package/src/cli/commands/unwrap.ts +8 -0
  53. package/src/cli/commands/update.ts +27 -1
  54. package/src/cli/commands/working/cleanup.ts +10 -1
  55. package/src/cli/commands/working/link.ts +76 -0
  56. package/src/cli/commands/working/working.ts +10 -0
  57. package/src/cli/commands/working/worktree.ts +356 -0
  58. package/src/cli/companion-link-wizard.tsx +2 -0
  59. package/src/cli/companion-selector.tsx +2 -0
  60. package/src/cli/confirm.ts +2 -0
  61. package/src/cli/install-plan.tsx +127 -160
  62. package/src/cli/launch-selector.tsx +2 -0
  63. package/src/cli/main.ts +18 -0
  64. package/src/cli/parse-flags.ts +9 -1
  65. package/src/cli/repo-list-table.tsx +2 -0
  66. package/src/cli/setup-selector.tsx +79 -20
  67. package/src/cli/usage.ts +11 -1
  68. package/src/create-mate.ts +5 -4
  69. package/src/hooks/tokensave-route.ts +26 -0
  70. package/src/lib/apply-context/fingerprint.ts +174 -0
  71. package/src/lib/apply-context/protocol.ts +193 -0
  72. package/src/lib/components/confirm-prompt.tsx +21 -9
  73. package/src/lib/components/select-menu.tsx +10 -3
  74. package/src/lib/components/spinner.tsx +4 -2
  75. package/src/lib/components/startup-progress.tsx +227 -41
  76. package/src/lib/components/text-input-display.tsx +2 -0
  77. package/src/lib/components/wizard-footer.tsx +2 -0
  78. package/src/lib/components/wizard-header.tsx +13 -11
  79. package/src/lib/delivery/archive-change.ts +14 -2
  80. package/src/lib/delivery/branches.ts +29 -5
  81. package/src/lib/delivery/environment.ts +7 -1
  82. package/src/lib/delivery/forge.ts +2 -2
  83. package/src/lib/delivery/merge-git.ts +261 -0
  84. package/src/lib/delivery/overlap.ts +11 -4
  85. package/src/lib/delivery/record-delivery.ts +97 -10
  86. package/src/lib/delivery/record.ts +67 -7
  87. package/src/lib/delivery/refresh.ts +104 -10
  88. package/src/lib/delivery/repository-access.ts +46 -2
  89. package/src/lib/delivery/resolve-branch.ts +162 -0
  90. package/src/lib/delivery/token.ts +7 -41
  91. package/src/lib/factory/attach-client.ts +113 -0
  92. package/src/lib/factory/attach.ts +178 -0
  93. package/src/lib/factory/broker.ts +190 -0
  94. package/src/lib/factory/bun-commands.ts +39 -0
  95. package/src/lib/factory/client.ts +92 -0
  96. package/src/lib/factory/command.ts +61 -0
  97. package/src/lib/factory/credential-store.ts +153 -0
  98. package/src/lib/factory/frames.ts +77 -0
  99. package/src/lib/factory/ids.ts +58 -0
  100. package/src/lib/factory/keyed-serial.ts +27 -0
  101. package/src/lib/factory/outcomes/actions.ts +114 -0
  102. package/src/lib/factory/outcomes/index.ts +381 -0
  103. package/src/lib/factory/outcomes/lifecycle.ts +205 -0
  104. package/src/lib/factory/outcomes/runs.ts +81 -0
  105. package/src/lib/factory/outcomes/sessions.ts +38 -0
  106. package/src/lib/factory/prepare.ts +49 -0
  107. package/src/lib/factory/pty.ts +103 -0
  108. package/src/lib/factory/runner/companion-context.ts +178 -0
  109. package/src/lib/factory/runner/control.ts +92 -0
  110. package/src/lib/factory/runner/harness-agent.ts +250 -0
  111. package/src/lib/factory/runner/live.ts +159 -0
  112. package/src/lib/factory/runner/questions.ts +22 -0
  113. package/src/lib/factory/runner/rank.ts +26 -0
  114. package/src/lib/factory/runner/run-policy.ts +12 -0
  115. package/src/lib/factory/runner/run.ts +199 -0
  116. package/src/lib/factory/runner/scheduler.ts +416 -0
  117. package/src/lib/factory/runner/state.ts +233 -0
  118. package/src/lib/factory/runner/workflow.ts +542 -0
  119. package/src/lib/factory/runtime.ts +972 -0
  120. package/src/lib/factory/sandbox.ts +292 -0
  121. package/src/lib/factory/worktree-branch.ts +17 -0
  122. package/src/lib/install.ts +66 -14
  123. package/src/lib/live-progress.ts +36 -0
  124. package/src/lib/member-choices.ts +67 -0
  125. package/src/lib/orchestrator/adapters/base.ts +55 -22
  126. package/src/lib/orchestrator/adapters/claude.ts +6 -1
  127. package/src/lib/orchestrator/config-store.ts +3 -2
  128. package/src/lib/orchestrator/editor.ts +29 -23
  129. package/src/lib/orchestrator/projection-entries.ts +56 -21
  130. package/src/lib/orchestrator/projection-opencode-copies.ts +32 -15
  131. package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
  132. package/src/lib/orchestrator/projection-types.ts +33 -1
  133. package/src/lib/orchestrator/session-context-link.ts +67 -0
  134. package/src/lib/orchestrator/setup-compatibilities.ts +55 -12
  135. package/src/lib/orchestrator/types.ts +5 -0
  136. package/src/lib/orchestrator/working-repo-projection.ts +50 -7
  137. package/src/lib/orchestrator/workspace-document.ts +105 -0
  138. package/src/lib/package-paths.ts +29 -0
  139. package/src/lib/runtime-directory-refresh.ts +17 -1
  140. package/src/lib/workset/record.ts +513 -0
  141. package/src/lib/workset/repositories.ts +55 -0
  142. package/src/lib/workset/stage.ts +148 -0
  143. package/src/lib/workset/stages.ts +113 -0
  144. package/src/lib/workset/worktree-index.ts +116 -0
  145. package/src/lib/workset/worktree.ts +830 -0
  146. package/src/opencode/companion-hooks.ts +45 -2
  147. package/src/opencode/enter-worktree.ts +72 -0
  148. package/src/opencode/tui.tsx +9 -4
  149. package/src/plugins.ts +1 -0
  150. package/src/runtime/claude-delivery-plan.ts +22 -5
  151. package/src/runtime/companion-git.ts +52 -10
  152. package/src/runtime/companion-guidance.ts +7 -7
  153. package/src/runtime/companion-lock.ts +30 -7
  154. package/src/runtime/env.ts +48 -3
  155. package/src/runtime/git-layout.ts +219 -0
  156. package/src/runtime/index.ts +24 -0
  157. package/src/runtime/physical-path.ts +111 -0
  158. package/src/runtime/policy.ts +36 -2
  159. package/src/runtime/runtime-directory.ts +5 -0
  160. package/src/runtime/secret-guard.ts +19 -5
  161. package/src/runtime/secret-patterns.ts +267 -34
  162. package/src/runtime/session-context.ts +98 -0
  163. package/src/runtime/tokensave-route.ts +152 -0
  164. package/src/runtime/wrap-state.ts +24 -16
  165. package/src/studio.ts +124 -0
  166. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +10 -8
  167. package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +16 -98
  168. package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +10 -2
  169. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +76 -18
  170. package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
  171. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +2 -0
  172. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +32 -5
  173. package/src/templates/mate-skills/agents/mate-backfill-spec/SKILL.md +8 -1
  174. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +16 -1
  175. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +22 -6
  176. package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +2 -0
  177. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +8 -1
  178. package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
  179. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +7 -0
  180. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +55 -50
  181. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +47 -0
  182. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +2 -0
  183. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +2 -0
  184. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +29 -10
  185. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +4 -2
  186. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +21 -0
  187. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +13 -0
  188. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +76 -18
  189. package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
  190. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +2 -0
  191. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +32 -5
  192. package/src/templates/mate-skills/claude/mate-backfill-spec/SKILL.md +8 -1
  193. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +16 -1
  194. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +22 -6
  195. package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +2 -0
  196. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +8 -1
  197. package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
  198. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +7 -0
  199. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +55 -50
  200. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +47 -0
  201. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +2 -0
  202. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +2 -0
  203. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +29 -10
  204. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +4 -2
  205. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +21 -0
  206. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +13 -0
  207. package/src/templates/mate-skills/openspec-references.ts +2 -0
  208. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +364 -224
  209. package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
  210. package/src/tools/setup/capabilities/context-mode.ts +34 -5
  211. package/src/tools/setup/capabilities/graphify-secrets.ts +2 -14
  212. package/src/tools/setup/capabilities/graphify.ts +34 -7
  213. package/src/tools/setup/capabilities/openspec.ts +12 -2
  214. package/src/tools/setup/capabilities/react-doctor.ts +8 -1
  215. package/src/tools/setup/capabilities/rtk.ts +4 -0
  216. package/src/tools/setup/capabilities/tokensave.ts +77 -68
  217. package/src/tools/setup/engine.ts +3 -2
  218. package/src/tools/setup/install-contract.ts +8 -0
  219. package/src/tools/setup/mate-skill-copies.ts +51 -0
  220. package/src/tools/setup/package-managers/uv.ts +73 -11
  221. package/src/tools/setup/plugin.ts +5 -0
  222. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  223. package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
  224. package/src/tools/setup/providers/claude.ts +11 -5
  225. package/src/tools/setup/utils.ts +4 -0
  226. package/src/tools/setup/working-repo-cleanup.ts +29 -1
  227. package/src/tools/setup/working-repo-local-state.ts +252 -75
  228. package/src/tools/setup.ts +57 -16
  229. package/studio-dist/client/assets/companion-view-Csva26Ir.js +1 -0
  230. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +1 -0
  231. package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
  232. package/studio-dist/client/assets/factory-B7l9ZQyx.js +4 -0
  233. package/studio-dist/client/assets/index-n6uo_92S.js +40 -0
  234. package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
  235. package/studio-dist/client/assets/prepaint-CD5OpmTM.js +24 -0
  236. package/studio-dist/client/assets/queries-CN3JwMBX.js +1 -0
  237. package/studio-dist/client/assets/react-CabXf2Ds.js +1 -0
  238. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +1 -0
  239. package/studio-dist/client/assets/reports-C01RsnMA.js +1 -0
  240. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
  241. package/studio-dist/client/assets/routes-4pbC-2Hj.js +1 -0
  242. package/studio-dist/client/assets/skills-CihQganl.js +1 -0
  243. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +1 -0
  244. package/studio-dist/client/assets/specs-D24_35_K.js +1 -0
  245. package/studio-dist/client/assets/studio-DKxfi691.css +1 -0
  246. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +3 -0
  247. package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
  248. package/studio-dist/client/assets/vault-Bd4CQiTK.js +1 -0
  249. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +1 -0
  250. package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
  251. package/studio-dist/client/assets/workflow-BJejeVwQ.js +1 -0
  252. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-BQKuMdJW.js +3881 -0
  253. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +85 -0
  254. package/studio-dist/server/assets/actions-Bvgj9eb8.js +54 -0
  255. package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
  256. package/studio-dist/server/assets/companion-view-aBady57v.js +33 -0
  257. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +459 -0
  258. package/studio-dist/server/assets/createServerRpc-tK2lE9R2.js +11 -0
  259. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +778 -0
  260. package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
  261. package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
  262. package/studio-dist/server/assets/factory-D6xnjedJ.js +2385 -0
  263. package/studio-dist/server/assets/factory-DT3UzHlh.js +68 -0
  264. package/studio-dist/server/assets/model-PyPALjii.js +18 -0
  265. package/studio-dist/server/assets/prepaint-BMke0fo1.js +41 -0
  266. package/studio-dist/server/assets/queries-Ag2iL8q2.js +107 -0
  267. package/studio-dist/server/assets/react-COs0LHn-.js +51 -0
  268. package/studio-dist/server/assets/report-time-DAfzln-N.js +8 -0
  269. package/studio-dist/server/assets/reports-BnUNJVtx.js +126 -0
  270. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +34 -0
  271. package/studio-dist/server/assets/router-BH--drIx.js +4298 -0
  272. package/studio-dist/server/assets/routes-khSDK1bV.js +361 -0
  273. package/studio-dist/server/assets/search-JAKurDNh.js +36 -0
  274. package/studio-dist/server/assets/shell-CboT2f66.js +51 -0
  275. package/studio-dist/server/assets/skills-MWYnWoKs.js +106 -0
  276. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +16 -0
  277. package/studio-dist/server/assets/specs-DE3w8hZP.js +155 -0
  278. package/studio-dist/server/assets/start-BW5ovN0k.js +33 -0
  279. package/studio-dist/server/assets/studio-BeltxxKt.js +216 -0
  280. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +3365 -0
  281. package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
  282. package/studio-dist/server/assets/vault-BGulVoNh.js +70 -0
  283. package/studio-dist/server/assets/vault-CuyyhLyB.js +832 -0
  284. package/studio-dist/server/assets/views-Bd7cRr27.js +82 -0
  285. package/studio-dist/server/assets/warnings-BH05rOuG.js +15 -0
  286. package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
  287. package/studio-dist/server/assets/workflow-BSuIKWqH.js +42 -0
  288. package/studio-dist/server/server.js +16220 -0
  289. package/src/cli/commands/studio/client-asset.ts +0 -16
  290. package/src/cli/commands/studio/views/client.ts +0 -44
  291. package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
  292. package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
  293. package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -102
  294. package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
  295. package/src/cli/commands/studio/views/document.tsx +0 -910
  296. package/src/cli/commands/studio/views/error.tsx +0 -20
  297. package/src/cli/commands/studio/views/markdown.tsx +0 -250
  298. package/src/cli/commands/studio/views/palette.ts +0 -134
  299. package/src/cli/commands/studio/views/reports/index.tsx +0 -44
  300. package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
  301. package/src/cli/commands/studio/views/skills/index.tsx +0 -68
  302. package/src/cli/commands/studio/views/specs/index.tsx +0 -149
  303. package/src/cli/commands/studio/views/studio-client/actions.ts +0 -51
  304. package/src/cli/commands/studio/views/studio-client/companion.ts +0 -13
  305. package/src/cli/commands/studio/views/studio-client/index.ts +0 -32
  306. package/src/cli/commands/studio/views/studio-client/keys.ts +0 -3
  307. package/src/cli/commands/studio/views/studio-client/main.ts +0 -3
  308. package/src/cli/commands/studio/views/studio-client/page.ts +0 -146
  309. package/src/cli/commands/studio/views/studio-client/panels.ts +0 -57
  310. package/src/cli/commands/studio/views/studio-client/reports.ts +0 -122
  311. package/src/cli/commands/studio/views/studio-client/theme.ts +0 -63
  312. package/src/cli/commands/studio/views/studio-client/vault-editor.ts +0 -166
  313. package/src/cli/commands/studio/views/studio-client/vault-pane.ts +0 -202
  314. package/src/cli/commands/studio/views/studio-client/vault-tree.ts +0 -258
  315. package/src/cli/commands/studio/views/studio-client.generated.ts +0 -2
  316. package/src/cli/commands/studio/views/styles.ts +0 -530
  317. package/src/cli/commands/studio/views/terminal.tsx +0 -484
  318. package/src/cli/commands/studio/views/vault/state.ts +0 -41
  319. package/src/cli/commands/studio/views/warnings.tsx +0 -21
  320. package/src/cli/commands/studio/views/workflow/delivery-path.tsx +0 -370
  321. package/src/cli/commands/studio/views/workflow/graph.ts +0 -220
  322. package/src/cli/commands/studio/views/workflow/index.tsx +0 -20
  323. package/src/cli/commands/studio/views/workflow/steps.ts +0 -278
  324. package/src/lib/components/theme.ts +0 -2
  325. package/src/tools/setup/git-utils.ts +0 -30
@@ -20,6 +20,8 @@ import type { BranchOutcome } from "./refresh";
20
20
  export type ArchiveStatus = "archived" | "needs-branch" | "failed";
21
21
 
22
22
  export interface ArchiveResult {
23
+ defaultBranch: string | null;
24
+ diagnostics: string[];
23
25
  status: ArchiveStatus;
24
26
  change: string;
25
27
  /** Companion-relative archive directory, once archived. */
@@ -41,6 +43,8 @@ export interface ArchiveRequest {
41
43
  delivery?: DeliveryEdit["delivery"];
42
44
  /** Archive with an unlinked record instead of answering `needs-branch`. */
43
45
  skipBranch?: boolean;
46
+ /** Fetch before the local merge check even when the companion's Git mode is not `auto`. */
47
+ fetch?: boolean;
44
48
  }
45
49
 
46
50
  export type ArchiveOutcome = { refusal: DeliveryRefusal } | { result: ArchiveResult };
@@ -73,9 +77,11 @@ export async function archiveChange(
73
77
  ...(request.repository ? { repository: request.repository } : {}),
74
78
  ...(request.delivery ? { edit: { delivery: request.delivery } } : {}),
75
79
  refresh: true,
80
+ ...(request.fetch ? { fetch: true } : {}),
76
81
  // The settlement covers every repository, so each delivery's merge state is refreshed.
77
82
  refreshAll: true,
78
83
  requireDelivery: !request.skipBranch,
84
+ markSkipped: request.skipBranch === true,
79
85
  },
80
86
  deps,
81
87
  );
@@ -91,10 +97,12 @@ export async function archiveChange(
91
97
  const warnings = [...overlap, ...(planning ? [planning] : [])];
92
98
 
93
99
  if ("needsBranch" in outcome) {
94
- const { record, suggestedBranch } = outcome.needsBranch;
100
+ const { record, suggestedBranch, defaultBranch, diagnostics } = outcome.needsBranch;
95
101
  return {
96
102
  result: {
97
103
  status: "needs-branch",
104
+ defaultBranch,
105
+ diagnostics,
98
106
  change,
99
107
  path: null,
100
108
  record,
@@ -107,7 +115,7 @@ export async function archiveChange(
107
115
  };
108
116
  }
109
117
 
110
- const [{ record, settlement, outcomes }] = outcome.results;
118
+ const [{ record, settlement, outcomes, defaultBranch, diagnostics }] = outcome.results;
111
119
  deps.onWarnings?.(warnings, settlement.unscoped);
112
120
 
113
121
  const run = await runner(["archive", change, "--yes"], { cwd });
@@ -116,6 +124,8 @@ export async function archiveChange(
116
124
  return {
117
125
  result: {
118
126
  status: "failed",
127
+ defaultBranch,
128
+ diagnostics,
119
129
  change,
120
130
  path: null,
121
131
  record,
@@ -131,6 +141,8 @@ export async function archiveChange(
131
141
  return {
132
142
  result: {
133
143
  status: "archived",
144
+ defaultBranch,
145
+ diagnostics,
134
146
  change,
135
147
  path: archived?.archived ? companionRelative(environment, archived.dir) : null,
136
148
  record,
@@ -1,7 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
 
4
- import type { CapabilityConfig } from "../orchestrator/types";
4
+ import type { CapabilityConfig, TicketFormat } from "../orchestrator/types";
5
+
6
+ export type { TicketFormat };
5
7
 
6
8
  const execFileAsync = promisify(execFile);
7
9
 
@@ -49,6 +51,23 @@ export function configuredProtectedPatterns(capabilities: readonly CapabilityCon
49
51
  : [];
50
52
  }
51
53
 
54
+ export interface TicketSetting {
55
+ format: TicketFormat;
56
+ /** Set for a value Mate does not know, which counts as `none`. */
57
+ diagnostic: string | null;
58
+ }
59
+
60
+ /** The openspec capability's `ticket` setting; absent or unknown means `none`. */
61
+ export function configuredTicketFormat(capabilities: readonly CapabilityConfig[]): TicketSetting {
62
+ const value = capabilities.find((capability) => capability.name === "openspec")?.ticket;
63
+ if (value === undefined || value === "none") return { format: "none", diagnostic: null };
64
+ if (value === "jira") return { format: "jira", diagnostic: null };
65
+ return {
66
+ format: "none",
67
+ diagnostic: `Unknown ticket setting ${JSON.stringify(value)} on the openspec capability; expected none or jira, so tickets are off.`,
68
+ };
69
+ }
70
+
52
71
  /** Read-only local Git queries against a Working Repository. Nothing here touches the network. */
53
72
  export interface WorkingRepoGit {
54
73
  /** Checked-out branch, or null in a detached HEAD. */
@@ -61,6 +80,8 @@ export interface WorkingRepoGit {
61
80
  unpushedCommits(): Promise<string[]>;
62
81
  /** True when the branch exists locally or as `origin/<branch>`. */
63
82
  branchExists(branch: string): Promise<boolean>;
83
+ /** True when the ref (`refs/heads/<b>`, `refs/remotes/origin/<b>`) resolves. */
84
+ hasRef(ref: string): Promise<boolean>;
64
85
  }
65
86
 
66
87
  export function workingRepoGit(repoPath: string): WorkingRepoGit {
@@ -85,6 +106,9 @@ export function workingRepoGit(repoPath: string): WorkingRepoGit {
85
106
  return (await run("config", "--get", "init.defaultBranch")) || "main";
86
107
  };
87
108
 
109
+ const hasRef = async (ref: string): Promise<boolean> =>
110
+ (await run("rev-parse", "--verify", "--quiet", ref)) !== null;
111
+
88
112
  const currentBranch = async (): Promise<string | null> =>
89
113
  (await run("symbolic-ref", "--quiet", "--short", "HEAD")) || null;
90
114
 
@@ -99,10 +123,10 @@ export function workingRepoGit(repoPath: string): WorkingRepoGit {
99
123
  return log ? log.split("\n").filter(Boolean) : [];
100
124
  },
101
125
  async branchExists(branch: string) {
102
- for (const ref of [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]) {
103
- if ((await run("rev-parse", "--verify", "--quiet", ref)) !== null) return true;
104
- }
105
- return false;
126
+ return (
127
+ (await hasRef(`refs/heads/${branch}`)) || (await hasRef(`refs/remotes/origin/${branch}`))
128
+ );
106
129
  },
130
+ hasRef,
107
131
  };
108
132
  }
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
 
3
- import type { WorkingRepoGit } from "./branches";
3
+ import type { TicketSetting, WorkingRepoGit } from "./branches";
4
4
  import type { ForgeRepo } from "./forge";
5
5
 
6
6
  export interface WorkingRepoInfo {
@@ -16,11 +16,17 @@ export interface DeliveryEnvironment {
16
16
  companionPath: string;
17
17
  workingRepo: WorkingRepoInfo | null;
18
18
  protectedPatterns: string[];
19
+ /** The companion's ticket setting; absent means `none`. */
20
+ ticket?: TicketSetting;
19
21
  /**
20
22
  * Host of a repository other than the Working Repository, from a linked checkout's
21
23
  * `origin` remote, else the Working Repository's host; null when neither is known.
22
24
  */
23
25
  hostOf?: (repository: string) => Promise<string | null>;
26
+ /** Path of a local checkout of the repository: the Working Repository or a linked one. */
27
+ checkoutOf?: (repository: string) => Promise<string | null>;
28
+ /** The companion's Git mode is `auto`: merge checks fetch before reading local refs. */
29
+ gitAutoMode?: boolean;
24
30
  }
25
31
 
26
32
  /** `dir` relative to the companion, with forward slashes. */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Forge adapters answer read-only questions about a repository and its Delivery Branch:
3
- * the default branch, whether the branch is protected, and which PR has it as head. GitHub (github.com) is the only adapter; every other host
4
- * falls back to asking the user. Every failure is returned, never thrown, and the token
3
+ * the default branch and which PR has it as head; branch protection is never asked. GitHub
4
+ * (github.com) is the only adapter; every other host falls back to asking the user. Every failure is returned, never thrown, and the token
5
5
  * is scrubbed from anything a failure carries.
6
6
  */
7
7
 
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Merge state from a local checkout: whether a delivery branch's head reached the default
3
+ * branch. Only `git` is started. Local queries never reach the network
4
+ * (`GIT_NO_LAZY_FETCH`); the fetch runs only when the caller decides to, never prompts,
5
+ * and uses the user's own remote and credential setup unchanged.
6
+ */
7
+
8
+ import { spawn } from "node:child_process";
9
+ import fs from "node:fs/promises";
10
+ import path from "node:path";
11
+
12
+ import { gitEnvironment, withGitConfig, withoutAskPass } from "../../runtime/companion-git";
13
+
14
+ export interface ProcessResult {
15
+ code: number;
16
+ stdout: string;
17
+ stderr: string;
18
+ timedOut?: boolean;
19
+ }
20
+
21
+ export type SpawnProcess = (
22
+ command: string,
23
+ args: readonly string[],
24
+ options: { cwd: string; env: NodeJS.ProcessEnv; input?: string; timeoutMs?: number },
25
+ ) => Promise<ProcessResult>;
26
+
27
+ export interface PatchMatch {
28
+ /** The commit on the default branch the delivery matched. */
29
+ commit: string;
30
+ /** `fast-forward`: the head is on the default branch's own line, which a branch without commits of its own is too. */
31
+ style: "squash" | "rebase" | "fast-forward";
32
+ }
33
+
34
+ export interface FetchResult {
35
+ ok: boolean;
36
+ message?: string;
37
+ }
38
+
39
+ export interface MergeGit {
40
+ /** True when the path is a Git work tree. */
41
+ isRepository(): Promise<boolean>;
42
+ /** `origin/<branch>`, else the local branch; null when neither exists. */
43
+ tip(branch: string): Promise<string | null>;
44
+ /** True when the commit exists locally, e.g. a recorded head after its branch was deleted. */
45
+ hasCommit(commit: string): Promise<boolean>;
46
+ /** True when `commit` is contained in `origin/<defaultBranch>`. */
47
+ isAncestor(commit: string, defaultBranch: string): Promise<boolean>;
48
+ /**
49
+ * True when `commit`, already contained in `origin/<defaultBranch>`, lies on its
50
+ * first-parent line: a fast-forward, or a branch that never had commits of its own.
51
+ * False when a merge commit brought it in.
52
+ */
53
+ onFirstParent(commit: string, defaultBranch: string): Promise<boolean>;
54
+ /**
55
+ * The commit on `origin/<defaultBranch>` that carries the delivery's changes by patch
56
+ * identity: every branch commit (rebase), else the whole branch diff (squash). Null in a
57
+ * partial clone, without a match, or above {@link PATCH_MATCH_LIMIT} upstream commits.
58
+ */
59
+ patchMatch(head: string, defaultBranch: string): Promise<PatchMatch | null>;
60
+ /** When `origin` was last fetched (ISO 8601), or null when unknown. */
61
+ lastFetchedAt(): Promise<string | null>;
62
+ /** Fetches the default branch, then the delivery branch; a missing branch is not a failure. */
63
+ fetch(defaultBranch: string, branch: string): Promise<FetchResult>;
64
+ }
65
+
66
+ export interface MergeGitDeps {
67
+ spawn?: SpawnProcess;
68
+ env?: NodeJS.ProcessEnv;
69
+ }
70
+
71
+ /** Upstream commits compared by patch identity at most; more is asked instead. */
72
+ const PATCH_MATCH_LIMIT = 500;
73
+ const FETCH_BUDGET_MS = 20_000;
74
+ const QUERY_TIMEOUT_MS = 15_000;
75
+
76
+ export const spawnProcess: SpawnProcess = (command, args, options) =>
77
+ new Promise((resolve) => {
78
+ const child = spawn(command, args, {
79
+ cwd: options.cwd,
80
+ env: options.env,
81
+ stdio: ["pipe", "pipe", "pipe"],
82
+ timeout: options.timeoutMs,
83
+ });
84
+ const stdout: Buffer[] = [];
85
+ const stderr: Buffer[] = [];
86
+ child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
87
+ child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
88
+ child.on("error", (error) => resolve({ code: -1, stdout: "", stderr: error.message }));
89
+ child.on("close", (code, signal) =>
90
+ resolve({
91
+ code: code ?? -1,
92
+ stdout: Buffer.concat(stdout).toString("utf8"),
93
+ stderr: Buffer.concat(stderr).toString("utf8"),
94
+ ...(signal ? { timedOut: true } : {}),
95
+ }),
96
+ );
97
+ child.stdin.on("error", () => {});
98
+ child.stdin.end(options.input ?? "");
99
+ });
100
+
101
+ const remoteRef = (branch: string) => `refs/remotes/origin/${branch}`;
102
+
103
+ function fetchFailure(result: ProcessResult): FetchResult {
104
+ return {
105
+ ok: false,
106
+ message: result.timedOut
107
+ ? "git fetch timed out"
108
+ : `git fetch failed: ${result.stderr.trim().split("\n").at(-1) || `exit ${result.code}`}`,
109
+ };
110
+ }
111
+
112
+ /** `<patch-id> <commit>` lines from `git patch-id --stable`. */
113
+ function patchIds(output: string): Array<[string, string]> {
114
+ return output
115
+ .split("\n")
116
+ .map((line) => line.trim().split(/\s+/))
117
+ .filter((parts): parts is [string, string] => parts.length === 2 && parts[0] !== "");
118
+ }
119
+
120
+ export function mergeGit(repoPath: string, deps: MergeGitDeps = {}): MergeGit {
121
+ const spawnFn = deps.spawn ?? spawnProcess;
122
+ const base = gitEnvironment(deps.env ?? process.env) as NodeJS.ProcessEnv;
123
+ const promptless: NodeJS.ProcessEnv = { ...withoutAskPass(base), GIT_TERMINAL_PROMPT: "0" };
124
+ const localEnv: NodeJS.ProcessEnv = { ...promptless, GIT_NO_LAZY_FETCH: "1" };
125
+
126
+ const git = (args: readonly string[], input?: string) =>
127
+ spawnFn("git", args, { cwd: repoPath, env: localEnv, input, timeoutMs: QUERY_TIMEOUT_MS });
128
+ const value = async (...args: string[]): Promise<string | null> => {
129
+ const result = await git(args);
130
+ return result.code === 0 ? result.stdout.trim() || null : null;
131
+ };
132
+ const verify = (ref: string) => value("rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
133
+
134
+ const isPartialClone = async (): Promise<boolean> =>
135
+ (await value("config", "--get", "remote.origin.promisor")) === "true" ||
136
+ (await value("config", "--get", "extensions.partialClone")) !== null;
137
+
138
+ /** Patch ids of `log -p` over a range, keyed by patch id. */
139
+ const rangePatchIds = async (range: string): Promise<Map<string, string> | null> => {
140
+ const log = await git(["log", "-p", "--no-merges", "--no-color", "--no-ext-diff", range]);
141
+ if (log.code !== 0) return null;
142
+ const ids = await git(["patch-id", "--stable"], log.stdout);
143
+ if (ids.code !== 0) return null;
144
+ return new Map(patchIds(ids.stdout));
145
+ };
146
+
147
+ return {
148
+ async isRepository() {
149
+ return (await value("rev-parse", "--is-inside-work-tree")) === "true";
150
+ },
151
+ async tip(branch) {
152
+ return (await verify(remoteRef(branch))) ?? (await verify(`refs/heads/${branch}`));
153
+ },
154
+ async hasCommit(commit) {
155
+ return (await git(["cat-file", "-e", `${commit}^{commit}`])).code === 0;
156
+ },
157
+ async isAncestor(commit, defaultBranch) {
158
+ return (
159
+ (await git(["merge-base", "--is-ancestor", commit, remoteRef(defaultBranch)])).code === 0
160
+ );
161
+ },
162
+ async onFirstParent(commit, defaultBranch) {
163
+ const line = await git([
164
+ "rev-list",
165
+ "--first-parent",
166
+ remoteRef(defaultBranch),
167
+ `^${commit}`,
168
+ ]);
169
+ if (line.code !== 0) return false;
170
+ const oldest = line.stdout.trim().split("\n").at(-1);
171
+ // Nothing listed: the head is the default branch's tip.
172
+ if (!oldest) return true;
173
+ return (await value("rev-parse", `${oldest}^1`)) === commit;
174
+ },
175
+ async patchMatch(head, defaultBranch) {
176
+ if (await isPartialClone()) return null;
177
+ const upstream = remoteRef(defaultBranch);
178
+ const forkPoint = await value("merge-base", head, upstream);
179
+ if (!forkPoint) return null;
180
+ const count = Number(
181
+ await value("rev-list", "--count", "--no-merges", `${forkPoint}..${upstream}`),
182
+ );
183
+ if (!count || count > PATCH_MATCH_LIMIT) return null;
184
+ const upstreamIds = await rangePatchIds(`${forkPoint}..${upstream}`);
185
+ const branchIds = await rangePatchIds(`${forkPoint}..${head}`);
186
+ if (!upstreamIds || !branchIds || branchIds.size === 0) return null;
187
+
188
+ const rebased = [...branchIds.keys()].map((id) => upstreamIds.get(id));
189
+ if (rebased.every(Boolean)) {
190
+ // `log` lists newest first, so the first match is where the rebase ended. One
191
+ // commit looks the same squashed or rebased; it is reported as a squash.
192
+ return {
193
+ commit: rebased[0] as string,
194
+ style: branchIds.size === 1 ? "squash" : "rebase",
195
+ };
196
+ }
197
+ const diff = await git(["diff", "--no-color", "--no-ext-diff", forkPoint, head]);
198
+ if (diff.code !== 0 || !diff.stdout) return null;
199
+ const combined = await git(["patch-id", "--stable"], diff.stdout);
200
+ const [entry] = combined.code === 0 ? patchIds(combined.stdout) : [];
201
+ const squash = entry ? upstreamIds.get(entry[0]) : undefined;
202
+ return squash ? { commit: squash, style: "squash" } : null;
203
+ },
204
+ async lastFetchedAt() {
205
+ const fetchHead = await value("rev-parse", "--git-path", "FETCH_HEAD");
206
+ if (!fetchHead) return null;
207
+ try {
208
+ const stat = await fs.stat(path.resolve(repoPath, fetchHead));
209
+ return stat.mtime.toISOString();
210
+ } catch {
211
+ return null;
212
+ }
213
+ },
214
+ async fetch(defaultBranch, branch) {
215
+ const deadline = Date.now() + FETCH_BUDGET_MS;
216
+ // No background maintenance or garbage collection from a fetch Mate started.
217
+ const env: NodeJS.ProcessEnv = withGitConfig(
218
+ { ...promptless, GCM_INTERACTIVE: "never" },
219
+ { "maintenance.auto": "false", "gc.auto": "0" },
220
+ );
221
+ // A user's own SSH command wins; otherwise SSH must not ask for a passphrase.
222
+ if (
223
+ !base.GIT_SSH_COMMAND &&
224
+ !base.GIT_SSH &&
225
+ !(await value("config", "--get", "core.sshCommand"))
226
+ ) {
227
+ env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
228
+ }
229
+ const fetchRef = async (name: string): Promise<ProcessResult> => {
230
+ // Names come from the shared Delivery Record: never fetch one Git would not accept.
231
+ if ((await git(["check-ref-format", `refs/heads/${name}`])).code !== 0) {
232
+ return { code: -1, stdout: "", stderr: `invalid branch name: ${name}` };
233
+ }
234
+ const remaining = deadline - Date.now();
235
+ if (remaining <= 0)
236
+ return { code: -1, stdout: "", stderr: "fetch time budget spent", timedOut: true };
237
+ return spawnFn(
238
+ "git",
239
+ [
240
+ "fetch",
241
+ "--no-tags",
242
+ "--no-recurse-submodules",
243
+ "origin",
244
+ `+refs/heads/${name}:${remoteRef(name)}`,
245
+ ],
246
+ { cwd: repoPath, env, timeoutMs: remaining },
247
+ );
248
+ };
249
+
250
+ const main = await fetchRef(defaultBranch);
251
+ if (main.code !== 0) return fetchFailure(main);
252
+ if (branch === defaultBranch) return { ok: true };
253
+ const delivery = await fetchRef(branch);
254
+ // A branch deleted after its merge is expected; its recorded head still answers.
255
+ if (delivery.code !== 0 && !/couldn't find remote ref/i.test(delivery.stderr)) {
256
+ return fetchFailure(delivery);
257
+ }
258
+ return { ok: true };
259
+ },
260
+ };
261
+ }
@@ -7,6 +7,7 @@ import {
7
7
  changeNameOf,
8
8
  changesDirOf,
9
9
  deltaSpecs,
10
+ isChangeName,
10
11
  } from "../change-layout";
11
12
  import { readFrontmatter } from "../frontmatter";
12
13
  import { isMateSchema } from "./stages";
@@ -73,12 +74,18 @@ export async function declaredDependencies(changeDir: string): Promise<string[]>
73
74
  }
74
75
  const names = new Set<string>();
75
76
  for (const file of files) {
77
+ let source: string;
78
+ try {
79
+ source = await fs.readFile(path.join(changeDir, file), "utf8");
80
+ } catch {
81
+ // An unreadable entry (a folder, a file gone since the listing) declares nothing.
82
+ continue;
83
+ }
76
84
  // A malformed header declares nothing; validation reports it elsewhere.
77
- const dependsOn = readFrontmatter(
78
- await fs.readFile(path.join(changeDir, file), "utf8"),
79
- )?.dependsOn;
85
+ const dependsOn = readFrontmatter(source)?.dependsOn;
80
86
  for (const name of Array.isArray(dependsOn) ? dependsOn : [dependsOn]) {
81
- if (typeof name === "string" && name.trim()) names.add(name.trim());
87
+ // Names become paths under the changes folder: only a single segment counts.
88
+ if (typeof name === "string" && isChangeName(name.trim())) names.add(name.trim());
82
89
  }
83
90
  }
84
91
  return [...names].toSorted();
@@ -1,10 +1,12 @@
1
- import type { ProtectionReason } from "./branches";
2
- import { locateChange, type ChangeLocation } from "../change-layout";
1
+ import { workingRepoGit, type ProtectionReason, type TicketFormat } from "./branches";
2
+ import { changeNameOf, locateChange, type ChangeLocation } from "../change-layout";
3
3
  import { companionRelative, type DeliveryEnvironment } from "./environment";
4
4
  import {
5
- defaultDeliveryBranch,
6
5
  findDelivery,
6
+ ticketCandidateOf,
7
+ legacyDeliveryBranch,
7
8
  readOrUnlinkedRecord,
9
+ sameRepository,
8
10
  settleChangeDir,
9
11
  upsertDelivery,
10
12
  writeDeliveryRecord,
@@ -18,6 +20,7 @@ import {
18
20
  type RefreshAccess,
19
21
  type RefreshCache,
20
22
  } from "./refresh";
23
+ import { resolveDeliveryBranch, type HasRef } from "./resolve-branch";
21
24
  import {
22
25
  repositoryAccessFor,
23
26
  type RepositoryAccess,
@@ -31,6 +34,8 @@ export interface DeliveryEdit {
31
34
  pr?: string;
32
35
  /** The user's answer, recorded after any refresh with source `user`. */
33
36
  confirm?: MergeState;
37
+ /** A Jira key recorded for the change; refused while the companion's tickets are off. */
38
+ ticket?: string;
34
39
  }
35
40
 
36
41
  export interface DeliveryRequest {
@@ -41,19 +46,27 @@ export interface DeliveryRequest {
41
46
  */
42
47
  repository?: string;
43
48
  edit?: DeliveryEdit;
44
- /** Ask the forge for each branch's merge state; a direct delivery needs the user's answer instead. */
49
+ /**
50
+ * Ask the forge, then a local checkout, for each branch's merge state; a direct delivery
51
+ * needs the user's answer instead.
52
+ */
45
53
  refresh?: boolean;
54
+ /** Fetch before a local check even when the companion's Git mode is not `auto`. */
55
+ fetch?: boolean;
46
56
  /** Refresh every delivery even when `repository` names the one to edit. */
47
57
  refreshAll?: boolean;
48
58
  /** Archived changes may be edited; otherwise only active ones are found. */
49
59
  includeArchived?: boolean;
50
60
  /** A change left without any delivery answers `needsBranch` and nothing is written. */
51
61
  requireDelivery?: boolean;
62
+ /** Marks a record left without any delivery as `skipped`, so it stays held back. */
63
+ markSkipped?: boolean;
52
64
  }
53
65
 
54
66
  export type DeliveryRefusal =
55
67
  | { reason: "unknown-change"; change: string }
56
68
  | { reason: "no-repository" }
69
+ | { reason: "tickets-off" }
57
70
  | { reason: "protected-branch"; branch: string; protection: ProtectionReason | null }
58
71
  | {
59
72
  reason: "no-delivery-branch";
@@ -63,6 +76,16 @@ export type DeliveryRefusal =
63
76
  };
64
77
 
65
78
  export interface DeliveryResult {
79
+ defaultBranch: string | null;
80
+ diagnostics: string[];
81
+ /** The companion's ticket setting. */
82
+ ticketFormat: TicketFormat;
83
+ /**
84
+ * With `ticketFormat` `jira` and no recorded ticket: the single Jira key in the branch
85
+ * recorded for the repository, else in the Working Repository's current branch. Never
86
+ * recorded without an explicit `--ticket`.
87
+ */
88
+ ticketCandidate: string | null;
66
89
  change: string;
67
90
  /** Companion-relative path of the change directory. */
68
91
  path: string;
@@ -74,9 +97,11 @@ export interface DeliveryResult {
74
97
  }
75
98
 
76
99
  export interface NeedsBranch {
100
+ defaultBranch: string | null;
101
+ diagnostics: string[];
77
102
  change: string;
78
103
  record: DeliveryRecord;
79
- /** `change/<change-name>` when that branch exists in the Working Repository. */
104
+ /** First existing safe default or legacy branch in the Working Repository. */
80
105
  suggestedBranch: string | null;
81
106
  }
82
107
 
@@ -91,6 +116,21 @@ export interface RecordDeliveryDeps extends RepositoryAccessDeps {
91
116
  repositoryAccess?: (repository: string) => RepositoryAccess;
92
117
  }
93
118
 
119
+ /** Ref lookup in the repository's local checkout; null when none is known. */
120
+ async function hasRefIn(
121
+ environment: DeliveryEnvironment,
122
+ repository: string,
123
+ ): Promise<HasRef | null> {
124
+ const working = environment.workingRepo;
125
+ if (working?.slug && sameRepository(working.slug, repository)) {
126
+ return (ref) => working.git.hasRef(ref);
127
+ }
128
+ const checkout = await environment.checkoutOf?.(repository);
129
+ if (!checkout) return null;
130
+ const git = workingRepoGit(checkout);
131
+ return (ref) => git.hasRef(ref);
132
+ }
133
+
94
134
  function hasDeliveryBranch(record: DeliveryRecord, repository: string): boolean {
95
135
  return Boolean(findDelivery(record, repository)?.branch);
96
136
  }
@@ -121,8 +161,14 @@ export async function recordDelivery(
121
161
  }
122
162
 
123
163
  const repository = request.repository ?? environment.workingRepo?.slug ?? null;
124
- const edits = edit.delivery !== undefined || edit.pr !== undefined || edit.confirm !== undefined;
125
- if (edits && !repository) return { refusal: { reason: "no-repository" } };
164
+ const ticketFormat = environment.ticket?.format ?? "none";
165
+ if (edit.ticket !== undefined && ticketFormat === "none") {
166
+ return { refusal: { reason: "tickets-off" } };
167
+ }
168
+ const repositoryEdits =
169
+ edit.delivery !== undefined || edit.pr !== undefined || edit.confirm !== undefined;
170
+ const edits = repositoryEdits || edit.ticket !== undefined || request.markSkipped === true;
171
+ if (repositoryEdits && !repository) return { refusal: { reason: "no-repository" } };
126
172
  if (repository && edit.delivery && "branch" in edit.delivery) {
127
173
  const { branch, direct } = edit.delivery;
128
174
  const protection = await access(repository).protection(branch);
@@ -134,20 +180,53 @@ export async function recordDelivery(
134
180
  const refreshAccess: RefreshAccess = {
135
181
  now,
136
182
  forgeAccess: (repo) => access(repo).forge(),
183
+ localAccess: async (repo) => (await access(repo).local?.()) ?? null,
184
+ fetch: request.fetch === true || environment.gitAutoMode === true,
137
185
  };
138
186
  const cache: RefreshCache = new Map();
139
187
  const resolved: Array<DeliveryResult & { dir: string }> = [];
188
+ const hasRef = repository ? await hasRefIn(environment, repository) : null;
189
+ const currentBranch = (await environment.workingRepo?.git.currentBranch()) ?? null;
140
190
 
141
191
  for (const { change, dir, archived } of located) {
142
192
  let record = await readOrUnlinkedRecord(dir, change);
193
+ const resolution = await resolveDeliveryBranch({
194
+ companionPath: environment.companionPath,
195
+ repository,
196
+ hasRef,
197
+ change,
198
+ });
199
+ const diagnostics = resolution.diagnostics;
200
+ const defaultBranch = resolution.branch;
201
+ const recordedBranch = repository ? findDelivery(record, repository)?.branch : undefined;
202
+ if (recordedBranch && defaultBranch && recordedBranch !== defaultBranch) {
203
+ diagnostics.push(
204
+ `Recorded branch ${recordedBranch} differs from default ${defaultBranch}; preserving recorded delivery unless explicitly relinked.`,
205
+ );
206
+ }
207
+ if (edit.ticket !== undefined) record = { ...record, ticket: edit.ticket };
143
208
  if (repository && edit.delivery) {
144
209
  record = upsertDelivery(record, repository, edit.delivery);
210
+ // Recording a branch keeps its local tip, so a later deletion cannot hide the merge.
211
+ if ("branch" in edit.delivery) {
212
+ const local = await access(repository).local?.();
213
+ const head = await local?.git.tip(edit.delivery.branch);
214
+ if (head) record = upsertDelivery(record, repository, { head });
215
+ }
145
216
  }
146
217
 
147
218
  if (request.requireDelivery && record.deliveries.length === 0) {
148
- const suggested = defaultDeliveryBranch(change);
149
- const exists = (await environment.workingRepo?.git.branchExists(suggested)) ?? false;
150
- return { needsBranch: { change, record, suggestedBranch: exists ? suggested : null } };
219
+ let suggestedBranch: string | null = null;
220
+ for (const candidate of [defaultBranch, legacyDeliveryBranch(changeNameOf(change))]) {
221
+ if (candidate && (await environment.workingRepo?.git.branchExists(candidate))) {
222
+ suggestedBranch = candidate;
223
+ break;
224
+ }
225
+ }
226
+ return { needsBranch: { change, record, defaultBranch, diagnostics, suggestedBranch } };
227
+ }
228
+ if (request.markSkipped && record.deliveries.length === 0) {
229
+ record = { ...record, skipped: true };
151
230
  }
152
231
 
153
232
  if (repository && edit.pr !== undefined) {
@@ -177,7 +256,15 @@ export async function recordDelivery(
177
256
  });
178
257
  }
179
258
 
259
+ const candidateSource = recordedBranch ?? currentBranch;
180
260
  resolved.push({
261
+ defaultBranch,
262
+ diagnostics,
263
+ ticketFormat,
264
+ ticketCandidate:
265
+ ticketFormat === "jira" && !record.ticket && candidateSource
266
+ ? ticketCandidateOf(candidateSource)
267
+ : null,
181
268
  dir,
182
269
  change: record.change,
183
270
  path: companionRelative(environment, dir),