pi-cowboy 0.0.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/agents/explore.toml +40 -0
  4. package/dist/agents/agent-assets.js +261 -0
  5. package/dist/agents/agent-cleanup.js +284 -0
  6. package/dist/agents/agent-discovery.js +108 -0
  7. package/dist/agents/agent-host.js +10 -0
  8. package/dist/agents/agent-manager.js +367 -0
  9. package/dist/agents/agent-reviver.js +64 -0
  10. package/dist/agents/agent-runner.js +288 -0
  11. package/dist/agents/agent-spawn-store.js +57 -0
  12. package/dist/agents/agent-template.js +46 -0
  13. package/dist/agents/agent-types.js +144 -0
  14. package/dist/agents/batch.js +92 -0
  15. package/dist/agents/cleanup-policy.js +194 -0
  16. package/dist/agents/cleanup-report.js +128 -0
  17. package/dist/agents/default-agents.js +19 -0
  18. package/dist/agents/harness/pi-bolt.js +15 -0
  19. package/dist/agents/harness/pi-compatible.js +68 -0
  20. package/dist/agents/harness/pig.js +16 -0
  21. package/dist/agents/harness/registry.js +27 -0
  22. package/dist/agents/harness.js +32 -0
  23. package/dist/agents/result-file-permissions.js +29 -0
  24. package/dist/agents/run-state.js +270 -0
  25. package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
  26. package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
  27. package/dist/agents/schemas/merge-batch.schema.js +25 -0
  28. package/dist/agents/schemas/steer-batch.schema.js +22 -0
  29. package/dist/agents/schemas/stop-batch.schema.js +18 -0
  30. package/dist/agents/spawn-defaults.js +70 -0
  31. package/dist/agents/subagent-session.js +601 -0
  32. package/dist/agents/tool-cleanup.js +57 -0
  33. package/dist/agents/tool-execution.js +125 -0
  34. package/dist/agents/tool-merge.js +190 -0
  35. package/dist/agents/tool-result.js +17 -0
  36. package/dist/agents/tool-steer.js +89 -0
  37. package/dist/agents/types.js +1 -0
  38. package/dist/availability.js +38 -0
  39. package/dist/config/config-io.js +261 -0
  40. package/dist/config/config-store.js +321 -0
  41. package/dist/config/config-validation.js +173 -0
  42. package/dist/config/layered-config.js +117 -0
  43. package/dist/config/types.js +23 -0
  44. package/dist/cow-support-launch.js +43 -0
  45. package/dist/events.js +146 -0
  46. package/dist/extension-toggle.js +28 -0
  47. package/dist/harness-availability-launch.js +23 -0
  48. package/dist/index.js +52 -0
  49. package/dist/infrastructure/exec-path.js +35 -0
  50. package/dist/infrastructure/git/cow-clone.js +398 -0
  51. package/dist/infrastructure/git/git-materializer.js +342 -0
  52. package/dist/infrastructure/git/git-merger.js +234 -0
  53. package/dist/infrastructure/git/git-retention.js +43 -0
  54. package/dist/infrastructure/git/git-runner.js +145 -0
  55. package/dist/infrastructure/git/git-worktree.js +143 -0
  56. package/dist/infrastructure/git/index.js +11 -0
  57. package/dist/infrastructure/git-client.js +11 -0
  58. package/dist/infrastructure/herdr/agent-stopper.js +60 -0
  59. package/dist/infrastructure/herdr/agents.js +329 -0
  60. package/dist/infrastructure/herdr/herdr-client.js +36 -0
  61. package/dist/infrastructure/herdr/herdr-transport.js +158 -0
  62. package/dist/infrastructure/herdr/index.js +15 -0
  63. package/dist/infrastructure/herdr/panes.js +174 -0
  64. package/dist/infrastructure/herdr/polling.js +44 -0
  65. package/dist/infrastructure/herdr/worktrees.js +76 -0
  66. package/dist/infrastructure/herdr-client.js +6 -0
  67. package/dist/infrastructure/herdr-host.js +163 -0
  68. package/dist/logger.js +79 -0
  69. package/dist/models/model-groups.js +72 -0
  70. package/dist/models/model-precedence.js +50 -0
  71. package/dist/models/model-request.js +108 -0
  72. package/dist/orchestrators/briefing-section.js +14 -0
  73. package/dist/orchestrators/context.js +116 -0
  74. package/dist/orchestrators/cues.js +90 -0
  75. package/dist/orchestrators/default-orchestrators.js +36 -0
  76. package/dist/orchestrators/orchestrator-discovery.js +68 -0
  77. package/dist/orchestrators/orchestrator-template.js +43 -0
  78. package/dist/orchestrators/orchestrator-types.js +78 -0
  79. package/dist/orchestrators/protocol.js +292 -0
  80. package/dist/orchestrators/types.js +7 -0
  81. package/dist/paths.js +66 -0
  82. package/dist/pi-settings.js +7 -0
  83. package/dist/predicates.js +25 -0
  84. package/dist/prompt/prompts.js +110 -0
  85. package/dist/prompt/skill-loader.js +153 -0
  86. package/dist/prompt/subagent-system-prompt.js +173 -0
  87. package/dist/registration.js +220 -0
  88. package/dist/shell.js +225 -0
  89. package/dist/spawn/cow-support.js +53 -0
  90. package/dist/spawn/herdr-launcher.js +80 -0
  91. package/dist/spawn/repo-lock.js +34 -0
  92. package/dist/spawn/sandbox.js +286 -0
  93. package/dist/spawn/spawn-coordinator.js +255 -0
  94. package/dist/spawn/spawn-id.js +39 -0
  95. package/dist/spawn/worktree-policy.js +137 -0
  96. package/dist/status-note.js +30 -0
  97. package/dist/subagent/ipc-protocol.js +68 -0
  98. package/dist/subagent/ipc.js +110 -0
  99. package/dist/subagent/pane-supervisor.js +24 -0
  100. package/dist/subagent/socket-ipc.js +240 -0
  101. package/dist/subagent/supervisor.js +315 -0
  102. package/dist/task-registry.js +258 -0
  103. package/dist/templates/template-files.js +84 -0
  104. package/dist/types.js +84 -0
  105. package/dist/ui/action-report.js +21 -0
  106. package/dist/ui/format.js +47 -0
  107. package/dist/ui/indicator.js +480 -0
  108. package/dist/ui/menu/helpers.js +227 -0
  109. package/dist/ui/menu/menu-agent-settings.js +182 -0
  110. package/dist/ui/menu/menu-agent-status.js +444 -0
  111. package/dist/ui/menu/menu-concurrency.js +226 -0
  112. package/dist/ui/menu/menu-model-settings.js +244 -0
  113. package/dist/ui/menu/menu-spawn-defaults.js +71 -0
  114. package/dist/ui/menu/menu-spawn-wizard.js +367 -0
  115. package/dist/ui/menu/menu-spawn-worktree.js +107 -0
  116. package/dist/ui/menu/menu-system-prompt.js +104 -0
  117. package/dist/ui/menu/menu-worktree-command.js +150 -0
  118. package/dist/ui/menu/menus.js +187 -0
  119. package/dist/ui/menu/model-picker.js +160 -0
  120. package/dist/ui/menu/screen-host.js +87 -0
  121. package/dist/ui/menu/submenus/confirm.js +23 -0
  122. package/dist/ui/menu/submenus/model-select.js +42 -0
  123. package/dist/ui/menu/submenus/name-field.js +43 -0
  124. package/dist/ui/menu/submenus/numeric-input.js +61 -0
  125. package/dist/ui/menu/submenus/target-select.js +129 -0
  126. package/dist/ui/menu/submenus/text-editor.js +49 -0
  127. package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
  128. package/dist/ui/menu/submenus/worktree-name.js +53 -0
  129. package/dist/ui/menu/wrappers/settings-list.js +101 -0
  130. package/dist/ui/searchable-select.js +147 -0
  131. package/dist/ui/types.js +1 -0
  132. package/dist/utils.js +70 -0
  133. package/docs/assets/grazing.png +0 -0
  134. package/docs/assets/herdr-containers.png +0 -0
  135. package/docs/assets/logo-transparent.png +0 -0
  136. package/orchestrators/with-code-review.toml +20 -0
  137. package/package.json +109 -3
@@ -0,0 +1,342 @@
1
+ /**
2
+ * git-materializer.ts — Layer 3: how a fresh worktree's working tree is populated.
3
+ *
4
+ * Copy-on-write is an optimization, not a requirement: when the volume cannot
5
+ * clone, `clone()` catches that one failure, asks git for a classic checkout
6
+ * instead (`fallbackToCheckout`), and reports it as the "cow-fallback" outcome.
7
+ * Every other failure still throws, so the caller fails the spawn and removes
8
+ * the worktree. The clone itself is `cow-clone.ts`, which probes the volume
9
+ * before anything is wiped, so an unclonable volume is known before any work
10
+ * starts.
11
+ *
12
+ * One `WorktreeMaterialization` strategy drives both `worktreeAddArgs` and this
13
+ * step, so the add and the materialization can never disagree. The separate
14
+ * `WorktreeCheckoutType` policy picks what a dirty main checkout contributes: a
15
+ * clone takes the whole tree ("dirty") or tracked-files-from-HEAD plus seeded
16
+ * ignored state ("clean"), while a classic checkout has the parent's tracked
17
+ * diff applied ("dirty") or stays as git's checkout of HEAD ("clean"). A clean
18
+ * main checkout always materializes as HEAD, either way.
19
+ */
20
+ import * as fs from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import * as path from "node:path";
23
+ import { DEFAULT_WORKTREE_CHECKOUT_TYPE } from "../../spawn/worktree-policy.js";
24
+ import { CowCloneError, defaultCowCloneDeps, materializeCowClone, } from "./cow-clone.js";
25
+ import { GitCommandRunner, GitError, GIT_WORKTREE_TIMEOUT_MS, locateMainCheckout, } from "./git-runner.js";
26
+ // --- Constants ---
27
+ /** Why a dirty main checkout seeds instead of cloning. */
28
+ const SEEDED_REASON = 'main checkout has uncommitted changes and the dirty-checkout policy is "clean"; tracked files stay as git\'s checkout, ignored state CoW-seeded';
29
+ /** Why a dirty main checkout was cloned whole. */
30
+ const CLONED_WIP_REASON = "main checkout has uncommitted changes; its tracked edits and untracked files were cloned into the worktree";
31
+ /** Why a copy-on-write materialization ended up as a plain checkout. */
32
+ const FALLBACK_REASON = "the worktree volume cannot clone; the checkout was completed by git instead";
33
+ /**
34
+ * `git worktree add` arguments per strategy. Copy-on-write populates the tree
35
+ * itself, so the add leaves the index empty; a classic checkout lets git
36
+ * populate it during the add.
37
+ */
38
+ export function worktreeAddArgs(strategy) {
39
+ return strategy === "copy-on-write" ? ["--no-checkout"] : [];
40
+ }
41
+ /**
42
+ * IGNORED paths a CoW seed should copy, from `git status --ignored
43
+ * --porcelain -z` entries. Only `!!` entries (untracked files would dirty the
44
+ * worktree); newline-containing paths are skipped (the seed list is
45
+ * newline-separated).
46
+ */
47
+ export function ignoredSeedPaths(entries) {
48
+ const rels = [];
49
+ for (const entry of entries) {
50
+ if (!entry.startsWith("!! "))
51
+ continue;
52
+ const rel = entry.slice(3);
53
+ if (rel === "" || rel.includes("\n"))
54
+ continue;
55
+ rels.push(rel);
56
+ }
57
+ return rels;
58
+ }
59
+ // --- Materialization ---
60
+ /** Materializes a fresh worktree's working tree per strategy. */
61
+ export class CowCloneMaterializer {
62
+ runner;
63
+ exec;
64
+ constructor(runner, exec) {
65
+ this.runner = runner;
66
+ this.exec = exec;
67
+ }
68
+ /**
69
+ * Populate a fresh worktree per strategy: `checkout` and `copy-on-write` each
70
+ * decide what a dirty main checkout contributes.
71
+ */
72
+ async materialize(wtPath, strategy, dirtyCheckout) {
73
+ return strategy === "checkout"
74
+ ? this.checkout(wtPath, dirtyCheckout)
75
+ : this.clone(wtPath, dirtyCheckout);
76
+ }
77
+ /**
78
+ * CoW-clone a `--no-checkout` worktree from the main checkout, then let git
79
+ * complete the checkout. A clean main, or a dirty main with the "dirty"
80
+ * policy, gets the whole tree ("cow"); a dirty main with "clean" gets tracked
81
+ * files from HEAD plus CoW-seeded ignored state ("seeded") — ignored files
82
+ * cannot dirty `git status`. A volume that cannot clone falls back to git's
83
+ * classic checkout ("cow-fallback"); every other failure throws.
84
+ */
85
+ async clone(wtPath, dirtyCheckout) {
86
+ const wt = path.resolve(wtPath);
87
+ const mainRoot = await this.mainCheckoutOf(wt);
88
+ const mainStatus = await this.mainStatus(mainRoot);
89
+ const expectation = mainStatus === ""
90
+ ? { kind: "clean-parent" }
91
+ : { kind: "dirty-parent", policy: dirtyCheckout };
92
+ const wholeTree = expectation.kind === "clean-parent" || expectation.policy === "dirty";
93
+ try {
94
+ await this.cloneWorkingTree(wt, mainRoot, wholeTree
95
+ ? { kind: "all" }
96
+ : { kind: "seed", rels: await this.ignoredRels(mainRoot) });
97
+ }
98
+ catch (err) {
99
+ if (!(err instanceof CowCloneError) || err.reason !== "unsupported") {
100
+ throw err;
101
+ }
102
+ await this.fallbackToCheckout(wt);
103
+ return { kind: "cow-fallback", reason: FALLBACK_REASON };
104
+ }
105
+ await this.completeCheckout(wt, wholeTree);
106
+ await this.verifyMaterialization(wt, mainRoot, expectation);
107
+ if (expectation.kind === "clean-parent") {
108
+ return { kind: "cow", clone: { mode: "cow" } };
109
+ }
110
+ return {
111
+ kind: "cow",
112
+ clone: wholeTree
113
+ ? { mode: "cow", reason: CLONED_WIP_REASON }
114
+ : { mode: "seeded", reason: SEEDED_REASON },
115
+ };
116
+ }
117
+ /**
118
+ * Complete a classic checkout: the add already laid the tracked files down, so
119
+ * the policy decides only whether a dirty main checkout's tracked changes are
120
+ * applied on top of them. Untracked and ignored state is never carried: there
121
+ * is no clone to share it with, and inventing one would mean copying a tree
122
+ * that may hold a `node_modules` of its own.
123
+ */
124
+ async checkout(wtPath, dirtyCheckout) {
125
+ if (dirtyCheckout === "dirty") {
126
+ const wt = path.resolve(wtPath);
127
+ await this.applyUncommitted(await this.mainCheckoutOf(wt), wt);
128
+ }
129
+ return { kind: "checkout" };
130
+ }
131
+ /**
132
+ * Apply the main checkout's tracked changes to the worktree. git writes the
133
+ * patch straight into a file — `--no-renames` so a rename arrives as a plain
134
+ * delete plus add, and `--binary` so a binary file survives the trip — and the
135
+ * file is removed again whether the apply lands or not.
136
+ */
137
+ async applyUncommitted(mainRoot, wt) {
138
+ const dir = fs.mkdtempSync(path.join(tmpdir(), "pi-cowboy-wip-"));
139
+ const patch = path.join(dir, "wip.patch");
140
+ try {
141
+ const read = await this.runner.test(["diff", "HEAD", "--binary", "--no-renames", `--output=${patch}`], mainRoot, GIT_WORKTREE_TIMEOUT_MS);
142
+ if (!read) {
143
+ throw new GitError(`checkout worktree materialization failed: could not read the main checkout's tracked changes`);
144
+ }
145
+ // git writes an empty file for an empty diff, and nothing at all when it
146
+ // could not write; both mean there is no tracked work to carry.
147
+ if (!fs.existsSync(patch) || fs.statSync(patch).size === 0)
148
+ return;
149
+ const applied = await this.runner.test(["apply", "--whitespace=nowarn", patch], wt, GIT_WORKTREE_TIMEOUT_MS);
150
+ if (!applied) {
151
+ throw new GitError(`checkout worktree materialization failed: could not apply the main checkout's tracked changes to the worktree`);
152
+ }
153
+ }
154
+ finally {
155
+ fs.rmSync(dir, { recursive: true, force: true });
156
+ }
157
+ }
158
+ /**
159
+ * Resolve `wt`'s main checkout root. A `.git` directory (not file) is the main
160
+ * checkout itself — never replaced — and the main checkout must not live
161
+ * inside the worktree, or wiping the worktree would destroy it.
162
+ */
163
+ async mainCheckoutOf(wt) {
164
+ let marker;
165
+ try {
166
+ if (!fs.statSync(wt).isDirectory())
167
+ cowFail("target is not a directory");
168
+ if (!fs.lstatSync(path.join(wt, ".git")).isFile()) {
169
+ cowFail("target is not a linked worktree (.git is not a file)");
170
+ }
171
+ marker = fs.readFileSync(path.join(wt, ".git"), "utf8");
172
+ }
173
+ catch (err) {
174
+ if (err instanceof GitError)
175
+ throw err;
176
+ cowFail("target is not a git worktree");
177
+ }
178
+ const common = await this.runner.probe(["rev-parse", "--git-common-dir"], wt);
179
+ if (common === undefined)
180
+ cowFail("git rev-parse --git-common-dir failed");
181
+ const { commonDir, mainRoot } = locateMainCheckout(common, wt);
182
+ if (!fs.existsSync(path.join(mainRoot, ".git"))) {
183
+ cowFail("main checkout not found");
184
+ }
185
+ if (path.resolve(mainRoot) === path.resolve(wt)) {
186
+ cowFail("target is the main checkout");
187
+ }
188
+ if (isWithin(wt, mainRoot)) {
189
+ cowFail("main checkout lives inside the worktree");
190
+ }
191
+ const trimmed = marker.trim();
192
+ const pointer = trimmed.startsWith("gitdir:")
193
+ ? trimmed.slice("gitdir:".length).trim()
194
+ : "";
195
+ if (pointer === "")
196
+ cowFail("malformed .git worktree marker");
197
+ const gitdir = path.isAbsolute(pointer)
198
+ ? pointer
199
+ : path.resolve(wt, pointer);
200
+ if (!gitdir.startsWith(commonDir + path.sep)) {
201
+ cowFail("worktree gitdir is outside this repo");
202
+ }
203
+ if (!fs.existsSync(gitdir))
204
+ cowFail("worktree gitdir missing");
205
+ return mainRoot;
206
+ }
207
+ /** Main checkout porcelain status; unreadable fails loud. */
208
+ async mainStatus(mainRoot) {
209
+ const mainStatus = await this.runner.probe(["status", "--porcelain"], mainRoot);
210
+ if (mainStatus === undefined)
211
+ cowFail("could not read main checkout status");
212
+ return mainStatus;
213
+ }
214
+ /** CoW-clone the working tree through the shared cloner; a failure is fatal. */
215
+ async cloneWorkingTree(wt, mainRoot, mode) {
216
+ try {
217
+ await materializeCowClone({ wtPath: wt, mainRoot }, mode, defaultCowCloneDeps(this.exec));
218
+ }
219
+ catch (err) {
220
+ // "This volume cannot clone" is the one failure with somewhere to go, so
221
+ // it reaches the caller as itself; everything else stays fatal.
222
+ if (err instanceof CowCloneError && err.reason === "unsupported")
223
+ throw err;
224
+ cowFail(err instanceof CowCloneError ? err.message : String(err));
225
+ }
226
+ }
227
+ /**
228
+ * Lay the tree down the way a classic checkout would. The worktree was added
229
+ * with `--no-checkout`, so a reset from HEAD is exactly what the add would
230
+ * have done on its own: tracked files from HEAD, nothing shared with the parent.
231
+ */
232
+ async fallbackToCheckout(wt) {
233
+ const done = await this.runner.test(["reset", "--hard", "HEAD"], wt, GIT_WORKTREE_TIMEOUT_MS);
234
+ if (!done) {
235
+ cowFail("the worktree volume cannot clone and its checkout could not be completed");
236
+ }
237
+ }
238
+ /** Dirty main: CoW-seed only the IGNORED paths; tracked files come from HEAD. */
239
+ async ignoredRels(mainRoot) {
240
+ const entries = await this.runner.lines(["status", "--ignored", "--porcelain", "-z"], mainRoot, "\0");
241
+ if (entries === undefined) {
242
+ cowFail("could not read main checkout ignored files");
243
+ }
244
+ return ignoredSeedPaths(entries);
245
+ }
246
+ /**
247
+ * Complete the checkout. A mixed reset refreshes the index without rewriting
248
+ * files, so CoW shares survive; when the tracked files were never copied they
249
+ * are materialized from HEAD instead — which would clobber a cloned working
250
+ * tree, so it is the seed path only.
251
+ */
252
+ async completeCheckout(wt, wholeTree) {
253
+ const done = wholeTree
254
+ ? await this.runner.test(["reset", "-q"], wt, GIT_WORKTREE_TIMEOUT_MS)
255
+ : await this.runner.test(["checkout", "-q", "HEAD", "--", "."], wt, GIT_WORKTREE_TIMEOUT_MS);
256
+ if (!done) {
257
+ cowFail(wholeTree
258
+ ? "could not refresh the worktree index after materialization"
259
+ : "could not materialize tracked files in the worktree");
260
+ }
261
+ }
262
+ /** Check what the materialization was asked to produce; an unreadable probe is a failure, never a pass. */
263
+ async verifyMaterialization(wt, mainRoot, expectation) {
264
+ /** Set-equality of two path lists; both are compared sorted. */
265
+ function samePaths(a, b) {
266
+ const left = [...a].sort();
267
+ const right = [...b].sort();
268
+ return (left.length === right.length &&
269
+ left.every((path, i) => path === right[i]));
270
+ }
271
+ /** The parent's paths the clone was able to carry; the rest it had to leave behind. */
272
+ const carried = (paths) => paths.filter((rel) => !overlapsWorktree(mainRoot, rel, wt));
273
+ if (expectation.kind === "clean-parent") {
274
+ return this.assertClean(wt, "a clean parent");
275
+ }
276
+ if (expectation.policy === "clean") {
277
+ return this.assertClean(wt, 'the "clean" dirty-checkout policy');
278
+ }
279
+ const main = await this.changeLists(mainRoot);
280
+ const clone = await this.changeLists(wt);
281
+ if (!samePaths(carried(main.tracked), clone.tracked) ||
282
+ !samePaths(carried(main.untracked), clone.untracked)) {
283
+ cowFail("worktree does not mirror the main checkout's uncommitted changes");
284
+ }
285
+ }
286
+ /**
287
+ * The parent's tracked changes against HEAD and its untracked, non-ignored
288
+ * files. Read together with the worktree's copy: a fresh worktree's index sits
289
+ * at HEAD, so a staged change reads differently per checkout while the content
290
+ * matches.
291
+ */
292
+ async changeLists(root) {
293
+ const tracked = await this.runner.lines(["diff", "HEAD", "--name-only", "-z"], root, "\0");
294
+ if (tracked === undefined)
295
+ cowFail("could not read tracked changes");
296
+ const untracked = await this.runner.lines(["ls-files", "--others", "--exclude-standard", "-z"], root, "\0");
297
+ if (untracked === undefined)
298
+ cowFail("could not read untracked files");
299
+ return { tracked, untracked };
300
+ }
301
+ /** The worktree must be clean afterwards; an unreadable status is not "clean". */
302
+ async assertClean(wt, expected) {
303
+ const wtStatus = await this.runner.probe(["status", "--porcelain"], wt);
304
+ if (wtStatus !== "") {
305
+ cowFail(`${expected} should leave the worktree clean, but it is not`);
306
+ }
307
+ }
308
+ }
309
+ // --- Free-function facade ---
310
+ /** Populate a fresh worktree per strategy (see `CowCloneMaterializer.materialize`). */
311
+ export async function materializeWorktree(pi, wtPath, strategy, dirtyCheckout = DEFAULT_WORKTREE_CHECKOUT_TYPE) {
312
+ return new CowCloneMaterializer(new GitCommandRunner(pi), execOf(pi)).materialize(wtPath, strategy, dirtyCheckout);
313
+ }
314
+ /** CoW-clone a `--no-checkout` worktree (see `CowCloneMaterializer.clone`). */
315
+ export async function cowCloneWorktree(pi, wtPath, dirtyCheckout = DEFAULT_WORKTREE_CHECKOUT_TYPE) {
316
+ return new CowCloneMaterializer(new GitCommandRunner(pi), execOf(pi)).clone(wtPath, dirtyCheckout);
317
+ }
318
+ /** `pi.exec` as the cloner's seam: the same one place shells out of the extension. */
319
+ function execOf(pi) {
320
+ return (command, args, options) => pi.exec(command, args, options);
321
+ }
322
+ // --- Internals ---
323
+ /** Throw a GitError for a failed CoW materialization. */
324
+ function cowFail(message) {
325
+ throw new GitError(`copy-on-write worktree materialization failed: ${message}`);
326
+ }
327
+ /** Whether `child` is `container` or inside it: node:path has no predicate, `relative` is its primitive. */
328
+ function isWithin(container, child) {
329
+ const rel = path.relative(path.resolve(container), path.resolve(child));
330
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
331
+ }
332
+ /**
333
+ * Whether a main-checkout-relative path is the worktree, holds it, or lives
334
+ * inside it: the entries a whole-tree clone never carries (cow-clone's
335
+ * `mainEntries`). Resolved, so git's trailing slash on an untracked directory
336
+ * does not matter.
337
+ */
338
+ function overlapsWorktree(mainRoot, rel, wt) {
339
+ const abs = path.resolve(mainRoot, rel);
340
+ const target = path.resolve(wt);
341
+ return isWithin(abs, target) || isWithin(target, abs);
342
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * git-merger.ts — Layer 3: branch lifecycle against the main checkout.
3
+ *
4
+ * - `BranchMerger`: merge a settled agent branch into the target.
5
+ * - `BranchCleaner`: delete the branch a worktree carried once its commits are
6
+ * merged. The branch a failed create minted is not this module's to remove:
7
+ * see git-worktree.ts's `deleteCreatedBranch`.
8
+ */
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import { z } from "zod";
12
+ import { GitError, GitCommandRunner, locateMainCheckout, } from "./git-runner.js";
13
+ import { deleteBranchRef, refExists, } from "./git-worktree.js";
14
+ // --- Constants ---
15
+ /** Large trees can be slow to merge. */
16
+ const MERGE_TIMEOUT_MS = 120_000;
17
+ /**
18
+ * Rejects refs git would misread: a leading `-` (parsed as a flag), `..`
19
+ * (range) and `@{` (reflog) — both of which resolve even under a
20
+ * fully-qualified `refs/heads/` prefix — and any character outside
21
+ * `[A-Za-z0-9._/-]`. Deliberately stricter than `git check-ref-format`.
22
+ */
23
+ const REF_OFFENSE = /^-|\.\.|@\{|[^A-Za-z0-9._/-]/;
24
+ /**
25
+ * Branch-name grammar at the boundary where a ref becomes a git argument:
26
+ * non-empty and free of {@link REF_OFFENSE}. A Zod schema so refusals carry
27
+ * structured reasons.
28
+ */
29
+ export const BranchRefSchema = z.string().check((ctx) => {
30
+ const clause = ctx.value === "" ? "is empty" : refusalClauseFor(ctx.value);
31
+ if (clause !== undefined) {
32
+ ctx.issues.push({ code: "custom", input: ctx.value, message: clause });
33
+ }
34
+ });
35
+ /** Earliest problem with `ref`, or `undefined` when it is valid. */
36
+ function refusalClauseFor(ref) {
37
+ const token = REF_OFFENSE.exec(ref)?.[0];
38
+ if (token === undefined)
39
+ return undefined;
40
+ if (token === "-") {
41
+ return `starts with "-": git would parse that as a command-line flag, not a branch name`;
42
+ }
43
+ if (token === "..") {
44
+ return `contains "..": revision ranges are not branch names`;
45
+ }
46
+ if (token === "@{") {
47
+ return `contains "@{": reflog/date syntax is not a branch name`;
48
+ }
49
+ return `contains invalid character ${describeRefChar(token)}: branch names may only use letters, digits, ".", "_", "/", and "-"`;
50
+ }
51
+ /** A rejected character, quoted; whitespace and control characters as `U+XXXX`. */
52
+ function describeRefChar(char) {
53
+ const code = char.charCodeAt(0);
54
+ if (code <= 0x20 || code === 0x7f) {
55
+ return `U+${code.toString(16).toUpperCase().padStart(4, "0")}`;
56
+ }
57
+ return JSON.stringify(char);
58
+ }
59
+ /**
60
+ * Reject an invalid branch/target ref before it reaches any git argv.
61
+ * Invalid input is never coerced or defaulted. Callers pass the trimmed
62
+ * value; any remaining whitespace is rejected as an invalid character.
63
+ */
64
+ export function assertValidBranchRef(ref, role) {
65
+ const parsed = BranchRefSchema.safeParse(ref);
66
+ if (parsed.success)
67
+ return;
68
+ const reasons = parsed.error.issues.map((issue) => issue.message).join("; ");
69
+ throw new Error(`refusing to merge: the ${role} ref ${JSON.stringify(ref)} ${reasons}.`);
70
+ }
71
+ // --- Merge ---
72
+ /**
73
+ * Merges a settled agent branch into the target branch (default `main`) in
74
+ * the repo's main checkout.
75
+ */
76
+ export class BranchMerger {
77
+ runner;
78
+ constructor(runner) {
79
+ this.runner = runner;
80
+ }
81
+ /**
82
+ * Runs in the main checkout, whose HEAD must already be the target — a
83
+ * merge anywhere else lands on the wrong branch. Refuses on an unknown or
84
+ * self branch, a dirty tree, or anything it could not verify; an
85
+ * already-merged branch is reported without running git, and conflicts are
86
+ * left in progress, never auto-resolved.
87
+ */
88
+ async merge(options) {
89
+ const branch = options.branch.trim();
90
+ assertValidBranchRef(branch, "branch");
91
+ const target = (options.target ?? "main").trim();
92
+ assertValidBranchRef(target, "target");
93
+ const toplevel = await this.runner.probe(["rev-parse", "--show-toplevel"], options.cwd);
94
+ if (toplevel === undefined) {
95
+ throw new Error(`cannot merge "${branch}": ${options.cwd} is not inside a git repository`);
96
+ }
97
+ const common = await this.runner.probe(["rev-parse", "--git-common-dir"], toplevel);
98
+ if (common === undefined) {
99
+ throw new Error(`cannot merge "${branch}": could not resolve the repo's git directory`);
100
+ }
101
+ const { mainRoot } = locateMainCheckout(common, toplevel);
102
+ if (!fs.existsSync(path.join(mainRoot, ".git"))) {
103
+ throw new Error(`cannot merge "${branch}": no main checkout found (unsupported repo layout)`);
104
+ }
105
+ const current = await this.runner.probe(["branch", "--show-current"], mainRoot);
106
+ if (current !== target) {
107
+ throw new Error(current === undefined
108
+ ? `refusing to merge "${branch}": could not read the current branch of the main checkout (${mainRoot})`
109
+ : `refusing to merge "${branch}": the main checkout (${mainRoot}) is on branch "${current || "(detached)"}", not the merge target "${target}". A merge would land on "${current || "(detached)"}" instead of "${target}".`);
110
+ }
111
+ if (branch === target) {
112
+ throw new Error(`refusing to merge "${branch}" into itself (already on "${target}")`);
113
+ }
114
+ // Fully qualified so the ref cannot parse as a flag; no `--` separator
115
+ // because `rev-parse --verify` takes exactly one revision.
116
+ const exists = await this.runner.test(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], mainRoot);
117
+ if (!exists) {
118
+ throw new Error(`refusing to merge: branch "${branch}" does not exist in ${mainRoot}.`);
119
+ }
120
+ const status = await this.runner.probe(["status", "--porcelain"], mainRoot);
121
+ if (status === undefined) {
122
+ throw new Error(`refusing to merge "${branch}": could not read the status of the main checkout (${mainRoot})`);
123
+ }
124
+ if (status !== "") {
125
+ throw new Error(`refusing to merge "${branch}": the main checkout (${mainRoot}) has uncommitted changes. Nothing was merged.`);
126
+ }
127
+ // `--` ends option parsing so the refs are never read as flags.
128
+ const ancestor = await this.runner.run(["merge-base", "--is-ancestor", "--", branch, "HEAD"], mainRoot);
129
+ if (!ancestor) {
130
+ throw new Error(`refusing to merge "${branch}": could not read its merge ancestry`);
131
+ }
132
+ if (ancestor.code === 0) {
133
+ return { merged: false, alreadyMerged: true, target, mainRoot };
134
+ }
135
+ const merge = await this.runner.run(["merge", "--no-edit", "--", branch], mainRoot, MERGE_TIMEOUT_MS);
136
+ if (!merge) {
137
+ throw new Error(`merge of "${branch}" into "${target}" failed to run (transport error); the checkout was not modified`);
138
+ }
139
+ if (merge.code === 0) {
140
+ return {
141
+ merged: true,
142
+ target,
143
+ mainRoot,
144
+ output: merge.stdout || merge.stderr || undefined,
145
+ };
146
+ }
147
+ // Conflicts are reported, never auto-resolved; the merge stays in progress.
148
+ // A probe that could not run reads as "unknown", never as "no conflicts": the merge state
149
+ // itself decides, so a conflict the listing missed still reaches the caller as a conflict.
150
+ const conflicted = await this.runner.probe(["diff", "--name-only", "--diff-filter=U"], mainRoot);
151
+ if (conflicted !== undefined && conflicted !== "") {
152
+ throw new Error(conflictMessage(branch, target, mainRoot, conflicted));
153
+ }
154
+ const mergeInProgress = await this.runner.test(["rev-parse", "--verify", "--quiet", "MERGE_HEAD"], mainRoot);
155
+ if (mergeInProgress) {
156
+ throw new Error(conflictMessage(branch, target, mainRoot, undefined));
157
+ }
158
+ throw new Error(`merge of "${branch}" into "${target}" failed: ${merge.stderr || merge.stdout || `exit code ${merge.code}`}`);
159
+ }
160
+ }
161
+ /**
162
+ * The conflict refusal, whose first line is the marker the merge tool classifies on. It reports
163
+ * what is true — the paths, and that the merge is unfinished — and does not instruct the caller,
164
+ * whose reader is an orchestrating agent rather than an operator.
165
+ *
166
+ * The unlisted-files variant keeps the marker and its explanation on one line, so the file-list
167
+ * parser reads no path rather than a placeholder dressed as one.
168
+ */
169
+ function conflictMessage(branch, target, mainRoot, files) {
170
+ const listing = files === undefined
171
+ ? `has conflicts in: (the conflicting files could not be listed — \`git diff --name-only --diff-filter=U\` did not run in ${mainRoot})`
172
+ : `has conflicts in:\n${files}`;
173
+ return (`merge of "${branch}" into "${target}" ${listing}\n` +
174
+ `The merge is still in progress in ${mainRoot}. No conflict was resolved automatically.`);
175
+ }
176
+ /**
177
+ * Deletes the branch a worktree carried, once the worktree is gone: a `cow-`
178
+ * branch that is merged and unattached. A branch a failed create minted is not
179
+ * this class's to judge — `deleteCreatedBranch` removes it unconditionally.
180
+ */
181
+ export class BranchCleaner {
182
+ runner;
183
+ constructor(runner) {
184
+ this.runner = runner;
185
+ }
186
+ /**
187
+ * Deletes the branch the caller names, and only it: a `cow-` branch that
188
+ * exists, is merged into HEAD, and whose checkout is not attached. An unmerged
189
+ * branch is kept — deleting it would orphan its commits. Omit `isAttached`
190
+ * only for a checkout the host never saw.
191
+ */
192
+ async delete(options, isAttached) {
193
+ const { branch, worktreePath, repoCwd } = options;
194
+ if (!branch.startsWith("cow-"))
195
+ return { kind: "not-applicable" };
196
+ try {
197
+ if (!(await refExists(this.runner, branch, repoCwd))) {
198
+ return { kind: "not-applicable" };
199
+ }
200
+ const merged = await this.runner.run(["merge-base", "--is-ancestor", "--", branch, "HEAD"], repoCwd);
201
+ if (merged === undefined) {
202
+ throw new GitError(`git merge-base --is-ancestor -- ${branch} HEAD could not run in ${repoCwd}`);
203
+ }
204
+ if (merged.code !== 0)
205
+ return { kind: "kept", reason: "unmerged" };
206
+ // Attachment belongs to the execution backend, hence the injected probe.
207
+ if (isAttached && (await isAttached(worktreePath))) {
208
+ return { kind: "kept", reason: "checked-out" };
209
+ }
210
+ return await deleteBranchRef(this.runner, branch, repoCwd);
211
+ }
212
+ catch (err) {
213
+ return {
214
+ kind: "delete-failed",
215
+ detail: err instanceof Error ? err.message : String(err),
216
+ };
217
+ }
218
+ }
219
+ }
220
+ // --- Free-function facade ---
221
+ /**
222
+ * Merge a settled agent branch into the target branch (default `main`).
223
+ * See `BranchMerger.merge` for the guardrails.
224
+ */
225
+ export async function mergeBranchIntoTarget(pi, options) {
226
+ return new BranchMerger(new GitCommandRunner(pi)).merge(options);
227
+ }
228
+ /**
229
+ * Delete the git branch a worktree carried, once the worktree is gone.
230
+ * See `BranchCleaner.delete` for the guards.
231
+ */
232
+ export async function deleteWorktreeBranch(pi, options, isAttached) {
233
+ return new BranchCleaner(new GitCommandRunner(pi)).delete(options, isAttached);
234
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * git-retention.ts — Layer 3: what a worktree holds that must not be destroyed.
3
+ *
4
+ * Conservative: an unverifiable tree is kept, never destroyed, always with a
5
+ * reason string. Branch merge state is out of scope — branch commits live in the
6
+ * object store, so removing a clean worktree never loses them (see
7
+ * git-merger.ts's BranchCleaner for branch deletion).
8
+ */
9
+ import { GitCommandRunner } from "./git-runner.js";
10
+ import { GitWorktree } from "./git-worktree.js";
11
+ function worktree(pi, worktreePath) {
12
+ return new GitWorktree(new GitCommandRunner(pi), worktreePath);
13
+ }
14
+ /** Whether a worktree has uncommitted changes; undefined when the probe fails. */
15
+ export async function isWorktreeDirty(pi, worktreePath) {
16
+ return worktree(pi, worktreePath).isDirty();
17
+ }
18
+ /**
19
+ * Why a worktree must be kept, or null when clean (the only removable state).
20
+ * An unreadable tree is kept as unverifiable, never destroyed.
21
+ */
22
+ export async function worktreeRetentionReason(pi, worktreePath) {
23
+ const dirty = await worktree(pi, worktreePath).isDirty();
24
+ if (dirty === undefined) {
25
+ return { kind: "unverifiable", detail: "git status probe failed" };
26
+ }
27
+ if (dirty)
28
+ return { kind: "dirty" };
29
+ return null;
30
+ }
31
+ /** Short reason clause for UI toasts. */
32
+ export function formatRetentionClause(reason) {
33
+ switch (reason.kind) {
34
+ case "dirty":
35
+ return "has uncommitted changes";
36
+ case "unverifiable":
37
+ return `state could not be verified (${reason.detail})`;
38
+ }
39
+ }
40
+ /** Full retention warning for UI toasts. */
41
+ export function formatRetentionReason(reason, worktreePath) {
42
+ return `Worktree ${worktreePath} ${formatRetentionClause(reason)} — NOT removed.`;
43
+ }