File size: 27,074 Bytes
98077a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { access, chmod, realpath, symlink } from "node:fs/promises";
import { homedir } from "node:os";
import { delimiter, join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts";
import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
import { FileError, getOrThrow, type ShellExecOptions, type ShellOutputView } from "../../src/harness/types.ts";
import { applyShellOutputUpdate } from "../../src/harness/utils/output-capture.ts";
import { executeShellWithCapture } from "../../src/harness/utils/shell-output.ts";
import { createTempDir } from "./session-test-utils.ts";

const chmodRestorePaths: string[] = [];

function withTimeout<T>(promise: Promise<T>, ms: number, onTimeout?: () => void): Promise<T> {
	return new Promise<T>((resolve, reject) => {
		const timeoutId = setTimeout(() => {
			onTimeout?.();
			reject(new Error(`Timed out after ${ms}ms`));
		}, ms);
		promise.then(
			(value) => {
				clearTimeout(timeoutId);
				resolve(value);
			},
			(error: unknown) => {
				clearTimeout(timeoutId);
				reject(error);
			},
		);
	});
}

async function collectShellOutput(
	env: NodeExecutionEnv,
	command: string,
	options: ShellExecOptions | undefined,
	context: Parameters<NodeExecutionEnv["exec"]>[2],
): Promise<{ result: Awaited<ReturnType<NodeExecutionEnv["exec"]>>; output: ShellOutputView | undefined }> {
	let output: ShellOutputView | undefined;
	const result = await env.exec(
		command,
		{
			...options,
			onUpdate: (update) => {
				output = applyShellOutputUpdate(output, update);
			},
		},
		context,
	);
	return { result, output };
}

function toBashSingleQuotedArg(value: string): string {
	return `'${value.replace(/\\/g, "/").replace(/'/g, `'"'"'`)}'`;
}

function createInheritedStdioCommand(pidFile: string): string {
	return (
		'node -e "' +
		"const fs=require('fs');" +
		"const {spawn}=require('child_process');" +
		"const child=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'inherit',detached:true});" +
		"fs.writeFileSync(process.argv[1], String(child.pid));" +
		"child.unref();" +
		"console.log('child-exiting');" +
		'" ' +
		toBashSingleQuotedArg(pidFile)
	);
}

function cleanupDetachedChild(pidFile: string): void {
	if (!existsSync(pidFile)) return;
	const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);
	if (!Number.isFinite(pid) || pid <= 0) return;
	try {
		execFileSync("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore" });
	} catch {}
}

class FailingSpillExecutionEnv extends NodeExecutionEnv {
	override async createTempFile(
		options: Parameters<NodeExecutionEnv["createTempFile"]>[0],
		context: Parameters<NodeExecutionEnv["createTempFile"]>[1],
	) {
		if (options?.prefix === "pi-output-") {
			return { ok: true as const, value: join(this.cwd, "missing", "spill.log") };
		}
		return super.createTempFile(options, context);
	}
}

afterEach(async () => {
	for (const path of chmodRestorePaths.splice(0)) {
		try {
			await access(path);
			await chmod(path, 0o700);
		} catch {}
	}
});

describe("NodeExecutionEnv", () => {
	it("reads, writes, lists, and removes files and directories", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		expect(getOrThrow(await env.absolutePath("nested/child", BACKGROUND_CONTEXT))).toBe(join(root, "nested/child"));
		expect(getOrThrow(await env.joinPath([root, "nested", "child"], BACKGROUND_CONTEXT))).toBe(
			join(root, "nested", "child"),
		);
		getOrThrow(await env.createDir("nested/child", undefined, BACKGROUND_CONTEXT));
		getOrThrow(await env.writeFile("nested/child/file.txt", "hel", BACKGROUND_CONTEXT));
		getOrThrow(await env.appendFile("nested/child/file.txt", "lo", BACKGROUND_CONTEXT));
		expect(getOrThrow(await env.readTextFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe("hello");
		expect(getOrThrow(await env.readTextLines("nested/child/file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual(
			["hello"],
		);
		expect(
			Buffer.from(getOrThrow(await env.readBinaryFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toString(
				"utf8",
			),
		).toBe("hello");

		const entries = getOrThrow(await env.listDir("nested/child", BACKGROUND_CONTEXT));
		expect(entries).toHaveLength(1);
		expect(entries[0]).toMatchObject({
			name: "file.txt",
			path: join(root, "nested/child/file.txt"),
			kind: "file",
			size: 5,
		});
		expect(typeof entries[0]!.mtimeMs).toBe("number");

		expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(true);
		getOrThrow(await env.remove("nested/child/file.txt", undefined, BACKGROUND_CONTEXT));
		expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(false);
	});

	it("expands home-relative paths and file URLs", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		expect(getOrThrow(await env.absolutePath("~/pi-node-env-test", BACKGROUND_CONTEXT))).toBe(
			join(homedir(), "pi-node-env-test"),
		);
		const filePath = join(root, "file with spaces.txt");
		expect(getOrThrow(await env.absolutePath(pathToFileURL(filePath).href, BACKGROUND_CONTEXT))).toBe(filePath);
	});

	it("returns fileInfo for files, directories, and symlinks without following symlinks", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.createDir("dir", { recursive: true }, BACKGROUND_CONTEXT));
		getOrThrow(await env.writeFile("dir/file.txt", "hello", BACKGROUND_CONTEXT));
		await symlink(join(root, "dir/file.txt"), join(root, "file-link"));
		await symlink(join(root, "dir"), join(root, "dir-link"));

		expect(getOrThrow(await env.fileInfo("dir", BACKGROUND_CONTEXT))).toMatchObject({
			name: "dir",
			path: join(root, "dir"),
			kind: "directory",
		});
		expect(getOrThrow(await env.fileInfo("dir/file.txt", BACKGROUND_CONTEXT))).toMatchObject({
			name: "file.txt",
			path: join(root, "dir/file.txt"),
			kind: "file",
			size: 5,
		});
		expect(getOrThrow(await env.fileInfo("file-link", BACKGROUND_CONTEXT))).toMatchObject({
			name: "file-link",
			path: join(root, "file-link"),
			kind: "symlink",
		});
		expect(getOrThrow(await env.fileInfo("dir-link", BACKGROUND_CONTEXT))).toMatchObject({
			name: "dir-link",
			path: join(root, "dir-link"),
			kind: "symlink",
		});
		expect(getOrThrow(await env.canonicalPath("file-link", BACKGROUND_CONTEXT))).toBe(
			await realpath(join(root, "dir/file.txt")),
		);
	});

	it("lists symlinks as symlinks", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("target.txt", "hello", BACKGROUND_CONTEXT));
		await symlink(join(root, "target.txt"), join(root, "link.txt"));

		const entries = getOrThrow(await env.listDir(".", BACKGROUND_CONTEXT));
		expect(
			entries.map((entry) => ({ name: entry.name, kind: entry.kind })).sort((a, b) => a.name.localeCompare(b.name)),
		).toEqual([
			{ name: "link.txt", kind: "symlink" },
			{ name: "target.txt", kind: "file" },
		]);
	});

	it("stops reading text lines at the requested limit", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("file.txt", "one\ntwo\nthree", BACKGROUND_CONTEXT));
		expect(getOrThrow(await env.readTextLines("file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual(["one"]);
	});

	it("returns FileError for missing paths and keeps exists false for missing paths", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const info = await env.fileInfo("missing.txt", BACKGROUND_CONTEXT);
		expect(info.ok).toBe(false);
		if (!info.ok) {
			expect(info.error).toBeInstanceOf(FileError);
			expect(info.error).toMatchObject({
				name: "FileError",
				code: "not_found",
				path: join(root, "missing.txt"),
			});
		}
		expect(getOrThrow(await env.exists("missing.txt", BACKGROUND_CONTEXT))).toBe(false);
	});

	it("returns FileError for listing non-directories", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT));
		const result = await env.listDir("file.txt", BACKGROUND_CONTEXT);
		expect(result.ok).toBe(false);
		if (!result.ok) {
			expect(result.error).toBeInstanceOf(FileError);
			expect(result.error).toMatchObject({ code: "not_directory" });
		}
	});

	it("appends to new files and creates parent directories", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.appendFile("new/nested/file.txt", "a", BACKGROUND_CONTEXT));
		getOrThrow(await env.appendFile("new/nested/file.txt", "b", BACKGROUND_CONTEXT));
		expect(getOrThrow(await env.readTextFile("new/nested/file.txt", BACKGROUND_CONTEXT))).toBe("ab");
	});

	it("atomically renames a file and replaces the destination", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("source.txt", "new", BACKGROUND_CONTEXT));
		getOrThrow(await env.writeFile("destination.txt", "old", BACKGROUND_CONTEXT));

		getOrThrow(await env.renameFile("source.txt", "destination.txt", BACKGROUND_CONTEXT));

		expect(getOrThrow(await env.exists("source.txt", BACKGROUND_CONTEXT))).toBe(false);
		expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("new");
	});

	it("reports the source path when rename fails because the source is missing", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("destination.txt", "unchanged", BACKGROUND_CONTEXT));

		const result = await env.renameFile("missing-source.txt", "destination.txt", BACKGROUND_CONTEXT);

		expect(result).toMatchObject({
			ok: false,
			error: {
				code: "not_found",
				path: join(root, "missing-source.txt"),
			},
		});
		expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("unchanged");
	});

	it("creates temporary directories and files", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const tempDir = getOrThrow(await env.createTempDir("node-env-test-", BACKGROUND_CONTEXT));
		await expect(access(tempDir)).resolves.toBeUndefined();
		const tempFile = getOrThrow(await env.createTempFile({ prefix: "prefix-", suffix: ".txt" }, BACKGROUND_CONTEXT));
		await expect(access(tempFile)).resolves.toBeUndefined();
		expect(tempFile.endsWith(".txt")).toBe(true);
	});

	it("honors createDir recursive false and remove recursive/force options", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const createResult = await env.createDir("missing/child", { recursive: false }, BACKGROUND_CONTEXT);
		expect(createResult.ok).toBe(false);
		if (!createResult.ok) expect(createResult.error).toMatchObject({ code: "not_found" });

		getOrThrow(await env.writeFile("dir/child/file.txt", "hello", BACKGROUND_CONTEXT));
		const removeDirectory = await env.remove("dir", { recursive: false }, BACKGROUND_CONTEXT);
		expect(removeDirectory.ok).toBe(false);
		getOrThrow(await env.remove("dir", { recursive: true }, BACKGROUND_CONTEXT));
		expect(getOrThrow(await env.exists("dir", BACKGROUND_CONTEXT))).toBe(false);

		const removeMissing = await env.remove("missing", { force: false }, BACKGROUND_CONTEXT);
		expect(removeMissing.ok).toBe(false);
		getOrThrow(await env.remove("missing", { force: true }, BACKGROUND_CONTEXT));
	});

	it("returns aborted results for pre-aborted cancellable file operations", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT));
		const controller = new AbortController();
		controller.abort();
		const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT);

		const results = await Promise.all([
			env.readTextFile("file.txt", context),
			env.readTextLines("file.txt", undefined, context),
			env.readBinaryFile("file.txt", context),
			env.writeFile("other.txt", "hello", context),
			env.renameFile("file.txt", "renamed.txt", context),
			env.listDir(".", context),
		]);
		for (const result of results) {
			expect(result.ok).toBe(false);
			if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
		}
	});

	it("cleanup is best-effort", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		await expect(env.cleanup(BACKGROUND_CONTEXT)).resolves.toBeUndefined();
	});

	it("executes commands in cwd with env overrides", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const collected = await collectShellOutput(
			env,
			'printf \'%s:%s\' "$PWD" "$NODE_ENV_TEST"',
			{ env: { NODE_ENV_TEST: "ok" } },
			BACKGROUND_CONTEXT,
		);
		const result = getOrThrow(collected.result);
		expect(collected.output?.text).toBe(`${await realpath(root)}:ok`);
		expect(result.exitCode).toBe(0);
	});

	it.each([
		["a missing override preserves the base value", undefined, "x:/stale/parent.jsonl"],
		["an empty override shadows the base value", { PI_SESSION_FILE: "" }, "x:"],
		[
			"a string override replaces the base value",
			{ PI_SESSION_FILE: "/sessions/current.jsonl" },
			"x:/sessions/current.jsonl",
		],
	] as const)(
		"applies string shell environment overrides when %s",
		async (_description, overrides, expectedSessionFile) => {
			const root = createTempDir();
			const env = new NodeExecutionEnv({
				cwd: root,
				shellEnv: {
					PI_SESSION_FILE: "/stale/parent.jsonl",
					PI_CODING_AGENT: "true",
					PI_NODE_ENV_PRESERVED_TEST: "preserved",
				},
			});
			const collected = await collectShellOutput(
				env,
				`printf '%s:%s|%s|%s' "\${PI_SESSION_FILE+x}" "\${PI_SESSION_FILE-}" "$PI_CODING_AGENT" "$PI_NODE_ENV_PRESERVED_TEST"`,
				{ env: overrides },
				BACKGROUND_CONTEXT,
			);
			getOrThrow(collected.result);
			expect(collected.output?.text).toBe(`${expectedSessionFile}|true|preserved`);
		},
	);

	it("can replace rather than inherit the default shell environment", async () => {
		const root = createTempDir();
		const inheritedKey = "PI_NODE_ENV_INHERITED_TEST";
		const configuredKey = "PI_NODE_ENV_CONFIGURED_TEST";
		const explicitKey = "PI_NODE_ENV_EXPLICIT_TEST";
		const previousInherited = process.env[inheritedKey];
		process.env[inheritedKey] = "host";
		try {
			const env = new NodeExecutionEnv({ cwd: root, shellEnv: { [configuredKey]: "configured" } });
			const collected = await collectShellOutput(
				env,
				`printf '%s:%s:%s' "\${${inheritedKey}-}" "\${${configuredKey}-}" "\${${explicitKey}-}"`,
				{ inheritEnv: false, env: { [explicitKey]: "explicit" } },
				BACKGROUND_CONTEXT,
			);
			getOrThrow(collected.result);
			expect(collected.output?.text).toBe("::explicit");
		} finally {
			if (previousInherited === undefined) delete process.env[inheritedKey];
			else process.env[inheritedKey] = previousInherited;
		}
	});

	it("uses stdin command transport for legacy WSL bash paths", async () => {
		if (process.platform === "win32") return;
		const root = createTempDir();
		const shellPath = "C:\\Windows\\System32\\bash.exe";
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(
			await env.writeFile(
				shellPath,
				'#!/bin/sh\nprintf \'args:%s\\n\' "$*" >&2\nexec /bin/bash "$@"\n',
				BACKGROUND_CONTEXT,
			),
		);
		await chmod(join(root, shellPath), 0o755);

		const originalCwd = process.cwd();
		const originalPath = process.env.PATH;
		const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
		try {
			process.chdir(root);
			process.env.PATH = `${root}${delimiter}${originalPath ?? ""}`;
			Object.defineProperty(process, "platform", {
				configurable: true,
				value: "win32",
			});

			const wslEnv = new NodeExecutionEnv({ cwd: root, shellPath });
			const nameExpansion = "$" + "{name}";
			const collected = await collectShellOutput(
				wslEnv,
				`name='World'; echo "Hello, ${nameExpansion}!"`,
				undefined,
				BACKGROUND_CONTEXT,
			);
			const result = getOrThrow(collected.result);
			expect(collected.output?.text).toContain("Hello, World!");
			expect(collected.output?.text).toContain("args:-s");
			expect(result.exitCode).toBe(0);
		} finally {
			process.chdir(originalCwd);
			process.env.PATH = originalPath;
			if (platformDescriptor) {
				Object.defineProperty(process, "platform", platformDescriptor);
			}
		}
	});

	it.skipIf(process.platform !== "win32")(
		"settles after the shell exits when a detached descendant retains inherited stdio",
		async () => {
			const root = createTempDir();
			const pidFile = join(root, "grandchild.pid");
			const env = new NodeExecutionEnv({ cwd: root });
			const controller = new AbortController();
			try {
				const collected = await withTimeout(
					collectShellOutput(
						env,
						createInheritedStdioCommand(pidFile),
						undefined,
						withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
					),
					3000,
					() => controller.abort(),
				);
				getOrThrow(collected.result);
				expect(collected.output?.text).toContain("child-exiting");
			} finally {
				controller.abort();
				cleanupDetachedChild(pidFile);
			}
		},
	);

	it("cleanup terminates active shell processes", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const execution = env.exec("touch started; sleep 60", undefined, BACKGROUND_CONTEXT);
		for (let attempt = 0; attempt < 100 && !getOrThrow(await env.exists("started", BACKGROUND_CONTEXT)); attempt++) {
			await new Promise((resolve) => setTimeout(resolve, 10));
		}
		expect(getOrThrow(await env.exists("started", BACKGROUND_CONTEXT))).toBe(true);
		await env.cleanup(BACKGROUND_CONTEXT);
		await expect(withTimeout(execution, 3000)).resolves.toMatchObject({ ok: true });
	});

	it("combines stdout and stderr into one bounded view", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const updates: string[] = [];
		let output: ShellOutputView | undefined;
		const result = getOrThrow(
			await env.exec(
				"printf out; printf err >&2",
				{
					onUpdate: (update) => {
						updates.push(update.kind);
						output = applyShellOutputUpdate(output, update);
					},
				},
				BACKGROUND_CONTEXT,
			),
		);
		expect(result.exitCode).toBe(0);
		expect(output?.text).toContain("out");
		expect(output?.text).toContain("err");
		expect(updates[0]).toBe("replace");
	});

	it("reports a missing working directory before spawning", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: join(root, "missing") });
		const result = await env.exec("printf ok", undefined, BACKGROUND_CONTEXT);

		expect(result).toMatchObject({
			ok: false,
			error: { code: "spawn_error", message: expect.stringContaining("Working directory does not exist") },
		});
	});

	it("returns non-zero command exit codes as successful execution results", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = getOrThrow(await env.exec("exit 7", undefined, BACKGROUND_CONTEXT));
		expect(result.exitCode).toBe(7);
		expect(result.truncation.totalBytes).toBe(0);
	});

	// Regression test for https://github.com/earendil-works/pi/issues/8992
	it.skipIf(process.platform === "win32")("maps signal-killed processes to a non-zero exit code", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = getOrThrow(await env.exec("kill -9 $$", undefined, BACKGROUND_CONTEXT));
		expect(result.exitCode).toBe(128 + 9);
	});

	it("returns timeout errors for commands exceeding the timeout", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = await env.exec("sleep 5", { timeout: 0.01 }, BACKGROUND_CONTEXT);
		expect(result.ok).toBe(false);
		if (!result.ok) expect(result.error).toMatchObject({ code: "timeout" });
	});

	it("returns callback errors from exec stream handlers", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = await env.exec(
			"printf out",
			{
				onUpdate: () => {
					throw new Error("callback failed");
				},
			},
			BACKGROUND_CONTEXT,
		);
		expect(result.ok).toBe(false);
		if (!result.ok) expect(result.error).toMatchObject({ code: "callback_error", message: "callback failed" });
	});

	it("returns shell unavailable and spawn errors", async () => {
		const root = createTempDir();
		const missingShellEnv = new NodeExecutionEnv({ cwd: root, shellPath: join(root, "missing-shell") });
		const missingShell = await missingShellEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT);
		expect(missingShell.ok).toBe(false);
		if (!missingShell.ok) expect(missingShell.error).toMatchObject({ code: "shell_unavailable" });

		const shellPath = join(root, "not-executable-shell");
		const env = new NodeExecutionEnv({ cwd: root });
		getOrThrow(await env.writeFile(shellPath, "not executable", BACKGROUND_CONTEXT));
		const spawnErrorEnv = new NodeExecutionEnv({ cwd: root, shellPath });
		const spawnError = await spawnErrorEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT);
		expect(spawnError.ok).toBe(false);
		if (!spawnError.ok) expect(spawnError.error).toMatchObject({ code: "spawn_error" });
	});

	it("returns an aborted result for aborted commands", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const controller = new AbortController();
		const promise = env.exec("sleep 5", undefined, withAbortSignal(controller.signal, BACKGROUND_CONTEXT));
		controller.abort();
		const result = await promise;
		expect(result.ok).toBe(false);
		if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
	});

	it.skipIf(process.platform === "win32")("ignores asynchronous taskkill spawn errors during abort", async () => {
		const root = createTempDir();
		const pidFile = join(root, "shell.pid");
		const controller = new AbortController();
		const env = new NodeExecutionEnv({ cwd: root, shellPath: "/bin/bash" });
		const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
		const previousSystemRoot = process.env.SystemRoot;
		process.env.SystemRoot = "/definitely/missing/windows";
		Object.defineProperty(process, "platform", { configurable: true, value: "win32" });

		let pid: number | undefined;
		try {
			const execution = env.exec(
				`echo $$ > ${toBashSingleQuotedArg(pidFile)}; exec sleep 60`,
				undefined,
				withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
			);
			for (let attempt = 0; attempt < 100 && !existsSync(pidFile); attempt++) {
				await new Promise((resolve) => setTimeout(resolve, 10));
			}
			expect(existsSync(pidFile)).toBe(true);

			controller.abort();
			await new Promise((resolve) => setTimeout(resolve, 0));
			pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10);
			process.kill(pid, "SIGKILL");

			const result = await execution;
			expect(result).toMatchObject({ ok: false, error: { code: "aborted" } });
		} finally {
			if (pid === undefined && existsSync(pidFile)) {
				pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10);
			}
			if (pid !== undefined && Number.isFinite(pid)) {
				try {
					process.kill(pid, "SIGKILL");
				} catch {}
			}
			if (previousSystemRoot === undefined) delete process.env.SystemRoot;
			else process.env.SystemRoot = previousSystemRoot;
			if (platformDescriptor) Object.defineProperty(process, "platform", platformDescriptor);
		}
	});

	it("does not create a spill before bounded output crosses its limits", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = getOrThrow(
			await env.exec(
				"printf short",
				{
					capture: { limits: { maxBytes: 100, maxLines: 10, retain: "tail" }, spill: true },
					onUpdate: () => {},
				},
				BACKGROUND_CONTEXT,
			),
		);
		expect(result.spillPath).toBeUndefined();
	});

	it("preserves exact raw bytes in the spill while decoding a bounded text view", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const expected = [0x66, 0x80, 0x00, 0x6f];
		const result = getOrThrow(
			await env.exec(
				`${JSON.stringify(process.execPath)} -e "process.stdout.write(Buffer.from([${expected.join(",")}]))"`,
				{
					capture: { limits: { maxBytes: 1, maxLines: 10, retain: "tail" }, spill: true },
					onUpdate: () => {},
				},
				BACKGROUND_CONTEXT,
			),
		);
		expect(result.spillPath).toBeDefined();
		expect([...getOrThrow(await env.readBinaryFile(result.spillPath!, BACKGROUND_CONTEXT))]).toEqual(expected);
	});

	it("fails rather than silently losing a requested spill", async () => {
		const root = createTempDir();
		const env = new FailingSpillExecutionEnv({ cwd: root });
		const result = await env.exec(
			"printf 12345678901234567890",
			{
				capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true },
				onUpdate: () => {},
			},
			BACKGROUND_CONTEXT,
		);
		expect(result).toMatchObject({
			ok: false,
			error: { code: "unknown", message: expect.stringContaining("Failed to preserve complete shell output") },
		});
	});

	it("preserves complete output when spill-stream backpressure pauses a process that exits quickly", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const size = 500_000;
		const result = getOrThrow(
			await env.exec(
				`${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`,
				{
					capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true },
					onUpdate: () => {},
				},
				BACKGROUND_CONTEXT,
			),
		);
		expect(result.spillPath).toBeDefined();
		expect(getOrThrow(await env.readTextFile(result.spillPath!, BACKGROUND_CONTEXT))).toHaveLength(size);
	});

	it("captures large shell output to a full output file through the execution env", async () => {
		const root = createTempDir();
		const env = new NodeExecutionEnv({ cwd: root });
		const result = getOrThrow(
			await executeShellWithCapture(env, "yes line | head -n 15000", undefined, BACKGROUND_CONTEXT),
		);
		expect(result.truncated).toBe(true);
		expect(result.fullOutputPath).toBeDefined();
		const fullOutput = getOrThrow(await env.readTextFile(result.fullOutputPath!, BACKGROUND_CONTEXT));
		expect(fullOutput.split("\n").length).toBeGreaterThan(10000);
		expect(result.output.length).toBeLessThan(fullOutput.length);
	});
});