@bermudi/pi-delegate 0.1.3 → 0.1.6

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.
package/workspace.ts ADDED
@@ -0,0 +1,908 @@
1
+ import { execFile } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { scheduleDeadline } from "./timer.ts";
5
+
6
+ const SCRATCH_CONTAINER_NAME = ".pi-delegate-scratch";
7
+ const SCRATCH_LEASE_PREFIX = "lease-";
8
+ const SCRATCH_LEGACY_PREFIX = ".pi-delegate-scratch-";
9
+ const SCRATCH_TREE_NAME = "project";
10
+ const SCRATCH_OWNER_NAME = ".owner";
11
+ const COPY_TIMEOUT_MS = 5 * 60 * 1000;
12
+
13
+ export interface ScratchWorkspace {
14
+ /** Canonical project root copied into the scratch directory. */
15
+ sourceRoot: string;
16
+ /** Canonical cwd requested by the caller. */
17
+ sourceCwd: string;
18
+ /** Root of the disposable reflink copy. */
19
+ scratchRoot: string;
20
+ /** sourceCwd translated into scratchRoot. */
21
+ cwd: string;
22
+ mapPathToSource(candidate: string): string;
23
+ /** Resolve a reported path physically, mapping disposable paths back to the
24
+ * source tree and preserving external host paths after cleanup. */
25
+ resolveReportedPath(candidate: string): Promise<string>;
26
+ /**
27
+ * Resolve an explicitly attributed path. Disposable paths return undefined;
28
+ * external paths are returned in physical (realpath) form so symlink aliases
29
+ * compare with the host path they actually touched.
30
+ */
31
+ resolveAttributedPath(candidate: string): Promise<string | undefined>;
32
+ /** True when the existing path resolves inside the disposable tree. */
33
+ isDisposablePath(candidate: string): Promise<boolean>;
34
+ cleanup(): Promise<void>;
35
+ }
36
+
37
+ export class ScratchSetupError extends Error {}
38
+
39
+ export class ScratchDeadlineError extends ScratchSetupError {}
40
+
41
+ class ScratchLeaseIdentityError extends Error {}
42
+
43
+ class CommandError extends Error {
44
+ constructor(
45
+ message: string,
46
+ readonly stderr: string,
47
+ options: ErrorOptions,
48
+ ) {
49
+ super(message, options);
50
+ }
51
+ }
52
+
53
+ function runFile(
54
+ file: string,
55
+ args: string[],
56
+ options: { cwd?: string; signal?: AbortSignal; timeout?: number } = {},
57
+ ): Promise<string> {
58
+ return new Promise((resolve, reject) => {
59
+ execFile(
60
+ file,
61
+ args,
62
+ {
63
+ cwd: options.cwd,
64
+ signal: options.signal,
65
+ timeout: options.timeout,
66
+ maxBuffer: 1024 * 1024,
67
+ },
68
+ (error, stdout, stderr) => {
69
+ if (error) {
70
+ const detail = stderr.trim();
71
+ reject(
72
+ new CommandError(
73
+ detail ? `${file}: ${detail}` : `${file}: ${error.message}`,
74
+ detail,
75
+ { cause: error },
76
+ ),
77
+ );
78
+ return;
79
+ }
80
+ resolve(stdout);
81
+ },
82
+ );
83
+ });
84
+ }
85
+
86
+ async function findCopyRoot(cwd: string, signal: AbortSignal): Promise<string> {
87
+ try {
88
+ const root = (
89
+ await runFile("git", ["rev-parse", "--show-toplevel"], {
90
+ cwd,
91
+ timeout: 5000,
92
+ signal,
93
+ })
94
+ ).trim();
95
+ if (!root) {
96
+ throw new ScratchSetupError("Git returned an empty repository root.");
97
+ }
98
+ return await fs.promises.realpath(root);
99
+ } catch (error) {
100
+ // Only Git's explicit "not a repository" result permits treating cwd as a
101
+ // plain directory. Missing Git, timeouts, dubious ownership, malformed
102
+ // metadata, and every other failure stop scratch creation: falling back
103
+ // could leave an ancestor repository or linked-worktree metadata reachable.
104
+ if (
105
+ error instanceof CommandError &&
106
+ /not a git repository/i.test(error.stderr)
107
+ ) {
108
+ return cwd;
109
+ }
110
+ throw new ScratchSetupError(
111
+ "Could not safely determine the scratch project root.",
112
+ {
113
+ cause: error,
114
+ },
115
+ );
116
+ }
117
+ }
118
+
119
+ function throwIfSetupCancelled(
120
+ signal: AbortSignal,
121
+ parentSignal: AbortSignal | undefined,
122
+ ): void {
123
+ if (!signal.aborted) return;
124
+ if (parentSignal?.aborted) {
125
+ throw new Error("Scratch workspace creation was aborted.");
126
+ }
127
+ throw new ScratchDeadlineError(
128
+ "Scratch workspace creation exceeded the task deadline.",
129
+ );
130
+ }
131
+
132
+ /** Validate the completed copy before any subagent receives its path. */
133
+ async function validateCopiedTree(
134
+ root: string,
135
+ signal: AbortSignal,
136
+ parentSignal: AbortSignal | undefined,
137
+ ): Promise<void> {
138
+ const pending = [root];
139
+ while (pending.length) {
140
+ throwIfSetupCancelled(signal, parentSignal);
141
+ const directory = pending.pop()!;
142
+ for (const entry of await fs.promises.readdir(directory, {
143
+ withFileTypes: true,
144
+ })) {
145
+ throwIfSetupCancelled(signal, parentSignal);
146
+ const candidate = path.join(directory, entry.name);
147
+ // The root repository is validated below. A non-directory .git entry can
148
+ // redirect metadata outside the copy. Nested repositories are rejected as
149
+ // unsupported because their own config, alternates, and worktree settings
150
+ // would each need the same independent validation as the root repository.
151
+ if (entry.name === ".git") {
152
+ if (!entry.isDirectory()) {
153
+ throw new ScratchSetupError(
154
+ `Scratch workspace cannot safely copy linked Git metadata at '${path.relative(root, candidate)}'.`,
155
+ );
156
+ }
157
+ if (directory !== root) {
158
+ throw new ScratchSetupError(
159
+ `Scratch workspace does not support nested Git repositories at '${path.relative(root, candidate)}'.`,
160
+ );
161
+ }
162
+ }
163
+ if (entry.isDirectory()) {
164
+ pending.push(candidate);
165
+ continue;
166
+ }
167
+ if (!entry.isSymbolicLink()) continue;
168
+ const target = await fs.promises.readlink(candidate);
169
+ const resolvedTarget = path.resolve(path.dirname(candidate), target);
170
+ if (path.isAbsolute(target) || !isWithin(root, resolvedTarget)) {
171
+ throw new ScratchSetupError(
172
+ `Scratch workspace cannot safely copy symlink '${path.relative(root, candidate)}' because it points outside the project.`,
173
+ );
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ function isWithin(root: string, candidate: string): boolean {
180
+ const relative = path.relative(root, candidate);
181
+ return (
182
+ relative === "" ||
183
+ (relative !== ".." &&
184
+ !relative.startsWith(`..${path.sep}`) &&
185
+ !path.isAbsolute(relative))
186
+ );
187
+ }
188
+
189
+ function isProcessAlive(pid: number): boolean {
190
+ try {
191
+ process.kill(pid, 0);
192
+ return true;
193
+ } catch (error) {
194
+ return !(
195
+ error instanceof Error &&
196
+ "code" in error &&
197
+ error.code === "ESRCH"
198
+ );
199
+ }
200
+ }
201
+
202
+ function sameFileIdentity(left: fs.Stats, right: fs.Stats): boolean {
203
+ // dev+ino alone can alias after an unlink+mkdir reuses the same inode
204
+ // (observed on ext4 in CI: project replaced in the sweep race test
205
+ // reused the previous ino). Birthtime distinguishes a recreated entry
206
+ // and is stable across the chmod 0500→0700 transitions that update
207
+ // ctime. Where birthtime is unavailable (0) we fall back to dev+ino.
208
+ if (left.dev !== right.dev || left.ino !== right.ino) return false;
209
+ if (left.birthtimeMs !== 0 || right.birthtimeMs !== 0) {
210
+ return left.birthtimeMs === right.birthtimeMs;
211
+ }
212
+ return true;
213
+ }
214
+
215
+ function parseOwnerPid(content: string): number | undefined {
216
+ const value = content.trim();
217
+ if (!/^[1-9][0-9]*$/.test(value)) return undefined;
218
+ const pid = Number(value);
219
+ return Number.isSafeInteger(pid) ? pid : undefined;
220
+ }
221
+
222
+ type LeaseDeletionExpectations =
223
+ | {
224
+ hasProject: true;
225
+ lease: fs.Stats;
226
+ project: fs.Stats;
227
+ owner: fs.Stats;
228
+ }
229
+ | {
230
+ hasProject: false;
231
+ lease: fs.Stats;
232
+ owner: fs.Stats;
233
+ };
234
+
235
+ async function deleteLeaseContentsAndRmdir(
236
+ parentHandle: fs.promises.FileHandle,
237
+ leaseName: string,
238
+ leaseHandle: fs.promises.FileHandle,
239
+ expectations: LeaseDeletionExpectations,
240
+ ): Promise<void> {
241
+ const leasePath = path.join(`/proc/self/fd/${parentHandle.fd}`, leaseName);
242
+ const openLeaseStat = await leaseHandle.stat();
243
+ const currentLeaseStat = await fs.promises.lstat(leasePath);
244
+ if (
245
+ !openLeaseStat.isDirectory() ||
246
+ !sameFileIdentity(openLeaseStat, expectations.lease) ||
247
+ !sameFileIdentity(currentLeaseStat, openLeaseStat)
248
+ ) {
249
+ throw new ScratchLeaseIdentityError(
250
+ "Scratch lease was moved or replaced; refusing cleanup.",
251
+ );
252
+ }
253
+
254
+ await leaseHandle.chmod(0o700);
255
+ const ownerPath = path.join(
256
+ `/proc/self/fd/${leaseHandle.fd}`,
257
+ SCRATCH_OWNER_NAME,
258
+ );
259
+ const initialOwnerStat = await fs.promises.lstat(ownerPath);
260
+ if (!sameFileIdentity(initialOwnerStat, expectations.owner)) {
261
+ throw new ScratchLeaseIdentityError(
262
+ "Scratch owner marker was replaced; refusing cleanup.",
263
+ );
264
+ }
265
+
266
+ if (expectations.hasProject) {
267
+ const projectPath = path.join(
268
+ `/proc/self/fd/${leaseHandle.fd}`,
269
+ SCRATCH_TREE_NAME,
270
+ );
271
+ const projectHandle = await fs.promises.open(
272
+ projectPath,
273
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
274
+ );
275
+ try {
276
+ const openProjectStat = await projectHandle.stat();
277
+ const currentProjectStat = await fs.promises.lstat(projectPath);
278
+ if (
279
+ !openProjectStat.isDirectory() ||
280
+ !sameFileIdentity(openProjectStat, expectations.project) ||
281
+ !sameFileIdentity(currentProjectStat, openProjectStat)
282
+ ) {
283
+ throw new ScratchLeaseIdentityError(
284
+ "Scratch project was moved or replaced; refusing cleanup.",
285
+ );
286
+ }
287
+
288
+ // Remove children through the opened project directory, not the project
289
+ // pathname. This means a replacement at `project` is never recursively
290
+ // traversed. The final rmdir is still a pathname operation; the identity
291
+ // is checked again immediately beforehand, so this is fail-closed for
292
+ // the deterministic replacement races we can observe, not an atomic
293
+ // guarantee against a cooperating same-user process.
294
+ for (const name of await fs.promises.readdir(
295
+ `/proc/self/fd/${projectHandle.fd}`,
296
+ )) {
297
+ await fs.promises.rm(
298
+ path.join(`/proc/self/fd/${projectHandle.fd}`, name),
299
+ { recursive: true, force: false },
300
+ );
301
+ }
302
+ const finalProjectStat = await fs.promises.lstat(projectPath);
303
+ if (!sameFileIdentity(finalProjectStat, openProjectStat)) {
304
+ throw new ScratchLeaseIdentityError(
305
+ "Scratch project was moved or replaced; refusing cleanup.",
306
+ );
307
+ }
308
+ await fs.promises.rmdir(projectPath);
309
+ } finally {
310
+ await projectHandle.close();
311
+ }
312
+ }
313
+
314
+ const currentOwnerStat = await fs.promises.lstat(ownerPath);
315
+ if (!sameFileIdentity(currentOwnerStat, expectations.owner)) {
316
+ throw new ScratchLeaseIdentityError(
317
+ "Scratch owner marker was replaced; refusing cleanup.",
318
+ );
319
+ }
320
+ await fs.promises.rm(ownerPath, { force: false });
321
+
322
+ const finalLeaseStat = await fs.promises.lstat(leasePath);
323
+ if (!sameFileIdentity(finalLeaseStat, openLeaseStat)) {
324
+ throw new ScratchLeaseIdentityError(
325
+ "Scratch lease was moved or replaced; refusing cleanup.",
326
+ );
327
+ }
328
+ await fs.promises.rmdir(leasePath);
329
+ }
330
+
331
+ async function ensureScratchContainer(
332
+ containerDir: string,
333
+ uid: number | undefined,
334
+ ): Promise<void> {
335
+ try {
336
+ await fs.promises.mkdir(containerDir, { mode: 0o700 });
337
+ await fs.promises.chmod(containerDir, 0o700);
338
+ return;
339
+ } catch (error) {
340
+ if (!(
341
+ error instanceof Error &&
342
+ "code" in error &&
343
+ error.code === "EEXIST"
344
+ )) {
345
+ throw error;
346
+ }
347
+ }
348
+
349
+ const stat = await fs.promises.lstat(containerDir);
350
+ if (!stat.isDirectory() || (uid !== undefined && stat.uid !== uid)) {
351
+ throw new ScratchSetupError(
352
+ `Scratch container directory '${containerDir}' is not a directory owned by the current user.`,
353
+ );
354
+ }
355
+ if ((stat.mode & 0o7777) !== 0o700) {
356
+ await fs.promises.chmod(containerDir, 0o700);
357
+ }
358
+ }
359
+
360
+ interface SweepOptions {
361
+ prefix?: string;
362
+ onLeaseOpened?: (leaseName: string, leaseFd: number) => Promise<void> | void;
363
+ onLeaseValidated?: (leaseName: string) => Promise<void> | void;
364
+ }
365
+
366
+ /** Remove leases left behind by a process that is no longer running.
367
+ *
368
+ * The owner marker distinguishes our leases from unrelated prefix-matching
369
+ * directories. Live owners are never touched. Descriptors make the scan
370
+ * independent of a renamed parent, while pathname identity checks ensure that
371
+ * a lease renamed or replaced after it was opened is left alone. These checks
372
+ * are snapshots rather than an atomic cross-process locking primitive.
373
+ */
374
+ async function sweepStaleScratchLeases(
375
+ container: string,
376
+ options: SweepOptions = {},
377
+ ): Promise<void> {
378
+ const uid = process.getuid?.();
379
+ if (uid === undefined) return;
380
+
381
+ let parentHandle: fs.promises.FileHandle;
382
+ try {
383
+ parentHandle = await fs.promises.open(
384
+ container,
385
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
386
+ );
387
+ } catch {
388
+ return;
389
+ }
390
+
391
+ try {
392
+ const parentStat = await parentHandle.stat();
393
+ if (!parentStat.isDirectory() || parentStat.uid !== uid) return;
394
+
395
+ let entries: fs.Dirent[];
396
+ try {
397
+ entries = await fs.promises.readdir(`/proc/self/fd/${parentHandle.fd}`, {
398
+ withFileTypes: true,
399
+ });
400
+ } catch (error) {
401
+ console.error("[delegate] scratch lease sweep failed", error);
402
+ return;
403
+ }
404
+
405
+ for (const entry of entries) {
406
+ if (!entry.isDirectory()) continue;
407
+ if (options.prefix && !entry.name.startsWith(options.prefix)) continue;
408
+
409
+ let leaseHandle: fs.promises.FileHandle | undefined;
410
+ try {
411
+ const leasePath = path.join(
412
+ `/proc/self/fd/${parentHandle.fd}`,
413
+ entry.name,
414
+ );
415
+ leaseHandle = await fs.promises.open(
416
+ leasePath,
417
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
418
+ );
419
+ const openedLeaseStat = await leaseHandle.stat();
420
+ const scannedLeaseStat = await fs.promises.lstat(leasePath);
421
+ if (
422
+ !openedLeaseStat.isDirectory() ||
423
+ openedLeaseStat.uid !== uid ||
424
+ !sameFileIdentity(scannedLeaseStat, openedLeaseStat)
425
+ ) {
426
+ continue;
427
+ }
428
+
429
+ // Snapshot the identities before the test hook / concurrent work. If
430
+ // either pathname changes, the opened descriptor is not used for
431
+ // deletion. In particular, a rename must not turn this into cleanup of
432
+ // a lease that merely moved elsewhere.
433
+ const ownerPath = path.join(
434
+ `/proc/self/fd/${leaseHandle.fd}`,
435
+ SCRATCH_OWNER_NAME,
436
+ );
437
+ let scannedOwnerStat: fs.Stats;
438
+ try {
439
+ scannedOwnerStat = await fs.promises.lstat(ownerPath);
440
+ } catch (error) {
441
+ if (
442
+ error instanceof Error &&
443
+ "code" in error &&
444
+ error.code === "ENOENT"
445
+ ) {
446
+ // Leases from versions without an owner marker, or partial leases
447
+ // from a crash between mkdtemp and the marker write: reclaim only
448
+ // when empty. Anything else may be an unrelated directory. The
449
+ // identity re-check keeps the rmdir anchored to the scanned lease.
450
+ const contents = await fs.promises.readdir(
451
+ `/proc/self/fd/${leaseHandle.fd}`,
452
+ );
453
+ if (contents.length === 0) {
454
+ const currentLeaseStat = await fs.promises.lstat(leasePath);
455
+ if (sameFileIdentity(currentLeaseStat, scannedLeaseStat)) {
456
+ await fs.promises.rmdir(leasePath);
457
+ }
458
+ }
459
+ continue;
460
+ }
461
+ throw error;
462
+ }
463
+ let scannedProjectStat: fs.Stats | undefined;
464
+ try {
465
+ scannedProjectStat = await fs.promises.lstat(
466
+ path.join(`/proc/self/fd/${leaseHandle.fd}`, SCRATCH_TREE_NAME),
467
+ );
468
+ } catch (error) {
469
+ if (!(
470
+ error instanceof Error &&
471
+ "code" in error &&
472
+ error.code === "ENOENT"
473
+ )) {
474
+ throw error;
475
+ }
476
+ }
477
+
478
+ if (options.onLeaseOpened) {
479
+ await options.onLeaseOpened(entry.name, leaseHandle.fd);
480
+ }
481
+
482
+ const currentLeaseStat = await fs.promises.lstat(leasePath);
483
+ if (!sameFileIdentity(currentLeaseStat, scannedLeaseStat)) continue;
484
+ const currentOwnerStat = await fs.promises.lstat(ownerPath);
485
+ if (!sameFileIdentity(currentOwnerStat, scannedOwnerStat)) continue;
486
+ if (scannedProjectStat) {
487
+ const currentProjectStat = await fs.promises.lstat(
488
+ path.join(`/proc/self/fd/${leaseHandle.fd}`, SCRATCH_TREE_NAME),
489
+ );
490
+ if (!sameFileIdentity(currentProjectStat, scannedProjectStat)) {
491
+ continue;
492
+ }
493
+ }
494
+
495
+ if (
496
+ !currentOwnerStat.isFile() ||
497
+ currentOwnerStat.uid !== uid ||
498
+ (currentOwnerStat.mode & 0o077) !== 0
499
+ ) {
500
+ continue;
501
+ }
502
+
503
+ const ownerContent = await fs.promises.readFile(ownerPath, "utf8");
504
+ const pid = parseOwnerPid(ownerContent);
505
+ if (pid === undefined || isProcessAlive(pid)) continue;
506
+
507
+ const contents = await fs.promises.readdir(
508
+ `/proc/self/fd/${leaseHandle.fd}`,
509
+ );
510
+ if (
511
+ contents.some(
512
+ (name) => name !== SCRATCH_OWNER_NAME && name !== SCRATCH_TREE_NAME,
513
+ )
514
+ ) {
515
+ continue;
516
+ }
517
+
518
+ const hasProject = contents.includes(SCRATCH_TREE_NAME);
519
+ if (
520
+ hasProject &&
521
+ (!scannedProjectStat ||
522
+ !scannedProjectStat.isDirectory() ||
523
+ scannedProjectStat.isSymbolicLink())
524
+ ) {
525
+ continue;
526
+ }
527
+
528
+ if (options.onLeaseValidated) {
529
+ await options.onLeaseValidated(entry.name);
530
+ }
531
+ if (hasProject) {
532
+ if (!scannedProjectStat) continue;
533
+ await deleteLeaseContentsAndRmdir(
534
+ parentHandle,
535
+ entry.name,
536
+ leaseHandle,
537
+ {
538
+ hasProject: true,
539
+ lease: scannedLeaseStat,
540
+ project: scannedProjectStat,
541
+ owner: scannedOwnerStat,
542
+ },
543
+ );
544
+ } else {
545
+ await deleteLeaseContentsAndRmdir(
546
+ parentHandle,
547
+ entry.name,
548
+ leaseHandle,
549
+ {
550
+ hasProject: false,
551
+ lease: scannedLeaseStat,
552
+ owner: scannedOwnerStat,
553
+ },
554
+ );
555
+ }
556
+ } catch (error) {
557
+ if (error instanceof ScratchLeaseIdentityError) continue;
558
+ if (
559
+ error instanceof Error &&
560
+ "code" in error &&
561
+ (error.code === "ENOENT" ||
562
+ error.code === "ENOTDIR" ||
563
+ error.code === "ENOTEMPTY")
564
+ ) {
565
+ continue;
566
+ }
567
+ console.error(
568
+ `[delegate] failed to sweep stale scratch lease '${entry.name}'`,
569
+ error,
570
+ );
571
+ } finally {
572
+ await leaseHandle?.close();
573
+ }
574
+ }
575
+ } finally {
576
+ await parentHandle.close();
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Make an ephemeral, same-filesystem CoW copy of the Git repository containing
582
+ * cwd (or cwd itself outside Git). This is accidental-write isolation, not a
583
+ * security boundary: absolute paths and commands can still reach the host.
584
+ */
585
+ export async function createScratchWorkspace(
586
+ cwd: string,
587
+ signal?: AbortSignal,
588
+ deadlineAt?: number,
589
+ ): Promise<ScratchWorkspace> {
590
+ // Creation requires GNU cp's reflink/archive flags, and cleanup deliberately
591
+ // uses Linux descriptor paths to avoid deleting a renamed/replaced tree.
592
+ if (process.platform !== "linux" || !fs.existsSync("/proc/self/fd")) {
593
+ throw new Error(
594
+ "Scratch workspaces require Linux with GNU cp and /proc/self/fd available.",
595
+ );
596
+ }
597
+
598
+ const controller = new AbortController();
599
+ const abort = () => controller.abort(signal?.reason);
600
+ signal?.addEventListener("abort", abort, { once: true });
601
+ const deadlineAbort = () =>
602
+ controller.abort(
603
+ new Error("Scratch workspace creation exceeded the task deadline."),
604
+ );
605
+ const clearDeadline =
606
+ deadlineAt === undefined
607
+ ? undefined
608
+ : scheduleDeadline(deadlineAt, deadlineAbort);
609
+ if (deadlineAt !== undefined && Date.now() >= deadlineAt) deadlineAbort();
610
+
611
+ let sourceCwd: string;
612
+ let sourceRoot: string;
613
+ let containerDir: string;
614
+ let leaseRoot: string | undefined;
615
+ let scratchRoot: string | undefined;
616
+ let copiedLeaseStat: fs.Stats | undefined;
617
+ let copiedRootStat: fs.Stats | undefined;
618
+ let copiedOwnerStat: fs.Stats | undefined;
619
+ try {
620
+ if (signal?.aborted) controller.abort(signal.reason);
621
+ throwIfSetupCancelled(controller.signal, signal);
622
+ sourceCwd = await fs.promises.realpath(cwd);
623
+ throwIfSetupCancelled(controller.signal, signal);
624
+ sourceRoot = await findCopyRoot(sourceCwd, controller.signal);
625
+ throwIfSetupCancelled(controller.signal, signal);
626
+ if (!isWithin(sourceRoot, sourceCwd)) {
627
+ throw new ScratchSetupError(
628
+ "Scratch workspace could not map the task cwd into its project root.",
629
+ );
630
+ }
631
+
632
+ containerDir = path.join(path.dirname(sourceRoot), SCRATCH_CONTAINER_NAME);
633
+ const uid = process.getuid?.();
634
+ await ensureScratchContainer(containerDir, uid);
635
+ if (uid !== undefined) {
636
+ await sweepStaleScratchLeases(containerDir);
637
+ await sweepStaleScratchLeases(path.dirname(sourceRoot), {
638
+ prefix: SCRATCH_LEGACY_PREFIX,
639
+ });
640
+ }
641
+
642
+ leaseRoot = await fs.promises.mkdtemp(
643
+ path.join(containerDir, SCRATCH_LEASE_PREFIX),
644
+ );
645
+ await fs.promises.chmod(leaseRoot, 0o700);
646
+ await fs.promises.writeFile(
647
+ path.join(leaseRoot, SCRATCH_OWNER_NAME),
648
+ `${process.pid}\n`,
649
+ { mode: 0o600 },
650
+ );
651
+ scratchRoot = path.join(leaseRoot, SCRATCH_TREE_NAME);
652
+ await fs.promises.mkdir(scratchRoot, { mode: 0o700 });
653
+ // `source/.` copies the contents into the already-created private directory.
654
+ // `always` deliberately refuses a full-copy fallback for unexpectedly large
655
+ // projects or a destination on the wrong filesystem.
656
+ await runFile(
657
+ "cp",
658
+ [
659
+ "--archive",
660
+ "--reflink=always",
661
+ "--",
662
+ `${sourceRoot}${path.sep}.`,
663
+ scratchRoot,
664
+ ],
665
+ { signal: controller.signal, timeout: COPY_TIMEOUT_MS },
666
+ );
667
+ // GNU cp --archive applies the source root's mode to the destination.
668
+ // Restore the private boundary after it has finished copying metadata.
669
+ await fs.promises.chmod(scratchRoot, 0o700);
670
+ await validateCopiedTree(scratchRoot, controller.signal, signal);
671
+ if (
672
+ await fs.promises.stat(path.join(scratchRoot, ".git")).then(
673
+ (stat) => stat.isDirectory(),
674
+ () => false,
675
+ )
676
+ ) {
677
+ const effectiveWorktree = path.resolve(
678
+ (
679
+ await runFile("git", ["rev-parse", "--show-toplevel"], {
680
+ cwd: scratchRoot,
681
+ signal: controller.signal,
682
+ timeout: 5000,
683
+ })
684
+ ).trim(),
685
+ );
686
+ const effectiveGitDir = path.resolve(
687
+ scratchRoot,
688
+ (
689
+ await runFile("git", ["rev-parse", "--absolute-git-dir"], {
690
+ cwd: scratchRoot,
691
+ signal: controller.signal,
692
+ timeout: 5000,
693
+ })
694
+ ).trim(),
695
+ );
696
+ const effectiveCommonDir = path.resolve(
697
+ effectiveGitDir,
698
+ (
699
+ await runFile("git", ["rev-parse", "--git-common-dir"], {
700
+ cwd: scratchRoot,
701
+ signal: controller.signal,
702
+ timeout: 5000,
703
+ })
704
+ ).trim(),
705
+ );
706
+ if (
707
+ effectiveWorktree !== scratchRoot ||
708
+ !isWithin(scratchRoot, effectiveGitDir) ||
709
+ !isWithin(scratchRoot, effectiveCommonDir)
710
+ ) {
711
+ throw new ScratchSetupError(
712
+ "Scratch workspace Git configuration redirects its worktree or metadata outside the copied project.",
713
+ );
714
+ }
715
+ }
716
+ throwIfSetupCancelled(controller.signal, signal);
717
+ // Keep the copied project writable, but make its private parent immutable
718
+ // to ordinary task commands. `mv "$PWD" …` then cannot unlink the project
719
+ // entry. This is accidental-write protection, not a same-user security
720
+ // boundary: unrestricted bash can deliberately chmod the parent again.
721
+ await fs.promises.chmod(leaseRoot, 0o500);
722
+ // Capture cleanup identities inside the guarded region: if either lookup
723
+ // fails, the catch below restores permissions and removes the partial copy.
724
+ copiedLeaseStat = await fs.promises.lstat(leaseRoot);
725
+ copiedRootStat = await fs.promises.lstat(scratchRoot);
726
+ copiedOwnerStat = await fs.promises.lstat(
727
+ path.join(leaseRoot, SCRATCH_OWNER_NAME),
728
+ );
729
+ } catch (error) {
730
+ if (leaseRoot) {
731
+ try {
732
+ await fs.promises.chmod(leaseRoot, 0o700);
733
+ await fs.promises.rm(leaseRoot, { recursive: true, force: true });
734
+ } catch (cleanupError) {
735
+ console.error(
736
+ "[delegate] failed to clean partial scratch workspace",
737
+ cleanupError,
738
+ );
739
+ }
740
+ }
741
+ if (controller.signal.aborted) {
742
+ if (signal?.aborted) {
743
+ throw new Error("Scratch workspace creation was aborted.", {
744
+ cause: error,
745
+ });
746
+ }
747
+ throw new ScratchDeadlineError(
748
+ "Scratch workspace creation exceeded the task deadline.",
749
+ { cause: error },
750
+ );
751
+ }
752
+ if (error instanceof ScratchSetupError) throw error;
753
+ throw new Error(
754
+ "Could not create a CoW scratch workspace. The project and scratch directory must be on a reflink-capable filesystem (for example Btrfs).",
755
+ { cause: error },
756
+ );
757
+ } finally {
758
+ signal?.removeEventListener("abort", abort);
759
+ clearDeadline?.();
760
+ }
761
+
762
+ // Assigned before successful exit from the try block above.
763
+ const completedLeaseRoot = leaseRoot!;
764
+ const completedRoot = scratchRoot!;
765
+ const completedLeaseStat = copiedLeaseStat!;
766
+ const completedRootStat = copiedRootStat!;
767
+ const completedOwnerStat = copiedOwnerStat!;
768
+ const relativeCwd = path.relative(sourceRoot!, sourceCwd!);
769
+ let cleaned = false;
770
+ const resolveReportedPath = async (candidate: string): Promise<string> => {
771
+ const absolute = path.resolve(candidate);
772
+ try {
773
+ const real = await fs.promises.realpath(absolute);
774
+ return isWithin(completedRoot, real)
775
+ ? path.join(sourceRoot!, path.relative(completedRoot, real))
776
+ : real;
777
+ } catch {
778
+ // A successful edit/write normally leaves a path behind. Keep the
779
+ // source mapping for a disposable path that was deleted immediately,
780
+ // while preserving an external path for later diagnostics.
781
+ return isWithin(completedRoot, absolute)
782
+ ? path.join(sourceRoot!, path.relative(completedRoot, absolute))
783
+ : absolute;
784
+ }
785
+ };
786
+ const resolveAttributedPath = async (
787
+ candidate: string,
788
+ ): Promise<string | undefined> => {
789
+ try {
790
+ const real = await fs.promises.realpath(candidate);
791
+ return isWithin(completedRoot, real) ? undefined : real;
792
+ } catch {
793
+ const absolute = path.resolve(candidate);
794
+ return isWithin(completedRoot, absolute) ? undefined : absolute;
795
+ }
796
+ };
797
+ return {
798
+ sourceRoot: sourceRoot!,
799
+ sourceCwd: sourceCwd!,
800
+ scratchRoot: completedRoot,
801
+ cwd: path.join(completedRoot, relativeCwd),
802
+ mapPathToSource(candidate: string): string {
803
+ const absolute = path.resolve(candidate);
804
+ if (!isWithin(completedRoot, absolute)) return candidate;
805
+ return path.join(sourceRoot!, path.relative(completedRoot, absolute));
806
+ },
807
+ resolveReportedPath,
808
+ resolveAttributedPath,
809
+ async isDisposablePath(candidate: string): Promise<boolean> {
810
+ return (await resolveAttributedPath(candidate)) === undefined;
811
+ },
812
+ async cleanup(): Promise<void> {
813
+ if (cleaned) return;
814
+ try {
815
+ if (
816
+ path.dirname(completedLeaseRoot) !== containerDir ||
817
+ !path.basename(completedLeaseRoot).startsWith(SCRATCH_LEASE_PREFIX) ||
818
+ path.dirname(completedRoot) !== completedLeaseRoot ||
819
+ path.basename(completedRoot) !== SCRATCH_TREE_NAME
820
+ ) {
821
+ throw new Error(
822
+ "Refusing to clean an unrecognised scratch workspace path.",
823
+ );
824
+ }
825
+ // Open the parent first, then resolve the lease through that handle. The
826
+ // descriptor identifies the checked directory even if its pathname is
827
+ // renamed or replaced while cleanup is running.
828
+ const parentHandle = await fs.promises.open(
829
+ containerDir,
830
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
831
+ );
832
+ let leaseHandle:
833
+ Awaited<ReturnType<typeof fs.promises.open>> | undefined;
834
+ let rootHandle:
835
+ Awaited<ReturnType<typeof fs.promises.open>> | undefined;
836
+ try {
837
+ const leaseName = path.basename(completedLeaseRoot);
838
+ leaseHandle = await fs.promises.open(
839
+ path.join(`/proc/self/fd/${parentHandle.fd}`, leaseName),
840
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
841
+ );
842
+ rootHandle = await fs.promises.open(
843
+ path.join(`/proc/self/fd/${leaseHandle.fd}`, SCRATCH_TREE_NAME),
844
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
845
+ );
846
+ const openLeaseStat = await leaseHandle.stat();
847
+ const openRootStat = await rootHandle.stat();
848
+ const currentLeaseStat = await fs.promises.lstat(
849
+ path.join(`/proc/self/fd/${parentHandle.fd}`, leaseName),
850
+ );
851
+ const currentRootStat = await fs.promises.lstat(
852
+ path.join(`/proc/self/fd/${leaseHandle.fd}`, SCRATCH_TREE_NAME),
853
+ );
854
+ if (
855
+ !openLeaseStat.isDirectory() ||
856
+ !sameFileIdentity(openLeaseStat, completedLeaseStat) ||
857
+ !sameFileIdentity(currentLeaseStat, completedLeaseStat) ||
858
+ !openRootStat.isDirectory() ||
859
+ !sameFileIdentity(openRootStat, completedRootStat) ||
860
+ !sameFileIdentity(currentRootStat, completedRootStat)
861
+ ) {
862
+ throw new Error(
863
+ "Scratch workspace root was moved or replaced; refusing to report cleanup success.",
864
+ );
865
+ }
866
+
867
+ // The identity checks are snapshots. The primitive repeats them and
868
+ // removes project children through its opened descriptor, so a
869
+ // replacement observed before removal is preserved. This is not an
870
+ // atomic guarantee against a cooperating process changing the path
871
+ // after the final check.
872
+ await deleteLeaseContentsAndRmdir(
873
+ parentHandle,
874
+ leaseName,
875
+ leaseHandle,
876
+ {
877
+ hasProject: true,
878
+ lease: completedLeaseStat,
879
+ project: completedRootStat,
880
+ owner: completedOwnerStat,
881
+ },
882
+ );
883
+ cleaned = true;
884
+ } finally {
885
+ await rootHandle?.close();
886
+ await leaseHandle?.close();
887
+ await parentHandle.close();
888
+ }
889
+ } catch (error) {
890
+ throw new Error(
891
+ `Scratch workspace cleanup failed for lease '${completedLeaseRoot}': ${error instanceof Error ? error.message : String(error)}`,
892
+ { cause: error },
893
+ );
894
+ }
895
+ },
896
+ };
897
+ }
898
+
899
+ export const _testHooks = {
900
+ sweepStaleScratchLeases,
901
+ ensureScratchContainer,
902
+ deleteLeaseContentsAndRmdir,
903
+ SCRATCH_CONTAINER_NAME,
904
+ SCRATCH_LEASE_PREFIX,
905
+ SCRATCH_LEGACY_PREFIX,
906
+ SCRATCH_TREE_NAME,
907
+ SCRATCH_OWNER_NAME,
908
+ };