@punks/cli 3.1.2 → 3.1.3

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.
@@ -1,17 +1,8 @@
1
- import {
2
- cp,
3
- lstat,
4
- mkdir,
5
- readFile,
6
- realpath,
7
- readdir,
8
- readlink,
9
- rm,
10
- symlink,
11
- writeFile,
12
- } from "node:fs/promises";
13
- import { createHash } from "node:crypto";
1
+ import { lstat, readFile, realpath, readdir, readlink } from "node:fs/promises";
2
+ import { spawn } from "node:child_process";
3
+ import { createHash, randomUUID } from "node:crypto";
14
4
  import path from "node:path";
5
+ import { createInterface } from "node:readline";
15
6
  import { fileURLToPath } from "node:url";
16
7
 
17
8
  import { agents, capabilityPacks } from "../subagents/manifest.mjs";
@@ -31,6 +22,776 @@ const projectionReceiptPath = path.join(repoRoot, ".devpunks/harness-projection-
31
22
  const adapters = [claudeAdapter, codexAdapter, cursorAdapter, openCodeAdapter];
32
23
  let previousCopyFallbacks = [];
33
24
  const currentCopyFallbacks = new Map();
25
+ let operationRepoRootIdentity;
26
+
27
+ const confinedMutationScript = String.raw`
28
+ import { spawnSync } from "node:child_process";
29
+ import {
30
+ closeSync,
31
+ constants,
32
+ fchmodSync,
33
+ fstatSync,
34
+ linkSync,
35
+ lstatSync,
36
+ mkdirSync,
37
+ openSync,
38
+ readSync,
39
+ renameSync,
40
+ rmSync,
41
+ statSync,
42
+ symlinkSync,
43
+ unlinkSync,
44
+ writeFileSync,
45
+ writeSync,
46
+ } from "node:fs";
47
+ import { createInterface } from "node:readline";
48
+
49
+ const parent = JSON.parse(process.argv[1]);
50
+ const assertParentIdentity = () => {
51
+ const current = statSync(".");
52
+ if (current.dev !== parent.device || current.ino !== parent.inode) {
53
+ const error = new Error("Confined mutation parent identity changed.");
54
+ error.code = "ESTALE";
55
+ throw error;
56
+ }
57
+ };
58
+
59
+ const leafKind = (entry) =>
60
+ entry.isSymbolicLink()
61
+ ? "symlink"
62
+ : entry.isFile()
63
+ ? "file"
64
+ : entry.isDirectory()
65
+ ? "directory"
66
+ : "other";
67
+
68
+ const assertExpectedLeaf = (targetPath, expected) => {
69
+ const target = lstatSync(targetPath, { throwIfNoEntry: false });
70
+ const matches =
71
+ expected.kind === "absent"
72
+ ? target === undefined
73
+ : target !== undefined &&
74
+ target.dev === expected.device &&
75
+ target.ino === expected.inode &&
76
+ leafKind(target) === expected.kind;
77
+ if (!matches) {
78
+ const error = new Error("Confined mutation target changed after validation.");
79
+ error.code = "ESTALE_TARGET";
80
+ throw error;
81
+ }
82
+ return target;
83
+ };
84
+
85
+ const confinedDirectoryCopyScript = [
86
+ 'import { cpSync, statSync } from "node:fs";',
87
+ "const expected = JSON.parse(process.argv[1]);",
88
+ 'const current = statSync(".");',
89
+ "if (current.dev !== expected.device || current.ino !== expected.inode) {",
90
+ ' throw new Error("Confined copy directory identity changed.");',
91
+ "}",
92
+ 'cpSync(process.argv[2], ".", { recursive: true });',
93
+ ].join("\n");
94
+
95
+ const copyIntoClaimedDirectory = (request, expected) => {
96
+ const result = spawnSync(
97
+ process.execPath,
98
+ ["--input-type=module", "--eval", confinedDirectoryCopyScript, JSON.stringify(expected), request.source],
99
+ { cwd: request.target, stdio: "ignore" },
100
+ );
101
+ if (result.error !== undefined) throw result.error;
102
+ if (result.status !== 0) {
103
+ const error = new Error("Confined directory copy failed.");
104
+ error.code = "EIO";
105
+ throw error;
106
+ }
107
+ };
108
+
109
+ const mutate = (request) => {
110
+ let descriptor;
111
+ let createdIdentity;
112
+ let response = {};
113
+ let sourceDescriptor;
114
+ let writePath;
115
+ try {
116
+ assertParentIdentity();
117
+ if (request.operation === "read") {
118
+ descriptor = openSync(
119
+ request.target,
120
+ constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0),
121
+ );
122
+ const opened = fstatSync(descriptor);
123
+ if (
124
+ !opened.isFile() ||
125
+ request.expectedTarget.kind !== "file" ||
126
+ opened.dev !== request.expectedTarget.device ||
127
+ opened.ino !== request.expectedTarget.inode
128
+ ) {
129
+ const error = new Error("Confined read target changed before descriptor read.");
130
+ error.code = "ESTALE_TARGET";
131
+ throw error;
132
+ }
133
+ if (opened.size > request.maximumBytes) {
134
+ const error = new Error("Confined file exceeds the read limit.");
135
+ error.code = "EFBIG";
136
+ throw error;
137
+ }
138
+ const chunks = [];
139
+ let total = 0;
140
+ while (total <= request.maximumBytes) {
141
+ const chunk = Buffer.alloc(Math.min(64 * 1024, request.maximumBytes + 1 - total));
142
+ const bytesRead = readSync(descriptor, chunk, 0, chunk.length, null);
143
+ if (bytesRead === 0) break;
144
+ chunks.push(chunk.subarray(0, bytesRead));
145
+ total += bytesRead;
146
+ }
147
+ if (total > request.maximumBytes) {
148
+ const error = new Error("Confined file exceeds the read limit.");
149
+ error.code = "EFBIG";
150
+ throw error;
151
+ }
152
+ response = { content: Buffer.concat(chunks).toString("base64") };
153
+ closeSync(descriptor);
154
+ descriptor = undefined;
155
+ } else if (request.operation === "mkdir") {
156
+ const target = lstatSync(request.target, { throwIfNoEntry: false });
157
+ if (target === undefined) {
158
+ mkdirSync(request.target);
159
+ } else if (target.isSymbolicLink() || !target.isDirectory()) {
160
+ const error = new Error("Refusing to replace an unsafe confined directory.");
161
+ error.code = "EINVAL";
162
+ throw error;
163
+ }
164
+ } else if (request.operation === "write") {
165
+ const target = lstatSync(request.target, { throwIfNoEntry: false });
166
+ if (target !== undefined && (target.isSymbolicLink() || !target.isFile())) {
167
+ const error = new Error("Refusing to replace an unsafe confined target.");
168
+ error.code = "EINVAL";
169
+ throw error;
170
+ }
171
+ const expectedTarget =
172
+ target === undefined
173
+ ? { kind: "absent" }
174
+ : { device: target.dev, inode: target.ino, kind: leafKind(target) };
175
+ writePath = request.temporary;
176
+ descriptor = openSync(
177
+ writePath,
178
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0),
179
+ target?.mode ?? 0o666,
180
+ );
181
+ const created = fstatSync(descriptor);
182
+ createdIdentity = { device: created.dev, inode: created.ino };
183
+ assertParentIdentity();
184
+ writeFileSync(descriptor, request.content);
185
+ if (target !== undefined) {
186
+ fchmodSync(descriptor, target.mode & 0o7777);
187
+ }
188
+ closeSync(descriptor);
189
+ descriptor = undefined;
190
+ assertParentIdentity();
191
+ assertExpectedLeaf(request.target, expectedTarget);
192
+ renameSync(request.temporary, request.target);
193
+ assertParentIdentity();
194
+ } else if (request.operation === "remove") {
195
+ assertExpectedLeaf(request.target, request.expectedTarget);
196
+ if (lstatSync(request.claim, { throwIfNoEntry: false }) !== undefined) {
197
+ const error = new Error("Confined removal claim path already exists.");
198
+ error.code = "EEXIST";
199
+ throw error;
200
+ }
201
+ renameSync(request.target, request.claim);
202
+ try {
203
+ assertParentIdentity();
204
+ assertExpectedLeaf(request.claim, request.expectedTarget);
205
+ rmSync(request.claim, { force: true, recursive: request.recursive });
206
+ } catch (error) {
207
+ if (lstatSync(request.claim, { throwIfNoEntry: false }) !== undefined) {
208
+ try {
209
+ if (lstatSync(request.target, { throwIfNoEntry: false }) !== undefined) {
210
+ const restorationError = new Error(
211
+ "Confined removal target was recreated before claim restoration.",
212
+ );
213
+ restorationError.code = "ESTALE_TARGET";
214
+ throw restorationError;
215
+ }
216
+ const claim = lstatSync(request.claim);
217
+ if (claim.isFile()) {
218
+ linkSync(request.claim, request.target);
219
+ unlinkSync(request.claim);
220
+ } else {
221
+ renameSync(request.claim, request.target);
222
+ }
223
+ } catch (cause) {
224
+ const restorationError = new Error(
225
+ "Confined removal could not restore its claimed target.",
226
+ { cause },
227
+ );
228
+ restorationError.backup = request.claim;
229
+ restorationError.code = "ESTALE_TARGET";
230
+ throw restorationError;
231
+ }
232
+ }
233
+ throw error;
234
+ }
235
+ assertParentIdentity();
236
+ } else if (request.operation === "symlink") {
237
+ if (lstatSync(request.target, { throwIfNoEntry: false }) !== undefined) {
238
+ const error = new Error("Confined symlink target already exists.");
239
+ error.code = "EEXIST";
240
+ throw error;
241
+ }
242
+ symlinkSync(request.linkTarget, request.target, request.type);
243
+ assertParentIdentity();
244
+ } else if (request.operation === "copy") {
245
+ assertExpectedLeaf(request.target, request.expectedTarget);
246
+ if (request.recursive) {
247
+ mkdirSync(request.target);
248
+ const created = lstatSync(request.target);
249
+ createdIdentity = { device: created.dev, inode: created.ino };
250
+ writePath = request.target;
251
+ copyIntoClaimedDirectory(request, createdIdentity);
252
+ assertParentIdentity();
253
+ assertExpectedLeaf(request.target, { ...createdIdentity, kind: "directory" });
254
+ } else {
255
+ sourceDescriptor = openSync(
256
+ request.source,
257
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
258
+ );
259
+ const source = fstatSync(sourceDescriptor);
260
+ if (!source.isFile()) {
261
+ const error = new Error("Confined copy source is not a regular file.");
262
+ error.code = "EINVAL";
263
+ throw error;
264
+ }
265
+ writePath = request.target;
266
+ descriptor = openSync(
267
+ request.target,
268
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
269
+ source.mode,
270
+ );
271
+ const created = fstatSync(descriptor);
272
+ createdIdentity = { device: created.dev, inode: created.ino };
273
+ const buffer = Buffer.alloc(64 * 1024);
274
+ for (;;) {
275
+ const bytesRead = readSync(sourceDescriptor, buffer, 0, buffer.length, null);
276
+ if (bytesRead === 0) break;
277
+ let offset = 0;
278
+ while (offset < bytesRead) {
279
+ offset += writeSync(descriptor, buffer, offset, bytesRead - offset);
280
+ }
281
+ }
282
+ fchmodSync(descriptor, source.mode & 0o7777);
283
+ closeSync(descriptor);
284
+ descriptor = undefined;
285
+ closeSync(sourceDescriptor);
286
+ sourceDescriptor = undefined;
287
+ }
288
+ writePath = undefined;
289
+ createdIdentity = undefined;
290
+ assertParentIdentity();
291
+ }
292
+ return response;
293
+ } catch (error) {
294
+ if (descriptor !== undefined) {
295
+ closeSync(descriptor);
296
+ }
297
+ if (sourceDescriptor !== undefined) {
298
+ closeSync(sourceDescriptor);
299
+ }
300
+ if (writePath !== undefined && createdIdentity !== undefined) {
301
+ const current = lstatSync(writePath, { throwIfNoEntry: false });
302
+ if (
303
+ current !== undefined &&
304
+ current.dev === createdIdentity.device &&
305
+ current.ino === createdIdentity.inode
306
+ ) {
307
+ rmSync(writePath, {
308
+ force: true,
309
+ recursive: request.operation === "copy" && request.recursive === true,
310
+ });
311
+ }
312
+ }
313
+ throw error;
314
+ }
315
+ };
316
+
317
+ const lines = createInterface({ input: process.stdin });
318
+ for await (const line of lines) {
319
+ try {
320
+ const response = mutate(JSON.parse(line));
321
+ process.stdout.write(JSON.stringify({ ok: true, ...response }) + "\n");
322
+ } catch (error) {
323
+ process.stdout.write(JSON.stringify({
324
+ ok: false,
325
+ backup: error && typeof error === "object" && "backup" in error ? error.backup : undefined,
326
+ code: error && typeof error === "object" && "code" in error ? error.code : undefined,
327
+ message: error instanceof Error ? error.message : String(error),
328
+ }) + "\n");
329
+ }
330
+ }
331
+ `;
332
+
333
+ const confinedMutationEnvironment = Object.fromEntries(
334
+ ["SystemRoot", "WINDIR"].flatMap((key) => {
335
+ const value = process.env[key];
336
+ return value === undefined ? [] : [[key, value]];
337
+ }),
338
+ );
339
+
340
+ const mutationWorkers = new Map();
341
+ const maximumMutationWorkers = 8;
342
+ let mutationWorkerReservations = 0;
343
+ const mutationWorkerCapacityWaiters = [];
344
+ const mutationWorkerExits = new Set();
345
+
346
+ function grantMutationWorkerCapacity() {
347
+ while (
348
+ mutationWorkers.size + mutationWorkerReservations < maximumMutationWorkers &&
349
+ mutationWorkerCapacityWaiters.length > 0
350
+ ) {
351
+ mutationWorkerReservations += 1;
352
+ mutationWorkerCapacityWaiters.shift()();
353
+ }
354
+ }
355
+
356
+ function evictIdleMutationWorker() {
357
+ for (const worker of mutationWorkers.values()) {
358
+ if (worker.pending.length === 0 && !worker.closing) {
359
+ closeMutationWorker(worker);
360
+ return;
361
+ }
362
+ }
363
+ }
364
+
365
+ async function acquireMutationWorkerCapacity() {
366
+ if (mutationWorkers.size + mutationWorkerReservations < maximumMutationWorkers) {
367
+ mutationWorkerReservations += 1;
368
+ return;
369
+ }
370
+ evictIdleMutationWorker();
371
+ await new Promise((resolve) => mutationWorkerCapacityWaiters.push(resolve));
372
+ }
373
+
374
+ function releaseMutationWorkerCapacity() {
375
+ mutationWorkerReservations -= 1;
376
+ grantMutationWorkerCapacity();
377
+ }
378
+
379
+ function closeMutationWorker(worker) {
380
+ if (mutationWorkers.get(worker.key) !== worker || worker.closing) return;
381
+ worker.closing = true;
382
+ if (!worker.child.stdin.destroyed) worker.child.stdin.end();
383
+ }
384
+
385
+ function scheduleMutationWorkerClose(worker) {
386
+ if (worker.pending.length > 0 || worker.closing) return;
387
+ if (worker.idleTimer !== undefined) clearTimeout(worker.idleTimer);
388
+ worker.idleTimer = setTimeout(() => closeMutationWorker(worker), 25);
389
+ }
390
+
391
+ function createMutationWorker(parentDirectory, parentIdentity, key) {
392
+ const child = spawn(
393
+ process.execPath,
394
+ ["--input-type=module", "--eval", confinedMutationScript, JSON.stringify(parentIdentity)],
395
+ {
396
+ cwd: parentDirectory,
397
+ env: confinedMutationEnvironment,
398
+ stdio: ["pipe", "pipe", "ignore"],
399
+ },
400
+ );
401
+ const pending = [];
402
+ let terminalError;
403
+ let resolveExited;
404
+ let exitSettled = false;
405
+ const exited = new Promise((resolve) => {
406
+ resolveExited = resolve;
407
+ });
408
+ mutationWorkerExits.add(exited);
409
+ void exited.then(() => mutationWorkerExits.delete(exited));
410
+ const worker = {
411
+ child,
412
+ closing: false,
413
+ exited,
414
+ idleTimer: undefined,
415
+ key,
416
+ pending,
417
+ request(request) {
418
+ if (terminalError !== undefined) return Promise.reject(terminalError);
419
+ return new Promise((resolve, reject) => {
420
+ pending.push({ reject, resolve });
421
+ child.stdin.write(`${JSON.stringify(request)}\n`, (error) => {
422
+ if (error !== null && error !== undefined) fail(error);
423
+ });
424
+ });
425
+ },
426
+ get terminalError() {
427
+ return terminalError;
428
+ },
429
+ };
430
+ const settleExit = () => {
431
+ if (exitSettled) return;
432
+ exitSettled = true;
433
+ if (worker.idleTimer !== undefined) clearTimeout(worker.idleTimer);
434
+ if (mutationWorkers.get(key) === worker) {
435
+ mutationWorkers.delete(key);
436
+ grantMutationWorkerCapacity();
437
+ }
438
+ resolveExited();
439
+ };
440
+ const fail = (error) => {
441
+ terminalError ??= error;
442
+ while (pending.length > 0) pending.shift().reject(error);
443
+ };
444
+ child.once("error", (error) => {
445
+ fail(error);
446
+ settleExit();
447
+ });
448
+ child.once("exit", (code) => {
449
+ if (code !== 0 || pending.length > 0) {
450
+ fail(new Error(`Confined filesystem mutation worker exited with ${code}.`));
451
+ }
452
+ settleExit();
453
+ });
454
+ child.stdout.setEncoding("utf-8");
455
+ createInterface({ input: child.stdout }).on("line", (line) => {
456
+ const waiter = pending.shift();
457
+ if (waiter === undefined) return;
458
+ try {
459
+ waiter.resolve(JSON.parse(line));
460
+ } catch (error) {
461
+ waiter.reject(error);
462
+ }
463
+ });
464
+ mutationWorkers.set(key, worker);
465
+ return worker;
466
+ }
467
+
468
+ async function runStableMutation(parentDirectory, request, content) {
469
+ const key = `${parentDirectory}\0${request.parent.device}:${request.parent.inode}`;
470
+ let worker = mutationWorkers.get(key);
471
+ if (worker === undefined || worker.closing || worker.terminalError !== undefined) {
472
+ await acquireMutationWorkerCapacity();
473
+ try {
474
+ worker = mutationWorkers.get(key);
475
+ if (worker === undefined || worker.closing || worker.terminalError !== undefined) {
476
+ worker = createMutationWorker(parentDirectory, request.parent, key);
477
+ }
478
+ } finally {
479
+ releaseMutationWorkerCapacity();
480
+ }
481
+ }
482
+ if (worker.idleTimer !== undefined) {
483
+ clearTimeout(worker.idleTimer);
484
+ worker.idleTimer = undefined;
485
+ }
486
+ let result;
487
+ try {
488
+ result = await worker.request({
489
+ ...request,
490
+ ...(content === undefined ? {} : { content }),
491
+ });
492
+ } finally {
493
+ scheduleMutationWorkerClose(worker);
494
+ }
495
+ if (!result.ok) {
496
+ const backupPath =
497
+ result.backup === undefined ? undefined : path.join(parentDirectory, result.backup);
498
+ const error = new Error(
499
+ `${result.message ?? "Confined filesystem mutation failed."}${
500
+ backupPath === undefined ? "" : ` Retained backup: ${backupPath}.`
501
+ }`,
502
+ );
503
+ if (result.code !== undefined) {
504
+ Object.assign(error, { code: result.code });
505
+ }
506
+ if (backupPath !== undefined) {
507
+ Object.assign(error, { backupPath });
508
+ }
509
+ throw error;
510
+ }
511
+ return result;
512
+ }
513
+
514
+ async function closeMutationWorkers() {
515
+ for (const worker of mutationWorkers.values()) closeMutationWorker(worker);
516
+ const exits = [...mutationWorkerExits];
517
+ await Promise.all(exits);
518
+ }
519
+
520
+ function isOutsideRoot(relativePath) {
521
+ return (
522
+ relativePath === ".." ||
523
+ relativePath.startsWith(`..${path.sep}`) ||
524
+ path.isAbsolute(relativePath)
525
+ );
526
+ }
527
+
528
+ async function lstatOrNull(targetPath) {
529
+ return lstat(targetPath).catch((error) => {
530
+ if (error?.code === "ENOENT") return null;
531
+ throw error;
532
+ });
533
+ }
534
+
535
+ function confinedRelativePath(targetPath, operation) {
536
+ const relativeTarget = path.relative(repoRoot, path.resolve(targetPath));
537
+ if (relativeTarget.length === 0 || isOutsideRoot(relativeTarget)) {
538
+ throw new Error(`Refusing to ${operation} outside ${repoRoot}`);
539
+ }
540
+ return relativeTarget;
541
+ }
542
+
543
+ async function captureRepoRootIdentity(operation) {
544
+ const root = await lstatOrNull(repoRoot);
545
+ if (root === null || root.isSymbolicLink() || !root.isDirectory()) {
546
+ throw new Error(`Refusing to ${operation} through changed root ${repoRoot}`);
547
+ }
548
+ return { device: root.dev, inode: root.ino };
549
+ }
550
+
551
+ function repoRootIdentityForOperation(operation) {
552
+ if (operationRepoRootIdentity === undefined) {
553
+ throw new Error(`Confined filesystem session is not initialized for ${operation}`);
554
+ }
555
+ return operationRepoRootIdentity;
556
+ }
557
+
558
+ async function assertRepoRootIdentity(expected, operation) {
559
+ const current = await lstatOrNull(repoRoot);
560
+ if (
561
+ current === null ||
562
+ current.isSymbolicLink() ||
563
+ !current.isDirectory() ||
564
+ current.dev !== expected.device ||
565
+ current.ino !== expected.inode
566
+ ) {
567
+ throw new Error(`Refusing to ${operation} through changed root ${repoRoot}`);
568
+ }
569
+ }
570
+
571
+ async function captureLeafExpectation(targetPath) {
572
+ const target = await lstatOrNull(targetPath);
573
+ if (target === null) return { kind: "absent" };
574
+ return {
575
+ device: target.dev,
576
+ inode: target.ino,
577
+ kind: target.isSymbolicLink()
578
+ ? "symlink"
579
+ : target.isFile()
580
+ ? "file"
581
+ : target.isDirectory()
582
+ ? "directory"
583
+ : "other",
584
+ };
585
+ }
586
+
587
+ async function assertConfinedDirectoryComponents(components, operation, repoRootIdentity) {
588
+ await assertRepoRootIdentity(repoRootIdentity, operation);
589
+ const resolvedRoot = await realpath(repoRoot);
590
+ let currentDirectory = repoRoot;
591
+ for (const component of components) {
592
+ currentDirectory = path.join(currentDirectory, component);
593
+ const entry = await lstatOrNull(currentDirectory);
594
+ if (entry === null) break;
595
+ if (
596
+ entry.isSymbolicLink() ||
597
+ !entry.isDirectory() ||
598
+ isOutsideRoot(path.relative(resolvedRoot, await realpath(currentDirectory)))
599
+ ) {
600
+ throw new Error(`Refusing to ${operation} through ${currentDirectory}`);
601
+ }
602
+ }
603
+ await assertRepoRootIdentity(repoRootIdentity, operation);
604
+ }
605
+
606
+ async function assertConfinedRegularFile(targetPath, suppliedRepoRootIdentity) {
607
+ const operation = "write scaffold content";
608
+ const repoRootIdentity = suppliedRepoRootIdentity ?? repoRootIdentityForOperation(operation);
609
+ const relativeTarget = confinedRelativePath(targetPath, "write scaffold content");
610
+ await assertConfinedDirectoryComponents(
611
+ relativeTarget.split(path.sep).slice(0, -1),
612
+ operation,
613
+ repoRootIdentity,
614
+ );
615
+
616
+ const target = await lstatOrNull(targetPath);
617
+ if (target !== null && (target.isSymbolicLink() || !target.isFile())) {
618
+ throw new Error(`Refusing to replace unsafe scaffold file ${targetPath}`);
619
+ }
620
+ await assertRepoRootIdentity(repoRootIdentity, operation);
621
+ return target;
622
+ }
623
+
624
+ async function captureConfinedDirectoryIdentity(directoryPath, operation, repoRootIdentity) {
625
+ const relativeDirectory = path.relative(repoRoot, path.resolve(directoryPath));
626
+ if (isOutsideRoot(relativeDirectory)) {
627
+ throw new Error(`Refusing to ${operation} through changed parent ${directoryPath}`);
628
+ }
629
+ await assertConfinedDirectoryComponents(
630
+ relativeDirectory.split(path.sep).filter(Boolean),
631
+ operation,
632
+ repoRootIdentity,
633
+ );
634
+ const entry = await lstatOrNull(directoryPath);
635
+ if (entry === null || entry.isSymbolicLink() || !entry.isDirectory()) {
636
+ throw new Error(`Refusing to ${operation} through changed parent ${directoryPath}`);
637
+ }
638
+ await assertRepoRootIdentity(repoRootIdentity, operation);
639
+ return { device: entry.dev, inode: entry.ino };
640
+ }
641
+
642
+ async function assertSameDirectoryIdentity(directoryPath, expected, operation, repoRootIdentity) {
643
+ const current = await captureConfinedDirectoryIdentity(
644
+ directoryPath,
645
+ operation,
646
+ repoRootIdentity,
647
+ );
648
+ if (current.device !== expected.device || current.inode !== expected.inode) {
649
+ throw new Error(`Refusing to ${operation} through changed parent ${directoryPath}`);
650
+ }
651
+ }
652
+
653
+ async function ensureConfinedDirectory(directoryPath, suppliedRepoRootIdentity) {
654
+ const operation = "create scaffold directories";
655
+ const repoRootIdentity = suppliedRepoRootIdentity ?? repoRootIdentityForOperation(operation);
656
+ if (path.resolve(directoryPath) === repoRoot) {
657
+ await assertRepoRootIdentity(repoRootIdentity, operation);
658
+ return;
659
+ }
660
+ const relativeDirectory = confinedRelativePath(directoryPath, operation);
661
+ await assertRepoRootIdentity(repoRootIdentity, operation);
662
+ const resolvedRoot = await realpath(repoRoot);
663
+ let currentDirectory = repoRoot;
664
+ for (const component of relativeDirectory.split(path.sep)) {
665
+ const parentDirectory = currentDirectory;
666
+ currentDirectory = path.join(currentDirectory, component);
667
+ let entry = await lstatOrNull(currentDirectory);
668
+ if (entry === null) {
669
+ const parentIdentity = await captureConfinedDirectoryIdentity(
670
+ parentDirectory,
671
+ operation,
672
+ repoRootIdentity,
673
+ );
674
+ await runStableMutation(parentDirectory, {
675
+ operation: "mkdir",
676
+ parent: parentIdentity,
677
+ target: component,
678
+ });
679
+ await assertSameDirectoryIdentity(
680
+ parentDirectory,
681
+ parentIdentity,
682
+ operation,
683
+ repoRootIdentity,
684
+ );
685
+ entry = await lstat(currentDirectory);
686
+ }
687
+ if (
688
+ entry.isSymbolicLink() ||
689
+ !entry.isDirectory() ||
690
+ isOutsideRoot(path.relative(resolvedRoot, await realpath(currentDirectory)))
691
+ ) {
692
+ throw new Error(`Refusing to create scaffold content through ${currentDirectory}`);
693
+ }
694
+ await assertRepoRootIdentity(repoRootIdentity, operation);
695
+ }
696
+ }
697
+
698
+ async function removeConfinedPath(targetPath, options = {}) {
699
+ const operation = "remove scaffold content";
700
+ const repoRootIdentity = repoRootIdentityForOperation(operation);
701
+ const relativeTarget = confinedRelativePath(targetPath, operation);
702
+ await assertConfinedDirectoryComponents(
703
+ relativeTarget.split(path.sep).slice(0, -1),
704
+ operation,
705
+ repoRootIdentity,
706
+ );
707
+ const expectedTarget = await captureLeafExpectation(targetPath);
708
+ if (expectedTarget.kind === "absent") {
709
+ await assertRepoRootIdentity(repoRootIdentity, operation);
710
+ return;
711
+ }
712
+ const parentDirectory = path.dirname(targetPath);
713
+ const parentIdentity = await captureConfinedDirectoryIdentity(
714
+ parentDirectory,
715
+ operation,
716
+ repoRootIdentity,
717
+ );
718
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
719
+ await runStableMutation(parentDirectory, {
720
+ claim: `.hi-remove-${randomUUID()}`,
721
+ expectedTarget,
722
+ operation: "remove",
723
+ parent: parentIdentity,
724
+ recursive: options.recursive === true,
725
+ target: path.basename(targetPath),
726
+ });
727
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
728
+ }
729
+
730
+ async function writeConfinedTextFile(targetPath, content) {
731
+ const operation = "write scaffold content";
732
+ const repoRootIdentity = repoRootIdentityForOperation(operation);
733
+ await assertConfinedRegularFile(targetPath, repoRootIdentity);
734
+ const parentDirectory = path.dirname(targetPath);
735
+ await ensureConfinedDirectory(parentDirectory, repoRootIdentity);
736
+ await assertConfinedRegularFile(targetPath, repoRootIdentity);
737
+ const parentIdentity = await captureConfinedDirectoryIdentity(
738
+ parentDirectory,
739
+ operation,
740
+ repoRootIdentity,
741
+ );
742
+
743
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
744
+ await runStableMutation(
745
+ parentDirectory,
746
+ {
747
+ operation: "write",
748
+ parent: parentIdentity,
749
+ target: path.basename(targetPath),
750
+ temporary: `.hi-${randomUUID()}.tmp`,
751
+ },
752
+ content,
753
+ );
754
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
755
+ }
756
+
757
+ async function readConfinedRegularFile(targetPath, maximumBytes = 16 * 1024 * 1024) {
758
+ const operation = "read scaffold content";
759
+ const repoRootIdentity = repoRootIdentityForOperation(operation);
760
+ const target = await assertConfinedRegularFile(targetPath, repoRootIdentity);
761
+ if (target === null) {
762
+ await assertRepoRootIdentity(repoRootIdentity, operation);
763
+ return null;
764
+ }
765
+ const parentDirectory = path.dirname(targetPath);
766
+ const parentIdentity = await captureConfinedDirectoryIdentity(
767
+ parentDirectory,
768
+ operation,
769
+ repoRootIdentity,
770
+ );
771
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
772
+ try {
773
+ const result = await runStableMutation(parentDirectory, {
774
+ expectedTarget: {
775
+ device: target.dev,
776
+ inode: target.ino,
777
+ kind: "file",
778
+ },
779
+ maximumBytes,
780
+ operation: "read",
781
+ parent: parentIdentity,
782
+ target: path.basename(targetPath),
783
+ });
784
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
785
+ if (typeof result.content !== "string") {
786
+ throw new Error("Confined filesystem read returned no content.");
787
+ }
788
+ return Buffer.from(result.content, "base64");
789
+ } catch (error) {
790
+ await assertSameDirectoryIdentity(parentDirectory, parentIdentity, operation, repoRootIdentity);
791
+ if (error?.code === "ENOENT") return null;
792
+ throw error;
793
+ }
794
+ }
34
795
 
35
796
  const codexDir = path.join(repoRoot, ".codex");
36
797
  const codexAgentsDir = path.join(codexDir, "agents");
@@ -249,7 +1010,8 @@ function buildOpenCodeConfig(existingConfig, { hasFormatHook }) {
249
1010
 
250
1011
  async function readJsonFile(filePath) {
251
1012
  try {
252
- return JSON.parse(await readFile(filePath, "utf8"));
1013
+ const content = await readConfinedRegularFile(filePath);
1014
+ return content === null ? {} : JSON.parse(content.toString("utf8"));
253
1015
  } catch (error) {
254
1016
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
255
1017
  return {};
@@ -437,13 +1199,16 @@ function buildOpenCodeAgent(agent, prompt) {
437
1199
  }
438
1200
 
439
1201
  const fileDigest = async (filePath) =>
440
- createHash("sha256").update(await readFile(filePath)).digest("hex");
1202
+ createHash("sha256")
1203
+ .update(await readFile(filePath))
1204
+ .digest("hex");
441
1205
 
442
1206
  const copyFallbackKey = ({ source, target }) => `${source}\0${target}`;
443
1207
 
444
1208
  async function ensureSymlink(linkPath, targetPath, fallbackIdentity) {
1209
+ const repoRootIdentity = repoRootIdentityForOperation("create scaffold symlink");
445
1210
  const relativeTarget = path.relative(path.dirname(linkPath), targetPath);
446
- await mkdir(path.dirname(linkPath), { recursive: true });
1211
+ await ensureConfinedDirectory(path.dirname(linkPath), repoRootIdentity);
447
1212
 
448
1213
  try {
449
1214
  const existingStat = await lstat(linkPath);
@@ -457,23 +1222,67 @@ async function ensureSymlink(linkPath, targetPath, fallbackIdentity) {
457
1222
  }
458
1223
  }
459
1224
 
460
- await rm(linkPath, { force: true, recursive: true });
1225
+ await removeConfinedPath(linkPath, { recursive: true });
1226
+ const parentDirectory = path.dirname(linkPath);
1227
+ const parentIdentity = await captureConfinedDirectoryIdentity(
1228
+ parentDirectory,
1229
+ "create scaffold symlink",
1230
+ repoRootIdentity,
1231
+ );
461
1232
  const targetStat = process.platform === "win32" ? await lstat(targetPath) : undefined;
462
1233
  const symlinkType = targetStat?.isDirectory() ? "junction" : undefined;
463
1234
 
464
1235
  try {
465
- await symlink(symlinkType === "junction" ? targetPath : relativeTarget, linkPath, symlinkType);
1236
+ await assertConfinedDirectoryComponents(
1237
+ confinedRelativePath(linkPath, "create scaffold symlink").split(path.sep).slice(0, -1),
1238
+ "create scaffold symlink",
1239
+ repoRootIdentity,
1240
+ );
1241
+ await assertSameDirectoryIdentity(
1242
+ parentDirectory,
1243
+ parentIdentity,
1244
+ "create scaffold symlink",
1245
+ repoRootIdentity,
1246
+ );
1247
+ await runStableMutation(parentDirectory, {
1248
+ linkTarget: symlinkType === "junction" ? targetPath : relativeTarget,
1249
+ operation: "symlink",
1250
+ parent: parentIdentity,
1251
+ target: path.basename(linkPath),
1252
+ ...(symlinkType === undefined ? {} : { type: symlinkType }),
1253
+ });
1254
+ await assertSameDirectoryIdentity(
1255
+ parentDirectory,
1256
+ parentIdentity,
1257
+ "create scaffold symlink",
1258
+ repoRootIdentity,
1259
+ );
466
1260
  } catch (error) {
467
1261
  if (!(error && typeof error === "object" && "code" in error && error.code === "EPERM")) {
468
1262
  throw error;
469
1263
  }
470
1264
 
471
1265
  const copyTargetStat = await lstat(targetPath);
472
- await cp(targetPath, linkPath, {
1266
+ await assertSameDirectoryIdentity(
1267
+ parentDirectory,
1268
+ parentIdentity,
1269
+ "copy scaffold fallback",
1270
+ repoRootIdentity,
1271
+ );
1272
+ await runStableMutation(parentDirectory, {
1273
+ expectedTarget: { kind: "absent" },
1274
+ operation: "copy",
1275
+ parent: parentIdentity,
473
1276
  recursive: copyTargetStat.isDirectory(),
474
- force: true,
475
- errorOnExist: false,
1277
+ source: targetPath,
1278
+ target: path.basename(linkPath),
476
1279
  });
1280
+ await assertSameDirectoryIdentity(
1281
+ parentDirectory,
1282
+ parentIdentity,
1283
+ "copy scaffold fallback",
1284
+ repoRootIdentity,
1285
+ );
477
1286
  if (fallbackIdentity !== undefined && !copyTargetStat.isDirectory()) {
478
1287
  currentCopyFallbacks.set(copyFallbackKey(fallbackIdentity), {
479
1288
  ...fallbackIdentity,
@@ -496,7 +1305,7 @@ async function pathExists(filePath) {
496
1305
  }
497
1306
 
498
1307
  async function writeManagedFiles(directory, extension, renderedByName, writeCurrent = true) {
499
- await mkdir(directory, { recursive: true });
1308
+ await ensureConfinedDirectory(directory);
500
1309
 
501
1310
  const managedNames = new Set(Object.keys(renderedByName).map((name) => `${name}.${extension}`));
502
1311
 
@@ -506,30 +1315,33 @@ async function writeManagedFiles(directory, extension, renderedByName, writeCurr
506
1315
  }
507
1316
 
508
1317
  const filePath = path.join(directory, filename);
509
- const existingContent = await readFile(filePath, "utf8");
1318
+ await assertConfinedRegularFile(filePath);
1319
+ const existingBytes = await readConfinedRegularFile(filePath);
1320
+ if (existingBytes === null) continue;
1321
+ const existingContent = existingBytes.toString("utf8");
510
1322
  const isManaged =
511
1323
  extension === "toml"
512
1324
  ? existingContent.startsWith(managedHeader)
513
1325
  : existingContent.includes(claudeManagedComment);
514
1326
 
515
1327
  if (isManaged && !managedNames.has(filename)) {
516
- await rm(filePath, { force: true });
1328
+ await removeConfinedPath(filePath);
517
1329
  }
518
1330
  }
519
1331
 
520
1332
  if (writeCurrent) {
521
1333
  for (const [name, content] of Object.entries(renderedByName)) {
522
- await writeFile(path.join(directory, `${name}.${extension}`), content, "utf8");
1334
+ await writeConfinedTextFile(path.join(directory, `${name}.${extension}`), content);
523
1335
  }
524
1336
  }
525
1337
  }
526
1338
 
527
1339
  async function syncHookSurface() {
528
- await mkdir(sharedHooksPath, { recursive: true });
529
- await mkdir(codexHooksDir, { recursive: true });
530
- await mkdir(claudeHooksDir, { recursive: true });
531
- await mkdir(cursorHooksDir, { recursive: true });
532
- await mkdir(opencodePluginsDir, { recursive: true });
1340
+ await ensureConfinedDirectory(sharedHooksPath);
1341
+ await ensureConfinedDirectory(codexHooksDir);
1342
+ await ensureConfinedDirectory(claudeHooksDir);
1343
+ await ensureConfinedDirectory(cursorHooksDir);
1344
+ await ensureConfinedDirectory(opencodePluginsDir);
533
1345
 
534
1346
  for (const hookName of ["format-edited-file.mjs", "scaffold-update-check.mjs"]) {
535
1347
  const sourcePath = path.join(sharedHooksPath, hookName);
@@ -546,7 +1358,7 @@ async function syncHookSurface() {
546
1358
  }
547
1359
  } else {
548
1360
  for (const targetPath of targetPaths) {
549
- await rm(targetPath, { force: true, recursive: true });
1361
+ await removeConfinedPath(targetPath, { recursive: true });
550
1362
  }
551
1363
  }
552
1364
  }
@@ -726,36 +1538,32 @@ async function assertRealPathContainment(action, actionPaths) {
726
1538
 
727
1539
  async function writeAdapterConfig(adapterId, availableHooks) {
728
1540
  if (adapterId === "codex") {
729
- await mkdir(path.dirname(codexConfigPath), { recursive: true });
730
- await writeFile(codexConfigPath, buildCodexAgentConfig(availableHooks), "utf8");
731
- await rm(path.join(codexDir, "hooks.json"), { force: true });
1541
+ await writeConfinedTextFile(codexConfigPath, buildCodexAgentConfig(availableHooks));
1542
+ await removeConfinedPath(path.join(codexDir, "hooks.json"));
732
1543
  return;
733
1544
  }
734
1545
  if (adapterId === "claude") {
735
- await mkdir(path.dirname(claudeSettingsPath), { recursive: true });
736
- await writeFile(
1546
+ await assertConfinedRegularFile(claudeSettingsPath);
1547
+ await writeConfinedTextFile(
737
1548
  claudeSettingsPath,
738
1549
  encodeJson(buildClaudeSettingsConfig(await readJsonFile(claudeSettingsPath), availableHooks)),
739
- "utf8",
740
1550
  );
741
1551
  return;
742
1552
  }
743
1553
  if (adapterId === "cursor") {
744
- await mkdir(path.dirname(cursorHooksJsonPath), { recursive: true });
745
- await writeFile(
1554
+ await writeConfinedTextFile(
746
1555
  cursorHooksJsonPath,
747
1556
  encodeJson(buildCursorHooksConfig(availableHooks)),
748
- "utf8",
749
1557
  );
750
1558
  return;
751
1559
  }
752
1560
  if (adapterId === "opencode") {
753
- await writeFile(
1561
+ await assertConfinedRegularFile(opencodeConfigPath);
1562
+ await writeConfinedTextFile(
754
1563
  opencodeConfigPath,
755
1564
  encodeOpenCodeConfig(
756
1565
  buildOpenCodeConfig(await readJsonFile(opencodeConfigPath), availableHooks),
757
1566
  ),
758
- "utf8",
759
1567
  );
760
1568
  }
761
1569
  }
@@ -773,7 +1581,7 @@ async function reconcileLifecycleHooks(action, adapterId, actionPaths) {
773
1581
  for (const [index, managedHookFile] of action.managedHookFiles.entries()) {
774
1582
  const hookId = path.basename(managedHookFile, ".mjs");
775
1583
  if (!activeHookIds.has(hookId)) {
776
- await rm(actionPaths[`managedHookFiles[${index}]`], { force: true, recursive: true });
1584
+ await removeConfinedPath(actionPaths[`managedHookFiles[${index}]`], { recursive: true });
777
1585
  }
778
1586
  }
779
1587
  const projectedHooks = {
@@ -870,8 +1678,7 @@ async function applyHarnessAction(action, application) {
870
1678
  throw new Error(`Missing ${adapterId} render input for ${name ?? "unknown template"}`);
871
1679
  }
872
1680
  const targetPath = resolveActionPath(target, "target");
873
- await mkdir(path.dirname(targetPath), { recursive: true });
874
- await writeFile(targetPath, content, "utf8");
1681
+ await writeConfinedTextFile(targetPath, content);
875
1682
  return;
876
1683
  }
877
1684
 
@@ -1575,8 +2382,11 @@ const contextPlanVersion = (contextPlan) =>
1575
2382
  : "unknown";
1576
2383
 
1577
2384
  async function main() {
2385
+ operationRepoRootIdentity = await captureRepoRootIdentity("synchronize scaffold output");
2386
+ await assertConfinedRegularFile(projectionReceiptPath);
2387
+ const previousReceiptBytes = await readConfinedRegularFile(projectionReceiptPath);
1578
2388
  try {
1579
- const previousReceipt = JSON.parse(await readFile(projectionReceiptPath, "utf8"));
2389
+ const previousReceipt = JSON.parse(previousReceiptBytes?.toString("utf8") ?? "null");
1580
2390
  previousCopyFallbacks = Array.isArray(previousReceipt.copyFallbacks)
1581
2391
  ? previousReceipt.copyFallbacks.filter(
1582
2392
  (copy) =>
@@ -1653,8 +2463,7 @@ async function main() {
1653
2463
  copyFallbackKey(left).localeCompare(copyFallbackKey(right)),
1654
2464
  ),
1655
2465
  };
1656
- await mkdir(path.dirname(projectionReceiptPath), { recursive: true });
1657
- await writeFile(projectionReceiptPath, encodeJson(receipt), "utf8");
2466
+ await writeConfinedTextFile(projectionReceiptPath, encodeJson(receipt));
1658
2467
  if (receipt.status === "failure") {
1659
2468
  throw new Error(
1660
2469
  `Harness projection failed; inspect ${path.relative(repoRoot, projectionReceiptPath)}`,
@@ -1662,4 +2471,8 @@ async function main() {
1662
2471
  }
1663
2472
  }
1664
2473
 
1665
- await main();
2474
+ try {
2475
+ await main();
2476
+ } finally {
2477
+ await closeMutationWorkers();
2478
+ }