@open-mercato/cezar 0.15.0 → 0.15.1

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 (212) hide show
  1. package/dist/automations/github-poller.d.ts +8 -1
  2. package/dist/automations/github-poller.js +78 -13
  3. package/dist/automations/github-poller.js.map +1 -1
  4. package/dist/automations/pr-head.js +15 -1
  5. package/dist/automations/pr-head.js.map +1 -1
  6. package/dist/automations/prompts.js +2 -2
  7. package/dist/automations/types.d.ts +10 -0
  8. package/dist/automations/types.js +12 -1
  9. package/dist/automations/types.js.map +1 -1
  10. package/dist/config.d.ts +1 -0
  11. package/dist/config.js +6 -0
  12. package/dist/config.js.map +1 -1
  13. package/dist/contract/automations.d.ts +31 -1
  14. package/dist/contract/index.d.ts +1 -0
  15. package/dist/contract/index.js +161 -17
  16. package/dist/contract/projects.d.ts +46 -0
  17. package/dist/contract/runs.d.ts +15 -0
  18. package/dist/contract/skills.d.ts +1 -0
  19. package/dist/contract/telemetry.d.ts +124 -0
  20. package/dist/contract/workspace.d.ts +3 -0
  21. package/dist/core/cursor-agent-runner.d.ts +11 -0
  22. package/dist/core/cursor-agent-runner.js +48 -4
  23. package/dist/core/cursor-agent-runner.js.map +1 -1
  24. package/dist/core/disclaim-spawn.d.ts +10 -0
  25. package/dist/core/disclaim-spawn.js +105 -8
  26. package/dist/core/disclaim-spawn.js.map +1 -1
  27. package/dist/git-diff-base.js +26 -19
  28. package/dist/git-diff-base.js.map +1 -1
  29. package/dist/git-remotes.d.ts +43 -0
  30. package/dist/git-remotes.js +127 -0
  31. package/dist/git-remotes.js.map +1 -0
  32. package/dist/git-worktree.d.ts +43 -19
  33. package/dist/git-worktree.js +138 -54
  34. package/dist/git-worktree.js.map +1 -1
  35. package/dist/index.js +46 -6
  36. package/dist/index.js.map +1 -1
  37. package/dist/runs/auto-name.d.ts +17 -0
  38. package/dist/runs/auto-name.js +47 -2
  39. package/dist/runs/auto-name.js.map +1 -1
  40. package/dist/runs/event-history.d.ts +10 -2
  41. package/dist/runs/event-history.js +290 -120
  42. package/dist/runs/event-history.js.map +1 -1
  43. package/dist/runs/retention.js +1 -1
  44. package/dist/runs/retention.js.map +1 -1
  45. package/dist/runs/store.d.ts +16 -3
  46. package/dist/runs/store.js +89 -10
  47. package/dist/runs/store.js.map +1 -1
  48. package/dist/server/checkout.d.ts +4 -0
  49. package/dist/server/checkout.js +9 -5
  50. package/dist/server/checkout.js.map +1 -1
  51. package/dist/server/create-project.d.ts +77 -0
  52. package/dist/server/create-project.js +342 -0
  53. package/dist/server/create-project.js.map +1 -0
  54. package/dist/server/forge/github.d.ts +2 -0
  55. package/dist/server/forge/github.js +32 -10
  56. package/dist/server/forge/github.js.map +1 -1
  57. package/dist/server/forge/index.d.ts +1 -12
  58. package/dist/server/forge/index.js +7 -29
  59. package/dist/server/forge/index.js.map +1 -1
  60. package/dist/server/forge/types.d.ts +2 -0
  61. package/dist/server/git-changes.d.ts +15 -0
  62. package/dist/server/git-changes.js +51 -1
  63. package/dist/server/git-changes.js.map +1 -1
  64. package/dist/server/git.d.ts +3 -2
  65. package/dist/server/git.js +4 -3
  66. package/dist/server/git.js.map +1 -1
  67. package/dist/server/project-context.js +1 -1
  68. package/dist/server/project-context.js.map +1 -1
  69. package/dist/server/server.d.ts +609 -302
  70. package/dist/server/server.js +191 -12
  71. package/dist/server/server.js.map +1 -1
  72. package/dist/server/star-count.d.ts +27 -11
  73. package/dist/server/star-count.js +57 -28
  74. package/dist/server/star-count.js.map +1 -1
  75. package/dist/telemetry-cli.d.ts +10 -0
  76. package/dist/telemetry-cli.js +54 -0
  77. package/dist/telemetry-cli.js.map +1 -0
  78. package/dist/telemetry-service.json +1 -0
  79. package/dist/telemetry.d.ts +79 -0
  80. package/dist/telemetry.js +453 -0
  81. package/dist/telemetry.js.map +1 -0
  82. package/dist/workflows/run.d.ts +28 -0
  83. package/dist/workflows/run.js +111 -16
  84. package/dist/workflows/run.js.map +1 -1
  85. package/dist/workspace/config.d.ts +10 -0
  86. package/dist/workspace/config.js +16 -0
  87. package/dist/workspace/config.js.map +1 -1
  88. package/dist/workspace/projects-cli.js +3 -0
  89. package/dist/workspace/projects-cli.js.map +1 -1
  90. package/package.json +3 -3
  91. package/scripts/mock-claude.mjs +32 -17
  92. package/scripts/stamp-telemetry-service.mjs +20 -0
  93. package/web/dist/assets/agent-task-pickers-mJzYn0UB.js +1 -0
  94. package/web/dist/assets/{alert-dialog-CF_-dmQ1.js → alert-dialog-Dd1WPOaz.js} +1 -1
  95. package/web/dist/assets/arrow-left-fsST4JqT.js +1 -0
  96. package/web/dist/assets/{automation-format-D1nqk0ID.js → automation-format-BTIFWfjt.js} +1 -1
  97. package/web/dist/assets/automations-route-DJjhwqug.js +1 -0
  98. package/web/dist/assets/button-BNnH7COh.js +100 -0
  99. package/web/dist/assets/{centered-state-T0J7VmBb.js → centered-state-sEYB3bgq.js} +1 -1
  100. package/web/dist/assets/check-DA37PQLT.js +1 -0
  101. package/web/dist/assets/chevron-left-zbXV2Qbu.js +1 -0
  102. package/web/dist/assets/chevron-right-Beu1pd6H.js +1 -0
  103. package/web/dist/assets/{collapsible-RD4hkew7.js → collapsible-MuXfYnM8.js} +1 -1
  104. package/web/dist/assets/commit-list-Bps23fvP.js +1 -0
  105. package/web/dist/assets/compare-variants-CQskdfDW.js +1 -0
  106. package/web/dist/assets/composer-DKWLJeo9.js +18 -0
  107. package/web/dist/assets/dashboard-BCNe_6p7.js +44 -0
  108. package/web/dist/assets/diff-CrLUECGW.js +3 -0
  109. package/web/dist/assets/{diff-stat-CFoeFye2.js → diff-stat-SpfygteL.js} +1 -1
  110. package/web/dist/assets/diff-view-DP4Gw3QJ.js +13 -0
  111. package/web/dist/assets/{download-BFQEsJRY.js → download-CBwSbmy_.js} +1 -1
  112. package/web/dist/assets/dropdown-menu-CxPGHgWX.js +1 -0
  113. package/web/dist/assets/ellipsis-BmusVE8U.js +1 -0
  114. package/web/dist/assets/{file-Df5WtpM_.js → file-DkvcUwxT.js} +1 -1
  115. package/web/dist/assets/file-preview-DxFusXAO.js +2 -0
  116. package/web/dist/assets/file-text-DBeC0yKb.js +1 -0
  117. package/web/dist/assets/file-tree-BTJZXRkM.js +1 -0
  118. package/web/dist/assets/{git-commit-horizontal-DawNm4qg.js → git-commit-horizontal-BM9_nEW7.js} +1 -1
  119. package/web/dist/assets/git-toolbar-DXyPCDkQ.js +1 -0
  120. package/web/dist/assets/github-G5fU4gJd.js +1 -0
  121. package/web/dist/assets/index-BN3w52uE.js +21 -0
  122. package/web/dist/assets/index-CAvSSpvF.css +2 -0
  123. package/web/dist/assets/{markdown-Bmfy_1Ll.js → markdown-BpZ4p95p.js} +1 -1
  124. package/web/dist/assets/{markdown-B_O1ys3h.js → markdown-C5F95Rt-.js} +1 -1
  125. package/web/dist/assets/{message-square-BOO9s3qX.js → message-square-BFQln9c4.js} +1 -1
  126. package/web/dist/assets/{pill-bO5OcHuK.js → pill-BcIQGDbn.js} +1 -1
  127. package/web/dist/assets/project-router-CWMOKp_H.js +3 -0
  128. package/web/dist/assets/reference-chip-B7lU_Pyh.js +1 -0
  129. package/web/dist/assets/reference-overflow-ClRRXWez.js +1 -0
  130. package/web/dist/assets/{refresh-cw-BaFyjVUz.js → refresh-cw-BBEYC6z2.js} +1 -1
  131. package/web/dist/assets/repo-git-CgxxZ7cO.js +1 -0
  132. package/web/dist/assets/{run-diff-GZbNs8fA.js → run-diff-BTB7nBeD.js} +1 -1
  133. package/web/dist/assets/run-header-BPNBEaOy.js +1 -0
  134. package/web/dist/assets/{image-preview-4SVDrBvn.js → scroll-within-DRt7mAnQ.js} +1 -1
  135. package/web/dist/assets/{search-x-bpAfQtVY.js → search-x-6BavY3mg.js} +1 -1
  136. package/web/dist/assets/sheet-D9PeyyRZ.js +1 -0
  137. package/web/dist/assets/skills-SIMzpL0l.js +1 -0
  138. package/web/dist/assets/square-DsFAQaY9.js +1 -0
  139. package/web/dist/assets/tab-link-DEUSZU49.js +1 -0
  140. package/web/dist/assets/{tag-DLwUkUsN.js → tag-DvCVnA6I.js} +1 -1
  141. package/web/dist/assets/task-changes-D-aajoMU.js +1 -0
  142. package/web/dist/assets/task-commits-BYD1GVkS.js +1 -0
  143. package/web/dist/assets/task-composer-7bdNNMP_.js +12 -0
  144. package/web/dist/assets/task-files-BfIOz-eN.js +1 -0
  145. package/web/dist/assets/task-graph-B5-5_IPh.js +1 -0
  146. package/web/dist/assets/task-notes-CfkTBgo8.js +1 -0
  147. package/web/dist/assets/task-thread-eEkjTDxr.js +10 -0
  148. package/web/dist/assets/{terminal-CwrL1hAi.js → terminal-xRHwWarr.js} +1 -1
  149. package/web/dist/assets/textarea-rKUFh5lI.js +1 -0
  150. package/web/dist/assets/thread-loading-DLlbK51g.js +1 -0
  151. package/web/dist/assets/{token-metrics-C149OWmd.js → token-metrics-BcPjL36-.js} +1 -1
  152. package/web/dist/assets/tooltip-BVqBAGNb.js +1 -0
  153. package/web/dist/assets/tracker-2DfMzsIE.js +4 -0
  154. package/web/dist/assets/triangle-alert-CP3Xp0FU.js +1 -0
  155. package/web/dist/assets/upload-bwO_2kok.js +1 -0
  156. package/web/dist/assets/use-automations-PceYR6ss.js +5 -0
  157. package/web/dist/assets/use-now-BAKdIYLG.js +1 -0
  158. package/web/dist/assets/use-submit-shortcut-BA4NVpJl.js +1 -0
  159. package/web/dist/assets/workflow-graph-HopaWPea.js +13 -0
  160. package/web/dist/assets/x-HaVPcg_B.js +1 -0
  161. package/web/dist/index.html +28 -31
  162. package/web/dist/assets/agent-task-pickers-C3ydGatB.js +0 -1
  163. package/web/dist/assets/arrow-left-BxBdc5DC.js +0 -1
  164. package/web/dist/assets/automations-route-BsflncpV.js +0 -1
  165. package/web/dist/assets/button-CjSjKnkd.js +0 -100
  166. package/web/dist/assets/check-DAAMuI4o.js +0 -1
  167. package/web/dist/assets/chevron-left-CvcqxpQZ.js +0 -1
  168. package/web/dist/assets/chevron-right-DKiL3NWw.js +0 -1
  169. package/web/dist/assets/commit-list-BJac2uO6.js +0 -1
  170. package/web/dist/assets/compare-variants-CfqICvRy.js +0 -1
  171. package/web/dist/assets/composer-DZx3cwQW.js +0 -18
  172. package/web/dist/assets/dashboard-CpCDiZdE.js +0 -44
  173. package/web/dist/assets/diff-LG2cl0PE.js +0 -3
  174. package/web/dist/assets/diff-controls-QgdH-r3F.js +0 -1
  175. package/web/dist/assets/diff-view-BVwSaBb2.js +0 -13
  176. package/web/dist/assets/dropdown-menu-DkEK7m00.js +0 -1
  177. package/web/dist/assets/editable-title-CJSWyCcL.js +0 -1
  178. package/web/dist/assets/ellipsis-vertical-CB0adfr7.js +0 -1
  179. package/web/dist/assets/external-link-DPKRidDg.js +0 -1
  180. package/web/dist/assets/eye-CEHQ0c-s.js +0 -1
  181. package/web/dist/assets/file-preview-kYsqZiLU.js +0 -2
  182. package/web/dist/assets/file-text-m0tZu8sU.js +0 -1
  183. package/web/dist/assets/git-merge-B7oVXcKc.js +0 -1
  184. package/web/dist/assets/git-toolbar-B0K4Q5Zv.js +0 -1
  185. package/web/dist/assets/github-C4WaHPni.js +0 -1
  186. package/web/dist/assets/index-CiQrbvAq.js +0 -21
  187. package/web/dist/assets/index-WWaEax-B.css +0 -2
  188. package/web/dist/assets/pencil-CCR9uUZ1.js +0 -1
  189. package/web/dist/assets/reference-chip-Bx_mG9QG.js +0 -1
  190. package/web/dist/assets/repo-git-Mn3_jrGP.js +0 -1
  191. package/web/dist/assets/run-header-i1D5Lvfs.js +0 -1
  192. package/web/dist/assets/sheet-DCdZVHFk.js +0 -1
  193. package/web/dist/assets/skills-Dea5ynJK.js +0 -1
  194. package/web/dist/assets/tab-link-BVItTl_Y.js +0 -1
  195. package/web/dist/assets/task-changes-xNbBM7FO.js +0 -1
  196. package/web/dist/assets/task-commits-BYozE_X3.js +0 -1
  197. package/web/dist/assets/task-composer-Brx0sa7_.js +0 -12
  198. package/web/dist/assets/task-files-MAPO-efK.js +0 -1
  199. package/web/dist/assets/task-graph-BSLCUr1E.js +0 -1
  200. package/web/dist/assets/task-thread-CRVmwchQ.js +0 -9
  201. package/web/dist/assets/textarea-Bb0_Hz53.js +0 -1
  202. package/web/dist/assets/thread-loading-Bo6IOu3Y.js +0 -1
  203. package/web/dist/assets/toaster-Hj_czp_o.js +0 -3
  204. package/web/dist/assets/tooltip--PYfu68E.js +0 -1
  205. package/web/dist/assets/tracker-DM5WtYD0.js +0 -4
  206. package/web/dist/assets/trash-2-EdjdGvEo.js +0 -1
  207. package/web/dist/assets/triangle-alert-DpH3QFz6.js +0 -1
  208. package/web/dist/assets/use-automations-XKvBTPM-.js +0 -5
  209. package/web/dist/assets/use-now-CrM50BFB.js +0 -1
  210. package/web/dist/assets/use-submit-shortcut-BJ10ZshV.js +0 -1
  211. package/web/dist/assets/workflow-graph-Y2Pr7ubb.js +0 -13
  212. package/web/dist/assets/x-BkwTUDpG.js +0 -1
@@ -0,0 +1,127 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { isSafeGitRef } from './git-refs.js';
3
+ /**
4
+ * Parse a git remote URL into host/owner/repo. Handles the scheme forms
5
+ * (`https://`, `ssh://`, `git://`, with optional credentials and port) and the
6
+ * scp-like form (`git@host:owner/repo.git`). Null for local paths and anything
7
+ * else that doesn't look like a forge remote.
8
+ */
9
+ export function parseRemote(remote) {
10
+ const r = remote.trim().replace(/\/+$/, '');
11
+ let host;
12
+ let path;
13
+ const url = /^(?:https?|ssh|git|git\+ssh):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/.exec(r);
14
+ if (url) {
15
+ [, host, path] = url;
16
+ }
17
+ else {
18
+ // scp-like: [user@]host:owner/repo(.git) — a leading '/' (local path)
19
+ // can't match the host group, so plain directories fall through to null.
20
+ const scp = /^(?:[^@/:]+@)?([^:/]+):(.+)$/.exec(r);
21
+ if (!scp)
22
+ return null;
23
+ [, host, path] = scp;
24
+ }
25
+ if (!host || !path)
26
+ return null;
27
+ const parts = path.replace(/\.git$/i, '').split('/').filter(Boolean);
28
+ const owner = parts[parts.length - 2];
29
+ const repo = parts[parts.length - 1];
30
+ if (!owner || !repo)
31
+ return null;
32
+ return { host: host.toLowerCase(), owner, repo };
33
+ }
34
+ const PARENT_TIMEOUT_MS = 10_000;
35
+ /** A failed lookup (offline, gh signed out) is retried after this long; an answer is kept. */
36
+ const PARENT_RETRY_MS = 10 * 60_000;
37
+ const parentCache = new Map();
38
+ const ghForkParent = (repo) => {
39
+ const key = `${repo.host}/${repo.owner}/${repo.repo}`.toLowerCase();
40
+ const hit = parentCache.get(key);
41
+ if (hit && hit.expires > Date.now())
42
+ return hit.value;
43
+ const value = new Promise((resolve) => {
44
+ execFile('gh', ['api', '--hostname', repo.host, `repos/${repo.owner}/${repo.repo}`, '--jq', '.parent.full_name // ""'], { timeout: PARENT_TIMEOUT_MS, encoding: 'utf8', env: { ...process.env, GH_PROMPT_DISABLED: '1' } }, (err, stdout) => resolve(err ? null : stdout.trim()));
45
+ });
46
+ // '' = "not a fork", a real answer; null = no answer, ask again later.
47
+ const entry = { value: value.then((v) => v || null), expires: Number.POSITIVE_INFINITY };
48
+ parentCache.set(key, entry);
49
+ void value.then((v) => {
50
+ if (v === null)
51
+ entry.expires = Date.now() + PARENT_RETRY_MS;
52
+ });
53
+ return entry.value;
54
+ };
55
+ let forkParentLookup = ghForkParent;
56
+ /** Test seam: replace the GitHub fork-parent lookup; `null` restores the real one. */
57
+ export function setForkParentLookup(lookup) {
58
+ forkParentLookup = lookup ?? ghForkParent;
59
+ parentCache.clear();
60
+ }
61
+ export async function resolveTaskRemotes(runGit) {
62
+ // One process: every `remote.*` key — urls (raw, before insteadOf), gh-resolved, pushDefault.
63
+ const res = await runGit(['config', '--get-regexp', '^remote\\.']);
64
+ const urls = new Map();
65
+ let ghResolved = null;
66
+ let pushDefault = '';
67
+ for (const line of res.ok ? res.stdout.split('\n') : []) {
68
+ const m = /^remote\.(.+)\.(url|gh-resolved) (.*)$/.exec(line.trim());
69
+ if (m) {
70
+ const [, name = '', key, value = ''] = m;
71
+ if (key === 'url' && !urls.has(name))
72
+ urls.set(name, value);
73
+ else if (key === 'gh-resolved' && value === 'base')
74
+ ghResolved ??= name;
75
+ continue;
76
+ }
77
+ const pd = /^remote\.pushdefault (.*)$/.exec(line.trim());
78
+ if (pd)
79
+ pushDefault = pd[1] ?? '';
80
+ }
81
+ // Dash-guard (#431): names become positional git operands.
82
+ const names = [...urls.keys()].filter(isSafeGitRef);
83
+ if (names.length === 0)
84
+ return { base: null, push: null, names };
85
+ let base = ghResolved && names.includes(ghResolved) ? ghResolved : null;
86
+ if (!base && names.includes('origin'))
87
+ base = await forkParentRemote(urls, names);
88
+ base ??= names.includes('origin') ? 'origin' : names[0];
89
+ const push = names.includes(pushDefault) ? pushDefault : names.includes('origin') ? 'origin' : base;
90
+ return { base, push, names };
91
+ }
92
+ /**
93
+ * The remote whose repo GitHub reports as `origin`'s fork parent. Name alone proves nothing:
94
+ * `upstream` is the canonical repo on a contributor's fork but the vendored project on a
95
+ * downstream fork — only the parent link tells them apart. Skipped under `CEZ_DRY_RUN=1`.
96
+ */
97
+ async function forkParentRemote(urls, names) {
98
+ if (names.length < 2 || process.env.CEZ_DRY_RUN === '1')
99
+ return null;
100
+ const origin = parseRemote(urls.get('origin') ?? '');
101
+ // Only GitHub can answer (`FORGE_HOSTS` in forge/index.ts); never spawn `gh` for GitLab & co.
102
+ if (origin?.host !== 'github.com')
103
+ return null;
104
+ const parent = (await forkParentLookup(origin))?.toLowerCase();
105
+ if (!parent)
106
+ return null;
107
+ for (const name of names) {
108
+ const r = name === 'origin' ? null : parseRemote(urls.get(name) ?? '');
109
+ if (r && r.host === origin.host && `${r.owner}/${r.repo}`.toLowerCase() === parent)
110
+ return name;
111
+ }
112
+ return null;
113
+ }
114
+ /**
115
+ * Split `upstream/main` into `{ remote: 'upstream', branch: 'main' }` when the prefix is a
116
+ * configured remote; anything else (`feat/x`) is `remote: null`. Longest remote name wins.
117
+ */
118
+ export function splitRemoteRef(ref, names) {
119
+ let best = null;
120
+ for (const name of names) {
121
+ if (ref.startsWith(`${name}/`) && ref.length > name.length + 1 && (!best || name.length > best.length)) {
122
+ best = name;
123
+ }
124
+ }
125
+ return best ? { remote: best, branch: ref.slice(best.length + 1) } : { remote: null, branch: ref };
126
+ }
127
+ //# sourceMappingURL=git-remotes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-remotes.js","sourceRoot":"","sources":["../src/git-remotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AA8B7C;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC5C,IAAI,IAAwB,CAAC;IAC7B,IAAI,IAAwB,CAAC;IAC7B,MAAM,GAAG,GAAG,uEAAuE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC5F,IAAI,GAAG,EAAE,CAAC;QACR,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC;IACvB,CAAC;SAAM,CAAC;QACN,sEAAsE;QACtE,yEAAyE;QACzE,MAAM,GAAG,GAAG,8BAA8B,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACnD,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC;IACvB,CAAC;IACD,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACrE,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAA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AC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,KAAwB;IAClE,IAAI,IAAI,GAAkB,IAAI,CAAC;IAC/B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YACvG,IAAI,GAAG,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;AACrG,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { type TaskRemotes } from './git-remotes.ts';
1
2
  /**
2
3
  * Git worktree per task (spec 006). Each run gets its own branch
3
4
  * `cez/<id8>` checked out into `.ai/cezar/worktrees/<runId>` so agents never
@@ -8,20 +9,31 @@
8
9
  */
9
10
  /** Repo-relative home of all task worktrees (gitignored via .ai/cezar/.gitignore). */
10
11
  export declare const WORKTREES_DIR = ".ai/cezar/worktrees";
12
+ /** The base (PR-target) and push remotes of `dir` (`git-remotes.ts`). */
13
+ export declare function taskRemotes(dir: string): Promise<TaskRemotes>;
11
14
  export declare function branchFor(runId: string): string;
15
+ /**
16
+ * A generated branch name (spec 2026-10-11-branch-naming-instructions) that no local or
17
+ * `origin/` branch already holds or blocks as a path prefix, so the fork can never attach to
18
+ * someone else's branch: the name as given, else `<name>-<id8>`. A name git refuses, or an option-like one, answers
19
+ * null and the caller keeps `cez/<id8>`. Never throws.
20
+ */
21
+ export declare function uniqueBranchName(repoRoot: string, wanted: string, runId: string): Promise<string | null>;
12
22
  /**
13
23
  * Resolve the configured base branch to something `git worktree add` can
14
24
  * fork from: the local branch, its remote-tracking ref, or null — the caller
15
25
  * falls back to the current branch with a note. Never throws.
16
26
  *
17
- * When BOTH the local branch and `origin/<base>` exist, prefer whichever is up
18
- * to date. A stale LOCAL base (behind origin, because nothing fetched it into
27
+ * "The remote" is the base (PR-target) remote, `taskRemotes` (#1383).
28
+ *
29
+ * When BOTH the local branch and `<remote>/<base>` exist, prefer whichever is up
30
+ * to date. A stale LOCAL base (behind the remote, because nothing fetched it into
19
31
  * this worktree's repo) is the classic inflated-diff trap: the merge-base every
20
32
  * diff is measured from collapses onto the stale tip, so all of the history
21
- * merged into origin since then counts as the task's own changes — the phantom
22
- * 142k-line diff. `origin/<base>` is the source of truth for a review base, so
23
- * only keep the local ref when it is equal to or ahead of origin (unpushed base
24
- * commits); otherwise use origin. `origin/<base>` is fetched first (best
33
+ * merged upstream since then counts as the task's own changes — the phantom
34
+ * 142k-line diff. `<remote>/<base>` is the source of truth for a review base, so
35
+ * only keep the local ref when it is equal to or ahead of it (unpushed base
36
+ * commits); otherwise use the remote. `<remote>/<base>` is fetched first (best
25
37
  * effort) so "up to date" means the remote as it is now, not at the last fetch.
26
38
  *
27
39
  * This answers the question once, when the worktree is forked. The local ref
@@ -30,22 +42,25 @@ export declare function branchFor(runId: string): string;
30
42
  * (`git-diff-base.ts`). Keep the two in agreement.
31
43
  *
32
44
  * `keepDiverged` is for the user's OWN checked-out branch (the zero-config
33
- * fork point): there a local branch that diverged from origin — rebased or
45
+ * fork point): there a local branch that diverged from the remote — rebased or
34
46
  * amended but not yet force-pushed — is the user's work, not staleness, so
35
- * origin wins only when local is strictly behind it (fast-forwardable). A
47
+ * the remote wins only when local is strictly behind it (fast-forwardable). A
36
48
  * deliberate `reset --hard HEAD~N` that is not force-pushed yet also reads as
37
49
  * "behind" — git cannot tell it from staleness — so such a task forks with the
38
- * dropped commits back in; push the reset first. An own branch origin has
39
- * never tracked is local-only work, so it skips the fetch round trip.
50
+ * dropped commits back in; push the reset first. An own branch the remote has
51
+ * never tracked is local-only work, so it skips the fetch round trip. A repo
52
+ * with no remote at all resolves to the local branch or null.
40
53
  */
41
54
  export declare function resolveBaseRef(repoRoot: string, base: string, opts?: {
42
55
  keepDiverged?: boolean;
56
+ remotes?: TaskRemotes;
43
57
  }): Promise<string | null>;
44
58
  /**
45
59
  * The ref a NEW task forks from: the configured base branch when it resolves,
46
- * else the checked-out branch — itself refreshed against origin, but keeping
47
- * local work that diverged from it (`keepDiverged`). A detached HEAD stays
48
- * `HEAD`; `createWorktree` pins it to the commit. Never throws.
60
+ * else the checked-out branch — itself refreshed against the base remote, but
61
+ * keeping local work that diverged from it (`keepDiverged`) — except on the
62
+ * default branch, where local-only commits are strays, not a base (#1383). A
63
+ * detached HEAD stays `HEAD`; `createWorktree` pins it to the commit. Never throws.
49
64
  */
50
65
  export declare function chooseForkBase(repoRoot: string, currentBranch: string, configured: string | undefined, note: (message: string) => void): Promise<string>;
51
66
  export declare function worktreePathFor(repoRoot: string, runId: string): string;
@@ -62,8 +77,16 @@ export interface WorktreeInfo {
62
77
  * branch after its directory/registration was removed. Existing non-empty
63
78
  * unregistered paths are never deleted because they may hold recoverable
64
79
  * uncommitted work.
80
+ *
81
+ * `opts.branch` is the run's recorded (or freshly generated) branch; without it the name is
82
+ * `cez/<id8>`. Recovery callers MUST pass the record's branch — a named branch cannot be
83
+ * recomputed from the run id. Precondition for a FRESH run: the name must already be unique
84
+ * (`uniqueBranchName`), because an existing branch of that name is treated as this run's own
85
+ * surviving branch and reattached — that is what rematerializing a reclaimed worktree needs.
65
86
  */
66
- export declare function createWorktree(repoRoot: string, runId: string, baseBranch: string): Promise<WorktreeInfo>;
87
+ export declare function createWorktree(repoRoot: string, runId: string, baseBranch: string, opts?: {
88
+ branch?: string;
89
+ }): Promise<WorktreeInfo>;
67
90
  /**
68
91
  * Best-effort on-disk size of a worktree directory in bytes, via POSIX
69
92
  * `du -sk` (kibibytes → bytes). Returns `null` when `du` is unavailable —
@@ -197,7 +220,7 @@ export declare function parseShortstat(s: string): DiffStat;
197
220
  * git failure (the caller notes it, never fails the run); an empty diff is a
198
221
  * valid all-zero stat.
199
222
  */
200
- /** Push `branch` to origin (the graph `git.push` node). Never throws; `CEZ_DRY_RUN=1` is a no-op. */
223
+ /** Push `branch` to the push remote (the graph `git.push` node). Never throws; `CEZ_DRY_RUN=1` is a no-op. */
201
224
  export declare function pushBranch(dir: string, branch: string): Promise<{
202
225
  ok: true;
203
226
  } | {
@@ -205,10 +228,11 @@ export declare function pushBranch(dir: string, branch: string): Promise<{
205
228
  error: string;
206
229
  }>;
207
230
  /**
208
- * Merge the freshest base into the worktree (the graph `git.sync-base` node): `origin/<base>`
209
- * after a fetch when origin has it, else the local base. A conflicted merge is LEFT IN PROGRESS
210
- * and reported with its files — the next node (an agent) resolves it; autosave refuses a
211
- * mid-merge tree, so nothing half-resolved gets committed meanwhile. Never throws.
231
+ * Merge the freshest base into the worktree (the graph `git.sync-base` node): `<remote>/<base>`
232
+ * after a fetch when the base remote (or the remote a recorded `upstream/main` names) has it,
233
+ * else the local base. A conflicted merge is LEFT IN PROGRESS and reported with its files — the
234
+ * next node (an agent) resolves it; autosave refuses a mid-merge tree, so nothing half-resolved
235
+ * gets committed meanwhile. Never throws.
212
236
  */
213
237
  export declare function syncWithBase(dir: string, baseBranch: string): Promise<{
214
238
  result: 'done';
@@ -4,6 +4,7 @@ import { readdir, readFile, rm, stat } from 'node:fs/promises';
4
4
  import { basename, join, resolve } from 'node:path';
5
5
  import { resolveTaskDiffBase } from './git-diff-base.js';
6
6
  import { isSafeGitRef } from './git-refs.js';
7
+ import { resolveTaskRemotes, splitRemoteRef } from './git-remotes.js';
7
8
  /**
8
9
  * Git worktree per task (spec 006). Each run gets its own branch
9
10
  * `cez/<id8>` checked out into `.ai/cezar/worktrees/<runId>` so agents never
@@ -23,28 +24,29 @@ function git(cwd, args, opts = {}) {
23
24
  }
24
25
  /** Upper bound on the pre-fork fetch; a slow or unreachable remote must not stall task start. */
25
26
  const FETCH_TIMEOUT_MS = 15_000;
27
+ /** The base (PR-target) and push remotes of `dir` (`git-remotes.ts`). */
28
+ export function taskRemotes(dir) {
29
+ return resolveTaskRemotes((args) => git(dir, args));
30
+ }
26
31
  /**
27
- * Refresh `origin/<base>` so a new task forks from the newest upstream tip,
32
+ * Refresh `<remote>/<base>` so a new task forks from the newest upstream tip,
28
33
  * not whatever the remote-tracking ref happened to hold at the last manual
29
- * fetch. Best effort: no `origin`, offline, auth required or a timeout all
30
- * leave the existing refs untouched. The explicit refspec updates the
31
- * tracking ref even when the remote has a narrowed fetch config. Skipped under
32
- * `CEZ_DRY_RUN=1`, which must stay network-free.
34
+ * fetch. Best effort: offline, auth required or a timeout all leave the
35
+ * existing refs untouched. The explicit refspec updates the tracking ref even
36
+ * when the remote has a narrowed fetch config. Skipped under `CEZ_DRY_RUN=1`,
37
+ * which must stay network-free.
33
38
  */
34
- async function fetchBase(repoRoot, base) {
39
+ async function fetchBase(repoRoot, remote, base) {
35
40
  if (process.env.CEZ_DRY_RUN === '1')
36
41
  return;
37
42
  // The name is spliced into a refspec — only a well-formed branch name may be.
38
43
  const wellFormed = await git(repoRoot, ['check-ref-format', `refs/heads/${base}`]);
39
44
  if (!wellFormed.ok)
40
45
  return;
41
- const hasOrigin = await git(repoRoot, ['remote', 'get-url', 'origin']);
42
- if (!hasOrigin.ok)
43
- return;
44
- const refspec = `+refs/heads/${base}:refs/remotes/origin/${base}`;
46
+ const refspec = `+refs/heads/${base}:refs/remotes/${remote}/${base}`;
45
47
  // GIT_TERMINAL_PROMPT only silences git's own (HTTPS) prompts; an SSH remote
46
48
  // can still ask on the controlling TTY — the timeout is what bounds that.
47
- await git(repoRoot, ['fetch', '--quiet', '--no-tags', '--no-recurse-submodules', 'origin', refspec], {
49
+ await git(repoRoot, ['fetch', '--quiet', '--no-tags', '--no-recurse-submodules', remote, refspec], {
48
50
  timeout: FETCH_TIMEOUT_MS,
49
51
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
50
52
  });
@@ -52,19 +54,59 @@ async function fetchBase(repoRoot, base) {
52
54
  export function branchFor(runId) {
53
55
  return `cez/${runId.slice(0, 8)}`;
54
56
  }
57
+ /**
58
+ * A generated branch name (spec 2026-10-11-branch-naming-instructions) that no local or
59
+ * `origin/` branch already holds or blocks as a path prefix, so the fork can never attach to
60
+ * someone else's branch: the name as given, else `<name>-<id8>`. A name git refuses, or an option-like one, answers
61
+ * null and the caller keeps `cez/<id8>`. Never throws.
62
+ */
63
+ export async function uniqueBranchName(repoRoot, wanted, runId) {
64
+ if (!isSafeGitRef(wanted))
65
+ return null;
66
+ const wellFormed = await git(repoRoot, ['check-ref-format', '--branch', wanted]);
67
+ if (!wellFormed.ok)
68
+ return null;
69
+ const exists = async (name) => {
70
+ const local = await git(repoRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]);
71
+ if (local.ok)
72
+ return true;
73
+ const remote = await git(repoRoot, ['show-ref', '--verify', '--quiet', `refs/remotes/origin/${name}`]);
74
+ return remote.ok;
75
+ };
76
+ // Git refs are paths: `feature` blocks `feature/x` and `feature/x/y` blocks `feature/x`.
77
+ const taken = async (name) => {
78
+ if (await exists(name))
79
+ return true;
80
+ const parts = name.split('/');
81
+ for (let i = 1; i < parts.length; i++) {
82
+ if (await exists(parts.slice(0, i).join('/')))
83
+ return true;
84
+ }
85
+ const nested = await git(repoRoot, [
86
+ 'for-each-ref', '--count=1', '--format=%(refname)', `refs/heads/${name}/`, `refs/remotes/origin/${name}/`,
87
+ ]);
88
+ return nested.ok && nested.stdout.trim() !== '';
89
+ };
90
+ if (!(await taken(wanted)))
91
+ return wanted;
92
+ const suffixed = `${wanted}-${runId.slice(0, 8)}`;
93
+ return (await taken(suffixed)) ? null : suffixed;
94
+ }
55
95
  /**
56
96
  * Resolve the configured base branch to something `git worktree add` can
57
97
  * fork from: the local branch, its remote-tracking ref, or null — the caller
58
98
  * falls back to the current branch with a note. Never throws.
59
99
  *
60
- * When BOTH the local branch and `origin/<base>` exist, prefer whichever is up
61
- * to date. A stale LOCAL base (behind origin, because nothing fetched it into
100
+ * "The remote" is the base (PR-target) remote, `taskRemotes` (#1383).
101
+ *
102
+ * When BOTH the local branch and `<remote>/<base>` exist, prefer whichever is up
103
+ * to date. A stale LOCAL base (behind the remote, because nothing fetched it into
62
104
  * this worktree's repo) is the classic inflated-diff trap: the merge-base every
63
105
  * diff is measured from collapses onto the stale tip, so all of the history
64
- * merged into origin since then counts as the task's own changes — the phantom
65
- * 142k-line diff. `origin/<base>` is the source of truth for a review base, so
66
- * only keep the local ref when it is equal to or ahead of origin (unpushed base
67
- * commits); otherwise use origin. `origin/<base>` is fetched first (best
106
+ * merged upstream since then counts as the task's own changes — the phantom
107
+ * 142k-line diff. `<remote>/<base>` is the source of truth for a review base, so
108
+ * only keep the local ref when it is equal to or ahead of it (unpushed base
109
+ * commits); otherwise use the remote. `<remote>/<base>` is fetched first (best
68
110
  * effort) so "up to date" means the remote as it is now, not at the last fetch.
69
111
  *
70
112
  * This answers the question once, when the worktree is forked. The local ref
@@ -73,54 +115,79 @@ export function branchFor(runId) {
73
115
  * (`git-diff-base.ts`). Keep the two in agreement.
74
116
  *
75
117
  * `keepDiverged` is for the user's OWN checked-out branch (the zero-config
76
- * fork point): there a local branch that diverged from origin — rebased or
118
+ * fork point): there a local branch that diverged from the remote — rebased or
77
119
  * amended but not yet force-pushed — is the user's work, not staleness, so
78
- * origin wins only when local is strictly behind it (fast-forwardable). A
120
+ * the remote wins only when local is strictly behind it (fast-forwardable). A
79
121
  * deliberate `reset --hard HEAD~N` that is not force-pushed yet also reads as
80
122
  * "behind" — git cannot tell it from staleness — so such a task forks with the
81
- * dropped commits back in; push the reset first. An own branch origin has
82
- * never tracked is local-only work, so it skips the fetch round trip.
123
+ * dropped commits back in; push the reset first. An own branch the remote has
124
+ * never tracked is local-only work, so it skips the fetch round trip. A repo
125
+ * with no remote at all resolves to the local branch or null.
83
126
  */
84
127
  export async function resolveBaseRef(repoRoot, base, opts = {}) {
85
128
  if (!isSafeGitRef(base))
86
129
  return null;
87
130
  const verify = (ref) => git(repoRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then((r) => r.ok);
88
- if (!opts.keepDiverged || (await verify(`origin/${base}`)))
89
- await fetchBase(repoRoot, base);
90
- const [hasLocal, hasRemote] = await Promise.all([verify(base), verify(`origin/${base}`)]);
131
+ const { base: baseRemote } = opts.remotes ?? (await taskRemotes(repoRoot));
132
+ if (!baseRemote)
133
+ return (await verify(base)) ? base : null;
134
+ const remoteRef = `${baseRemote}/${base}`;
135
+ if (!opts.keepDiverged || (await verify(remoteRef)))
136
+ await fetchBase(repoRoot, baseRemote, base);
137
+ const [hasLocal, hasRemote] = await Promise.all([verify(base), verify(remoteRef)]);
91
138
  if (hasLocal && hasRemote) {
92
- // `--is-ancestor origin/<base> <base>` succeeds iff local is equal-or-ahead.
93
- const localCurrent = await git(repoRoot, ['merge-base', '--is-ancestor', `origin/${base}`, base]);
139
+ // `--is-ancestor <remote>/<base> <base>` succeeds iff local is equal-or-ahead.
140
+ const localCurrent = await git(repoRoot, ['merge-base', '--is-ancestor', remoteRef, base]);
94
141
  if (localCurrent.ok)
95
142
  return base;
96
143
  if (!opts.keepDiverged)
97
- return `origin/${base}`;
98
- // `--is-ancestor <base> origin/<base>` succeeds iff local is strictly behind here.
99
- const localBehind = await git(repoRoot, ['merge-base', '--is-ancestor', base, `origin/${base}`]);
100
- return localBehind.ok ? `origin/${base}` : base;
144
+ return remoteRef;
145
+ // `--is-ancestor <base> <remote>/<base>` succeeds iff local is strictly behind here.
146
+ const localBehind = await git(repoRoot, ['merge-base', '--is-ancestor', base, remoteRef]);
147
+ return localBehind.ok ? remoteRef : base;
101
148
  }
102
149
  if (hasLocal)
103
150
  return base;
104
151
  if (hasRemote)
105
- return `origin/${base}`;
152
+ return remoteRef;
106
153
  return null;
107
154
  }
155
+ /** `<base remote>/HEAD` names `branch`; `main`/`master` when the remote recorded no HEAD. */
156
+ async function isDefaultBranch(repoRoot, branch, baseRemote) {
157
+ if (baseRemote) {
158
+ const head = await git(repoRoot, ['symbolic-ref', '--quiet', '--short', `refs/remotes/${baseRemote}/HEAD`]);
159
+ const name = head.ok ? head.stdout.trim() : '';
160
+ if (name.startsWith(`${baseRemote}/`))
161
+ return name.slice(baseRemote.length + 1) === branch;
162
+ }
163
+ return branch === 'main' || branch === 'master';
164
+ }
108
165
  /**
109
166
  * The ref a NEW task forks from: the configured base branch when it resolves,
110
- * else the checked-out branch — itself refreshed against origin, but keeping
111
- * local work that diverged from it (`keepDiverged`). A detached HEAD stays
112
- * `HEAD`; `createWorktree` pins it to the commit. Never throws.
167
+ * else the checked-out branch — itself refreshed against the base remote, but
168
+ * keeping local work that diverged from it (`keepDiverged`) — except on the
169
+ * default branch, where local-only commits are strays, not a base (#1383). A
170
+ * detached HEAD stays `HEAD`; `createWorktree` pins it to the commit. Never throws.
113
171
  */
114
172
  export async function chooseForkBase(repoRoot, currentBranch, configured, note) {
173
+ const remotes = await taskRemotes(repoRoot);
115
174
  if (configured) {
116
- const resolved = await resolveBaseRef(repoRoot, configured);
175
+ const resolved = await resolveBaseRef(repoRoot, configured, { remotes });
117
176
  if (resolved)
118
177
  return resolved;
119
- note(`configured base branch "${configured}" not found (locally or on origin) — using "${currentBranch}"`);
178
+ note(`configured base branch "${configured}" not found (locally or on the base remote) — using "${currentBranch}"`);
120
179
  }
121
180
  if (currentBranch === 'HEAD')
122
181
  return currentBranch;
123
- return (await resolveBaseRef(repoRoot, currentBranch, { keepDiverged: true })) ?? currentBranch;
182
+ const keepDiverged = !(await isDefaultBranch(repoRoot, currentBranch, remotes.base));
183
+ const resolved = (await resolveBaseRef(repoRoot, currentBranch, { keepDiverged, remotes })) ?? currentBranch;
184
+ // Say so when a diverged default branch's local-only commits are left out of the task.
185
+ if (!keepDiverged && resolved !== currentBranch) {
186
+ const contained = await git(repoRoot, ['merge-base', '--is-ancestor', currentBranch, resolved]);
187
+ if (!contained.ok)
188
+ note(`local "${currentBranch}" diverged from "${resolved}" — forking from "${resolved}"; local-only commits are not in this task`);
189
+ }
190
+ return resolved;
124
191
  }
125
192
  export function worktreePathFor(repoRoot, runId) {
126
193
  return join(repoRoot, WORKTREES_DIR, runId);
@@ -169,8 +236,14 @@ function canonicalPath(path) {
169
236
  * branch after its directory/registration was removed. Existing non-empty
170
237
  * unregistered paths are never deleted because they may hold recoverable
171
238
  * uncommitted work.
239
+ *
240
+ * `opts.branch` is the run's recorded (or freshly generated) branch; without it the name is
241
+ * `cez/<id8>`. Recovery callers MUST pass the record's branch — a named branch cannot be
242
+ * recomputed from the run id. Precondition for a FRESH run: the name must already be unique
243
+ * (`uniqueBranchName`), because an existing branch of that name is treated as this run's own
244
+ * surviving branch and reattached — that is what rematerializing a reclaimed worktree needs.
172
245
  */
173
- export async function createWorktree(repoRoot, runId, baseBranch) {
246
+ export async function createWorktree(repoRoot, runId, baseBranch, opts = {}) {
174
247
  let base = baseBranch;
175
248
  if (!base || base === 'HEAD') {
176
249
  // Detached HEAD — pin the base to the current commit so the record and
@@ -184,7 +257,9 @@ export async function createWorktree(repoRoot, runId, baseBranch) {
184
257
  // option-like value would be argument injection.
185
258
  if (!isSafeGitRef(base))
186
259
  throw new Error(`refusing option-like base ref: ${base}`);
187
- const branch = branchFor(runId);
260
+ const branch = opts.branch ?? branchFor(runId);
261
+ if (!isSafeGitRef(branch))
262
+ throw new Error(`refusing option-like branch name: ${branch}`);
188
263
  const absolutePath = join(canonicalPath(repoRoot), WORKTREES_DIR, runId);
189
264
  const branchRef = `refs/heads/${branch}`;
190
265
  // A missing directory can leave stale administrative metadata behind.
@@ -600,34 +675,37 @@ export function parseShortstat(s) {
600
675
  * git failure (the caller notes it, never fails the run); an empty diff is a
601
676
  * valid all-zero stat.
602
677
  */
603
- /** Push `branch` to origin (the graph `git.push` node). Never throws; `CEZ_DRY_RUN=1` is a no-op. */
678
+ /** Push `branch` to the push remote (the graph `git.push` node). Never throws; `CEZ_DRY_RUN=1` is a no-op. */
604
679
  export async function pushBranch(dir, branch) {
605
680
  if (process.env.CEZ_DRY_RUN === '1')
606
681
  return { ok: true };
607
682
  if (!isSafeGitRef(branch))
608
683
  return { ok: false, error: `refusing option-like branch: ${branch}` };
609
- const remote = await git(dir, ['remote', 'get-url', 'origin']);
610
- if (!remote.ok)
611
- return { ok: false, error: 'no origin remote' };
612
- const push = await git(dir, ['-c', 'credential.interactive=false', 'push', '-u', 'origin', branch]);
684
+ const { push: remote } = await taskRemotes(dir);
685
+ if (!remote)
686
+ return { ok: false, error: 'no git remote' };
687
+ const push = await git(dir, ['-c', 'credential.interactive=false', 'push', '-u', remote, branch]);
613
688
  return push.ok ? { ok: true } : { ok: false, error: (push.stderr || push.stdout).trim().split('\n')[0] || 'git push failed' };
614
689
  }
615
690
  /**
616
- * Merge the freshest base into the worktree (the graph `git.sync-base` node): `origin/<base>`
617
- * after a fetch when origin has it, else the local base. A conflicted merge is LEFT IN PROGRESS
618
- * and reported with its files — the next node (an agent) resolves it; autosave refuses a
619
- * mid-merge tree, so nothing half-resolved gets committed meanwhile. Never throws.
691
+ * Merge the freshest base into the worktree (the graph `git.sync-base` node): `<remote>/<base>`
692
+ * after a fetch when the base remote (or the remote a recorded `upstream/main` names) has it,
693
+ * else the local base. A conflicted merge is LEFT IN PROGRESS and reported with its files — the
694
+ * next node (an agent) resolves it; autosave refuses a mid-merge tree, so nothing half-resolved
695
+ * gets committed meanwhile. Never throws.
620
696
  */
621
697
  export async function syncWithBase(dir, baseBranch) {
622
698
  if (!isSafeGitRef(baseBranch))
623
699
  return { result: 'failed', error: `refusing option-like base: ${baseBranch}` };
624
700
  let ref = baseBranch;
625
- const remote = await git(dir, ['remote', 'get-url', 'origin']);
626
- if (remote.ok && process.env.CEZ_DRY_RUN !== '1') {
627
- await git(dir, ['fetch', 'origin', baseBranch]);
628
- const remoteRef = await git(dir, ['rev-parse', '--verify', '--quiet', `origin/${baseBranch}`]);
701
+ const remotes = await taskRemotes(dir);
702
+ const split = splitRemoteRef(baseBranch, remotes.names);
703
+ const remote = split.remote ?? remotes.base;
704
+ if (remote && process.env.CEZ_DRY_RUN !== '1') {
705
+ await fetchBase(dir, remote, split.branch);
706
+ const remoteRef = await git(dir, ['rev-parse', '--verify', '--quiet', `${remote}/${split.branch}`]);
629
707
  if (remoteRef.ok)
630
- ref = `origin/${baseBranch}`;
708
+ ref = `${remote}/${split.branch}`;
631
709
  }
632
710
  const identityArgs = (await gitHasIdentity(dir)) ? [] : ['-c', 'user.name=cezar', '-c', 'user.email=cezar@local'];
633
711
  const merge = await git(dir, [...identityArgs, 'merge', '--no-edit', ref]);
@@ -680,10 +758,16 @@ export async function pruneOrphans(repoRoot, validIds) {
680
758
  return []; // no worktrees dir yet
681
759
  }
682
760
  const removed = [];
761
+ const registered = await registeredWorktrees(repoRoot);
683
762
  for (const entry of entries) {
684
763
  if (!entry.isDirectory() || validIds.has(entry.name))
685
764
  continue;
686
- await removeWorktree(repoRoot, worktreePathFor(repoRoot, entry.name), branchFor(entry.name));
765
+ const path = worktreePathFor(repoRoot, entry.name);
766
+ // An orphan has no record, so its branch is whatever the worktree has checked out — a
767
+ // named branch (spec 2026-10-11-branch-naming-instructions) is not derivable from the id.
768
+ const checkedOut = registered.find((item) => canonicalPath(item.path) === canonicalPath(path))?.branch;
769
+ const branch = checkedOut?.startsWith('refs/heads/') ? checkedOut.slice('refs/heads/'.length) : branchFor(entry.name);
770
+ await removeWorktree(repoRoot, path, branch);
687
771
  removed.push(entry.name);
688
772
  }
689
773
  return removed;