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

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 (186) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/hooks/hooks.json +21 -1
  3. package/claude-plugin/hooks/session-attention.mjs +10 -0
  4. package/claude-plugin/hooks/session-end.mjs +9 -0
  5. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  6. package/opencode-plugin/src/server.ts +13 -2
  7. package/package.json +1 -1
  8. package/src/cli/commands/artifact/delivery/archive.ts +2 -2
  9. package/src/cli/commands/artifact/delivery/link.ts +22 -5
  10. package/src/cli/commands/artifact/delivery/output.ts +9 -1
  11. package/src/cli/commands/artifact/finish/openspec.ts +1 -3
  12. package/src/cli/commands/companion/companion.ts +1 -1
  13. package/src/cli/commands/companion/link.ts +36 -4
  14. package/src/cli/commands/companion/open.ts +40 -12
  15. package/src/cli/commands/doctor.ts +122 -0
  16. package/src/cli/commands/session/prepare.ts +32 -4
  17. package/src/cli/commands/session/registry.ts +90 -0
  18. package/src/cli/commands/studio/companion-removal.ts +79 -0
  19. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  20. package/src/cli/commands/studio/payload.ts +12 -1
  21. package/src/cli/commands/studio/server.ts +39 -16
  22. package/src/cli/commands/studio/services.ts +20 -0
  23. package/src/cli/commands/studio/skill-files.ts +133 -0
  24. package/src/cli/commands/studio/vault.ts +218 -44
  25. package/src/cli/commands/studio/views/model.ts +0 -5
  26. package/src/cli/commands/studio/views/vault/markdown-tree.ts +255 -4
  27. package/src/cli/commands/unwrap.ts +8 -0
  28. package/src/cli/commands/update.ts +26 -8
  29. package/src/cli/commands/vscode/setup.ts +155 -0
  30. package/src/cli/commands/vscode/vsix.ts +73 -0
  31. package/src/cli/commands/working/cleanup.ts +34 -10
  32. package/src/cli/commands/working/worktree.ts +58 -8
  33. package/src/cli/commands/wrap.ts +33 -7
  34. package/src/cli/main.ts +9 -2
  35. package/src/cli/usage.ts +6 -1
  36. package/src/hooks/companion-instructions.ts +19 -11
  37. package/src/hooks/hook-io.ts +15 -0
  38. package/src/hooks/session-banner.ts +5 -3
  39. package/src/hooks/session-end.ts +10 -0
  40. package/src/hooks/session-guidance.ts +10 -6
  41. package/src/hooks/session-prepare.ts +47 -31
  42. package/src/hooks/session-register.ts +199 -0
  43. package/src/hooks/tokensave-route.ts +7 -3
  44. package/src/hooks/validate-artifact-path.ts +9 -2
  45. package/src/lib/delivery/archive-change.ts +0 -1
  46. package/src/lib/delivery/branches.ts +15 -0
  47. package/src/lib/delivery/record-delivery.ts +94 -39
  48. package/src/lib/delivery/record.ts +30 -28
  49. package/src/lib/delivery/refresh.ts +37 -17
  50. package/src/lib/delivery/resolve-branch.ts +258 -37
  51. package/src/lib/factory/outcomes/index.ts +11 -1
  52. package/src/lib/factory/runtime.ts +10 -1
  53. package/src/lib/opencode-server.ts +238 -0
  54. package/src/lib/orchestrator/adapters/claude.ts +147 -2
  55. package/src/lib/orchestrator/adapters/opencode.ts +53 -2
  56. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  57. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  58. package/src/lib/orchestrator/editor.ts +2 -2
  59. package/src/lib/orchestrator/framework-context.ts +26 -14
  60. package/src/lib/orchestrator/global-config-store.ts +11 -0
  61. package/src/lib/orchestrator/launcher.ts +15 -2
  62. package/src/lib/orchestrator/projection-claude-links.ts +52 -5
  63. package/src/lib/orchestrator/projection-claude-skills.ts +28 -2
  64. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  65. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  66. package/src/lib/orchestrator/repository-link.ts +216 -57
  67. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  68. package/src/lib/orchestrator/session-context-link.ts +11 -5
  69. package/src/lib/orchestrator/session-prepare.ts +36 -6
  70. package/src/lib/orchestrator/types.ts +5 -0
  71. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  72. package/src/lib/public-npm.ts +17 -0
  73. package/src/lib/session-attribution.ts +52 -0
  74. package/src/lib/session-state.ts +285 -0
  75. package/src/lib/session-stop.ts +64 -0
  76. package/src/lib/workset/record.ts +20 -0
  77. package/src/lib/workset/worktree.ts +85 -17
  78. package/src/opencode/background-server.ts +145 -0
  79. package/src/opencode/companion-hooks.ts +3 -1
  80. package/src/opencode/companion-policy.ts +2 -2
  81. package/src/opencode/projected-guidance.ts +2 -1
  82. package/src/opencode/session-register.ts +176 -0
  83. package/src/runtime/claude-delivery-plan.ts +14 -3
  84. package/src/runtime/current-branch.ts +10 -0
  85. package/src/runtime/env.ts +13 -7
  86. package/src/runtime/git-layout.ts +164 -17
  87. package/src/runtime/launch-env-guard.ts +65 -0
  88. package/src/runtime/opencode-server-record.ts +136 -0
  89. package/src/runtime/projection.ts +40 -6
  90. package/src/runtime/repo-local.ts +6 -1
  91. package/src/runtime/serving-claude-wrap.ts +28 -0
  92. package/src/runtime/session-context.ts +4 -3
  93. package/src/runtime/session-registry.ts +434 -0
  94. package/src/runtime/tokensave-route.ts +10 -5
  95. package/src/runtime/wrap-state.ts +31 -0
  96. package/src/studio.ts +2 -0
  97. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +49 -21
  98. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +0 -5
  99. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +2 -8
  100. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +1 -3
  101. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -4
  102. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +49 -21
  103. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +0 -5
  104. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +2 -8
  105. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +1 -3
  106. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -4
  107. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +404 -30
  108. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -3
  109. package/src/tools/setup/providers/claude-plugin-hooks.ts +26 -0
  110. package/src/tools/setup/providers/claude.ts +21 -1
  111. package/studio-dist/client/assets/app-CdPiFv59.css +2 -0
  112. package/studio-dist/client/assets/button-BIIHE0EQ.js +3 -0
  113. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +1 -0
  114. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +1 -0
  115. package/studio-dist/client/assets/factory-BZy0E8ty.js +4 -0
  116. package/studio-dist/client/assets/index-B3wkMzjA.js +40 -0
  117. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +1 -0
  118. package/studio-dist/client/assets/panel-CbajlC3p.js +1 -0
  119. package/studio-dist/client/assets/{prepaint-CD5OpmTM.js → prepaint-CwSrpdFA.js} +7 -4
  120. package/studio-dist/client/assets/react-CN2GSx7x.js +1 -0
  121. package/studio-dist/client/assets/reports-DllhYQ5_.js +1 -0
  122. package/studio-dist/client/assets/routes-COm-G3mK.js +1 -0
  123. package/studio-dist/client/assets/skills-DmWAy-jZ.js +1 -0
  124. package/studio-dist/client/assets/specs-BG3Wi3ln.js +1 -0
  125. package/studio-dist/client/assets/steps-DFsH3Neu.js +1 -0
  126. package/studio-dist/client/assets/vault-B2q1nBY5.js +1 -0
  127. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +1 -0
  128. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +1 -0
  129. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → __23tanstack-start-server-fn-resolver-M2GBs8s3.js} +179 -9
  130. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +35 -25
  131. package/studio-dist/server/assets/button-CIJqAhni.js +11929 -0
  132. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DISASvdJ.js} +13 -7
  133. package/studio-dist/server/assets/companions-BYbHWKOZ.js +15 -0
  134. package/studio-dist/server/assets/delivery-path-C29fBynY.js +654 -0
  135. package/studio-dist/server/assets/{factory-DT3UzHlh.js → factory-DGPmNGbo.js} +1 -0
  136. package/studio-dist/server/assets/{factory-D6xnjedJ.js → factory-DUTa0eDs.js} +317 -530
  137. package/studio-dist/server/assets/markdown-view-Bn7xPdks.js +86 -0
  138. package/studio-dist/server/assets/panel-3Jmn4awF.js +169 -0
  139. package/studio-dist/server/assets/{prepaint-BMke0fo1.js → prepaint-DJfTQ_VH.js} +6 -2
  140. package/studio-dist/server/assets/{react-COs0LHn-.js → react-Ce6dj15C.js} +4 -9
  141. package/studio-dist/server/assets/reports-C06RXVE2.js +18 -0
  142. package/studio-dist/server/assets/reports-D6YMqhnO.js +142 -0
  143. package/studio-dist/server/assets/router-C8MGqlAY.js +13713 -0
  144. package/studio-dist/server/assets/routes-BcFgvqf7.js +622 -0
  145. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DS3wUexh.js} +1 -0
  146. package/studio-dist/server/assets/skills-BEnOxiDl.js +266 -0
  147. package/studio-dist/server/assets/skills-CtrBAtX3.js +28 -0
  148. package/studio-dist/server/assets/specs-C8rv34-5.js +211 -0
  149. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  150. package/studio-dist/server/assets/steps-Dq_CwY_s.js +181 -0
  151. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-BmWnryh3.js} +16 -1
  152. package/studio-dist/server/assets/vault-Fvxt2Tzl.js +1032 -0
  153. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-BgYa-za2.js} +1 -3
  154. package/studio-dist/server/assets/warnings-DzR6fyZh.js +23 -0
  155. package/studio-dist/server/assets/workflow-liRYecHk.js +73 -0
  156. package/studio-dist/server/server.js +3 -157
  157. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  158. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  159. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  160. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  161. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  162. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  163. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  164. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  165. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  166. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  167. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  168. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  169. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  170. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  171. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  172. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  173. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  174. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  175. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  176. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  177. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  178. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  179. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  180. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  181. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  182. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  183. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +0 -3365
  184. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  185. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  186. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
@@ -181,16 +181,15 @@ async function localLookup(
181
181
  const base = { repository, branch };
182
182
  const fetch = options.fetch ? await local.fetch(branch) : undefined;
183
183
  const withFetch = fetch ? { fetch } : {};
184
- const live = await local.git.tip(branch);
185
- const head =
186
- live ?? (recordedHead && (await local.git.hasCommit(recordedHead)) ? recordedHead : null);
187
- const onDefault = head !== null && (await local.git.isAncestor(head, local.defaultBranch));
188
- // A fast-forward and a branch without commits of its own look the same: only a merge
189
- // commit settles by itself.
190
- if (onDefault && !(await local.git.onFirstParent(head, local.defaultBranch))) {
184
+ const { live, head, merged, suggestion } = await localMergeEvidence(
185
+ local.git,
186
+ local.defaultBranch,
187
+ branch,
188
+ recordedHead,
189
+ );
190
+ if (merged && head) {
191
191
  return { ...base, ...withFetch, result: "merged", needsAnswer: false, source: "git", head };
192
192
  }
193
- const suggestion = await suggestionFor(local, head, onDefault);
194
193
  const fetchedAt = await local.git.lastFetchedAt();
195
194
  return {
196
195
  ...base,
@@ -204,15 +203,36 @@ async function localLookup(
204
203
  };
205
204
  }
206
205
 
207
- /** What local Git can only suggest: a head on the default branch's own line, else a patch match. */
208
- async function suggestionFor(
209
- local: LocalMergeAccess,
210
- head: string | null,
211
- onDefault: boolean,
212
- ): Promise<PatchMatch | null> {
213
- if (!head) return null;
214
- if (onDefault) return { commit: head, style: "fast-forward" };
215
- return local.git.patchMatch(head, local.defaultBranch);
206
+ /** What a local checkout alone knows about a branch's merge; no fetch, no forge. */
207
+ export interface LocalMergeEvidence {
208
+ /** The branch tip, on `origin` or local; null when the branch is gone. */
209
+ live: string | null;
210
+ /** `live`, else the recorded head while the commit still exists. */
211
+ head: string | null;
212
+ /** A merge commit on the default branch settles it. */
213
+ merged: boolean;
214
+ /** Short of `merged`: a head on the default branch's own line, else a patch match. */
215
+ suggestion: PatchMatch | null;
216
+ }
217
+
218
+ export async function localMergeEvidence(
219
+ git: MergeGit,
220
+ defaultBranch: string,
221
+ branch: string,
222
+ recordedHead: string | undefined,
223
+ ): Promise<LocalMergeEvidence> {
224
+ const live = await git.tip(branch);
225
+ const head = live ?? (recordedHead && (await git.hasCommit(recordedHead)) ? recordedHead : null);
226
+ const onDefault = head !== null && (await git.isAncestor(head, defaultBranch));
227
+ // A fast-forward and a branch without commits of its own look the same: only a merge
228
+ // commit settles by itself.
229
+ if (onDefault && !(await git.onFirstParent(head, defaultBranch))) {
230
+ return { live, head, merged: true, suggestion: null };
231
+ }
232
+ let suggestion: PatchMatch | null = null;
233
+ if (head && onDefault) suggestion = { commit: head, style: "fast-forward" };
234
+ else if (head) suggestion = await git.patchMatch(head, defaultBranch);
235
+ return { live, head, merged: false, suggestion };
216
236
  }
217
237
 
218
238
  async function forgeLookup(
@@ -1,8 +1,17 @@
1
1
  import { locateChange } from "../change-layout";
2
- import { findWorkset, resolveWorksetBranch, resolveWorksetOf } from "../workset/record";
2
+ import type { MergeGit } from "./merge-git";
3
+ import { declaredDependencies } from "./overlap";
4
+ import { localMergeEvidence } from "./refresh";
5
+ import {
6
+ findWorkset,
7
+ resolveWorksetBranch,
8
+ resolveWorksetOf,
9
+ type WorksetRecord,
10
+ } from "../workset/record";
3
11
  import {
4
12
  defaultDeliveryBranch,
5
13
  findDelivery,
14
+ isJiraKey,
6
15
  readDeliveryRecord,
7
16
  type DeliveryRecord,
8
17
  } from "./record";
@@ -10,6 +19,9 @@ import {
10
19
  /** True when the ref resolves in the repository's checkout. */
11
20
  export type HasRef = (ref: string) => Promise<boolean>;
12
21
 
22
+ /** Full names of the refs under the given prefixes, e.g. `refs/heads/workset/`. */
23
+ export type ListRefs = (prefixes: string[]) => Promise<string[]>;
24
+
13
25
  /** Where the resolved branch lives: a local branch, only `origin/<branch>`, or nowhere yet. */
14
26
  export type BranchSource = "local" | "remote" | "new";
15
27
 
@@ -19,29 +31,55 @@ export interface DeliveryBranchRequest {
19
31
  repository: string | null;
20
32
  /** Null when no checkout is known: the computed name, with `source` null. */
21
33
  hasRef: HasRef | null;
34
+ /**
35
+ * Finds an existing `workset/<TICKET>-<id>` when no ticket is given; without it only
36
+ * `workset/<id>` is probed.
37
+ */
38
+ listRefs?: ListRefs | null;
39
+ /**
40
+ * Checks a dependency never checked for a merge before its branch is inherited; without it
41
+ * such a branch is inherited with a diagnostic asking for a refresh.
42
+ */
43
+ mergeProbe?: MergeProbe | null;
44
+ /**
45
+ * Names the branch `workset/<TICKET>-<id>`, even over an existing `workset/<id>`; never
46
+ * renames a recorded or inherited one. Defaults to the explicit Workset record's ticket,
47
+ * which yields to any existing `workset/<id>` or `workset/<TICKET>-<id>`.
48
+ */
49
+ ticket?: string | null;
22
50
  }
23
51
 
24
52
  export interface DeliveryBranchResolution {
25
- /** Null on a Workset identity problem or when its changes record different branches. */
53
+ /** Null on a Workset identity problem or an ambiguous branch. */
26
54
  branch: string | null;
27
55
  /** Null when `branch` is null or no checkout was probed. */
28
56
  source: BranchSource | null;
29
- /** The Workset's single distinct ticket, or null for none or several. */
30
- ticket: string | null;
57
+ /** The `dependsOn` changes whose branch `branch` is; empty when it is not inherited. */
58
+ inheritedFrom: string[];
31
59
  diagnostics: string[];
32
60
  }
33
61
 
34
- /** The records of the Workset's changes: an explicit record's `changes`, else the change itself. */
35
- async function memberRecords(companionPath: string, worksetId: string): Promise<DeliveryRecord[]> {
36
- const workset = await findWorkset(companionPath, worksetId);
62
+ interface Member {
63
+ change: string;
64
+ dir: string;
65
+ record: DeliveryRecord | null;
66
+ }
67
+
68
+ /** The Workset's changes: an explicit record's `changes`, else the change itself. */
69
+ async function members(
70
+ companionPath: string,
71
+ worksetId: string,
72
+ workset: WorksetRecord | undefined,
73
+ ): Promise<Member[]> {
37
74
  const changes = workset ? workset.changes : [worksetId];
38
- const records = await Promise.all(
75
+ const found = await Promise.all(
39
76
  changes.map(async (change) => {
40
77
  const location = await locateChange(companionPath, change);
41
- return location ? readDeliveryRecord(location.dir) : null;
78
+ if (!location) return null;
79
+ return { change, dir: location.dir, record: await readDeliveryRecord(location.dir) };
42
80
  }),
43
81
  );
44
- return records.filter((record): record is DeliveryRecord => record !== null);
82
+ return found.filter((member): member is Member => member !== null);
45
83
  }
46
84
 
47
85
  function distinct(values: Array<string | undefined>): string[] {
@@ -54,27 +92,146 @@ async function sourceOf(branch: string, hasRef: HasRef): Promise<BranchSource> {
54
92
  return "new";
55
93
  }
56
94
 
95
+ const WORKSET_REF = /^refs\/(?:heads|remotes\/origin)\/workset\//;
96
+
97
+ /** The key of `workset/<TICKET>-<id>`, else null. */
98
+ function ticketKeyOf(branch: string, worksetId: string): string | null {
99
+ const prefix = "workset/";
100
+ const suffix = `-${worksetId}`;
101
+ if (!branch.startsWith(prefix) || !branch.endsWith(suffix)) return null;
102
+ const key = branch.slice(prefix.length, -suffix.length);
103
+ return isJiraKey(key) ? key : null;
104
+ }
105
+
106
+ /** Existing `workset/<TICKET>-<id>` branches, local or on `origin`, for any ticket. */
107
+ async function ticketedBranches(worksetId: string, listRefs: ListRefs): Promise<string[]> {
108
+ const refs = await listRefs(["refs/heads/workset/", "refs/remotes/origin/workset/"]);
109
+ return distinct(
110
+ refs.map((ref) => {
111
+ if (!WORKSET_REF.test(ref)) return undefined;
112
+ const branch = `workset/${ref.replace(WORKSET_REF, "")}`;
113
+ return ticketKeyOf(branch, worksetId) ? branch : undefined;
114
+ }),
115
+ ).toSorted();
116
+ }
117
+
118
+ /** A local checkout's merge check, without fetch or forge; see {@link mergeProbeWith}. */
119
+ export type MergeProbe = (
120
+ branch: string,
121
+ recordedHead: string | undefined,
122
+ ) => Promise<"merged" | "squashed" | "open">;
123
+
124
+ /**
125
+ * A {@link MergeProbe} over local Git: a merge commit settles `merged`, commits matched on the
126
+ * default branch read as `squashed`. A head on the default branch's own line is `open`: it
127
+ * may be a fast-forward, but then its commits are already there and continuing on it is safe.
128
+ */
129
+ export function mergeProbeWith(git: MergeGit, defaultBranch: string): MergeProbe {
130
+ return async (branch, recordedHead) => {
131
+ const evidence = await localMergeEvidence(git, defaultBranch, branch, recordedHead);
132
+ if (evidence.merged) return "merged";
133
+ const style = evidence.suggestion?.style;
134
+ return style === "squash" || style === "rebase" ? "squashed" : "open";
135
+ };
136
+ }
137
+
138
+ const SETTLED: ReadonlySet<string> = new Set(["merged", "closed-unmerged"]);
139
+
140
+ interface Inherited {
141
+ branch: string;
142
+ from: string[];
143
+ /** Dependencies whose merge state was never looked up and could not be probed. */
144
+ unchecked: string[];
145
+ }
146
+
147
+ /**
148
+ * The branches the Workset's direct `dependsOn` changes deliver in `repository` that are still
149
+ * open (not direct, not merged or dropped, present when refs can be probed), each with the
150
+ * dependencies recording it. A dependency never checked for a merge is probed locally when
151
+ * `mergeProbe` is given; one that looks merged is skipped and named in `diagnostics`.
152
+ */
153
+ async function inheritedBranches(
154
+ companionPath: string,
155
+ found: Member[],
156
+ repository: string,
157
+ { hasRef, mergeProbe }: Pick<DeliveryBranchRequest, "hasRef" | "mergeProbe">,
158
+ diagnostics: string[],
159
+ ): Promise<Inherited[]> {
160
+ const own = new Set(found.map((member) => member.change));
161
+ const declared = await Promise.all(found.map((member) => declaredDependencies(member.dir)));
162
+ const names = [...new Set(declared.flat().filter((name) => !own.has(name)))].toSorted();
163
+ const open = await Promise.all(
164
+ names.map(async (name) => {
165
+ const location = await locateChange(companionPath, name);
166
+ const record = location ? await readDeliveryRecord(location.dir) : null;
167
+ const delivery = record ? findDelivery(record, repository) : undefined;
168
+ if (!delivery?.branch || delivery.direct || SETTLED.has(delivery.merge?.state ?? "")) {
169
+ return null;
170
+ }
171
+ const { branch } = delivery;
172
+ if (hasRef && (await sourceOf(branch, hasRef)) === "new") return null;
173
+ if (delivery.merge !== undefined) return { name, branch, unchecked: false };
174
+ if (!mergeProbe) return { name, branch, unchecked: true };
175
+ const probed = await mergeProbe(branch, delivery.head);
176
+ if (probed === "open") return { name, branch, unchecked: false };
177
+ diagnostics.push(
178
+ probed === "merged"
179
+ ? `${branch} of ${name} is merged into the default branch; it is not inherited.`
180
+ : `${branch} of ${name} looks squash-merged into the default branch; it is not inherited. If it is still open, run \`mate artifact link ${name} --confirm-open\`.`,
181
+ );
182
+ return null;
183
+ }),
184
+ );
185
+ const branches = new Map<string, Inherited>();
186
+ for (const entry of open) {
187
+ if (!entry) continue;
188
+ const inherited = branches.get(entry.branch) ?? {
189
+ branch: entry.branch,
190
+ from: [],
191
+ unchecked: [],
192
+ };
193
+ inherited.from.push(entry.name);
194
+ if (entry.unchecked) inherited.unchecked.push(entry.name);
195
+ branches.set(entry.branch, inherited);
196
+ }
197
+ return [...branches.values()];
198
+ }
199
+
57
200
  /** Branch order for a Workset whose identity is already checked. */
58
201
  async function branchOf(
59
202
  request: DeliveryBranchRequest,
60
203
  worksetId: string,
61
204
  ): Promise<DeliveryBranchResolution> {
62
- const { companionPath, repository, hasRef } = request;
63
- const records = await memberRecords(companionPath, worksetId);
205
+ const { companionPath, repository, hasRef, listRefs } = request;
206
+ const workset = await findWorkset(companionPath, worksetId);
207
+ const ticket = request.ticket ?? workset?.ticket ?? null;
208
+ // The branch the ticket names; `workset/<id>` without one.
209
+ const named = defaultDeliveryBranch(worksetId, ticket);
210
+ const found = await members(companionPath, worksetId, workset);
211
+ const records = found.flatMap((member) => (member.record ? [member.record] : []));
64
212
  const diagnostics: string[] = [];
65
- const tickets = distinct(records.map((record) => record.ticket));
66
- if (tickets.length > 1) {
67
- diagnostics.push(
68
- `Workset ${worksetId}'s changes record different tickets (${tickets.join(", ")}); its computed branch carries none.`,
69
- );
70
- }
71
- const ticket = tickets.length === 1 ? tickets[0]! : null;
72
- const resolved = async (branch: string, source?: BranchSource) => ({
73
- branch,
74
- source: source ?? (hasRef ? await sourceOf(branch, hasRef) : null),
75
- ticket,
213
+ const unresolved = (): DeliveryBranchResolution => ({
214
+ branch: null,
215
+ source: null,
216
+ inheritedFrom: [],
76
217
  diagnostics,
77
218
  });
219
+ const resolved = async (
220
+ branch: string,
221
+ { source, inheritedFrom = [] }: { source?: BranchSource; inheritedFrom?: string[] } = {},
222
+ ): Promise<DeliveryBranchResolution> => {
223
+ if (ticket && branch !== named) {
224
+ diagnostics.push(
225
+ `Ticket ${ticket} does not name the branch: ${branch} already delivers Workset ${worksetId}.`,
226
+ );
227
+ }
228
+ return {
229
+ branch,
230
+ source: source ?? (hasRef ? await sourceOf(branch, hasRef) : null),
231
+ inheritedFrom,
232
+ diagnostics,
233
+ };
234
+ };
78
235
 
79
236
  if (repository) {
80
237
  const recorded = distinct(
@@ -87,29 +244,93 @@ async function branchOf(
87
244
  diagnostics.push(
88
245
  `Workset ${worksetId}'s changes record different branches for ${repository} (${recorded.join(", ")}); select a branch explicitly.`,
89
246
  );
90
- return { branch: null, source: null, ticket, diagnostics };
247
+ return unresolved();
248
+ }
249
+ if (recorded.length === 1) {
250
+ const branch = recorded[0]!;
251
+ const key = ticketKeyOf(branch, worksetId);
252
+ // Only the branch name carries a ticket, so a wrong one is fixed by renaming the branch.
253
+ if (request.ticket && key && key.toUpperCase() !== request.ticket.toUpperCase()) {
254
+ const changes = found.map((member) => member.change).join(" ");
255
+ diagnostics.push(
256
+ `To change the ticket of ${branch} before it is pushed, run \`git branch -m ${branch} ${named}\`, then \`mate artifact link ${changes} --branch ${named}\`.`,
257
+ );
258
+ }
259
+ return resolved(branch);
260
+ }
261
+
262
+ const inherited = await inheritedBranches(
263
+ companionPath,
264
+ found,
265
+ repository,
266
+ request,
267
+ diagnostics,
268
+ );
269
+ if (inherited.length > 1) {
270
+ const names = inherited.map((entry) => entry.branch).join(", ");
271
+ diagnostics.push(
272
+ `Workset ${worksetId}'s dependencies record different branches for ${repository} (${names}); none is inherited.`,
273
+ );
274
+ }
275
+ if (inherited.length === 1) {
276
+ const { branch, from, unchecked } = inherited[0]!;
277
+ if (unchecked.length > 0) {
278
+ diagnostics.push(
279
+ `${branch} is inherited from ${unchecked.join(", ")}, whose merge state was never checked; if it is merged, run \`mate artifact link ${unchecked[0]} --refresh\`.`,
280
+ );
281
+ }
282
+ return resolved(branch, { inheritedFrom: from });
91
283
  }
92
- if (recorded.length === 1) return resolved(recorded[0]!);
93
284
  }
94
285
 
95
- const computed = defaultDeliveryBranch(worksetId, ticket);
96
- if (hasRef) {
97
- const candidates = distinct([ticket ? computed : undefined, defaultDeliveryBranch(worksetId)]);
98
- for (const candidate of candidates) {
99
- // oxlint-disable-next-line no-await-in-loop -- the first existing candidate wins
100
- const source = await sourceOf(candidate, hasRef);
101
- if (source !== "new") return resolved(candidate, source);
286
+ const plain = defaultDeliveryBranch(worksetId);
287
+ if (!hasRef) return resolved(named);
288
+ if (ticket) {
289
+ const source = await sourceOf(named, hasRef);
290
+ if (source !== "new") return resolved(named, { source });
291
+ // An explicit ticket asks for its own branch; a stale plain one must not take its place.
292
+ if (request.ticket) {
293
+ if ((await sourceOf(plain, hasRef)) !== "new") {
294
+ diagnostics.push(
295
+ `Existing ${plain} is not used: ticket ${ticket} names ${named}; record ${plain} with --branch to keep it.`,
296
+ );
297
+ }
298
+ return resolved(named, { source });
102
299
  }
300
+ // A Workset record's ticket only names a branch none of whose forms exists yet.
103
301
  }
104
- return resolved(computed, hasRef ? "new" : undefined);
302
+ const plainSource = await sourceOf(plain, hasRef);
303
+ if (plainSource !== "new") return resolved(plain, { source: plainSource });
304
+ if (!listRefs) return resolved(named, { source: "new" });
305
+ // The ticket lives only in the branch name, so a branch created with one is found by name.
306
+ const ticketed = await ticketedBranches(worksetId, listRefs);
307
+ if (ticketed.length > 1) {
308
+ diagnostics.push(
309
+ `Workset ${worksetId} has several ticket branches (${ticketed.join(", ")}); select a branch explicitly.`,
310
+ );
311
+ return unresolved();
312
+ }
313
+ if (ticketed.length === 1) return resolved(ticketed[0]!);
314
+ return resolved(named, { source: "new" });
315
+ }
316
+
317
+ /** A {@link ListRefs} over a Git runner that answers stdout, or null on failure. */
318
+ export function listRefsWith(git: (args: string[]) => Promise<string | null>): ListRefs {
319
+ return async (prefixes) => {
320
+ const stdout = await git(["for-each-ref", "--format=%(refname)", ...prefixes]);
321
+ return stdout ? stdout.split("\n").filter(Boolean) : [];
322
+ };
105
323
  }
106
324
 
107
325
  /**
108
326
  * The Delivery Branch link, worktree, and factory spawning share, for a change or a Workset in
109
327
  * `repository`: the Workset identity check, then the branch its changes record when they agree,
110
- * an existing `workset/<TICKET>-<id>`, an existing `workset/<id>`, else the computed name. Direct
111
- * deliveries are not a Workset's branch. Existence is read through `hasRef`, local branch first,
112
- * so callers fetch before resolving. A damaged record throws, as when it is read on its own.
328
+ * a branch inherited from a `dependsOn` change, then with a ticket `workset/<TICKET>-<id>`
329
+ * (a record's ticket yields to any existing Workset branch); without one an existing
330
+ * `workset/<id>`, else the single existing `workset/<TICKET>-<id>`, else `workset/<id>`. Direct
331
+ * deliveries are not a Workset's branch. Existence is read through `hasRef`, local branch
332
+ * first, so callers fetch before resolving. A damaged record throws, as
333
+ * when it is read on its own.
113
334
  */
114
335
  export async function resolveDeliveryBranch(
115
336
  request: DeliveryBranchRequest & ({ change: string } | { worksetId: string }),
@@ -124,7 +345,7 @@ export async function resolveDeliveryBranch(
124
345
  worksetId: null,
125
346
  branch: null,
126
347
  source: null,
127
- ticket: null,
348
+ inheritedFrom: [],
128
349
  diagnostics: identity.diagnostics,
129
350
  };
130
351
  }
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
 
3
3
  import { activeChanges } from "../../change-layout";
4
+ import { companionTicketFormat, TICKETS_OFF } from "../../delivery/branches";
4
5
  import {
5
6
  createOutcome,
6
7
  findWorkset,
@@ -161,9 +162,18 @@ async function acceptedAction(
161
162
  /** A new Outcome from the outcome input; true when it was started. */
162
163
  async function createOutcomeFrom(companionPath: string, fields: OutcomeFields): Promise<boolean> {
163
164
  const start = fields("start") !== "later";
165
+ const ticket = fields("ticket").trim();
166
+ if (ticket && (await companionTicketFormat(companionPath)) !== "jira") {
167
+ throw new WorksetError(TICKETS_OFF);
168
+ }
164
169
  await createOutcome(
165
170
  companionPath,
166
- { text: fields("text"), repository: fields("repository"), ...(start ? { start } : {}) },
171
+ {
172
+ text: fields("text"),
173
+ repository: fields("repository"),
174
+ ...(start ? { start } : {}),
175
+ ...(ticket ? { ticket } : {}),
176
+ },
167
177
  await linkedRepositoryIdentities(companionPath),
168
178
  );
169
179
  return start;
@@ -1,6 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { newBranchBase, resolveDeliveryBranch, worktreeAddArgs } from "../delivery/resolve-branch";
3
+ import {
4
+ listRefsWith,
5
+ newBranchBase,
6
+ resolveDeliveryBranch,
7
+ worktreeAddArgs,
8
+ } from "../delivery/resolve-branch";
4
9
  import { resolveWorksetBranch } from "../workset/record";
5
10
 
6
11
  import { type CommandResult, type CommandRunner, runCommand } from "./command";
@@ -433,6 +438,10 @@ export class WorksetRuntime {
433
438
  companionPath: companion,
434
439
  repository: request.repository,
435
440
  hasRef,
441
+ listRefs: listRefsWith(async (args) => {
442
+ const listed = await this.git(["-C", repoDir, ...args]);
443
+ return listed.status === 0 ? listed.stdout : null;
444
+ }),
436
445
  worksetId: request.id,
437
446
  });
438
447
  const { branch, source } = resolution;