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,398 @@
1
+ /**
2
+ * cow-clone.ts — materialize a worktree's working tree as a copy-on-write clone.
3
+ *
4
+ * Node owns the orchestration, and every filesystem call here is asynchronous:
5
+ * a wipe or a seed never blocks the event loop.
6
+ *
7
+ * The clone is one clonefile(2) call per entry through a tiny embedded python3
8
+ * snippet — Node cannot make that call directly: libuv writes
9
+ * the bytes for COPYFILE_FICLONE (measured: 512 MB written for a 512 MB file on
10
+ * APFS) and fails ENOSYS for the forced flag. Linux clones through the FICLONE
11
+ * ioctl instead, and `cp --reflink=always` is what reaches it for a whole tree:
12
+ * fs.cp honours COPYFILE_FICLONE_FORCE on the top-level target alone and copies
13
+ * every nested file byte for byte (measured on ext4, btrfs and ZFS), so the
14
+ * forced flag there guarantees nothing. `always` makes the copy fail rather than
15
+ * degrade, which is what keeps a clone a clone.
16
+ *
17
+ * A clone never degrades into a byte copy: the probe runs before anything is
18
+ * wiped, and a volume that cannot clone fails the clone instead of quietly
19
+ * copying bytes. The caller then completes the checkout with git
20
+ * (see git-materializer.ts).
21
+ */
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import { commandPath, resolveCommand } from "../exec-path.js";
25
+ // --- The clone primitives ---
26
+ /**
27
+ * Embedded clonefile(2) helper: paths as argv, program as `-c`
28
+ * (`python3 -c <snippet> <src> <dst>`), exit 1 when the call fails.
29
+ */
30
+ const CLONEFILE_SNIPPET = `import ctypes, sys
31
+ libc = ctypes.CDLL(None, use_errno=True)
32
+ # CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
33
+ if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
34
+ sys.exit(1)
35
+ `;
36
+ /** Budget for one clone call. */
37
+ const COW_CLONE_TIMEOUT_MS = 10 * 60_000;
38
+ /**
39
+ * Whole-tree clonefile pays off above ~1 MB: below that, starting python3 costs
40
+ * more than cloning the tree per file.
41
+ */
42
+ const BIG_DIRECTORY_KB = 1024;
43
+ /**
44
+ * Programs the platform's clone path cannot run without. A missing one is a
45
+ * setup problem the user must fix, not a volume that cannot clone, so it is
46
+ * named before the first worktree is created.
47
+ */
48
+ const REQUIRED_CLONE_PROGRAMS = {
49
+ darwin: ["python3"],
50
+ linux: [],
51
+ };
52
+ /** What the user has to do about each missing program, per platform. */
53
+ const CLONE_PROGRAM_HINTS = {
54
+ darwin: {
55
+ python3: "install the Xcode Command Line Tools: xcode-select --install",
56
+ },
57
+ };
58
+ /** How a platform is named in a message; the raw name reads like a bug report. */
59
+ const PLATFORM_LABELS = {
60
+ darwin: "macOS",
61
+ linux: "Linux",
62
+ };
63
+ /** Programs the platform's clone path needs that are not on PATH. */
64
+ export function missingClonePrograms(platform = process.platform) {
65
+ const required = REQUIRED_CLONE_PROGRAMS[platform] ?? [];
66
+ return required.filter((name) => commandPath(name) === undefined);
67
+ }
68
+ /**
69
+ * Why clone-on-write cannot run on this machine, in one sentence the user can
70
+ * act on, or undefined when every program is present.
71
+ */
72
+ export function missingCloneProgramReport(platform = process.platform) {
73
+ const missing = missingClonePrograms(platform);
74
+ if (missing.length === 0)
75
+ return undefined;
76
+ const label = PLATFORM_LABELS[platform] ?? platform;
77
+ const named = missing
78
+ .map((name) => {
79
+ const hint = CLONE_PROGRAM_HINTS[platform]?.[name];
80
+ return hint === undefined ? name : `${name}: ${hint}`;
81
+ })
82
+ .join(", ");
83
+ return `Copy-on-write worktrees need ${named}, which ${missing.length === 1 ? "is" : "are"} not on PATH on ${label}. pi-cowboy stays inactive in this session. Install ${missing.length === 1 ? "it" : "them"} and start a new session.`;
84
+ }
85
+ export class CowCloneError extends Error {
86
+ reason;
87
+ failures;
88
+ constructor(reason, message, failures = []) {
89
+ super(message);
90
+ this.reason = reason;
91
+ this.failures = failures;
92
+ this.name = "CowCloneError";
93
+ }
94
+ }
95
+ // --- Entry point ---
96
+ /**
97
+ * Populate a worktree's working tree. "all" wipes the worktree (`.git` excepted)
98
+ * and clones every entry of the main checkout; "seed" clones only the given
99
+ * relative paths (ignored state for a dirty main).
100
+ */
101
+ export async function materializeCowClone(request, mode, deps) {
102
+ const wt = path.resolve(request.wtPath);
103
+ const main = path.resolve(request.mainRoot);
104
+ // What the wipe may touch is decided on the paths the roots really name: the
105
+ // same directory can be spelled through a link (a symlinked worktree root, or
106
+ // `/var` for `/private/var`), and a lexical compare cannot see that.
107
+ const realWt = await resolvedRoot(wt);
108
+ const realMain = await resolvedRoot(main);
109
+ if (realWt === realMain) {
110
+ throw new CowCloneError("setup", "the worktree is the main checkout; refusing to materialize");
111
+ }
112
+ if (containsPath(realWt, realMain)) {
113
+ throw new CowCloneError("setup", "the worktree contains the main checkout; refusing to materialize");
114
+ }
115
+ // Before the wipe: an unsupported volume must cost the worktree nothing.
116
+ await deps.probe(wt);
117
+ const entries = mode.kind === "all"
118
+ ? await withSetupContext(`cannot read ${main}`, () => mainEntries(main, wt, deps))
119
+ : await withSetupContext(`cannot prepare the ignored paths in ${wt}`, () => seedEntries(main, wt, mode.rels));
120
+ if (mode.kind === "all") {
121
+ await withSetupContext(`cannot wipe ${wt}`, () => wipeWorktree(wt, deps));
122
+ }
123
+ const failures = [];
124
+ for (const entry of entries) {
125
+ try {
126
+ await deps.cloneEntry(entry.src, entry.dst);
127
+ }
128
+ catch (err) {
129
+ if (err instanceof CowCloneError && err.reason !== "entry-failed") {
130
+ throw err;
131
+ }
132
+ failures.push({
133
+ path: entry.src,
134
+ message: err instanceof Error ? err.message : String(err),
135
+ });
136
+ }
137
+ }
138
+ if (failures.length > 0) {
139
+ throw new CowCloneError("entry-failed", `${failures.length} ${failures.length === 1 ? "entry" : "entries"} could not be cloned`, failures);
140
+ }
141
+ return { mechanism: entries.length === 0 ? "empty" : deps.mechanism };
142
+ }
143
+ /**
144
+ * The directory a root really names; the root as given when it cannot be
145
+ * resolved (a missing path is reported by the read that needs it).
146
+ */
147
+ async function resolvedRoot(target) {
148
+ try {
149
+ return await fs.promises.realpath(target);
150
+ }
151
+ catch {
152
+ return target;
153
+ }
154
+ }
155
+ /** Whether either path is the other or lives inside it. */
156
+ function overlapsPath(a, b) {
157
+ return containsPath(a, b) || containsPath(b, a);
158
+ }
159
+ /** Whether `child` is `container` or lives inside it. */
160
+ export function containsPath(container, child) {
161
+ const from = path.resolve(container);
162
+ const to = path.resolve(child);
163
+ return to === from || to.startsWith(from + path.sep);
164
+ }
165
+ // --- Planning ---
166
+ /** The worktree's own entries, minus `.git`; the wipe list. */
167
+ async function wipeWorktree(wt, deps) {
168
+ for (const entry of await deps.list(wt)) {
169
+ if (entry.name === ".git")
170
+ continue;
171
+ await removeEntry(path.join(wt, entry.name), entry);
172
+ }
173
+ }
174
+ /**
175
+ * Remove one entry, descending only into what the entry's own listing reported
176
+ * as a directory and unlinking everything else: a symlink is never followed, so
177
+ * a link out of the worktree — to another checkout, an ancestor, or in a loop
178
+ * with a sibling — cannot redirect the wipe. Recursing here rather than through
179
+ * `fs.rm` is the point: a path that ends in a separator is resolved through a
180
+ * link, and this never hands one to a removal call.
181
+ */
182
+ async function removeEntry(target, entry) {
183
+ if (!entry.isDirectory()) {
184
+ await ignoreMissing(() => fs.promises.unlink(target));
185
+ return;
186
+ }
187
+ const children = await ignoreMissing(() => fs.promises.readdir(target, { withFileTypes: true }));
188
+ for (const child of children ?? []) {
189
+ await removeEntry(path.join(target, child.name), child);
190
+ }
191
+ await ignoreMissing(() => fs.promises.rmdir(target));
192
+ }
193
+ /** An entry that is already gone is removal that already happened. */
194
+ async function ignoreMissing(run) {
195
+ try {
196
+ return await run();
197
+ }
198
+ catch (err) {
199
+ if (err?.code !== "ENOENT")
200
+ throw err;
201
+ return undefined;
202
+ }
203
+ }
204
+ /** Every main-checkout entry except `.git` and anything holding the worktree. */
205
+ async function mainEntries(main, wt, deps) {
206
+ const entries = [];
207
+ for (const { name } of await deps.list(main)) {
208
+ if (name === ".git")
209
+ continue;
210
+ const src = path.join(main, name);
211
+ // eslint-disable-next-line lite/no-invariant-comment -- encodes a non-obvious choice; the type can't represent it
212
+ // Never clone the worktree into itself, not even through an ancestor entry.
213
+ if (overlapsPath(src, wt))
214
+ continue;
215
+ entries.push({ src, dst: path.join(wt, name) });
216
+ }
217
+ return entries;
218
+ }
219
+ /** The listed ignored paths that exist in the main checkout. */
220
+ async function seedEntries(main, wt, rels) {
221
+ const entries = [];
222
+ for (const raw of rels) {
223
+ // git reports ignored directories as "node_modules/"; clonefile(2) refuses a
224
+ // destination that ends in a separator, so the trailing slash comes off here.
225
+ const rel = raw.replace(/[/\\]+$/, "");
226
+ if (rel === "")
227
+ continue;
228
+ // `.git` is the worktree's own link back to the main checkout, never state.
229
+ if (rel === ".git" || rel.startsWith(".git/") || rel.startsWith(".git\\")) {
230
+ continue;
231
+ }
232
+ const src = path.join(main, rel);
233
+ // An ignored directory that holds the worktree (a store dir) is not state to
234
+ // copy: seeding it would clone the worktree into itself.
235
+ if (overlapsPath(src, wt))
236
+ continue;
237
+ if (!(await exists(src)))
238
+ continue;
239
+ const dst = path.join(wt, rel);
240
+ await fs.promises.mkdir(path.dirname(dst), { recursive: true });
241
+ entries.push({ src, dst });
242
+ }
243
+ return entries;
244
+ }
245
+ async function exists(target) {
246
+ try {
247
+ await fs.promises.lstat(target);
248
+ return true;
249
+ }
250
+ catch {
251
+ return false;
252
+ }
253
+ }
254
+ /** Wrap a raw filesystem failure as a setup failure with a readable message. */
255
+ async function withSetupContext(what, run) {
256
+ try {
257
+ return await run();
258
+ }
259
+ catch (err) {
260
+ if (err instanceof CowCloneError)
261
+ throw err;
262
+ throw new CowCloneError("setup", `${what}: ${err instanceof Error ? err.message : String(err)}`);
263
+ }
264
+ }
265
+ /** This platform's probe and clone, over the real filesystem, through `pi.exec`. */
266
+ export function defaultCowCloneDeps(exec, timeoutMs = COW_CLONE_TIMEOUT_MS) {
267
+ const list = (dir) => fs.promises.readdir(dir, { withFileTypes: true });
268
+ // Resolved once: a bare name costs the child ~50 ms of PATH search, two orders
269
+ // of magnitude over the child itself (1.3 ms), and `pi.exec` does not resolve
270
+ // on our behalf.
271
+ const tools = {
272
+ cp: resolveCommand("cp"),
273
+ du: resolveCommand("du"),
274
+ python: resolveCommand("python3"),
275
+ };
276
+ switch (process.platform) {
277
+ case "darwin":
278
+ return {
279
+ mechanism: "clonefile",
280
+ list,
281
+ probe: (wt) => probe(exec, wt, tools, timeoutMs, clonefileChild),
282
+ cloneEntry: (src, dst) => darwinEntry(exec, tools, src, dst, timeoutMs),
283
+ };
284
+ case "linux":
285
+ return {
286
+ mechanism: "reflink",
287
+ list,
288
+ // The same probe, over the same primitive the real entries use.
289
+ probe: (wt) => probe(exec, wt, tools, timeoutMs, reflinkChild),
290
+ cloneEntry: (src, dst) => reflinkChild(exec, tools, src, dst, timeoutMs),
291
+ };
292
+ default:
293
+ return {
294
+ mechanism: "empty",
295
+ list,
296
+ probe: () => Promise.reject(unsupportedPlatform()),
297
+ cloneEntry: () => Promise.reject(unsupportedPlatform()),
298
+ };
299
+ }
300
+ }
301
+ function unsupportedPlatform() {
302
+ return new CowCloneError("unsupported", `copy-on-write worktree materialization is not implemented on ${process.platform}`);
303
+ }
304
+ /**
305
+ * Create a small tree inside the worktree, clone it, drop it again. The clone
306
+ * runs before anything is wiped, so an unsupported volume costs nothing.
307
+ */
308
+ async function probe(exec, wt, tools, timeoutMs, clone) {
309
+ const root = path.join(wt, `.cow-probe-${process.pid}`);
310
+ const from = path.join(root, "p");
311
+ try {
312
+ // The worktree is the agent's, links included: the probe may only write under
313
+ // a directory it created itself, never through a link left at that name.
314
+ await fs.promises.mkdir(root, { recursive: true });
315
+ if (!(await fs.promises.lstat(root)).isDirectory()) {
316
+ throw new CowCloneError("setup", `${root} is not a directory; refusing to probe the volume through it`);
317
+ }
318
+ await fs.promises.mkdir(from, { recursive: true });
319
+ await fs.promises.writeFile(path.join(from, "f"), "x");
320
+ await clone(exec, tools, from, path.join(root, "p-clone"), timeoutMs);
321
+ }
322
+ catch (err) {
323
+ if (err instanceof CowCloneError && err.reason === "entry-failed") {
324
+ throw new CowCloneError("unsupported", `copy-on-write is not supported on the worktree volume: ${err.message}`);
325
+ }
326
+ throw err;
327
+ }
328
+ finally {
329
+ await fs.promises
330
+ .rm(root, { recursive: true, force: true })
331
+ .catch(() => { });
332
+ }
333
+ }
334
+ /**
335
+ * macOS: a big directory goes through clonefile(2) — one call clones the whole
336
+ * tree — while files and small directories go through `cp -c`, which is cheaper
337
+ * to start. Either way the probe has
338
+ * already proved this volume clones, so `cp -c` cannot be the silent byte copy
339
+ * it would be on its own.
340
+ */
341
+ async function darwinEntry(exec, tools, src, dst, timeoutMs) {
342
+ const info = await fs.promises.lstat(src);
343
+ if (!info.isDirectory()) {
344
+ return copyChild(exec, tools, src, dst, timeoutMs, []);
345
+ }
346
+ const kb = await directoryKb(exec, tools, src, timeoutMs);
347
+ return kb >= BIG_DIRECTORY_KB
348
+ ? clonefileChild(exec, tools, src, dst, timeoutMs)
349
+ : copyChild(exec, tools, src, dst, timeoutMs, ["-R"]);
350
+ }
351
+ /** `du -sk` in KB; an unreadable tree counts as small. */
352
+ async function directoryKb(exec, tools, src, timeoutMs) {
353
+ try {
354
+ const out = await run(exec, tools.du, ["-sk", src], timeoutMs, `du -sk ${src}`);
355
+ return Number.parseInt(out.trim().split(/\s+/)[0] ?? "", 10) || 0;
356
+ }
357
+ catch {
358
+ return 0;
359
+ }
360
+ }
361
+ /**
362
+ * macOS: one clonefile(2) call through the embedded snippet. The child may block
363
+ * for as long as the tree takes; Node waits on it asynchronously.
364
+ */
365
+ function clonefileChild(exec, tools, src, dst, timeoutMs) {
366
+ // `-c`, not stdin: `pi.exec` spawns with stdin ignored, so the snippet travels
367
+ // as an argument, with src then dst following it in argv.
368
+ return run(exec, tools.python, ["-c", CLONEFILE_SNIPPET, src, dst], timeoutMs, `clonefile ${src}`, "could not start python3 (needed to clone a worktree on macOS)").then(() => undefined);
369
+ }
370
+ /** macOS: clone one entry with `cp -P -c` (symlinks preserved). */
371
+ function copyChild(exec, tools, src, dst, timeoutMs, flags) {
372
+ return run(exec, tools.cp, ["-P", "-c", ...flags, src, dst], timeoutMs, `cp -c ${src}`).then(() => undefined);
373
+ }
374
+ /**
375
+ * Linux: clone one entry with `cp -P --reflink=always -R` (symlinks preserved).
376
+ * `always` is the load-bearing part — the copy fails instead of falling back to
377
+ * bytes. `-R` is what puts the FICLONE ioctl on every file in the tree; the
378
+ * recursion belongs inside cp, not in a recursive fs.cp, which would only clone
379
+ * the top-level target. One child per entry, as on macOS.
380
+ */
381
+ function reflinkChild(exec, tools, src, dst, timeoutMs) {
382
+ return run(exec, tools.cp, ["-P", "--reflink=always", "-R", src, dst], timeoutMs, `cp --reflink ${src}`).then(() => undefined);
383
+ }
384
+ /** Run one command that must exit 0; a kill or a non-zero exit is a failure. */
385
+ async function run(exec, command, args, timeoutMs, what, launchHint) {
386
+ const result = await exec(command, [...args], { timeout: timeoutMs }).catch((err) => {
387
+ throw new CowCloneError("launch", `${launchHint ?? `could not start ${command}`}: ${err instanceof Error ? err.message : String(err)}`);
388
+ });
389
+ // `pi.exec` reports a child it killed as code 0 with killed set.
390
+ if (result.killed) {
391
+ throw new CowCloneError("timeout", `${what} exceeded ${Math.round(timeoutMs / 1000)}s`);
392
+ }
393
+ if (result.code !== 0) {
394
+ const detail = result.stderr.trim().split("\n").at(-1) ?? "";
395
+ throw new CowCloneError("entry-failed", `${what} exited ${String(result.code)}${detail === "" ? "" : `: ${detail}`}`);
396
+ }
397
+ return result.stdout;
398
+ }