diff --git a/CHANGELOG.md b/CHANGELOG.md index da51b5384..09975abc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Copied uploads start retention at the send time on Windows too.** When a hard link cannot be used or its timestamp cannot be changed, the host writes a fresh exclusive copy instead of inheriting an old staging timestamp. Failed copies remain retryable without replacing unrelated files. - **Windows servers can manage pools of Unix workers.** Pool configuration and clone paths use the worker's path rules, not the web server's OS. Creation journals retain their synced-file, atomic-rename commit on Windows without requiring unsupported directory fsync. - **Session HTML export supports Windows OMP launchers.** Export uses the same `.cmd` and `.bat` handling as RPC sessions and version checks. +- **Git status and pool preparation work under Windows short paths.** A workspace opened through an 8.3 short name (such as `C:\Users\RUNNER~1`) or with backslashes no longer loses its Git changes, and pooled preparation no longer rejects its own clone as "not an independent repository". Repository roots are located relative to the workspace instead of comparing Git's spelling of the path with the caller's. - **Newly sent uploads survive an overlapping retention sweep.** The host refreshes the staged file's timestamp before making its hard link visible, for attachments and Files-panel uploads alike, so cleanup cannot mistake a just-sent file for an expired one. A Files-panel overwrite of an expired file can no longer be deleted by a sweep that inspected the file it replaced. - **Windows upload cleanup respects each daemon's retention policy.** Shared temporary roots now keep each daemon's attachments in its own subfolder, so a seven-day policy cannot delete another daemon's “Never” uploads, even with copied session UUIDs. Existing flat fallback files remain readable and are left untouched because their owner is unknown. - **Credential copies and config `.env` files stay private without blocking independent uploads.** The file viewer and upload preflight/overwrite deny editor swaps and backups such as `.agent.db.swp`, `agent.db~`, `.models.yml.swp` and `models.yml-backup` only directly in omp's actual agent directories (including profiles). `.env` and `.env.*` are also denied at genuine default/profile config roots and agent directories, including their symlinked real targets. Same-named session uploads, workspace files and package assets remain readable and replaceable. diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index b79ab388a..3afc351d8 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -3,7 +3,7 @@ import test from "node:test"; import { execFileSync } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, dirname, join } from "node:path"; +import { join, posix } from "node:path"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; @@ -434,7 +434,8 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold invalidateSessionLists: () => null, preparePoolProject: ({ input }) => { preparations.push({ hostId: link.id, ...input }); - return { ok: true, value: { cwd: join(dirname(input.cloneRoot), `.${basename(input.cloneRoot)}_worktrees`, "session", input.creationId), projectRoot: input.cloneRoot, baseCommit: "a".repeat(40) } }; + // A simulated POSIX worker: its paths follow POSIX rules whatever OS runs this test. + return { ok: true, value: { cwd: posix.join(posix.dirname(input.cloneRoot), `.${posix.basename(input.cloneRoot)}_worktrees`, "session", input.creationId), projectRoot: input.cloneRoot, baseCommit: "a".repeat(40) } }; }, addProject: () => ({ ok: true, value: {} }), updateProject: () => ({ ok: true, value: { projects: [], newRoots: [] } }), diff --git a/lib/git-changes.ts b/lib/git-changes.ts index 757b12db5..8afc0de0b 100644 --- a/lib/git-changes.ts +++ b/lib/git-changes.ts @@ -36,9 +36,10 @@ async function git(cwd: string, args: string[], maxBuffer = GIT_STATUS_MAX_BUFFE return (await pending).stdout; } +/** The toplevel in `cwd`'s own spelling: Git's --show-toplevel can differ in separators, 8.3 names and symlinks. */ async function findRepositoryRoot(cwd: string): Promise { try { - return (await git(cwd, ["rev-parse", "--show-toplevel"])).trim() || null; + return path.resolve(cwd, (await git(cwd, ["rev-parse", "--show-cdup"])).trim()); } catch { return null; } diff --git a/lib/hosts/files-owner.integration.test.mjs b/lib/hosts/files-owner.integration.test.mjs index 43c366099..e14ca21aa 100644 --- a/lib/hosts/files-owner.integration.test.mjs +++ b/lib/hosts/files-owner.integration.test.mjs @@ -180,7 +180,8 @@ async function startDaemon(machine, token) { await until(() => hub.getHost(machine.hostId)?.status() === "online", `${machine.name} daemon to link`, 20000); } async function stopDaemon(machine) { - if (!machine.process || machine.process.exitCode !== null) return; + // Windows kill() terminates without a handler: exitCode stays null and signalCode is set. + if (!machine.process || machine.process.exitCode !== null || machine.process.signalCode !== null) return; const exited = new Promise((resolve) => machine.process.once("exit", resolve)); machine.process.kill("SIGTERM"); await exited; diff --git a/lib/hosts/pool-starts.test.mjs b/lib/hosts/pool-starts.test.mjs index fd02a831d..9a846e605 100644 --- a/lib/hosts/pool-starts.test.mjs +++ b/lib/hosts/pool-starts.test.mjs @@ -2,10 +2,20 @@ import assert from "node:assert/strict"; import { execFileSync, spawn } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, dirname, join } from "node:path"; +import { join, posix, sep } from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; +// Windows cannot spawn a shebang script: run it through a .cmd launcher (which wrapWindowsScript routes via cmd.exe). +function writeFakeOmp(file, source) { + if (process.platform !== "win32") { + writeFileSync(file, `#!${process.execPath}\n${source}`, { mode: 0o700 }); + return; + } + writeFileSync(`${file}.cjs`, source); + writeFileSync(file, `@"${process.execPath.replaceAll("%", "%%")}" "${file.replaceAll("%", "%%")}.cjs" %*\r\n`); +} + const root = fileURLToPath(new URL("../../", import.meta.url)); const scratch = realpathSync(mkdtempSync(join(tmpdir(), "omp-pool-starts-"))); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; @@ -21,7 +31,8 @@ const sample = (overrides = {}) => ({ effectiveCpus: 4, load1: 0, busyFraction: const intent = { type: "prompt", message: "first prompt", provider: "test", modelId: "model-a", thinkingLevel: "high", toolNames: ["read"], advisor: false }; const records = () => JSON.stringify(JSON.parse(readFileSync(journalPath, "utf8"))); const input = (fixture, suffix, overrides = {}) => ({ creationId: `${fixture.id}-${suffix}`, poolId: fixture.id, projectId: "project", intent, ...overrides }); -const preparedFor = (request) => ({ cwd: join(dirname(request.cloneRoot), `.${basename(request.cloneRoot)}_worktrees`, "session", request.creationId), projectRoot: request.cloneRoot, baseCommit: "a".repeat(40) }); +// Simulated POSIX workers: their paths follow POSIX rules whatever OS runs this test. +const preparedFor = (request) => ({ cwd: posix.join(posix.dirname(request.cloneRoot), `.${posix.basename(request.cloneRoot)}_worktrees`, "session", request.creationId), projectRoot: request.cloneRoot, baseCommit: "a".repeat(40) }); async function fixture(t, { members = 1, memory = 3 * GiB, prepare } = {}) { const id = `pool-${++serial}`; @@ -285,16 +296,17 @@ async function durableDaemonFixture(t, hold) { git(source, "push", "origin", "HEAD:refs/heads/main"); git(dir, "--git-dir", remote, "symbolic-ref", "HEAD", "refs/heads/main"); const ssh = join(dir, "ssh"); - writeFileSync(ssh, `#!/bin/sh\nexec git-upload-pack '${remote.replaceAll("'", "'\\''")}'\n`, { mode: 0o700 }); - gitEnv.GIT_SSH_COMMAND = ssh; + // Git runs GIT_SSH_COMMAND through sh; forward slashes keep Windows paths intact there. + const quotePath = (path) => `'${path.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`; + writeFileSync(ssh, `#!/bin/sh\nexec git-upload-pack ${quotePath(remote)}\n`, { mode: 0o700 }); + Object.assign(gitEnv, { GIT_SSH_COMMAND: `sh ${quotePath(ssh)}`, GIT_SSH_VARIANT: "simple" }); const logFile = join(dir, "omp.jsonl"); const killsFile = join(dir, "kills.jsonl"); const eventsFile = join(dir, "events.jsonl"); const holdFile = join(dir, hold); writeFileSync(holdFile, ""); - const fakeOmp = join(dir, "fake-omp"); - writeFileSync(fakeOmp, `#!${process.execPath} -if (process.argv.includes("--version")) { console.log("14.0.0-fake"); process.exit(0); } + const fakeOmp = join(dir, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp"); + writeFakeOmp(fakeOmp, `if (process.argv.includes("--version")) { console.log("14.0.0-fake"); process.exit(0); } if (process.argv.includes("update")) { console.log("Current version: 14.0.0-fake"); process.exit(0); } const fs = require("node:fs"), path = require("node:path"); const id = require("node:crypto").randomUUID(); @@ -327,7 +339,7 @@ require("node:readline").createInterface({input:process.stdin}).on("line", (line reply({}); }); process.stdin.on("end",()=>process.exit(0)); -`, { mode: 0o700 }); +`); const mainScript = ` import {appendFileSync,existsSync,readFileSync,rmSync,writeFileSync} from "node:fs"; const hub=await import("./lib/hosts/hub.ts"); @@ -355,7 +367,7 @@ const wrap=(ws)=>{let value=wrapped.get(ws);if(!value){value={data:ws.data,send( if(message.type==="kill")appendFileSync(${JSON.stringify(killsFile)},JSON.stringify(message)+"\\n"); const launch=message.type==="req"?(message.op==="open"?message.args.launch:message.op==="spawn"?message.args:null):null; if(launch?.creationId&&existsSync(${JSON.stringify(join(dir, "remove-cwd"))})){ - if(!launch.cwd.startsWith(${JSON.stringify(`${projectsRoot}/`)}))throw new Error("fixture refused deleting outside its projects root"); + if(!launch.cwd.startsWith(${JSON.stringify(projectsRoot + sep)}))throw new Error("fixture refused deleting outside its projects root"); rmSync(launch.cwd,{recursive:true,force:true}); writeFileSync(${JSON.stringify(join(dir, "cwd-removed"))},""); } diff --git a/lib/pooled-projects.test.mjs b/lib/pooled-projects.test.mjs index db023085b..c6246d207 100644 --- a/lib/pooled-projects.test.mjs +++ b/lib/pooled-projects.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { execFileSync, spawn } from "node:child_process"; import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { devNull, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -56,11 +56,12 @@ async function hostileGitEnvironment(run) { const outside = realpathSync(mkdtempSync(join(tmpdir(), "omp-pool-outside-"))); const saved = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith("GIT_"))); const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))); - Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: "1" }); + // Git for Windows maps /dev/null itself; Node's os.devNull (\\.\nul) is not a usable config path there. + Object.assign(env, { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }); const repository = join(outside, "repository.git"); const index = join(outside, "index"); try { - execFileSync("git", ["init", "--bare", repository], { env, stdio: "ignore" }); + execFileSync("git", ["init", "--bare", repository], { env, stdio: ["ignore", "ignore", "pipe"] }); const config = readFileSync(join(repository, "config")); writeFileSync(index, "outside index sentinel\n"); Object.assign(process.env, { @@ -99,284 +100,286 @@ function rejected(result) { const worktree = (f, id = "creation-1") => join(f.workers, ".registered-project_worktrees", "session", id); -// Subtests are serial: each owns its Git config and restores process.env before the next. -test("pool project preparation uses real isolated Git repositories", async (t) => { - const { preparePoolProject } = await import("./pooled-projects.ts"); +// Tests in a file run serially: each owns its Git config and restores process.env before the next. +const { preparePoolProject } = await import("./pooled-projects.ts"); - await t.test("fixture Git cannot write an ambient outside repository or index", () => hostileGitEnvironment(() => fixture(async (f) => { - const value = prepared(await preparePoolProject(f.input)); - assert.equal(readFileSync(join(value.cwd, "tracked.txt"), "utf8"), "committed\n"); - }))); +test("fixture Git cannot write an ambient outside repository or index", () => hostileGitEnvironment(() => fixture(async (f) => { + const value = prepared(await preparePoolProject(f.input)); + assert.equal(readFileSync(join(value.cwd, "tracked.txt"), "utf8"), "committed\n"); +}))); - await t.test("clones a registered origin and creates an external session branch", () => fixture(async (f) => { - const value = prepared(await preparePoolProject(f.input)); - assert.deepEqual(value, { cwd: worktree(f), projectRoot: f.cloneRoot, baseCommit: f.baseCommit }); - assert.equal(git(f.cloneRoot, "config", "--get", "remote.origin.url"), f.origin); - assert.equal(git(value.cwd, "branch", "--show-current"), "session/creation-1"); - assert.equal(readFileSync(join(value.cwd, "tracked.txt"), "utf8"), "committed\n"); - assert.equal(lstatSync(join(value.cwd, ".git")).isFile(), true); - assert.deepEqual(readdirSync(f.workers).sort(), [".registered-project_worktrees", "registered-project"]); - })); +test("clones a registered origin and creates an external session branch", () => fixture(async (f) => { + const value = prepared(await preparePoolProject(f.input)); + assert.deepEqual(value, { cwd: worktree(f), projectRoot: f.cloneRoot, baseCommit: f.baseCommit }); + assert.equal(git(f.cloneRoot, "config", "--get", "remote.origin.url"), f.origin); + assert.equal(git(value.cwd, "branch", "--show-current"), "session/creation-1"); + assert.equal(readFileSync(join(value.cwd, "tracked.txt"), "utf8"), "committed\n"); + assert.equal(lstatSync(join(value.cwd, ".git")).isFile(), true); + assert.deepEqual(readdirSync(f.workers).sort(), [".registered-project_worktrees", "registered-project"]); +})); - await t.test("fetches pushed refs from another clone without resetting a dirty checkout", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - writeFileSync(join(f.cloneRoot, "tracked.txt"), "local edit\n"); - writeFileSync(join(f.cloneRoot, "private.txt"), "untracked\n"); - git(f.source, "checkout", "-b", "feature/pushed"); - writeFileSync(join(f.source, "pushed.txt"), "available on every worker\n"); - git(f.source, "add", "."); - git(f.source, "-c", "commit.gpgsign=false", "commit", "-qm", "pushed ref"); - git(f.source, "push", "origin", "feature/pushed"); - const commit = git(f.source, "rev-parse", "HEAD"); - const value = prepared(await preparePoolProject({ ...f.input, ref: "feature/pushed" })); - assert.equal(value.baseCommit, commit); - assert.equal(readFileSync(join(value.cwd, "pushed.txt"), "utf8"), "available on every worker\n"); - assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "local edit\n"); - assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "untracked\n"); - assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); - })); +test("fetches pushed refs from another clone without resetting a dirty checkout", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + writeFileSync(join(f.cloneRoot, "tracked.txt"), "local edit\n"); + writeFileSync(join(f.cloneRoot, "private.txt"), "untracked\n"); + git(f.source, "checkout", "-b", "feature/pushed"); + writeFileSync(join(f.source, "pushed.txt"), "available on every worker\n"); + git(f.source, "add", "."); + git(f.source, "-c", "commit.gpgsign=false", "commit", "-qm", "pushed ref"); + git(f.source, "push", "origin", "feature/pushed"); + const commit = git(f.source, "rev-parse", "HEAD"); + const value = prepared(await preparePoolProject({ ...f.input, ref: "feature/pushed" })); + assert.equal(value.baseCommit, commit); + assert.equal(readFileSync(join(value.cwd, "pushed.txt"), "utf8"), "available on every worker\n"); + assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "local edit\n"); + assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "untracked\n"); + assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); +})); - await t.test("same creation is idempotent and preserves its dirty worktree", () => fixture(async (f) => { - const first = prepared(await preparePoolProject(f.input)); - writeFileSync(join(first.cwd, "tracked.txt"), "session edit\n"); - writeFileSync(join(first.cwd, "notes.txt"), "session notes\n"); - writeFileSync(join(f.source, "later.txt"), "new default branch commit\n"); - git(f.source, "add", "."); - git(f.source, "-c", "commit.gpgsign=false", "commit", "-qm", "advance default"); - git(f.source, "push", "origin", "main"); - const second = prepared(await preparePoolProject(f.input)); - assert.deepEqual(second, first); - assert.equal(readFileSync(join(first.cwd, "tracked.txt"), "utf8"), "session edit\n"); - assert.equal(readFileSync(join(first.cwd, "notes.txt"), "utf8"), "session notes\n"); - assert.equal(git(f.cloneRoot, "worktree", "list", "--porcelain").match(/^worktree /gm).length, 2); - })); +test("same creation is idempotent and preserves its dirty worktree", () => fixture(async (f) => { + const first = prepared(await preparePoolProject(f.input)); + writeFileSync(join(first.cwd, "tracked.txt"), "session edit\n"); + writeFileSync(join(first.cwd, "notes.txt"), "session notes\n"); + writeFileSync(join(f.source, "later.txt"), "new default branch commit\n"); + git(f.source, "add", "."); + git(f.source, "-c", "commit.gpgsign=false", "commit", "-qm", "advance default"); + git(f.source, "push", "origin", "main"); + const second = prepared(await preparePoolProject(f.input)); + assert.deepEqual(second, first); + assert.equal(readFileSync(join(first.cwd, "tracked.txt"), "utf8"), "session edit\n"); + assert.equal(readFileSync(join(first.cwd, "notes.txt"), "utf8"), "session notes\n"); + assert.equal(git(f.cloneRoot, "worktree", "list", "--porcelain").match(/^worktree /gm).length, 2); +})); - await t.test("concurrent distinct creations serialize clone publication and use unique worktrees", () => fixture(async (f) => { - const [a, b, repeated] = await Promise.all([ - preparePoolProject(f.input), - preparePoolProject({ ...f.input, creationId: "creation-2" }), - preparePoolProject(f.input), - ]); - assert.equal(prepared(a).cwd, worktree(f)); - assert.equal(prepared(b).cwd, worktree(f, "creation-2")); - assert.deepEqual(prepared(repeated), prepared(a)); - writeFileSync(join(prepared(a).cwd, "only-a.txt"), "isolated\n"); - assert.equal(existsSync(join(prepared(b).cwd, "only-a.txt")), false); - assert.equal(git(f.cloneRoot, "worktree", "list", "--porcelain").match(/^worktree /gm).length, 3); - assert.deepEqual(readdirSync(f.workers).sort(), [".registered-project_worktrees", "registered-project"]); - })); +test("concurrent distinct creations serialize clone publication and use unique worktrees", () => fixture(async (f) => { + const [a, b, repeated] = await Promise.all([ + preparePoolProject(f.input), + preparePoolProject({ ...f.input, creationId: "creation-2" }), + preparePoolProject(f.input), + ]); + assert.equal(prepared(a).cwd, worktree(f)); + assert.equal(prepared(b).cwd, worktree(f, "creation-2")); + assert.deepEqual(prepared(repeated), prepared(a)); + writeFileSync(join(prepared(a).cwd, "only-a.txt"), "isolated\n"); + assert.equal(existsSync(join(prepared(b).cwd, "only-a.txt")), false); + assert.equal(git(f.cloneRoot, "worktree", "list", "--porcelain").match(/^worktree /gm).length, 3); + assert.deepEqual(readdirSync(f.workers).sort(), [".registered-project_worktrees", "registered-project"]); +})); - await t.test("equal origin basenames do not merge different registered projects", () => fixture(async (f) => { - const a = prepared(await preparePoolProject(f.input)); - const otherRoot = join(f.workers, "other-project"); - const b = prepared(await preparePoolProject({ ...f.input, projectId: "other-project", cloneRoot: otherRoot })); - assert.equal(b.projectRoot, otherRoot); - assert.equal(b.cwd, join(f.workers, ".other-project_worktrees", "session", "creation-1")); - assert.notEqual(a.cwd, b.cwd); - })); +test("equal origin basenames do not merge different registered projects", () => fixture(async (f) => { + const a = prepared(await preparePoolProject(f.input)); + const otherRoot = join(f.workers, "other-project"); + const b = prepared(await preparePoolProject({ ...f.input, projectId: "other-project", cloneRoot: otherRoot })); + assert.equal(b.projectRoot, otherRoot); + assert.equal(b.cwd, join(f.workers, ".other-project_worktrees", "session", "creation-1")); + assert.notEqual(a.cwd, b.cwd); +})); - await t.test("rejects a mismatched literal origin without changing dirty data", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - git(f.cloneRoot, "remote", "set-url", "origin", "https://different.invalid/repo.git"); - writeFileSync(join(f.cloneRoot, "tracked.txt"), "keep me\n"); - rejected(await preparePoolProject(f.input)); - assert.equal(git(f.cloneRoot, "config", "--get", "remote.origin.url"), "https://different.invalid/repo.git"); - assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "keep me\n"); - assert.equal(existsSync(worktree(f)), false); - })); +test("rejects a mismatched literal origin without changing dirty data", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + git(f.cloneRoot, "remote", "set-url", "origin", "https://different.invalid/repo.git"); + writeFileSync(join(f.cloneRoot, "tracked.txt"), "keep me\n"); + rejected(await preparePoolProject(f.input)); + assert.equal(git(f.cloneRoot, "config", "--get", "remote.origin.url"), "https://different.invalid/repo.git"); + assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "keep me\n"); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("rejects a mismatched first origin even when the last literal matches", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - git(f.cloneRoot, "remote", "set-url", "origin", "https://different.invalid/repo.git"); +test("rejects a mismatched first origin even when the last literal matches", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + git(f.cloneRoot, "remote", "set-url", "origin", "https://different.invalid/repo.git"); + git(f.cloneRoot, "config", "--add", "remote.origin.url", f.origin); + const contacted = join(f.root, "network-contacted"); + writeFileSync(f.ssh, `#!/bin/sh\necho contacted > ${quotePath(contacted)}\nexit 128\n`, { mode: 0o700 }); + writeFileSync(join(f.cloneRoot, "tracked.txt"), "keep me\n"); + rejected(await preparePoolProject(f.input)); + assert.equal(existsSync(contacted), false, "ambiguous origins fail before network access"); + assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "keep me\n"); + assert.equal(git(f.cloneRoot, "config", "--get-all", "remote.origin.url"), `https://different.invalid/repo.git\n${f.origin}`); + assert.equal(existsSync(worktree(f)), false); + for (const second of [f.origin, ""]) { + git(f.cloneRoot, "config", "--unset-all", "remote.origin.url"); git(f.cloneRoot, "config", "--add", "remote.origin.url", f.origin); - const contacted = join(f.root, "network-contacted"); - writeFileSync(f.ssh, `#!/bin/sh\necho contacted > ${quotePath(contacted)}\nexit 128\n`, { mode: 0o700 }); - writeFileSync(join(f.cloneRoot, "tracked.txt"), "keep me\n"); + git(f.cloneRoot, "config", "--add", "remote.origin.url", second); rejected(await preparePoolProject(f.input)); - assert.equal(existsSync(contacted), false, "ambiguous origins fail before network access"); - assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "keep me\n"); - assert.equal(git(f.cloneRoot, "config", "--get-all", "remote.origin.url"), `https://different.invalid/repo.git\n${f.origin}`); + assert.equal(existsSync(contacted), false, "duplicate and empty extra origins are also ambiguous"); assert.equal(existsSync(worktree(f)), false); - for (const second of [f.origin, ""]) { - git(f.cloneRoot, "config", "--unset-all", "remote.origin.url"); - git(f.cloneRoot, "config", "--add", "remote.origin.url", f.origin); - git(f.cloneRoot, "config", "--add", "remote.origin.url", second); - rejected(await preparePoolProject(f.input)); - assert.equal(existsSync(contacted), false, "duplicate and empty extra origins are also ambiguous"); - assert.equal(existsSync(worktree(f)), false); - } - })); + } +})); - await t.test("preserves a pre-existing non-repository clone target", () => fixture(async (f) => { - mkdirSync(f.cloneRoot); - writeFileSync(join(f.cloneRoot, "private.txt"), "not ours\n"); - rejected(await preparePoolProject(f.input)); - assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "not ours\n"); - assert.equal(existsSync(worktree(f)), false); - })); +test("preserves a pre-existing non-repository clone target", () => fixture(async (f) => { + mkdirSync(f.cloneRoot); + writeFileSync(join(f.cloneRoot, "private.txt"), "not ours\n"); + rejected(await preparePoolProject(f.input)); + assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "not ours\n"); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("rejects a clone-root symlink without touching its destination", () => fixture(async (f) => { - const outside = join(f.root, "outside"); - git(f.root, "clone", f.origin, outside); - writeFileSync(join(outside, "private.txt"), "outside\n"); - symlinkSync(outside, f.cloneRoot, "dir"); - rejected(await preparePoolProject(f.input)); - assert.equal(lstatSync(f.cloneRoot).isSymbolicLink(), true); - assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); - assert.equal(existsSync(worktree(f)), false); - })); +test("rejects a clone-root symlink without touching its destination", () => fixture(async (f) => { + const outside = join(f.root, "outside"); + git(f.root, "clone", f.origin, outside); + writeFileSync(join(outside, "private.txt"), "outside\n"); + symlinkSync(outside, f.cloneRoot, "dir"); + rejected(await preparePoolProject(f.input)); + assert.equal(lstatSync(f.cloneRoot).isSymbolicLink(), true); + assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("rejects symlinked worktree parents and leaves outside data alone", () => fixture(async (f) => { - const outside = join(f.root, "outside"); - mkdirSync(outside); - writeFileSync(join(outside, "private.txt"), "outside\n"); - symlinkSync(outside, join(f.workers, ".registered-project_worktrees"), "dir"); - rejected(await preparePoolProject(f.input)); - assert.deepEqual(readdirSync(outside), ["private.txt"]); - assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); - })); +test("rejects symlinked worktree parents and leaves outside data alone", () => fixture(async (f) => { + const outside = join(f.root, "outside"); + mkdirSync(outside); + writeFileSync(join(outside, "private.txt"), "outside\n"); + symlinkSync(outside, join(f.workers, ".registered-project_worktrees"), "dir"); + rejected(await preparePoolProject(f.input)); + assert.deepEqual(readdirSync(outside), ["private.txt"]); + assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); +})); - await t.test("rejects a symlink at the session destination", () => fixture(async (f) => { - const outside = join(f.root, "outside"); - mkdirSync(outside); - writeFileSync(join(outside, "private.txt"), "outside\n"); - mkdirSync(join(f.workers, ".registered-project_worktrees", "session"), { recursive: true }); - symlinkSync(outside, worktree(f), "dir"); - rejected(await preparePoolProject(f.input)); - assert.equal(lstatSync(worktree(f)).isSymbolicLink(), true); - assert.deepEqual(readdirSync(outside), ["private.txt"]); - assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); - })); +test("rejects a symlink at the session destination", () => fixture(async (f) => { + const outside = join(f.root, "outside"); + mkdirSync(outside); + writeFileSync(join(outside, "private.txt"), "outside\n"); + mkdirSync(join(f.workers, ".registered-project_worktrees", "session"), { recursive: true }); + symlinkSync(outside, worktree(f), "dir"); + rejected(await preparePoolProject(f.input)); + assert.equal(lstatSync(worktree(f)).isSymbolicLink(), true); + assert.deepEqual(readdirSync(outside), ["private.txt"]); + assert.equal(readFileSync(join(outside, "private.txt"), "utf8"), "outside\n"); +})); - await t.test("rejects an occupied worktree path without deleting its files", () => fixture(async (f) => { - mkdirSync(worktree(f), { recursive: true }); - writeFileSync(join(worktree(f), "private.txt"), "pre-existing\n"); - rejected(await preparePoolProject(f.input)); - assert.equal(readFileSync(join(worktree(f), "private.txt"), "utf8"), "pre-existing\n"); - })); +test("rejects an occupied worktree path without deleting its files", () => fixture(async (f) => { + mkdirSync(worktree(f), { recursive: true }); + writeFileSync(join(worktree(f), "private.txt"), "pre-existing\n"); + rejected(await preparePoolProject(f.input)); + assert.equal(readFileSync(join(worktree(f), "private.txt"), "utf8"), "pre-existing\n"); +})); - await t.test("does not relocate a conflicting existing session branch", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - const existing = join(f.root, "existing-session"); - git(f.cloneRoot, "worktree", "add", "-b", "session/creation-1", existing, "HEAD"); - writeFileSync(join(existing, "private.txt"), "existing session\n"); - rejected(await preparePoolProject(f.input)); - assert.equal(readFileSync(join(existing, "private.txt"), "utf8"), "existing session\n"); - assert.equal(existsSync(worktree(f)), false); - })); +test("does not relocate a conflicting existing session branch", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + const existing = join(f.root, "existing-session"); + git(f.cloneRoot, "worktree", "add", "-b", "session/creation-1", existing, "HEAD"); + writeFileSync(join(existing, "private.txt"), "existing session\n"); + rejected(await preparePoolProject(f.input)); + assert.equal(readFileSync(join(existing, "private.txt"), "utf8"), "existing session\n"); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("unpublished local refs do not become worker session bases", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - git(f.cloneRoot, "branch", "local-only"); - rejected(await preparePoolProject({ ...f.input, ref: "local-only" })); - assert.equal(existsSync(worktree(f)), false); - assert.equal(git(f.cloneRoot, "rev-parse", "local-only"), f.baseCommit); - })); +test("unpublished local refs do not become worker session bases", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + git(f.cloneRoot, "branch", "local-only"); + rejected(await preparePoolProject({ ...f.input, ref: "local-only" })); + assert.equal(existsSync(worktree(f)), false); + assert.equal(git(f.cloneRoot, "rev-parse", "local-only"), f.baseCommit); +})); - await t.test("accepts opaque creation IDs including underscore at the 128-character boundary", () => fixture(async (f) => { - const creationId = `request_${"a".repeat(120)}`; - const value = prepared(await preparePoolProject({ ...f.input, creationId })); - assert.equal(value.cwd, worktree(f, creationId)); - assert.equal(git(value.cwd, "branch", "--show-current"), `session/${creationId}`); - })); +test("accepts opaque creation IDs including underscore at the 128-character boundary", () => fixture(async (f) => { + const creationId = `request_${"a".repeat(120)}`; + // Git for Windows refuses a GIT_DIR of PATH_MAX - 40 (220) characters or more, and a linked worktree's is + // \.git\worktrees\: the 128-character ID leaves 76 for the clone root, which the temp fixture path exceeds. + const cloneRoot = join(f.root, "p"); + const value = prepared(await preparePoolProject({ ...f.input, cloneRoot, creationId })); + assert.equal(value.cwd, join(f.root, ".p_worktrees", "session", creationId)); + assert.equal(git(value.cwd, "branch", "--show-current"), `session/${creationId}`); +})); - await t.test("unsafe origins and IDs cannot create paths or escape the worker root", () => fixture(async (f) => { - for (const change of [ - { origin: `file://${f.remote}` }, - { origin: f.remote }, - { origin: "http://pool-fixture.invalid/repo.git" }, - { origin: "https://token@pool-fixture.invalid/repo.git" }, - { origin: "https://user:password@pool-fixture.invalid/repo.git" }, - { creationId: "../../escape" }, - { creationId: "bad/ref" }, - { creationId: "a".repeat(129) }, - { creationId: "has space" }, - { creationId: "" }, - { projectId: "../escape" }, - ]) rejected(await preparePoolProject({ ...f.input, ...change })); - assert.deepEqual(readdirSync(f.workers), []); - assert.equal(existsSync(join(f.root, "escape")), false); - })); +test("unsafe origins and IDs cannot create paths or escape the worker root", () => fixture(async (f) => { + for (const change of [ + { origin: `file://${f.remote}` }, + { origin: f.remote }, + { origin: "http://pool-fixture.invalid/repo.git" }, + { origin: "https://token@pool-fixture.invalid/repo.git" }, + { origin: "https://user:password@pool-fixture.invalid/repo.git" }, + { creationId: "../../escape" }, + { creationId: "bad/ref" }, + { creationId: "a".repeat(129) }, + { creationId: "has space" }, + { creationId: "" }, + { projectId: "../escape" }, + ]) rejected(await preparePoolProject({ ...f.input, ...change })); + assert.deepEqual(readdirSync(f.workers), []); + assert.equal(existsSync(join(f.root, "escape")), false); +})); - await t.test("authentication failure leaves no clone or launchable worktree", () => fixture(async (f) => { - writeFileSync(f.ssh, '#!/bin/sh\necho "Permission denied (publickey)." >&2\nexit 128\n', { mode: 0o700 }); - rejected(await preparePoolProject(f.input)); - assert.equal(existsSync(f.cloneRoot), false); - assert.equal(existsSync(worktree(f)), false); - assert.deepEqual(readdirSync(f.workers), []); - })); +test("authentication failure leaves no clone or launchable worktree", () => fixture(async (f) => { + writeFileSync(f.ssh, '#!/bin/sh\necho "Permission denied (publickey)." >&2\nexit 128\n', { mode: 0o700 }); + rejected(await preparePoolProject(f.input)); + assert.equal(existsSync(f.cloneRoot), false); + assert.equal(existsSync(worktree(f)), false); + assert.deepEqual(readdirSync(f.workers), []); +})); - await t.test("failed fetch preserves an existing dirty clone and unrelated files", () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - writeFileSync(join(f.cloneRoot, "tracked.txt"), "local edit\n"); - writeFileSync(join(f.cloneRoot, "private.txt"), "untracked\n"); - writeFileSync(f.ssh, '#!/bin/sh\necho "Permission denied (publickey)." >&2\nexit 128\n', { mode: 0o700 }); - rejected(await preparePoolProject(f.input)); - assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "local edit\n"); - assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "untracked\n"); - assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); - assert.equal(existsSync(worktree(f)), false); - })); +test("failed fetch preserves an existing dirty clone and unrelated files", () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + writeFileSync(join(f.cloneRoot, "tracked.txt"), "local edit\n"); + writeFileSync(join(f.cloneRoot, "private.txt"), "untracked\n"); + writeFileSync(f.ssh, '#!/bin/sh\necho "Permission denied (publickey)." >&2\nexit 128\n', { mode: 0o700 }); + rejected(await preparePoolProject(f.input)); + assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "local edit\n"); + assert.equal(readFileSync(join(f.cloneRoot, "private.txt"), "utf8"), "untracked\n"); + assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("existing clone fetch cannot open its parent's controlling terminal", { skip: process.platform === "win32" }, () => fixture(async (f) => { - git(f.root, "clone", f.origin, f.cloneRoot); - const terminal = join(f.root, "fetch-terminal"); - const resultFile = join(f.root, "fetch-result.json"); - writeFileSync(f.ssh, `#!/bin/sh\nif (: /dev/null; then echo attached > ${quotePath(terminal)}; else echo detached > ${quotePath(terminal)}; fi\nexit 128\n`, { mode: 0o700 }); - const moduleUrl = new URL("./pooled-projects.ts", import.meta.url).href; - const program = `const {preparePoolProject}=await import(${JSON.stringify(moduleUrl)}); const {writeFileSync}=await import("node:fs"); const {execFileSync}=await import("node:child_process"); execFileSync("sh",["-c","(: /dev/null"],{stdio:"ignore"}); writeFileSync(${JSON.stringify(resultFile)},JSON.stringify(await preparePoolProject(${JSON.stringify(f.input)})));`; - const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`; - const args = process.platform === "darwin" - ? ["-q", "/dev/null", process.execPath, "--eval", program] - : ["-q", "-c", [process.execPath, "--eval", program].map(quote).join(" "), "/dev/null"]; - execFileSync("script", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10000 }); - rejected(JSON.parse(readFileSync(resultFile, "utf8"))); - assert.equal(readFileSync(terminal, "utf8"), "detached\n"); - assert.equal(existsSync(worktree(f)), false); - })); +test("existing clone fetch cannot open its parent's controlling terminal", { skip: process.platform === "win32" }, () => fixture(async (f) => { + git(f.root, "clone", f.origin, f.cloneRoot); + const terminal = join(f.root, "fetch-terminal"); + const resultFile = join(f.root, "fetch-result.json"); + writeFileSync(f.ssh, `#!/bin/sh\nif (: /dev/null; then echo attached > ${quotePath(terminal)}; else echo detached > ${quotePath(terminal)}; fi\nexit 128\n`, { mode: 0o700 }); + const moduleUrl = new URL("./pooled-projects.ts", import.meta.url).href; + const program = `const {preparePoolProject}=await import(${JSON.stringify(moduleUrl)}); const {writeFileSync}=await import("node:fs"); const {execFileSync}=await import("node:child_process"); execFileSync("sh",["-c","(: /dev/null"],{stdio:"ignore"}); writeFileSync(${JSON.stringify(resultFile)},JSON.stringify(await preparePoolProject(${JSON.stringify(f.input)})));`; + const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`; + const args = process.platform === "darwin" + ? ["-q", "/dev/null", process.execPath, "--eval", program] + : ["-q", "-c", [process.execPath, "--eval", program].map(quote).join(" "), "/dev/null"]; + execFileSync("script", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10000 }); + rejected(JSON.parse(readFileSync(resultFile, "utf8"))); + assert.equal(readFileSync(terminal, "utf8"), "detached\n"); + assert.equal(existsSync(worktree(f)), false); +})); - await t.test("a separate-process clone with valid HEAD cannot be consumed before its owner completes", () => fixture(async (f) => { - const started = join(f.root, "post-checkout-started"); - const resultFile = join(f.root, "clone-result.json"); - const poolResultFile = join(f.root, "pool-result.json"); - const template = join(f.root, "template"); - mkdirSync(join(template, "hooks"), { recursive: true }); - // Git installs this real template hook; session worktree checkouts must not pause. - writeFileSync(join(template, "hooks", "post-checkout"), `#!/bin/sh\nif [ "$(git rev-parse --show-toplevel)" = ${quotePath(f.cloneRoot)} ]; then echo paused > ${quotePath(started)}; while :; do sleep 1; done; fi\n`, { mode: 0o700 }); - git(f.root, "config", "--global", "init.templateDir", template); - const cloneModule = new URL("./project-clone.ts", import.meta.url).href; - const poolModule = new URL("./pooled-projects.ts", import.meta.url).href; - const program = `const {cloneRepository}=await import(${JSON.stringify(cloneModule)}); const {writeFileSync}=await import("node:fs"); const controller=new AbortController(); process.stdin.once("data",()=>controller.abort()); const result=await cloneRepository({origin:${JSON.stringify(f.origin)},target:${JSON.stringify(f.cloneRoot)},signal:controller.signal}); writeFileSync(${JSON.stringify(resultFile)},JSON.stringify(result)); process.exit(0);`; - const child = spawn(process.execPath, ["--eval", program], { stdio: ["pipe", "pipe", "pipe"] }); - child.stdout.resume(); - child.stderr.resume(); - const closed = Promise.withResolvers(); - child.once("error", closed.reject); - child.once("exit", closed.resolve); - try { - const deadline = Date.now() + 5000; - while (!existsSync(started)) { - assert.ok(Date.now() < deadline, "standalone clone did not reach its post-checkout hook"); - await new Promise((resolve) => setTimeout(resolve, 10)); - } - assert.equal(git(f.cloneRoot, "rev-parse", "--verify", "HEAD^{commit}"), f.baseCommit); - assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "committed\n"); - const inode = lstatSync(f.cloneRoot).ino; - writeFileSync(join(f.cloneRoot, "owned.txt"), "owned by standalone attempt\n"); - const poolProgram = `const {preparePoolProject}=await import(${JSON.stringify(poolModule)}); const {writeFileSync}=await import("node:fs"); writeFileSync(${JSON.stringify(poolResultFile)},JSON.stringify(await preparePoolProject(${JSON.stringify(f.input)})));`; - execFileSync(process.execPath, ["--eval", poolProgram], { stdio: ["ignore", "pipe", "pipe"], timeout: 10000 }); - const result = JSON.parse(readFileSync(poolResultFile, "utf8")); - rejected(result); - assert.equal(result.status, 409, "valid HEAD does not relinquish the other process's clone ownership"); - assert.equal(lstatSync(f.cloneRoot).ino, inode); - assert.equal(readFileSync(join(f.cloneRoot, "owned.txt"), "utf8"), "owned by standalone attempt\n"); - assert.equal(existsSync(worktree(f)), false); - } finally { - child.stdin.end("cancel\n"); - assert.equal(await closed.promise, 0); +test("a separate-process clone with valid HEAD cannot be consumed before its owner completes", () => fixture(async (f) => { + const started = join(f.root, "post-checkout-started"); + const resultFile = join(f.root, "clone-result.json"); + const poolResultFile = join(f.root, "pool-result.json"); + const template = join(f.root, "template"); + mkdirSync(join(template, "hooks"), { recursive: true }); + // Git installs this real template hook; session worktree checkouts must not pause. Both paths come + // from Git, so their spelling matches even where the fixture path differs (Windows 8.3 names). + writeFileSync(join(template, "hooks", "post-checkout"), `#!/bin/sh\nif [ "$(git rev-parse --path-format=absolute --git-dir)" = "$(git rev-parse --path-format=absolute --git-common-dir)" ]; then echo paused > ${quotePath(started)}; while :; do sleep 1; done; fi\n`, { mode: 0o700 }); + git(f.root, "config", "--global", "init.templateDir", template); + const cloneModule = new URL("./project-clone.ts", import.meta.url).href; + const poolModule = new URL("./pooled-projects.ts", import.meta.url).href; + const program = `const {cloneRepository}=await import(${JSON.stringify(cloneModule)}); const {writeFileSync}=await import("node:fs"); const controller=new AbortController(); process.stdin.once("data",()=>controller.abort()); const result=await cloneRepository({origin:${JSON.stringify(f.origin)},target:${JSON.stringify(f.cloneRoot)},signal:controller.signal}); writeFileSync(${JSON.stringify(resultFile)},JSON.stringify(result)); process.exit(0);`; + const child = spawn(process.execPath, ["--eval", program], { stdio: ["pipe", "pipe", "pipe"] }); + child.stdout.resume(); + child.stderr.resume(); + const closed = Promise.withResolvers(); + child.once("error", closed.reject); + child.once("exit", closed.resolve); + try { + const deadline = Date.now() + 5000; + while (!existsSync(started)) { + assert.ok(Date.now() < deadline, "standalone clone did not reach its post-checkout hook"); + await new Promise((resolve) => setTimeout(resolve, 10)); } - rejected(JSON.parse(readFileSync(resultFile, "utf8"))); - assert.equal(existsSync(f.cloneRoot), false, "only the standalone clone owner cleans its cancelled target"); - assert.deepEqual(readdirSync(f.workers), [], "completed cancellation releases its reservation too"); - })); -}); + assert.equal(git(f.cloneRoot, "rev-parse", "--verify", "HEAD^{commit}"), f.baseCommit); + assert.equal(readFileSync(join(f.cloneRoot, "tracked.txt"), "utf8"), "committed\n"); + const inode = lstatSync(f.cloneRoot).ino; + writeFileSync(join(f.cloneRoot, "owned.txt"), "owned by standalone attempt\n"); + const poolProgram = `const {preparePoolProject}=await import(${JSON.stringify(poolModule)}); const {writeFileSync}=await import("node:fs"); writeFileSync(${JSON.stringify(poolResultFile)},JSON.stringify(await preparePoolProject(${JSON.stringify(f.input)})));`; + execFileSync(process.execPath, ["--eval", poolProgram], { stdio: ["ignore", "pipe", "pipe"], timeout: 10000 }); + const result = JSON.parse(readFileSync(poolResultFile, "utf8")); + rejected(result); + assert.equal(result.status, 409, "valid HEAD does not relinquish the other process's clone ownership"); + assert.equal(lstatSync(f.cloneRoot).ino, inode); + assert.equal(readFileSync(join(f.cloneRoot, "owned.txt"), "utf8"), "owned by standalone attempt\n"); + assert.equal(existsSync(worktree(f)), false); + } finally { + child.stdin.end("cancel\n"); + assert.equal(await closed.promise, 0); + } + rejected(JSON.parse(readFileSync(resultFile, "utf8"))); + assert.equal(existsSync(f.cloneRoot), false, "only the standalone clone owner cleans its cancelled target"); + assert.deepEqual(readdirSync(f.workers), [], "completed cancellation releases its reservation too"); +})); diff --git a/lib/pooled-projects.ts b/lib/pooled-projects.ts index 2daaddc16..630698242 100644 --- a/lib/pooled-projects.ts +++ b/lib/pooled-projects.ts @@ -155,7 +155,8 @@ async function prepare(input: { if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new PreparationError("pool_clone_conflict", "Clone target is not a completed repository"); throw error; } - if (!gitStat.isDirectory() || gitStat.isSymbolicLink() || await git(cloneRoot, "rev-parse", "--show-toplevel") !== cloneRoot) { + // --show-cdup is empty only at the toplevel; no comparison between Git's and the caller's path spelling (8.3 names, separators). + if (!gitStat.isDirectory() || gitStat.isSymbolicLink() || await git(cloneRoot, "rev-parse", "--show-cdup") !== "") { throw new PreparationError("pool_clone_conflict", "Clone root must be an independent repository"); } // Reject multiple literal URLs: Git fetches the first, whereas config --get returns the last. @@ -172,7 +173,7 @@ async function prepare(input: { if (currentWorktree) { const dotGit = await lstat(join(cwd, ".git")); if (!dotGit.isFile() || dotGit.isSymbolicLink() - || await git(cwd, "rev-parse", "--show-toplevel") !== cwd + || await git(cwd, "rev-parse", "--show-cdup") !== "" || await realpath(await git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir")) !== await realpath(gitDirectory) || await git(cwd, "symbolic-ref", "--quiet", "--short", "HEAD") !== branch) { throw new PreparationError("pool_worktree_conflict", "Worktree target is owned by another checkout"); diff --git a/lib/projects-clone-route.test.mjs b/lib/projects-clone-route.test.mjs index 78344f078..fa848dcf7 100644 --- a/lib/projects-clone-route.test.mjs +++ b/lib/projects-clone-route.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; -import { devNull, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { createServer } from "node:net"; import { join } from "node:path"; import test from "node:test"; @@ -55,11 +55,12 @@ async function hostileGitEnvironment(run) { const outside = realpathSync(mkdtempSync(join(tmpdir(), "omp-clone-outside-"))); const saved = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith("GIT_"))); const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))); - Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: "1" }); + // Git for Windows maps /dev/null itself; Node's os.devNull (\\.\nul) is not a usable config path there. + Object.assign(env, { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }); const repository = join(outside, "repository.git"); const index = join(outside, "index"); try { - execFileSync("git", ["init", "--bare", repository], { env, stdio: "ignore" }); + execFileSync("git", ["init", "--bare", repository], { env, stdio: ["ignore", "ignore", "pipe"] }); const config = readFileSync(join(repository, "config")); writeFileSync(index, "outside index sentinel\n"); Object.assign(process.env, {