@uniqbit/mate-core 0.21.1 → 1.0.0-canary.10

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 (467) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/hooks/hooks.json +32 -1
  3. package/claude-plugin/hooks/workflow-turn.mjs +68 -0
  4. package/opencode-plugin/src/companion.ts +6 -0
  5. package/opencode-plugin/src/server.ts +24 -0
  6. package/package.json +9 -4
  7. package/src/cli/commands/artifact/apply-context.ts +1 -0
  8. package/src/cli/commands/artifact/artifact.ts +16 -0
  9. package/src/cli/commands/artifact/delivery/archive.ts +37 -112
  10. package/src/cli/commands/artifact/delivery/branch-flags.ts +19 -1
  11. package/src/cli/commands/artifact/delivery/environment.ts +30 -90
  12. package/src/cli/commands/artifact/delivery/link.ts +26 -26
  13. package/src/cli/commands/artifact/delivery/output.ts +27 -4
  14. package/src/cli/commands/artifact/delivery/resolve.ts +102 -0
  15. package/src/cli/commands/artifact/delivery/submit.ts +171 -0
  16. package/src/cli/commands/artifact/delivery/take.ts +46 -0
  17. package/src/cli/commands/artifact/extract-repo-name.ts +1 -1
  18. package/src/cli/commands/artifact/finish/command.ts +486 -55
  19. package/src/cli/commands/artifact/finish/engine.ts +87 -69
  20. package/src/cli/commands/artifact/finish/finisher.ts +5 -12
  21. package/src/cli/commands/artifact/finish/git.ts +9 -10
  22. package/src/cli/commands/artifact/finish/openspec.ts +21 -174
  23. package/src/cli/commands/artifact/finish/secret-scan.ts +5 -43
  24. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +57 -7
  25. package/src/cli/commands/artifact/pending/command.ts +187 -10
  26. package/src/cli/commands/artifact/pending/discovery.ts +7 -11
  27. package/src/cli/commands/artifact/project/command.ts +59 -0
  28. package/src/cli/commands/cap/tokensave.ts +2 -2
  29. package/src/cli/commands/companion/hub.ts +11 -6
  30. package/src/cli/commands/companion/link.ts +173 -46
  31. package/src/cli/commands/companion/list.ts +70 -14
  32. package/src/cli/commands/companion/sync.ts +18 -0
  33. package/src/cli/commands/companion/update.ts +4 -3
  34. package/src/cli/commands/doctor.ts +84 -4
  35. package/src/cli/commands/friction.ts +558 -0
  36. package/src/cli/commands/install.ts +9 -4
  37. package/src/cli/commands/plugin/install.ts +82 -35
  38. package/src/cli/commands/studio/companion-add.ts +12 -27
  39. package/src/cli/commands/studio/connection.ts +53 -0
  40. package/src/{lib/factory/outcomes/sessions.ts → cli/commands/studio/live-sessions.ts} +7 -5
  41. package/src/cli/commands/studio/mcp-manager.ts +162 -0
  42. package/src/cli/commands/studio/payload.ts +172 -17
  43. package/src/cli/commands/studio/reports.ts +19 -18
  44. package/src/cli/commands/studio/routes.ts +8 -24
  45. package/src/cli/commands/studio/selection.ts +13 -4
  46. package/src/cli/commands/studio/server.ts +267 -243
  47. package/src/cli/commands/studio/service-host.ts +269 -0
  48. package/src/cli/commands/studio/services.ts +53 -34
  49. package/src/cli/commands/studio/studio-app.ts +1 -0
  50. package/src/cli/commands/studio/terminal.ts +1 -1
  51. package/src/cli/commands/studio/vault.ts +41 -40
  52. package/src/cli/commands/studio/views/model.ts +1 -9
  53. package/src/cli/commands/studio/views/vault/markdown-tree.ts +6 -5
  54. package/src/cli/commands/triage.ts +172 -0
  55. package/src/cli/commands/vscode/release-vsix.json +2 -2
  56. package/src/cli/commands/workflow/workflow.ts +516 -0
  57. package/src/cli/commands/working/cleanup.ts +1 -18
  58. package/src/cli/companion-link-wizard.tsx +158 -91
  59. package/src/cli/install-plan.tsx +3 -0
  60. package/src/cli/main.ts +106 -26
  61. package/src/cli/plugin-commands.ts +6 -1
  62. package/src/cli/repo-list-table.tsx +73 -37
  63. package/src/cli/usage.ts +30 -9
  64. package/src/create-mate.ts +15 -6
  65. package/src/distribution.ts +2 -0
  66. package/src/factory-host.ts +75 -0
  67. package/src/hooks/companion-instructions.ts +19 -8
  68. package/src/hooks/hook-io.ts +3 -1
  69. package/src/hooks/session-banner.ts +25 -0
  70. package/src/hooks/validate-artifact-path.ts +73 -22
  71. package/src/hooks/workflow-turn.ts +219 -0
  72. package/src/index.ts +1 -0
  73. package/src/lib/apply-context/fingerprint.ts +2 -1
  74. package/src/lib/apply-context/protocol.ts +2 -2
  75. package/src/lib/artifact-trailer.ts +27 -0
  76. package/src/lib/change-layout.ts +83 -38
  77. package/src/lib/delivery/branch-template.ts +4 -12
  78. package/src/lib/delivery/checkout.ts +3 -2
  79. package/src/lib/delivery/environment.ts +129 -7
  80. package/src/lib/delivery/merge-git.ts +312 -28
  81. package/src/lib/delivery/overlap.ts +81 -16
  82. package/src/lib/delivery/record-delivery.ts +102 -9
  83. package/src/lib/delivery/record.ts +186 -24
  84. package/src/lib/delivery/refresh.ts +241 -152
  85. package/src/lib/delivery/remote.ts +66 -0
  86. package/src/lib/delivery/repository-access.ts +30 -66
  87. package/src/lib/delivery/stages.ts +83 -50
  88. package/src/lib/delivery/staging/apply-chain.ts +182 -0
  89. package/src/lib/delivery/staging/artifact-type.ts +101 -0
  90. package/src/lib/delivery/staging/declared-type.ts +277 -0
  91. package/src/lib/delivery/staging/linked-merges.ts +175 -0
  92. package/src/lib/delivery/staging/naming.ts +67 -0
  93. package/src/lib/delivery/staging/openspec-type.ts +166 -0
  94. package/src/lib/delivery/staging/pending-edit.ts +291 -0
  95. package/src/lib/delivery/staging/pending.ts +922 -0
  96. package/src/lib/delivery/staging/preflight.ts +239 -0
  97. package/src/lib/delivery/staging/project.ts +512 -0
  98. package/src/lib/delivery/staging/publish.ts +1024 -0
  99. package/src/lib/delivery/staging/refs.ts +258 -0
  100. package/src/lib/delivery/staging/registry.ts +73 -0
  101. package/src/lib/delivery/staging/replay.ts +310 -0
  102. package/src/lib/delivery/staging/requirement-blocks.ts +10 -0
  103. package/src/lib/delivery/staging/resolve.ts +264 -0
  104. package/src/lib/delivery/staging/settle-linked.ts +176 -0
  105. package/src/lib/delivery/staging/submit.ts +1050 -0
  106. package/src/lib/delivery/staging/worktree.ts +130 -0
  107. package/src/lib/delivery/submit-change.ts +569 -0
  108. package/src/lib/friction/describe.ts +42 -0
  109. package/src/lib/friction/fields.ts +60 -0
  110. package/src/lib/friction/mark.ts +194 -0
  111. package/src/lib/friction/view/model.ts +67 -0
  112. package/src/lib/friction/view/read.ts +145 -0
  113. package/src/lib/friction/view/select.ts +54 -0
  114. package/src/lib/git-key.ts +15 -0
  115. package/src/lib/install.ts +2 -0
  116. package/src/lib/mcp-manager/resolve.ts +88 -0
  117. package/src/lib/mcp-manager/store.ts +133 -0
  118. package/src/lib/mcp-manager/types.ts +72 -0
  119. package/src/lib/mcp-manager/validate.ts +242 -0
  120. package/src/lib/openspec-canonical-frontmatter.ts +159 -0
  121. package/src/lib/openspec-cli.ts +10 -5
  122. package/src/lib/orchestrator/adapters/base.ts +31 -20
  123. package/src/lib/orchestrator/adapters/claude.ts +21 -7
  124. package/src/lib/orchestrator/adapters/opencode.ts +4 -0
  125. package/src/lib/orchestrator/companion-git-sync.ts +152 -16
  126. package/src/lib/orchestrator/config-store.ts +30 -7
  127. package/src/lib/orchestrator/engine-floor.ts +16 -4
  128. package/src/lib/orchestrator/engine-guard.ts +7 -1
  129. package/src/lib/orchestrator/framework-context.ts +15 -1
  130. package/src/lib/orchestrator/projection-claude-links.ts +1 -0
  131. package/src/lib/orchestrator/refresh-working-claude-links.ts +1 -0
  132. package/src/lib/orchestrator/repo-local-store.ts +14 -0
  133. package/src/lib/orchestrator/repository-link.ts +80 -52
  134. package/src/lib/orchestrator/root-context.ts +40 -7
  135. package/src/lib/orchestrator/session-prepare.ts +11 -1
  136. package/src/lib/orchestrator/types.ts +4 -0
  137. package/src/lib/orchestrator/umbrella-checkouts.ts +4 -4
  138. package/src/lib/package-paths.ts +23 -15
  139. package/src/lib/prebuilt-workspace-prepare.ts +2 -1
  140. package/src/lib/prebuilt-workspace.ts +1 -0
  141. package/src/lib/session-attribution.ts +3 -7
  142. package/src/lib/session-state.ts +3 -2
  143. package/src/lib/skills-cli.ts +38 -0
  144. package/src/lib/tool-manifest.ts +73 -0
  145. package/src/lib/triage/context.ts +312 -0
  146. package/src/lib/triage/launch.ts +52 -0
  147. package/src/lib/triage/prepare.ts +112 -0
  148. package/src/lib/triage/session.ts +126 -0
  149. package/src/lib/workflow/declaration.ts +6 -0
  150. package/src/lib/workflow/handoff.ts +90 -0
  151. package/src/lib/workflow/hook-trust.ts +108 -0
  152. package/src/lib/workflow/position.ts +524 -0
  153. package/src/lib/workflow/report.ts +79 -0
  154. package/src/lib/workflow/work.ts +106 -0
  155. package/src/lib/workset/factory-local.ts +2 -2
  156. package/src/lib/workset/repositories.ts +2 -2
  157. package/src/lib/workset/stage.ts +4 -2
  158. package/src/lib/workset/stages.ts +64 -4
  159. package/src/lib/workset/worktree.ts +32 -14
  160. package/src/opencode/companion-hooks.ts +63 -14
  161. package/src/opencode/projected-guidance.ts +7 -2
  162. package/src/opencode/turn-hook.ts +241 -0
  163. package/src/playbooks/companion-guidance.ts +7 -4
  164. package/src/plugin-api.ts +48 -0
  165. package/src/runtime/artifact-trailers.ts +63 -0
  166. package/src/runtime/claude-hook-group.ts +2 -0
  167. package/src/runtime/command-arg.ts +15 -0
  168. package/src/runtime/command-friction.ts +97 -0
  169. package/src/runtime/companion-git-state.ts +155 -10
  170. package/src/runtime/companion-git.ts +86 -11
  171. package/src/runtime/companion-guidance.ts +120 -17
  172. package/src/runtime/companion-instructions.ts +1 -1
  173. package/src/runtime/companion-sync.ts +109 -21
  174. package/src/runtime/env-names.ts +2 -2
  175. package/src/runtime/env.ts +7 -6
  176. package/src/runtime/forge-remote.ts +54 -0
  177. package/src/runtime/friction-fingerprint.ts +35 -0
  178. package/src/runtime/friction-log.ts +376 -0
  179. package/src/runtime/friction-recorder.ts +212 -0
  180. package/src/runtime/friction-retention.ts +1 -0
  181. package/src/runtime/friction-state.ts +110 -0
  182. package/src/runtime/friction-switch.ts +26 -0
  183. package/src/runtime/friction-vocabulary.ts +42 -0
  184. package/src/runtime/git-layout.ts +21 -7
  185. package/src/runtime/git-tracked.ts +13 -2
  186. package/src/runtime/json-fields.ts +8 -0
  187. package/src/runtime/pending-records.ts +533 -0
  188. package/src/runtime/projected-guidance.ts +8 -3
  189. package/src/runtime/publication-secret-scan.ts +45 -0
  190. package/src/runtime/secret-patterns.ts +7 -5
  191. package/src/runtime/secret-values.ts +16 -0
  192. package/src/runtime/session-id.ts +24 -0
  193. package/src/runtime/session-prepare-runner.ts +3 -0
  194. package/src/runtime/skill-prefix.ts +75 -0
  195. package/src/runtime/submitted-arrivals.ts +547 -0
  196. package/src/runtime/turn-state.d.mts +14 -0
  197. package/src/runtime/turn-state.mjs +93 -0
  198. package/src/runtime/umbrella-children.ts +52 -0
  199. package/src/runtime/umbrella-folder.ts +31 -3
  200. package/src/runtime/workflow/change-folders.ts +66 -0
  201. package/src/runtime/workflow/declaration.ts +720 -0
  202. package/src/runtime/workflow/globs.ts +85 -0
  203. package/src/runtime/workflow/next-handoff-process.ts +99 -0
  204. package/src/runtime/workflow/turn.ts +311 -0
  205. package/src/runtime/workflow/workflow.ts +262 -0
  206. package/src/studio.ts +113 -23
  207. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/schema.yaml +3 -3
  208. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/design.md +1 -1
  209. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/proposal.md +1 -1
  210. package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/tasks.md +1 -1
  211. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +7 -3
  212. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +28 -0
  213. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +84 -28
  214. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +1 -1
  215. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +30 -68
  216. package/src/templates/mate-skills/agents/mate-backfill-spec/SKILL.md +23 -1
  217. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +39 -8
  218. package/src/templates/mate-skills/agents/mate-domain-modeling/SKILL.md +38 -0
  219. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +65 -12
  220. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +28 -0
  221. package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +28 -0
  222. package/src/templates/mate-skills/agents/mate-grilling/SKILL.md +25 -0
  223. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +28 -0
  224. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +68 -28
  225. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +13 -7
  226. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +1 -1
  227. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +136 -86
  228. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +111 -100
  229. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +28 -3
  230. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +39 -5
  231. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +138 -0
  232. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +84 -28
  233. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +1 -1
  234. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +30 -68
  235. package/src/templates/mate-skills/claude/mate-backfill-spec/SKILL.md +23 -1
  236. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +39 -8
  237. package/src/templates/mate-skills/claude/mate-domain-modeling/SKILL.md +38 -0
  238. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +65 -12
  239. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +28 -0
  240. package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +28 -0
  241. package/src/templates/mate-skills/claude/mate-grilling/SKILL.md +25 -0
  242. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +28 -0
  243. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +68 -28
  244. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +13 -7
  245. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +1 -1
  246. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +136 -86
  247. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +111 -100
  248. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +28 -3
  249. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +39 -5
  250. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +138 -0
  251. package/src/templates/mate-skills/openspec-references.ts +3 -2
  252. package/src/templates/triage/PLAYBOOK.md +120 -0
  253. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +678 -170
  254. package/src/tools/setup/capabilities/graphify.ts +23 -1
  255. package/src/tools/setup/capabilities/mcp-manager.ts +73 -0
  256. package/src/tools/setup/capabilities/openspec.ts +54 -15
  257. package/src/tools/setup/capabilities/rtk.ts +47 -94
  258. package/src/tools/setup/capabilities/tokensave.ts +79 -56
  259. package/src/tools/setup/context-services.ts +35 -6
  260. package/src/tools/setup/dynamic-plugins/api.ts +38 -0
  261. package/src/tools/setup/dynamic-plugins/audiences.ts +31 -16
  262. package/src/tools/setup/dynamic-plugins/host.ts +2 -32
  263. package/src/tools/setup/dynamic-plugins/hydrate.ts +32 -14
  264. package/src/tools/setup/dynamic-plugins/install.ts +2 -0
  265. package/src/tools/setup/dynamic-plugins/installed.ts +73 -0
  266. package/src/tools/setup/dynamic-plugins/loader.ts +12 -10
  267. package/src/tools/setup/dynamic-plugins/local.ts +492 -0
  268. package/src/tools/setup/dynamic-plugins/paths.ts +34 -6
  269. package/src/tools/setup/dynamic-plugins/verify.ts +34 -14
  270. package/src/tools/setup/dynamic-plugins/workspaces.ts +21 -12
  271. package/src/tools/setup/engine.ts +75 -4
  272. package/src/tools/setup/mate.ts +28 -1
  273. package/src/tools/setup/package-managers/bun.ts +8 -8
  274. package/src/tools/setup/plugin.ts +28 -1
  275. package/src/tools/setup/plugins/gitignore.ts +45 -12
  276. package/src/tools/setup/plugins/guidance.ts +4 -2
  277. package/src/tools/setup/providers/claude-format.ts +39 -2
  278. package/src/tools/setup/providers/claude-plugin-hooks.ts +18 -0
  279. package/src/tools/setup/providers/claude.ts +56 -6
  280. package/src/tools/setup/providers/opencode-format.ts +13 -3
  281. package/src/tools/setup/providers/opencode.ts +7 -18
  282. package/src/tools/setup/providers/relative-path-warnings.ts +26 -0
  283. package/src/tools/setup/service-registry.ts +69 -0
  284. package/src/tools/setup/service.ts +245 -0
  285. package/src/tools/setup/utils.ts +34 -4
  286. package/src/tools/setup.ts +16 -2
  287. package/studio-dist/client/assets/DialogTitle-B_G47-lk.js +1 -0
  288. package/studio-dist/client/assets/app-0NoFqMou.css +2 -0
  289. package/studio-dist/client/assets/button-D_0295cs.js +1 -0
  290. package/studio-dist/client/assets/cn-Cx_D6I3u.js +1 -0
  291. package/studio-dist/client/assets/combobox-D0iPQP50.js +1 -0
  292. package/studio-dist/client/assets/{companion-view-CrabvxS8.js → companion-view-D3A76MLj.js} +1 -1
  293. package/studio-dist/client/assets/fields-Ctheim1h.js +1 -0
  294. package/studio-dist/client/assets/friction-Cn9n_zBA.js +1 -0
  295. package/studio-dist/client/assets/getting-started-DgoVWbWo.js +1 -0
  296. package/studio-dist/client/assets/{getting-started-D6kgWwWZ.js → getting-started-MmLqvy01.js} +1 -1
  297. package/studio-dist/client/assets/getting-started._topic-DBF0khhz.js +1 -0
  298. package/studio-dist/client/assets/getting-started.index-BRdAVqIh.js +1 -0
  299. package/studio-dist/client/assets/graph-BVRdq46V.js +2 -0
  300. package/studio-dist/client/assets/{graph-canvas-Ba37Y5AE.js → graph-canvas-BNzd-eVb.js} +1 -1
  301. package/studio-dist/client/assets/guides-DY1W9LRs.js +1 -0
  302. package/studio-dist/client/assets/index-CuTIc9yd.js +40 -0
  303. package/studio-dist/client/assets/{markdown-view-BOX6x0rL.js → markdown-view-BqZQkk_k.js} +1 -1
  304. package/studio-dist/client/assets/mcp-CIFxmDs0.js +4 -0
  305. package/studio-dist/client/assets/panel-DafanLQ4.js +1 -0
  306. package/studio-dist/client/assets/plugins._service._view-xSRLxHNM.js +1 -0
  307. package/studio-dist/client/assets/prepaint-C--F50QZ.js +27 -0
  308. package/studio-dist/client/assets/{queries-RvHeXY12.js → queries-ByCoiacy.js} +1 -1
  309. package/studio-dist/client/assets/react-BYUSgtBs.js +1 -0
  310. package/studio-dist/client/assets/reports-Diryyked.js +1 -0
  311. package/studio-dist/client/assets/routes-DbRwPd55.js +1 -0
  312. package/studio-dist/client/assets/search-BDKQRwa5.js +1 -0
  313. package/studio-dist/client/assets/select-_9JT3hpU.js +1 -0
  314. package/studio-dist/client/assets/skills-D5a6ybQM.js +1 -0
  315. package/studio-dist/client/assets/{specs-B0ldF_6J.js → specs-COAWUTog.js} +1 -1
  316. package/studio-dist/client/assets/specs-view-9eTn9TcN.js +1 -0
  317. package/studio-dist/client/assets/steps-BS588WAV.js +1 -0
  318. package/studio-dist/client/assets/store-3cffhIO6.js +1 -0
  319. package/studio-dist/client/assets/studio-CG9eioSx.js +100 -0
  320. package/studio-dist/client/assets/studio-queries-BS1yR7Wc.js +2 -0
  321. package/studio-dist/client/assets/{usage-C2QJ_0IZ.js → usage-Ccl4d7w0.js} +15 -15
  322. package/studio-dist/client/assets/useAnchoredPopupScrollLock-D_y83VP7.js +1 -0
  323. package/studio-dist/client/assets/useBlocker-BQOfcu_f.js +1 -0
  324. package/studio-dist/client/assets/useMutation-BDmS2V6y.js +1 -0
  325. package/studio-dist/client/assets/usePopupHandleStore-BcqpNR-F.js +1 -0
  326. package/studio-dist/client/assets/vault-C1tOhQMe.js +1 -0
  327. package/studio-dist/client/assets/warnings-BZ_X1nkO.js +1 -0
  328. package/studio-dist/client/assets/workflow-Cm2fsnly.js +1 -0
  329. package/studio-dist/server/assets/DialogTitle-KSVhF_7V.js +421 -0
  330. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-Bn896ZYj.js → __23tanstack-start-server-fn-resolver-QQnIXyKi.js} +40 -28
  331. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +84 -74
  332. package/studio-dist/server/assets/{button-CgOIVdmD.js → button-C7EMLaX6.js} +229 -5527
  333. package/studio-dist/server/assets/cn-D7uJiH_O.js +5528 -0
  334. package/studio-dist/server/assets/{combobox-DV_s9W0s.js → combobox-Dc4_y20Y.js} +6 -5
  335. package/studio-dist/server/assets/{companion-view-BKVXD3TO.js → companion-view-CrSi37Mb.js} +2 -2
  336. package/studio-dist/server/assets/{companions-C7fctnU9.js → companions-CDSuLqA4.js} +1 -1
  337. package/studio-dist/server/assets/{fields-BbieQTD0.js → fields-BxBN6-Dz.js} +10 -2
  338. package/studio-dist/server/assets/friction-B1K8Kp8r.js +62 -0
  339. package/studio-dist/server/assets/friction-Vl3B6THL.js +943 -0
  340. package/studio-dist/server/assets/{getting-started-CRxMWorQ.js → getting-started-B3lu5W7M.js} +2 -2
  341. package/studio-dist/server/assets/{getting-started._topic-DJKQAzYl.js → getting-started._topic-EYtxZM-Y.js} +2 -2
  342. package/studio-dist/server/assets/{getting-started.index-D84gec1t.js → getting-started.index-CTaXYycH.js} +2 -2
  343. package/studio-dist/server/assets/{graph-DDZzXM1L.js → graph-Bhmk7H8V.js} +1 -1
  344. package/studio-dist/server/assets/{graph-CSje3029.js → graph-D3fXCaKt.js} +8 -8
  345. package/studio-dist/server/assets/{graph-canvas-22bWB5-2.js → graph-canvas-DIvTodML.js} +2 -2
  346. package/studio-dist/server/assets/{guides-IE-19POz.js → guides-BZWFpJl-.js} +1 -1
  347. package/studio-dist/server/assets/{guides-D9dk1Frq.js → guides-CHBkRO6R.js} +1 -1
  348. package/studio-dist/server/assets/{guides.server-vcYRY5wx.js → guides.server-DX9KRkcK.js} +1 -1
  349. package/studio-dist/server/assets/{markdown-view-BR8dJ7aR.js → markdown-view-qrCSkVta.js} +1 -1
  350. package/studio-dist/server/assets/mcp-Ljf4simO.js +1103 -0
  351. package/studio-dist/server/assets/mcp-manager-DohRwmJU.js +50 -0
  352. package/studio-dist/server/assets/{panel-BR_t9iMM.js → panel-CAwz4mKp.js} +6 -4
  353. package/studio-dist/server/assets/plugins._service._view-DUpAo5D_.js +97 -0
  354. package/studio-dist/server/assets/prepaint-BxZ-pU7t.js +45 -0
  355. package/studio-dist/server/assets/{queries-DWoTin-q.js → queries-W4LXzTnT.js} +1 -1
  356. package/studio-dist/server/assets/react-CiBZPDs8.js +45 -0
  357. package/studio-dist/server/assets/{reports-CQ9qQ1-n.js → reports-BVNSPHU3.js} +13 -7
  358. package/studio-dist/server/assets/{reports-dYDEoBeq.js → reports-CGG_wRN5.js} +1 -1
  359. package/studio-dist/server/assets/{router-DkRHNTpE.js → router-KH1x6ryF.js} +1039 -1096
  360. package/studio-dist/server/assets/{routes-B6GfOew4.js → routes-Bl90FC4R.js} +333 -38
  361. package/studio-dist/server/assets/search-BjG5f16n.js +110 -0
  362. package/studio-dist/server/assets/{select-Af7Wibii.js → select-B8q9tLbl.js} +5 -4
  363. package/studio-dist/server/assets/{shell-Hq-hXgnT.js → shell-C5emwofr.js} +12 -3
  364. package/studio-dist/server/assets/{skills-B7nEuVbx.js → skills-10l0eCfP.js} +8 -8
  365. package/studio-dist/server/assets/{skills-B_YYL7q8.js → skills-vG6TTvP1.js} +1 -1
  366. package/studio-dist/server/assets/{specs-BpLUFntA.js → specs-C1P2BEao.js} +4 -4
  367. package/studio-dist/server/assets/{specs-view-0peMVd22.js → specs-view-csUBtMWU.js} +10 -10
  368. package/studio-dist/server/assets/{steps-D56DApvK.js → steps-T4wXftgd.js} +88 -45
  369. package/studio-dist/server/assets/store-CWlRjv9s.js +93 -0
  370. package/studio-dist/server/assets/{studio-CAcKp3bM.js → studio-D-ZPWSMv.js} +1567 -59
  371. package/studio-dist/server/assets/{studio-queries-BtRGzDdh.js → studio-queries-DC273ifg.js} +66 -124
  372. package/studio-dist/server/assets/{usage-COdjd1gD.js → usage-CT3IWLJc.js} +13 -30
  373. package/studio-dist/server/assets/{usage-f6pqE1tm.js → usage-D4t_ibR8.js} +1 -1
  374. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-DlBKHRw7.js → useAnchoredPopupScrollLock-BchJDJYg.js} +2 -2
  375. package/studio-dist/server/assets/useBlocker-CQtANHK8.js +111 -0
  376. package/studio-dist/server/assets/{useMutation-DzTZGenE.js → useMutation-0HbcKUsQ.js} +2 -2
  377. package/studio-dist/server/assets/usePopupHandleStore-B3SNGTic.js +26 -0
  378. package/studio-dist/server/assets/{vault-BDuIUq0F.js → vault-BIytrudF.js} +10 -117
  379. package/studio-dist/server/assets/{vault-BVLp6zu3.js → vault-MINXmyXA.js} +1 -1
  380. package/studio-dist/server/assets/{views-flRUr21z.js → views-DrmY_3J5.js} +7 -4
  381. package/studio-dist/server/assets/{warnings-CDy9pdgL.js → warnings-BVZCDbIz.js} +2 -2
  382. package/studio-dist/server/assets/{workflow-D9GKI2EV.js → workflow-DFdqnMtW.js} +57 -50
  383. package/studio-dist/server/server.js +2 -2
  384. package/tool-manifest.yaml +85 -0
  385. package/src/cli/commands/factory/factory.ts +0 -311
  386. package/src/cli/commands/studio/factory-credential.ts +0 -35
  387. package/src/cli/commands/studio/factory-git-tokens.ts +0 -40
  388. package/src/cli/commands/studio/factory-relay.ts +0 -18
  389. package/src/cli/commands/studio/repository-add.ts +0 -116
  390. package/src/cli/commands/studio/workset-session.ts +0 -164
  391. package/src/lib/delivery/archive-change.ts +0 -165
  392. package/src/lib/delivery/forge.ts +0 -279
  393. package/src/lib/delivery/token.ts +0 -24
  394. package/src/lib/factory/attach-client.ts +0 -123
  395. package/src/lib/factory/attach.ts +0 -178
  396. package/src/lib/factory/broker.ts +0 -187
  397. package/src/lib/factory/bun-commands.ts +0 -39
  398. package/src/lib/factory/client.ts +0 -113
  399. package/src/lib/factory/clone-url.ts +0 -39
  400. package/src/lib/factory/command.ts +0 -77
  401. package/src/lib/factory/credential-store.ts +0 -153
  402. package/src/lib/factory/frames.ts +0 -77
  403. package/src/lib/factory/git-auth.ts +0 -61
  404. package/src/lib/factory/git-credential-store.ts +0 -181
  405. package/src/lib/factory/ids.ts +0 -68
  406. package/src/lib/factory/outcomes/actions.ts +0 -130
  407. package/src/lib/factory/outcomes/index.ts +0 -457
  408. package/src/lib/factory/outcomes/lifecycle.ts +0 -212
  409. package/src/lib/factory/outcomes/runs.ts +0 -81
  410. package/src/lib/factory/prepare.ts +0 -55
  411. package/src/lib/factory/pty.ts +0 -103
  412. package/src/lib/factory/runner/companion-context.ts +0 -178
  413. package/src/lib/factory/runner/control.ts +0 -92
  414. package/src/lib/factory/runner/harness-agent.ts +0 -250
  415. package/src/lib/factory/runner/live.ts +0 -159
  416. package/src/lib/factory/runner/questions.ts +0 -22
  417. package/src/lib/factory/runner/rank.ts +0 -26
  418. package/src/lib/factory/runner/run-policy.ts +0 -12
  419. package/src/lib/factory/runner/run.ts +0 -199
  420. package/src/lib/factory/runner/scheduler.ts +0 -498
  421. package/src/lib/factory/runner/state.ts +0 -233
  422. package/src/lib/factory/runner/workflow.ts +0 -546
  423. package/src/lib/factory/runtime.ts +0 -1081
  424. package/src/lib/factory/sandbox.ts +0 -292
  425. package/src/lib/factory/worktree-branch.ts +0 -17
  426. package/src/templates/capabilities/openspec-cap/mate-v1/templates/explore-brief.md +0 -25
  427. package/studio-dist/client/assets/app-D9cw6szy.css +0 -2
  428. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +0 -1
  429. package/studio-dist/client/assets/button-Br0O1sXw.js +0 -1
  430. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +0 -1
  431. package/studio-dist/client/assets/factory-DGS0E16C.js +0 -6
  432. package/studio-dist/client/assets/fields-6aXBpFhJ.js +0 -1
  433. package/studio-dist/client/assets/getting-started-Clde4w6P.js +0 -1
  434. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +0 -1
  435. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +0 -1
  436. package/studio-dist/client/assets/graph-B_TCBVbu.js +0 -2
  437. package/studio-dist/client/assets/guides-Du_RtJxP.js +0 -1
  438. package/studio-dist/client/assets/index-Df8L1LQa.js +0 -40
  439. package/studio-dist/client/assets/panel-dbmCx7Mx.js +0 -1
  440. package/studio-dist/client/assets/react-3QStrcDO.js +0 -27
  441. package/studio-dist/client/assets/report-url-XRL0x1SY.js +0 -1
  442. package/studio-dist/client/assets/reports-r3IK7Doz.js +0 -1
  443. package/studio-dist/client/assets/routes-C0A5LTFc.js +0 -1
  444. package/studio-dist/client/assets/select-CnaMd617.js +0 -1
  445. package/studio-dist/client/assets/skills-CzjzHpBT.js +0 -1
  446. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +0 -1
  447. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +0 -1
  448. package/studio-dist/client/assets/steps-C0p2N1Pb.js +0 -1
  449. package/studio-dist/client/assets/store-Dw34catY.js +0 -1
  450. package/studio-dist/client/assets/studio-Cpz_HRHp.js +0 -100
  451. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +0 -2
  452. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +0 -1
  453. package/studio-dist/client/assets/useMutation-aAr2uiay.js +0 -1
  454. package/studio-dist/client/assets/vault-BGcxkSIY.js +0 -1
  455. package/studio-dist/client/assets/warnings-R1cE1rLf.js +0 -1
  456. package/studio-dist/client/assets/workflow-C2qTrMDH.js +0 -1
  457. package/studio-dist/server/assets/actions-DYSv-9VV.js +0 -60
  458. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +0 -216
  459. package/studio-dist/server/assets/factory-C7Ybg0xG.js +0 -3075
  460. package/studio-dist/server/assets/factory-Df5uAHjb.js +0 -116
  461. package/studio-dist/server/assets/react-CdqSUhaL.js +0 -89
  462. package/studio-dist/server/assets/report-url-BUXPcE_8.js +0 -9
  463. package/studio-dist/server/assets/search-BJnWLfkG.js +0 -55
  464. package/studio-dist/server/assets/spinner-CdwJW4VB.js +0 -20
  465. package/studio-dist/server/assets/store-Cs17okNG.js +0 -280
  466. /package/src/lib/{factory/keyed-serial.ts → keyed-serial.ts} +0 -0
  467. /package/src/templates/capabilities/openspec-cap/{mate-v1 → mate-full}/templates/spec.md +0 -0
@@ -0,0 +1,922 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { parse } from "yaml";
6
+
7
+ import { isChangeName } from "../../change-layout";
8
+ import { scopedRepositories } from "../../openspec-scopes";
9
+ import { FRAMEWORK_NAME } from "../../../framework";
10
+ import {
11
+ companionGit,
12
+ LITERAL_PATHSPECS,
13
+ nulPaths,
14
+ outputLines,
15
+ type CompanionGit,
16
+ } from "../../../runtime/companion-git";
17
+ import { readSubmittedFolders } from "../../../runtime/companion-git-state";
18
+ import { isWithin } from "../../../runtime/physical-path";
19
+ import {
20
+ inboxText,
21
+ isSubmittedName,
22
+ matchingArchive,
23
+ sameTextBesidesLineEndings,
24
+ submitters,
25
+ } from "../../../runtime/pending-records";
26
+ import { blobsAt } from "../../../runtime/submitted-arrivals";
27
+ import { errorMessage } from "../../../runtime/error-message";
28
+ import type { DeliveryEnvironment } from "../environment";
29
+ import { declaredDependencies } from "../overlap";
30
+ import {
31
+ findDelivery,
32
+ isPublishable,
33
+ readDeliveryState,
34
+ sameRepository,
35
+ settleDelivery,
36
+ upsertDelivery,
37
+ type DeliveryBlock,
38
+ type DeliveryRecord,
39
+ type DeliveryState,
40
+ type MergeSource,
41
+ } from "../record";
42
+ import type { ArtifactType, StalePart } from "./artifact-type";
43
+ import { findLinkedMerges, settleable, type UncheckedDelivery } from "./linked-merges";
44
+ import type { DeltaFailure } from "./replay";
45
+ import { deliveryGroupFor } from "./naming";
46
+ import {
47
+ defaultRef,
48
+ fetchPendingBranches,
49
+ lastFetchedAt,
50
+ mapLimited,
51
+ pendingRef,
52
+ recordsAt,
53
+ stagingRemote,
54
+ type StagingRemote,
55
+ type TrailerRecord,
56
+ } from "./refs";
57
+ import { defaultArtifactType } from "./registry";
58
+
59
+ /** A change submitted on the pending branch, read from its folder there. */
60
+ export interface SubmittedChange {
61
+ name: string;
62
+ /** Its Delivery Group. */
63
+ group: string;
64
+ /** Companion-relative source folder. */
65
+ path: string;
66
+ /** Its Delivery Record, settled against its scopes. */
67
+ delivery: DeliveryState;
68
+ /** The repositories it is scoped to. */
69
+ scoped: string[];
70
+ blocked?: DeliveryBlock;
71
+ specBase?: string;
72
+ /** Change names it declares in `dependsOn`. */
73
+ dependsOn: string[];
74
+ /** The parts it rewrites or removes, as its type reads them; empty for a type that cannot. */
75
+ touches: StalePart[];
76
+ }
77
+
78
+ /** Concurrent folders read at once; each runs a few Git processes. */
79
+ const READ_CONCURRENCY = 4;
80
+
81
+ /** Folders listed by one `git ls-tree`, which keeps its arguments far below the system's limit. */
82
+ const LIST_CHUNK = 200;
83
+
84
+ /** Files written at once. */
85
+ const WRITE_CONCURRENCY = 16;
86
+
87
+ /** Companion-relative source folder of change `name`. */
88
+ export function sourcePathOf(type: ArtifactType, name: string): string {
89
+ return `${type.source}/${name}`;
90
+ }
91
+
92
+ /** Change names with a source folder at `ref`, the archive folder left out. */
93
+ async function sourceNamesAt(
94
+ git: CompanionGit,
95
+ ref: string,
96
+ type: ArtifactType,
97
+ ): Promise<string[]> {
98
+ const listed = await git.run([
99
+ "ls-tree",
100
+ "-d",
101
+ "-z",
102
+ "--name-only",
103
+ "--end-of-options",
104
+ ref,
105
+ "--",
106
+ `${type.source}/`,
107
+ ]);
108
+ if (listed.status !== 0) return [];
109
+ return nulPaths(listed.stdout)
110
+ .filter((entry) => entry !== type.archiveRoot)
111
+ .map((entry) => path.posix.basename(entry))
112
+ .filter((name) => isChangeName(name) && isSubmittedName(name));
113
+ }
114
+
115
+ /** Submit orders by commit and source folder: a commit's history never changes. */
116
+ const submitOrders = new Map<string, string[]>();
117
+
118
+ /** Orders kept; a run reads a handful of inbox tips. */
119
+ const SUBMIT_ORDERS_KEPT = 8;
120
+
121
+ /**
122
+ * Folder names below the source in the order a commit first added them at `ref`. The walk reads
123
+ * the inbox's whole history, so it runs once per inbox tip in a process.
124
+ */
125
+ async function submitOrder(git: CompanionGit, ref: string, type: ArtifactType): Promise<string[]> {
126
+ const tip = await git.run(["rev-parse", "--verify", "-q", "--end-of-options", `${ref}^{commit}`]);
127
+ const key = tip.status === 0 && tip.stdout.trim() ? `${tip.stdout.trim()}\0${type.source}` : null;
128
+ const known = key === null ? undefined : submitOrders.get(key);
129
+ if (known) return known;
130
+ const order = await walkSubmitOrder(git, ref, type);
131
+ if (key !== null && order !== null) {
132
+ if (submitOrders.size >= SUBMIT_ORDERS_KEPT) {
133
+ submitOrders.delete(submitOrders.keys().next().value!);
134
+ }
135
+ submitOrders.set(key, order);
136
+ }
137
+ return order ?? [];
138
+ }
139
+
140
+ /** {@link submitOrder}, read from Git; null when the walk fails. */
141
+ async function walkSubmitOrder(
142
+ git: CompanionGit,
143
+ ref: string,
144
+ type: ArtifactType,
145
+ ): Promise<string[] | null> {
146
+ const log = await git.run([
147
+ "log",
148
+ "--reverse",
149
+ "--diff-filter=A",
150
+ "--format=",
151
+ "--name-only",
152
+ "-z",
153
+ "--end-of-options",
154
+ ref,
155
+ "--",
156
+ `${type.source}/`,
157
+ ]);
158
+ if (log.status !== 0) return null;
159
+ const prefix = `${type.source}/`;
160
+ const order: string[] = [];
161
+ for (const file of nulPaths(log.stdout)) {
162
+ const name = file.trim().slice(prefix.length).split("/")[0];
163
+ if (file.trim().startsWith(prefix) && name && !order.includes(name)) order.push(name);
164
+ }
165
+ return order;
166
+ }
167
+
168
+ /**
169
+ * Writes the Delivery Record and Markdown files of the change folders `names` at `ref` into one
170
+ * folder each below `scratch`, with one listing per {@link LIST_CHUNK} folders and one batched
171
+ * read, so the number of Git processes does not grow with the files. Contents are decoded as
172
+ * text. A folder holding a path that would leave it (a crafted tree) is left out.
173
+ */
174
+ async function materializeChanges(
175
+ git: CompanionGit,
176
+ ref: string,
177
+ type: ArtifactType,
178
+ names: readonly string[],
179
+ scratch: string,
180
+ ): Promise<void> {
181
+ const files: { name: string; id: string; target: string }[] = [];
182
+ const unsafe = new Set<string>();
183
+ for (let at = 0; at < names.length; at += LIST_CHUNK) {
184
+ const folders = names.slice(at, at + LIST_CHUNK).map((name) => `${sourcePathOf(type, name)}/`);
185
+ // oxlint-disable-next-line no-await-in-loop -- one listing per chunk, in order
186
+ const listed = await git.run([
187
+ "ls-tree",
188
+ "-r",
189
+ "-z",
190
+ "--end-of-options",
191
+ ref,
192
+ "--",
193
+ ...folders,
194
+ ]);
195
+ if (listed.status !== 0) continue;
196
+ for (const entry of nulPaths(listed.stdout)) {
197
+ const tab = entry.indexOf("\t");
198
+ if (tab < 0) continue;
199
+ const [, kind, id] = entry.slice(0, tab).split(" ");
200
+ const [name, ...rest] = path.posix.relative(type.source, entry.slice(tab + 1)).split("/");
201
+ const relative = rest.join("/");
202
+ if (kind !== "blob" || !id || !name) continue;
203
+ if (relative !== type.deliveryFile && !relative.endsWith(".md")) continue;
204
+ const dir = path.join(scratch, name);
205
+ const target = path.join(dir, ...rest);
206
+ if (target === dir || !isWithin(target, dir)) unsafe.add(name);
207
+ else files.push({ name, id, target });
208
+ }
209
+ }
210
+ const blobs = await git.readBlobs([...new Set(files.map((file) => file.id))]);
211
+ if (!blobs) return;
212
+ await mapLimited(
213
+ files.filter((file) => !unsafe.has(file.name)),
214
+ WRITE_CONCURRENCY,
215
+ async ({ id, target }) => {
216
+ const text = blobs.get(id);
217
+ if (text === undefined) return;
218
+ await fs.mkdir(path.dirname(target), { recursive: true });
219
+ await fs.writeFile(target, text);
220
+ },
221
+ );
222
+ }
223
+
224
+ /** Compares change names as Git lists the folders one commit adds: `acme-a-b/` before `acme-a/`. */
225
+ export function byFolderPath(a: string, b: string): number {
226
+ return `${a}/` < `${b}/` ? -1 : `${a}/` > `${b}/` ? 1 : 0;
227
+ }
228
+
229
+ /** Compares change names by their place in `order`, then by `tie`; names not in it go last. */
230
+ export function bySubmitOrder(
231
+ order: readonly string[],
232
+ tie: (a: string, b: string) => number = (a, b) => a.localeCompare(b),
233
+ ): (a: string, b: string) => number {
234
+ const rank = (name: string): number => {
235
+ const at = order.indexOf(name);
236
+ return at === -1 ? order.length : at;
237
+ };
238
+ return (a, b) => rank(a) - rank(b) || tie(a, b);
239
+ }
240
+
241
+ /**
242
+ * The changes of `type` submitted at `ref` (`state: submitted` in their Delivery Record), in
243
+ * submit order, then by name; with `only`, just those of that name. Only each folder's Delivery
244
+ * Record and Markdown files are read, into a scratch folder below `tmpRoot` that is removed
245
+ * afterwards.
246
+ */
247
+ export async function submittedAt(
248
+ git: CompanionGit,
249
+ ref: string,
250
+ type: ArtifactType,
251
+ tmpRoot?: string,
252
+ only?: readonly string[],
253
+ ): Promise<SubmittedChange[]> {
254
+ const names = (await sourceNamesAt(git, ref, type)).filter(
255
+ (name) => only === undefined || only.includes(name),
256
+ );
257
+ if (names.length === 0) return [];
258
+ const scratch = await fs.mkdtemp(
259
+ path.join(tmpRoot ?? os.tmpdir(), `${FRAMEWORK_NAME}-submitted-`),
260
+ );
261
+ try {
262
+ await materializeChanges(git, ref, type, names, scratch);
263
+ const read = await mapLimited(names, READ_CONCURRENCY, async (name) => {
264
+ const dir = path.join(scratch, name);
265
+ const delivery = await readDeliveryState(dir);
266
+ if (delivery.record?.state !== "submitted") return null;
267
+ const { record } = delivery;
268
+ const scoped = await scopedRepositories(dir);
269
+ return {
270
+ name,
271
+ group: deliveryGroupFor(name, record, scoped).group,
272
+ path: sourcePathOf(type, name),
273
+ delivery,
274
+ scoped,
275
+ ...(record.blocked ? { blocked: record.blocked } : {}),
276
+ ...(record.specBase ? { specBase: record.specBase } : {}),
277
+ dependsOn: await declaredDependencies(dir),
278
+ touches: (await type.touches?.(dir)) ?? [],
279
+ } satisfies SubmittedChange;
280
+ });
281
+ const found = read.filter((entry): entry is SubmittedChange => entry !== null);
282
+ // One change needs no order.
283
+ const order = found.length > 1 ? await submitOrder(git, ref, type) : [];
284
+ const compare = bySubmitOrder(order);
285
+ return found.toSorted((a, b) => compare(a.name, b.name));
286
+ } finally {
287
+ await fs.rm(scratch, { recursive: true, force: true });
288
+ }
289
+ }
290
+
291
+ /** Blob ids by path relative to `prefix` at `ref`, the delivery file left out. */
292
+ async function contentAt(
293
+ git: CompanionGit,
294
+ ref: string,
295
+ prefix: string,
296
+ type: ArtifactType,
297
+ ): Promise<Map<string, string>> {
298
+ const blobs = await blobsAt(git, ref, prefix);
299
+ blobs.delete(type.deliveryFile);
300
+ return blobs;
301
+ }
302
+
303
+ /**
304
+ * The record on `defaultRef` that change `name` at `pendingRef` was published as: an archive of
305
+ * that name holding the same files, line endings and its Delivery Record aside (publication
306
+ * settles it). Null while unpublished. `records` are those on `defaultRef`, when the caller
307
+ * listed them with {@link recordsAt}.
308
+ */
309
+ export async function publishedAs(
310
+ git: CompanionGit,
311
+ defaultTip: string,
312
+ pendingTip: string,
313
+ type: ArtifactType,
314
+ name: string,
315
+ records?: readonly TrailerRecord[],
316
+ ): Promise<string | null> {
317
+ const named = (records ?? (await recordsAt(git, defaultTip, type))).filter(
318
+ (record) => type.recordName(record.id) === name,
319
+ );
320
+ if (named.length === 0) return null;
321
+ const { archiveRoot } = type;
322
+ if (archiveRoot === undefined) return publishedByTrailer(git, pendingTip, type, name, named);
323
+ return matchingArchive(
324
+ named.map((record) => record.id),
325
+ await contentAt(git, pendingTip, sourcePathOf(type, name), type),
326
+ (record) => contentAt(git, defaultTip, `${archiveRoot}/${record}`, type),
327
+ async (source, archived) => {
328
+ const texts = await git.readBlobs([source, archived]);
329
+ const [mine, theirs] = [texts?.get(source), texts?.get(archived)];
330
+ return mine !== undefined && theirs !== undefined && sameTextBesidesLineEndings(mine, theirs);
331
+ },
332
+ );
333
+ }
334
+
335
+ /** The commit on `ref` that last changed the folder `folder`, its Delivery Record aside. */
336
+ async function folderWrittenBy(
337
+ git: CompanionGit,
338
+ ref: string,
339
+ folder: string,
340
+ type: Pick<ArtifactType, "deliveryFile">,
341
+ ): Promise<string | null> {
342
+ const written = await git.run([
343
+ "log",
344
+ "-1",
345
+ "--format=%H",
346
+ "--end-of-options",
347
+ ref,
348
+ "--",
349
+ `:(literal)${folder}/`,
350
+ `:(exclude,literal)${folder}/${type.deliveryFile}`,
351
+ ]);
352
+ return written.status === 0 ? (outputLines(written.stdout)[0] ?? null) : null;
353
+ }
354
+
355
+ /**
356
+ * {@link publishedAs} for a type that keeps no archive: the newest of `records`, those of that
357
+ * name, published from an inbox commit that already held the folder as `pendingTip` holds it.
358
+ * Ancestry, not commit dates: submitter and publisher clocks may disagree. A later change of
359
+ * the same name was written after that commit, so it does not count.
360
+ */
361
+ async function publishedByTrailer(
362
+ git: CompanionGit,
363
+ pendingTip: string,
364
+ type: ArtifactType,
365
+ name: string,
366
+ records: readonly TrailerRecord[],
367
+ ): Promise<string | null> {
368
+ const written = await folderWrittenBy(git, pendingTip, sourcePathOf(type, name), type);
369
+ if (written === null) return null;
370
+ for (const record of records) {
371
+ if (record.inbox === null) continue;
372
+ // oxlint-disable-next-line no-await-in-loop -- newest first, usually the first
373
+ const held = await git.run(["merge-base", "--is-ancestor", written, record.inbox]);
374
+ if (held.status === 0) return record.id;
375
+ }
376
+ return null;
377
+ }
378
+
379
+ /** How far ahead of this clock an inbox commit's date may be and still date a delta. */
380
+ const CLOCK_TOLERANCE_S = 5 * 60;
381
+
382
+ /**
383
+ * The commit a submitted change's delta was written against: its `specBase` when the default
384
+ * branch holds it, else the default tip when the pending branch last changed its folder, at
385
+ * submit or resolution, by that commit's date; edits of its Delivery Record alone (a settlement,
386
+ * a block) do not count. Null when neither is known, or the date is ahead of this clock.
387
+ */
388
+ export async function deltaBase(
389
+ git: CompanionGit,
390
+ defaultTip: string,
391
+ pendingTip: string,
392
+ change: Pick<SubmittedChange, "path" | "specBase">,
393
+ type: Pick<ArtifactType, "deliveryFile">,
394
+ ): Promise<string | null> {
395
+ if (change.specBase) {
396
+ const held = await git.run(["merge-base", "--is-ancestor", change.specBase, defaultTip]);
397
+ if (held.status === 0) return change.specBase;
398
+ }
399
+ const written = await git.run([
400
+ "log",
401
+ "-1",
402
+ "--format=%ct",
403
+ "--end-of-options",
404
+ pendingTip,
405
+ "--",
406
+ // Literal: a change name is no glob pattern.
407
+ `:(literal)${change.path}/`,
408
+ `:(exclude,literal)${change.path}/${type.deliveryFile}`,
409
+ ]);
410
+ const at = outputLines(written.stdout)[0];
411
+ if (written.status !== 0 || !at) return null;
412
+ // A date ahead of this clock would name the current tip, and nothing would be stale.
413
+ if (!(Number(at) <= Date.now() / 1000 + CLOCK_TOLERANCE_S)) return null;
414
+ const tip = await git.run([
415
+ "rev-list",
416
+ "-1",
417
+ "--first-parent",
418
+ `--before=${at}`,
419
+ "--end-of-options",
420
+ defaultTip,
421
+ ]);
422
+ return tip.status === 0 ? (outputLines(tip.stdout)[0] ?? null) : null;
423
+ }
424
+
425
+ /** Bound on the stale parts one scan collects. */
426
+ export const STALE_SCAN_LIMIT = 50;
427
+
428
+ /**
429
+ * Every part the change at `sourcePath` in `ref` changes that changed between `base` and `tip`,
430
+ * up to {@link STALE_SCAN_LIMIT}; none for a type without a stale check.
431
+ */
432
+ export async function staleParts(
433
+ type: Pick<ArtifactType, "stale">,
434
+ git: CompanionGit,
435
+ ref: string,
436
+ sourcePath: string,
437
+ base: string,
438
+ tip: string,
439
+ ): Promise<DeltaFailure[]> {
440
+ const found: DeltaFailure[] = [];
441
+ while (type.stale && found.length < STALE_SCAN_LIMIT) {
442
+ // oxlint-disable-next-line no-await-in-loop -- each call skips what the earlier ones found
443
+ const next = await type.stale(git, ref, sourcePath, base, tip, found);
444
+ if (!next) break;
445
+ found.push(next);
446
+ }
447
+ return found;
448
+ }
449
+
450
+ /**
451
+ * `changes` ordered so each comes after the ones it declares in `dependsOn` among them, else in
452
+ * their given order. A cycle keeps the given order for its members.
453
+ */
454
+ export function orderByDependencies<T extends { name: string; dependsOn: readonly string[] }>(
455
+ changes: readonly T[],
456
+ ): T[] {
457
+ const ordered: T[] = [];
458
+ const visiting = new Set<string>();
459
+ const visit = (change: T): void => {
460
+ if (ordered.includes(change) || visiting.has(change.name)) return;
461
+ visiting.add(change.name);
462
+ for (const dependency of change.dependsOn) {
463
+ const found = changes.find((entry) => entry.name === dependency);
464
+ if (found) visit(found);
465
+ }
466
+ ordered.push(change);
467
+ };
468
+ for (const change of changes) visit(change);
469
+ return ordered;
470
+ }
471
+
472
+ /**
473
+ * A final merge result a submitted change records, with who recorded it. The inbox takes any
474
+ * teammate's push and Git's author is what the pusher wrote, so this says whose claim a
475
+ * publication rests on; it proves nothing.
476
+ */
477
+ export interface MergeClaim {
478
+ repository: string;
479
+ state: "merged" | "dropped";
480
+ /** `git`: a checkout found the merge; `user`: someone answered. */
481
+ source: MergeSource;
482
+ /** Who committed it to the inbox; absent when Git cannot say or it is not committed yet. */
483
+ recordedBy?: string;
484
+ /** Committed with your Git email, or recorded in this run. */
485
+ yours: boolean;
486
+ }
487
+
488
+ /** Inbox commits of one Delivery Record read for {@link mergeClaims}. */
489
+ const CLAIM_HISTORY = 50;
490
+
491
+ /** What identifies a recorded merge result of `repository` in a Delivery Record's YAML. */
492
+ function claimKey(yaml: string | undefined, repository: string): string | null {
493
+ if (yaml === undefined) return null;
494
+ try {
495
+ const deliveries = (parse(yaml) as { deliveries?: unknown } | null)?.deliveries;
496
+ for (const entry of Array.isArray(deliveries) ? deliveries : []) {
497
+ const delivery = (entry ?? {}) as { repository?: unknown; merge?: unknown };
498
+ if (typeof delivery.repository !== "string") continue;
499
+ if (!sameRepository(delivery.repository, repository)) continue;
500
+ const merge = (delivery.merge ?? null) as Record<string, unknown> | null;
501
+ return merge && typeof merge === "object"
502
+ ? JSON.stringify([merge.state, merge.source, merge.checkedAt, merge.mergeCommit])
503
+ : null;
504
+ }
505
+ } catch {
506
+ // An unreadable earlier version recorded nothing.
507
+ }
508
+ return null;
509
+ }
510
+
511
+ /**
512
+ * The final merge results `record` holds for the change at `changePath`, each with the author
513
+ * of the inbox commit at or before `ref` that first recorded it as it reads now: a later commit
514
+ * that only blocks or resolves the change keeps the claim its recorder's. A result `ref` does
515
+ * not hold yet was recorded in this run and is `yours`.
516
+ */
517
+ export async function mergeClaims(
518
+ git: CompanionGit,
519
+ ref: string,
520
+ changePath: string,
521
+ record: DeliveryRecord | null,
522
+ type: Pick<ArtifactType, "deliveryFile">,
523
+ ): Promise<MergeClaim[]> {
524
+ const settled = (record?.deliveries ?? []).filter(
525
+ (delivery) => delivery.merge !== undefined && delivery.merge.state !== "open",
526
+ );
527
+ if (settled.length === 0) return [];
528
+ const file = `${changePath}/${type.deliveryFile}`;
529
+ const [log, configured] = await Promise.all([
530
+ git.run([
531
+ ...LITERAL_PATHSPECS,
532
+ "log",
533
+ `-n${CLAIM_HISTORY}`,
534
+ "--format=%H%x02%an%x02%ae",
535
+ "--end-of-options",
536
+ ref,
537
+ "--",
538
+ file,
539
+ ]),
540
+ git.run(["config", "--get", "user.email"]),
541
+ ]);
542
+ const commits = (log.status === 0 ? outputLines(log.stdout) : []).map((line) => {
543
+ const [id = "", name = "", email = ""] = line.split("\x02");
544
+ return { spec: `${id}:${file}`, name, email };
545
+ });
546
+ const texts = await git.readBlobs(commits.map((commit) => commit.spec));
547
+ // Without the history nobody is named, and nothing counts as yours.
548
+ const known = log.status === 0 && texts !== null;
549
+ const mine = configured.status === 0 ? configured.stdout.trim().toLowerCase() : "";
550
+ return settled.map((delivery) => {
551
+ const merge = delivery.merge!;
552
+ const key = JSON.stringify([merge.state, merge.source, merge.checkedAt, merge.mergeCommit]);
553
+ let recorder: (typeof commits)[number] | undefined;
554
+ for (const commit of commits) {
555
+ if (claimKey(texts?.get(commit.spec), delivery.repository) !== key) break;
556
+ recorder = commit;
557
+ }
558
+ return {
559
+ repository: delivery.repository,
560
+ state: merge.state as MergeClaim["state"],
561
+ source: merge.source,
562
+ ...(recorder?.name ? { recordedBy: recorder.name } : {}),
563
+ // Not at `ref` when its newest commit lacks it: recorded in this run.
564
+ yours:
565
+ known && (recorder === undefined || (mine !== "" && recorder.email.toLowerCase() === mine)),
566
+ };
567
+ });
568
+ }
569
+
570
+ /** True for a claim someone else answered: no checkout found the merge, and it is not yours. */
571
+ export function isOthersAnswer(claim: MergeClaim): boolean {
572
+ return !claim.yours && claim.source !== "git";
573
+ }
574
+
575
+ /** Why a submitted change's delivery keeps its group unpublished, or null when it may publish. */
576
+ export function deliveryHold(change: SubmittedChange): string | null {
577
+ const { delivery } = change;
578
+ if (delivery.error) return `${change.name} (unreadable delivery: ${inboxText(delivery.error)})`;
579
+ if (isPublishable(delivery.status) && delivery.missing.length === 0) return null;
580
+ const waiting =
581
+ delivery.unsettled.length > 0 ? `: ${delivery.unsettled.map(inboxText).join(", ")}` : "";
582
+ return `${change.name} (${delivery.status}${waiting})`;
583
+ }
584
+
585
+ /** A Delivery Group of submitted changes, in publication order. */
586
+ export interface SubmittedGroup {
587
+ group: string;
588
+ changes: SubmittedChange[];
589
+ }
590
+
591
+ /** `submitted` by Delivery Group, groups in the submit order of their first change. */
592
+ export function groupsOf(submitted: readonly SubmittedChange[]): SubmittedGroup[] {
593
+ const groups: SubmittedGroup[] = [];
594
+ for (const change of submitted) {
595
+ const group = groups.find((entry) => entry.group === change.group);
596
+ if (group) group.changes.push(change);
597
+ else groups.push({ group: change.group, changes: [change] });
598
+ }
599
+ return groups.map((entry) => ({ ...entry, changes: orderByDependencies(entry.changes) }));
600
+ }
601
+
602
+ /** The changes of other groups that `group`'s changes depend on and that are still submitted. */
603
+ export function unpublishedDependencies(
604
+ group: SubmittedGroup,
605
+ submitted: readonly SubmittedChange[],
606
+ ): SubmittedChange[] {
607
+ const own = new Set(group.changes.map((change) => change.name));
608
+ const names = new Set(
609
+ group.changes.flatMap((change) => change.dependsOn).filter((name) => !own.has(name)),
610
+ );
611
+ return submitted.filter((change) => names.has(change.name));
612
+ }
613
+
614
+ /**
615
+ * Groups ordered so a group comes after the groups its changes depend on, else in submit
616
+ * order; `publish --all` publishes them in this order.
617
+ */
618
+ export function publicationOrder(
619
+ groups: readonly SubmittedGroup[],
620
+ submitted: readonly SubmittedChange[],
621
+ ): SubmittedGroup[] {
622
+ const withDependencies = groups.map((group) => ({
623
+ group,
624
+ name: group.group,
625
+ dependsOn: [
626
+ ...new Set(unpublishedDependencies(group, submitted).map((change) => change.group)),
627
+ ],
628
+ }));
629
+ return orderByDependencies(withDependencies).map((entry) => entry.group);
630
+ }
631
+
632
+ /**
633
+ * Whether every group's changes may publish: each delivery settled, and each group its changes
634
+ * depend on publishable too, so both publish in one run. Keyed by group.
635
+ */
636
+ function publishableGroups(
637
+ groups: readonly SubmittedGroup[],
638
+ submitted: readonly SubmittedChange[],
639
+ ): Map<string, boolean> {
640
+ const verdicts = new Map<string, boolean>();
641
+ const visit = (group: SubmittedGroup, seen: ReadonlySet<string>): boolean => {
642
+ const known = verdicts.get(group.group);
643
+ if (known !== undefined) return known;
644
+ if (seen.has(group.group)) return false;
645
+ const next = new Set([...seen, group.group]);
646
+ const verdict =
647
+ group.changes.every((change) => deliveryHold(change) === null) &&
648
+ [...new Set(unpublishedDependencies(group, submitted).map((change) => change.group))].every(
649
+ (name) => {
650
+ const dependency = groups.find((entry) => entry.group === name);
651
+ return dependency !== undefined && visit(dependency, next);
652
+ },
653
+ );
654
+ verdicts.set(group.group, verdict);
655
+ return verdict;
656
+ };
657
+ for (const group of groups) visit(group, new Set());
658
+ return verdicts;
659
+ }
660
+
661
+ /** A submitted change as `mate artifact pending` lists it. */
662
+ export interface SubmittedChangeView {
663
+ name: string;
664
+ delivery: DeliveryState;
665
+ blocked?: DeliveryBlock;
666
+ dependsOn: string[];
667
+ /** The parts it rewrites or removes; see {@link SubmittedChange.touches}. */
668
+ touches: StalePart[];
669
+ /** Its folder on the pending branch, readable as `git show <ref>:<path>/<file>`. */
670
+ path: string;
671
+ /** `yours`: committed with your Git email or submitted from this checkout; else `others`. */
672
+ origin: "yours" | "others";
673
+ /** Who submitted it, by the pending branch's history; absent when Git cannot say. */
674
+ author?: string;
675
+ /** Its final merge results on the pending branch and who recorded each; see {@link MergeClaim}. */
676
+ merges: MergeClaim[];
677
+ /** Deliveries whose merge this run's check found and nothing recorded yet; absent when none. */
678
+ found?: FoundDelivery[];
679
+ }
680
+
681
+ export interface SubmittedGroupView {
682
+ group: string;
683
+ changes: SubmittedChangeView[];
684
+ /** A change of it records a block. */
685
+ blocked: boolean;
686
+ /** Every delivery is settled and no unpublishable group holds it; one selection publishes it. */
687
+ publishable: boolean;
688
+ /** Changes of other groups it depends on whose group cannot publish yet. */
689
+ heldBy: string[];
690
+ /**
691
+ * Publishable only through a merge in `found`, of its own or of a dependency's group: publish
692
+ * it with `--refresh`, which records that merge.
693
+ */
694
+ needsRefresh?: true;
695
+ }
696
+
697
+ /** A branch delivery of one repository. */
698
+ export interface FoundDelivery {
699
+ repository: string;
700
+ branch: string;
701
+ }
702
+
703
+ /** The local merge check of one discovery; see {@link DiscoverSubmittedOptions.checkMerges}. */
704
+ export interface MergeCheck {
705
+ /** False when the check was not asked for or could not run. */
706
+ ran: boolean;
707
+ /** Linked deliveries not checked in time, or whose check failed; their stored state stands. */
708
+ unchecked: (FoundDelivery & { change: string })[];
709
+ /** Why the check, or some delivery's check, failed. */
710
+ warning?: string;
711
+ }
712
+
713
+ /** `stale`: the fetch failed or was not attempted; the refs are the last fetched ones. */
714
+ export interface SubmittedDiscovery {
715
+ pendingBranch: string | null;
716
+ /** The pending branch's remote-tracking ref as last fetched; absent without an upstream. */
717
+ ref?: string;
718
+ fetchedAt: string | null;
719
+ stale: boolean;
720
+ error?: string;
721
+ groups: SubmittedGroupView[];
722
+ /** Present when the caller asked for the merge check. */
723
+ mergeCheck?: MergeCheck;
724
+ }
725
+
726
+ /** `changes` at `ref` without those the default branch already archived. */
727
+ async function withoutPublished(
728
+ git: CompanionGit,
729
+ remote: StagingRemote,
730
+ ref: string,
731
+ type: ArtifactType,
732
+ changes: SubmittedChange[],
733
+ ): Promise<SubmittedChange[]> {
734
+ const records = await recordsAt(git, defaultRef(remote), type);
735
+ const published = await mapLimited(changes, READ_CONCURRENCY, (change) =>
736
+ publishedAs(git, defaultRef(remote), ref, type, change.name, records),
737
+ );
738
+ return changes.filter((_, index) => published[index] === null);
739
+ }
740
+
741
+ export interface DiscoverSubmittedOptions {
742
+ /** Fetch the default and pending branches first; otherwise use the last fetched refs. */
743
+ fetch: boolean;
744
+ git?: (cwd: string) => CompanionGit;
745
+ tmpRoot?: string;
746
+ type?: ArtifactType;
747
+ /** Home of Mate's local companion state; `HOME` by default. */
748
+ stateHome?: string;
749
+ /**
750
+ * Checks unsettled branch deliveries in the checkouts `environment` links, stopping every check
751
+ * after `budgetMs`, and counts the merges Git proves without recording them. `environment` is
752
+ * resolved only when such a delivery exists. Off when absent.
753
+ */
754
+ checkMerges?: { environment: () => Promise<DeliveryEnvironment>; budgetMs: number };
755
+ }
756
+
757
+ /** Bound on discovery's fetch and reads. */
758
+ const DISCOVERY_BUDGET_MS = 60_000;
759
+
760
+ function discoveryGit(cwd: string): CompanionGit {
761
+ return companionGit(cwd, { prompt: "never", budgetMs: DISCOVERY_BUDGET_MS });
762
+ }
763
+
764
+ /**
765
+ * The submitted changes on the companion's pending branch by Delivery Group, with each one's
766
+ * delivery, block and origin. Read-only apart from the optional fetch; a failed fetch keeps the
767
+ * last fetched state, marked stale.
768
+ */
769
+ export async function discoverSubmitted(
770
+ companionPath: string,
771
+ options: DiscoverSubmittedOptions,
772
+ ): Promise<SubmittedDiscovery> {
773
+ const git = (options.git ?? discoveryGit)(companionPath);
774
+ const remote = await stagingRemote(git);
775
+ if (!remote) {
776
+ return {
777
+ pendingBranch: null,
778
+ fetchedAt: null,
779
+ stale: false,
780
+ groups: [],
781
+ ...(options.checkMerges ? { mergeCheck: { ran: false, unchecked: [] } } : {}),
782
+ };
783
+ }
784
+ let stale = !options.fetch;
785
+ let error: string | undefined;
786
+ if (options.fetch) {
787
+ const fetched = await fetchPendingBranches(git, remote);
788
+ if ("error" in fetched) {
789
+ stale = true;
790
+ error = fetched.error;
791
+ }
792
+ }
793
+ const type = options.type ?? defaultArtifactType();
794
+ // Published, but the inbox was not emptied yet: no longer pending.
795
+ const stored = await withoutPublished(
796
+ git,
797
+ remote,
798
+ pendingRef(remote),
799
+ type,
800
+ await submittedAt(git, pendingRef(remote), type, options.tmpRoot),
801
+ );
802
+ const checked = options.checkMerges
803
+ ? await withFoundMerges(stored, options.checkMerges)
804
+ : { submitted: stored, found: new Map<string, FoundDelivery[]>(), mergeCheck: undefined };
805
+ const { submitted, found, mergeCheck } = checked;
806
+ const who = await submitters(
807
+ companionPath,
808
+ pendingRef(remote),
809
+ submitted.map((change) => change.path),
810
+ readSubmittedFolders(companionPath, options.stateHome),
811
+ );
812
+ const groups = groupsOf(submitted);
813
+ const publishable = publishableGroups(groups, submitted);
814
+ // A group publishable only through a found merge, its own or a dependency's, needs a refresh.
815
+ const storedPublishable =
816
+ found.size > 0 ? publishableGroups(groupsOf(stored), stored) : publishable;
817
+ // Stored records only: a found merge is nobody's claim yet.
818
+ const claims = await mapLimited(stored, READ_CONCURRENCY, (change) =>
819
+ mergeClaims(git, pendingRef(remote), change.path, change.delivery.record, type),
820
+ );
821
+ const merges = new Map(stored.map((change, index) => [change.name, claims[index]!]));
822
+ return {
823
+ pendingBranch: remote.pendingBranch,
824
+ ref: pendingRef(remote),
825
+ fetchedAt: await lastFetchedAt(git),
826
+ stale,
827
+ ...(error ? { error } : {}),
828
+ ...(mergeCheck ? { mergeCheck } : {}),
829
+ groups: groups.map((group) => ({
830
+ group: group.group,
831
+ changes: group.changes.map((change) => {
832
+ const submitter = who.get(change.path);
833
+ return {
834
+ name: change.name,
835
+ delivery: change.delivery,
836
+ ...(change.blocked ? { blocked: change.blocked } : {}),
837
+ dependsOn: change.dependsOn,
838
+ touches: change.touches,
839
+ path: change.path,
840
+ origin: submitter?.mine ? ("yours" as const) : ("others" as const),
841
+ ...(submitter?.author ? { author: submitter.author } : {}),
842
+ merges: merges.get(change.name) ?? [],
843
+ ...(found.has(change.name) ? { found: found.get(change.name)! } : {}),
844
+ };
845
+ }),
846
+ blocked: group.changes.some((change) => change.blocked !== undefined),
847
+ publishable: publishable.get(group.group) === true,
848
+ heldBy: unpublishedDependencies(group, submitted)
849
+ .filter((change) => publishable.get(change.group) !== true)
850
+ .map((change) => change.name),
851
+ ...(publishable.get(group.group) === true && storedPublishable.get(group.group) !== true
852
+ ? { needsRefresh: true as const }
853
+ : {}),
854
+ })),
855
+ };
856
+ }
857
+
858
+ /**
859
+ * `submitted` with each change settled as if the merges the local check proves were recorded,
860
+ * and the deliveries found that way by change. Records nothing: `record` stays the stored one.
861
+ */
862
+ async function withFoundMerges(
863
+ submitted: SubmittedChange[],
864
+ { environment, budgetMs }: NonNullable<DiscoverSubmittedOptions["checkMerges"]>,
865
+ ): Promise<{
866
+ submitted: SubmittedChange[];
867
+ found: Map<string, FoundDelivery[]>;
868
+ mergeCheck: MergeCheck;
869
+ }> {
870
+ if (!submitted.some((change) => change.delivery.record?.deliveries.some(settleable))) {
871
+ return { submitted, found: new Map(), mergeCheck: { ran: true, unchecked: [] } };
872
+ }
873
+ const unchecked: UncheckedDelivery[] = [];
874
+ // Kills the checks' Git commands too, so the budget bounds the whole check.
875
+ const signal = budgetMs > 0 ? AbortSignal.timeout(budgetMs) : AbortSignal.abort();
876
+ let merges: Awaited<ReturnType<typeof findLinkedMerges>>;
877
+ try {
878
+ merges = await findLinkedMerges(await environment(), submitted, {
879
+ signal,
880
+ onUnchecked: (delivery) => unchecked.push(delivery),
881
+ });
882
+ } catch (error) {
883
+ const warning = `could not run: ${errorMessage(error)}`;
884
+ return { submitted, found: new Map(), mergeCheck: { ran: false, unchecked: [], warning } };
885
+ }
886
+ const found = new Map<string, FoundDelivery[]>();
887
+ const next = submitted.map((change) => {
888
+ let record = change.delivery.record;
889
+ const applied: FoundDelivery[] = [];
890
+ for (const { repository, branch, patch } of merges.get(change.name) ?? []) {
891
+ const delivery = record && findDelivery(record, repository);
892
+ if (!record || !delivery || delivery.branch !== branch || !settleable(delivery)) continue;
893
+ record = upsertDelivery(record, repository, patch);
894
+ applied.push({ repository: delivery.repository, branch });
895
+ }
896
+ if (applied.length === 0) return change;
897
+ found.set(change.name, applied);
898
+ return {
899
+ ...change,
900
+ delivery: { ...change.delivery, ...settleDelivery(record, change.scoped) },
901
+ };
902
+ });
903
+ const failures = unchecked
904
+ .filter((delivery) => delivery.error !== undefined)
905
+ .map(
906
+ (failure) =>
907
+ `checking ${failure.branch} in ${failure.repository} failed: ${errorMessage(failure.error)}`,
908
+ );
909
+ return {
910
+ submitted: next,
911
+ found,
912
+ mergeCheck: {
913
+ ran: true,
914
+ unchecked: unchecked.map(({ change, repository, branch }) => ({
915
+ change,
916
+ repository,
917
+ branch,
918
+ })),
919
+ ...(failures.length > 0 ? { warning: failures.join("; ") } : {}),
920
+ },
921
+ };
922
+ }