Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/git-safe/__serial__/clone-runtime.test.ts

Raw
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
	chmodSync,
	existsSync,
	mkdirSync,
	mkdtempSync,
	readdirSync,
	readFileSync,
	rmSync,
	symlinkSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
import { createCodemodeExtension } from "@earendil-works/pi-coding-agent";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import { canonicalizeTarget, publishStagedClone, safeClone } from "../clone.js";
import gitSafeExtension from "../index.ts";

const fakeGit = vi.hoisted(() => ({ path: undefined as string | undefined }));
vi.mock("node:child_process", async (original) => {
	const native = await original<typeof import("node:child_process")>();
	return {
		...native,
		spawn: (...args: unknown[]) => {
			if (args[0] === "git" && fakeGit.path && Array.isArray(args[1]))
				return native.spawn(
					process.execPath,
					[fakeGit.path, ...args[1]],
					args[2] as import("node:child_process").SpawnOptions,
				);
			return Reflect.apply(native.spawn, undefined, args);
		},
	};
});

const limits = {
	sizeLimitBytes: 10_000,
	fileCountLimit: 100,
	cloneTimeoutMs: 10_000,
};
const originalPath = process.env["PATH"];

async function waitForFile(file: string): Promise<void> {
	for (let attempt = 0; attempt < 100; attempt++) {
		if (existsSync(file)) return;
		await new Promise((resolve) => setTimeout(resolve, 10));
	}
	throw new Error(`timed out waiting for ${file}`);
}

function fixture(
	delayMs = 0,
	descendant = false,
	options: {
		holdSecond?: boolean;
		metadataFailure?: boolean;
		malformedTree?: boolean;
	} = {},
): {
	root: string;
	bin: string;
	calls: string;
	started: string;
	childStarted: string;
	heartbeat: string;
	secondStarted: string;
	releaseSecond: string;
} {
	const root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-native-"));
	const bin = path.join(root, "bin");
	mkdirSync(bin);
	const calls = path.join(root, "calls");
	const started = path.join(root, "clone-started");
	const childStarted = path.join(root, "clone-child-started");
	const heartbeat = path.join(root, "clone-child-heartbeat");
	const secondStarted = path.join(root, "second-started");
	const releaseSecond = path.join(root, "release-second");
	const script = `#!/usr/bin/env node
const fs = require('node:fs');
const path = require('node:path');
const args = process.argv.slice(2);
const command = args.at(-1) === 'checkout' ? 'checkout' : args[0];
fs.appendFileSync(${JSON.stringify(calls)}, command + '\\n');
if (command === 'clone') {
  const target = args.at(-1);
  fs.mkdirSync(path.join(target, '.git', 'info'), { recursive: true });
  fs.mkdirSync(path.join(target, '.git', 'hooks'), { recursive: true });
  const count = fs.existsSync(${JSON.stringify(started)}) ? Number(fs.readFileSync(${JSON.stringify(started)}, 'utf8')) + 1 : 1;
  fs.writeFileSync(${JSON.stringify(started)}, String(count));
  ${options.holdSecond ? `if (count === 2) { fs.writeFileSync(${JSON.stringify(secondStarted)}, 'started'); while (!fs.existsSync(${JSON.stringify(releaseSecond)})) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); }` : ""}
  ${descendant ? `require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(`const fs = require('node:fs'); process.on('SIGTERM', () => {}); fs.writeFileSync(${JSON.stringify(childStarted)}, 'started'); setInterval(() => { try { fs.appendFileSync(${JSON.stringify(heartbeat)}, 'x'); } catch { process.exit(0); } }, 25);`)}], { stdio: 'ignore' }).unref();` : ""}
  ${delayMs ? `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${delayMs});` : ""}
} else if (command === 'config') {
  fs.appendFileSync(path.join(process.cwd(), '.git', 'config'), '\\n' + args.slice(1).join(' '));
} else if (command === 'ls-tree') {
  ${options.metadataFailure ? "process.stderr.write('cannot inspect tree'); process.exit(128);" : options.malformedTree ? "process.stdout.write('not tree metadata\\n');" : "process.stdout.write('100644 blob deadbeef 4\\tREADME.md\\n');"}
} else if (command === 'status') {
  process.stdout.write('# branch.oid deadbeef\\n');
} else if (command === 'checkout') {
  fs.writeFileSync(path.join(process.cwd(), 'README.md'), 'safe fixture');
}
`;
	const executable = path.join(bin, "git.cjs");
	fakeGit.path = executable;
	writeFileSync(executable, script);
	chmodSync(executable, 0o755);
	return {
		root,
		bin,
		calls,
		started,
		childStarted,
		heartbeat,
		secondStarted,
		releaseSecond,
	};
}

describe("git-safe clone runtime", () => {
	let session: PiSession | undefined;
	let root: string | undefined;
	afterEach(async () => {
		await session?.dispose();
		if (root) rmSync(root, { recursive: true, force: true });
		session = undefined;
		root = undefined;
		fakeGit.path = undefined;
		if (originalPath === undefined) delete process.env["PATH"];
		else process.env["PATH"] = originalPath;
	});

	it("lists clone guidance in the codemode description", async () => {
		const fake = fixture();
		root = fake.root;
		session = await createPiSession({
			cwd: fake.root,
			extensionFactories: [gitSafeExtension, createCodemodeExtension()],
			userSettings: { defaultTools: ["+codemode"] },
		});
		let description = "";
		session.setResponses([
			(context) => {
				description =
					context.messages
						.filter((message) => message.role === "system")
						.flatMap((message) => message.toolsAdded ?? [])
						.findLast((tool) => tool.name === "codemode")?.description ?? "";
				return fauxAssistantMessage("done");
			},
		]);
		await session.session.prompt("Inspect an unfamiliar repository.");
		expect(session.errors).toEqual([]);
		expect(description).toContain("git_clone_safe");
		expect(description).toContain(
			"Use git_clone_safe instead of raw git clone.",
		);
	});

	it("returns structured clone data through real SDK codemode", async () => {
		const fake = fixture();
		root = fake.root;
		process.env["PATH"] = `${fake.bin}:${originalPath ?? ""}`;
		session = await createPiSession({
			cwd: fake.root,
			extensionFactories: [gitSafeExtension, createCodemodeExtension()],
			userSettings: { defaultTools: ["+codemode"] },
			env: { PATH: `${fake.bin}:${process.env["PATH"] ?? ""}` },
			responses: [
				fauxAssistantMessage(
					fauxToolCall(
						"codemode",
						{
							code: `return await tools.git_clone_safe({url:"https://example.invalid/o/r.git",path:"repos/o/r"})`,
						},
						{ id: "clone-call" },
					),
					{ stopReason: "toolUse" },
				),
				fauxAssistantMessage("done"),
			],
		});
		let codemodeResult: unknown;
		const unsubscribe = session.session.subscribe((event) => {
			if (event.type === "tool_execution_end" && event.toolName === "codemode")
				codemodeResult = event.result;
		});
		await session.session.prompt("Clone fixture repo using codemode");
		unsubscribe();
		expect(session.errors).toEqual([]);
		expect(JSON.stringify(codemodeResult)).toContain('\\"fileCount\\":1');
		expect(existsSync(path.join(fake.root, "repos/o/r/.pi-git-safe"))).toBe(
			true,
		);
	});

	it("aborts native git and preserves caller reason without leaving partial target", async () => {
		const fake = fixture(2_000, true);
		root = fake.root;
		process.env["PATH"] = `${fake.bin}:${process.env["PATH"] ?? ""}`;
		const controller = new AbortController();
		const reason = new Error("caller cancelled clone");
		const target = path.join(fake.root, "repos/o/r");
		const cloning = safeClone("https://example.invalid/o/r.git", target, {
			cwd: fake.root,
			limits,
			signal: controller.signal,
		});
		await waitForFile(fake.started);
		await waitForFile(fake.childStarted);
		controller.abort(reason);
		await expect(cloning).rejects.toBe(reason);
		expect(existsSync(target)).toBe(false);
		await new Promise((resolve) => setTimeout(resolve, 100));
		const heartbeat = existsSync(fake.heartbeat)
			? readFileSync(fake.heartbeat, "utf8")
			: "";
		await new Promise((resolve) => setTimeout(resolve, 300));
		expect(
			existsSync(fake.heartbeat) ? readFileSync(fake.heartbeat, "utf8") : "",
		).toBe(heartbeat);
	});

	it("preserves pre-existing unmarked target", async () => {
		const fake = fixture();
		root = fake.root;
		const target = path.join(fake.root, "repos/o/r");
		mkdirSync(target, { recursive: true });
		const sentinel = path.join(target, "keep.txt");
		writeFileSync(sentinel, "user data");
		await expect(
			safeClone("https://example.invalid/o/r.git", target, {
				cwd: fake.root,
				limits,
			}),
		).rejects.toThrow(/target directory already exists/);
		expect(existsSync(sentinel)).toBe(true);
	});

	it("does not remove a successful clone when queued sibling is aborted", async () => {
		const fake = fixture(250);
		root = fake.root;
		process.env["PATH"] = `${fake.bin}:${process.env["PATH"] ?? ""}`;
		const target = "repos/o/r";
		const first = safeClone("https://example.invalid/o/r.git", target, {
			cwd: fake.root,
			limits,
		});
		const controller = new AbortController();
		const reason = new Error("cancel queued replacement");
		const sibling = safeClone("https://example.invalid/o/r.git", target, {
			cwd: fake.root,
			limits,
			signal: controller.signal,
		});
		setTimeout(() => controller.abort(reason), 75);
		const successful = await first;
		await expect(sibling).rejects.toBe(reason);
		expect(existsSync(path.join(successful.path, ".pi-git-safe"))).toBe(true);
	});

	it("preserves prior marked clone when final publish rename fails", async () => {
		const fake = fixture();
		root = fake.root;
		const target = path.join(fake.root, "repos/o/r");
		const staged = path.join(fake.root, "repos/o/staged");
		mkdirSync(target, { recursive: true });
		writeFileSync(path.join(target, ".pi-git-safe"), "old clone");
		writeFileSync(path.join(target, "old.txt"), "preserve me");
		mkdirSync(staged, { recursive: true });
		writeFileSync(path.join(staged, ".pi-git-safe"), "new clone");
		await expect(
			publishStagedClone(staged, target, async (from, to) => {
				if (from === staged && to === target)
					throw new Error("injected final rename failure");
				const { rename } = await import("node:fs/promises");
				await rename(from, to);
			}),
		).rejects.toThrow("injected final rename failure");
		expect(readFileSync(path.join(target, "old.txt"), "utf8")).toBe(
			"preserve me",
		);
		expect(existsSync(staged)).toBe(false);
		expect(
			readdirSync(path.dirname(target)).some((name) =>
				name.includes(".pi-git-safe-backup-"),
			),
		).toBe(false);
	});

	it("keeps root-adjacent target canonicalization intact", () => {
		const rootPath = path.parse(process.cwd()).root;
		const target = path.join(rootPath, `pi-git-safe-${randomUUID()}`);
		expect(canonicalizeTarget(target)).toBe(target);
	});

	it("rejects active parent and child targets", async () => {
		const fake = fixture(250);
		root = fake.root;
		process.env["PATH"] = `${fake.bin}:${process.env["PATH"] ?? ""}`;
		const child = safeClone("https://example.invalid/o/r.git", "repos/o/r", {
			cwd: fake.root,
			limits,
		});
		await waitForFile(fake.started);
		await expect(
			safeClone("https://example.invalid/o/r.git", "repos/o", {
				cwd: fake.root,
				limits,
			}),
		).rejects.toThrow(/overlaps active clone/);
		await child;
	});

	it("keeps overlap protection while a queued same-target replacement is active", async () => {
		const fake = fixture(0, false, { holdSecond: true });
		root = fake.root;
		const opts = { cwd: fake.root, limits };
		const first = safeClone(
			"https://example.invalid/o/r.git",
			"repos/o/r",
			opts,
		);
		const second = safeClone(
			"https://example.invalid/o/r.git",
			"repos/o/r",
			opts,
		);
		try {
			await first;
			await waitForFile(fake.secondStarted);
			await expect(
				safeClone("https://example.invalid/o/parent.git", "repos/o", opts),
			).rejects.toThrow(/overlaps active clone/);
		} finally {
			writeFileSync(fake.releaseSecond, "release");
			await Promise.allSettled([first, second]);
		}
	});

	it("refuses checkout when tree inspection fails on a nonempty repository", async () => {
		const fake = fixture(0, false, { metadataFailure: true });
		root = fake.root;
		await expect(
			safeClone("https://example.invalid/o/r.git", "repos/o/r", {
				cwd: fake.root,
				limits,
			}),
		).rejects.toThrow(/inspect repository tree/);
		expect(readFileSync(fake.calls, "utf8")).not.toContain("checkout");
		expect(readdirSync(path.join(fake.root, "repos/o"))).toEqual([]);
	});

	it("refuses malformed tree metadata without checking out files", async () => {
		const fake = fixture(0, false, { malformedTree: true });
		root = fake.root;
		await expect(
			safeClone("https://example.invalid/o/r.git", "repos/o/r", {
				cwd: fake.root,
				limits,
			}),
		).rejects.toThrow(/inspect repository tree/);
		expect(readFileSync(fake.calls, "utf8")).not.toContain("checkout");
		expect(readdirSync(path.join(fake.root, "repos/o"))).toEqual([]);
	});

	it("clones a real unborn repository without requiring checkout", async () => {
		root = mkdtempSync(path.join(tmpdir(), "pi-git-safe-empty-"));
		const upstream = path.join(root, "upstream.git");
		execFileSync("git", ["init", "--bare", "--initial-branch=main", upstream], {
			stdio: "ignore",
		});
		const result = await safeClone(upstream, "repos/o/r", {
			cwd: root,
			limits,
		});
		expect(result.fileCount).toBe(0);
		expect(
			execFileSync("git", ["status", "--porcelain=v2", "--branch"], {
				cwd: result.path,
				encoding: "utf8",
			}),
		).toContain("# branch.oid (initial)");
		expect(existsSync(path.join(result.path, ".pi-git-safe"))).toBe(true);
	});

	it("serializes concurrent clones targeting one canonical directory", async () => {
		const fake = fixture(50);
		root = fake.root;
		process.env["PATH"] = `${fake.bin}:${process.env["PATH"] ?? ""}`;
		mkdirSync(path.join(fake.root, "repos/o"), { recursive: true });
		symlinkSync(
			path.join(fake.root, "repos/o"),
			path.join(fake.root, "alias"),
			process.platform === "win32" ? "junction" : "dir",
		);
		const first = safeClone("https://example.invalid/o/r.git", "repos/o/r", {
			cwd: fake.root,
			limits,
		});
		const alias = safeClone(
			"https://example.invalid/o/r.git",
			path.join(fake.root, "alias", "r"),
			{ cwd: fake.root, limits },
		);
		const results = await Promise.all([first, alias]);
		expect(results.map((result) => result.path)).toEqual([
			results[0]!.path,
			results[0]!.path,
		]);
		expect(existsSync(path.join(results[1]!.path, ".pi-git-safe"))).toBe(true);
	});
});