diff --git a/CHANGELOG.md b/CHANGELOG.md index da51b5384..5715a03b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added +- **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. - **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url ` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent. - **Sidebar marks sessions with an unsent draft.** A session whose composer still holds text or attachments shows a small pencil beside its title, so a half-written message is easy to find again. The mark follows this browser tab's drafts. @@ -60,6 +61,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/README.md b/README.md index e0e399c7c..bfe5ba7d5 100644 --- a/README.md +++ b/README.md @@ -243,9 +243,13 @@ executable/entrypoint identity and maintenance state without credentials. `ompweb host drain` synchronously checks children (idle included), preparations, uploads/controls, pending operations and reliable results, and closes new-work admission only when idle. A busy refusal never kills work or changes admission. -`ompweb host resume` reopens the live daemon. Controls use a private Unix socket inside -the existing daemon, not TCP or a separate service. A disconnected deployer cannot release -a live drain. Ordinary standalone Windows hosts remain unchanged; local controls are Unix-only. +`ompweb host resume` reopens the live daemon. Controls run inside the existing daemon, not +TCP or a separate service: a private Unix socket on Linux and macOS, and on Windows a named +pipe with a random name and a per-start token. Windows keeps both in +`/omp-web/host-control.json`, which only the daemon's user can read through the +agent directory; a request without the current token is refused. A disconnected deployer +cannot release a live drain. Windows hosts report CPU and memory capacity too, so they can be +pool workers. Disable central member admission before worker rollout; native drain is the final race-free guard. Worker service cutovers can additionally start drained through `OMP_WEB_HOST_DRAINED=1` diff --git a/bin/omp-web-host.test.mjs b/bin/omp-web-host.test.mjs index a4cea97be..478b84815 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/omp-web-host.test.mjs @@ -195,22 +195,36 @@ test("CLI startup failure cleans its endpoint without dialing or needing credent assert.equal(existsSync(hostControlPath(f.agentDir)), false); }); -test("CLI controls explicitly reject Windows while ordinary host startup stays available", { skip: process.platform !== "win32" && "Windows-only control-command contract" }, async (t) => { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-win-")); - t.after(() => rmSync(scratch, { recursive: true, force: true })); - const env = { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: join(scratch, "agent") }; - for (const command of ["status", "drain", "resume"]) { - const result = await hostCommand(env, command); - assert.equal(result.code, 1); - assert.match(result.stderr, /Windows.*unsupported|not supported.*Windows|Unix.only/i); +test("Windows: status/drain/resume reach the real daemon over its pipe; a duplicate is refused and a crash leaves no live control", { skip: process.platform !== "win32" && "Windows named-pipe CLI control" }, async (t) => { + const f = controlFixture(t); + const daemon = launchHost(t, f.env); + let status = await controlReady(f.env); + assert.equal(status.pid, daemon.child.pid); + assert.equal(status.drained, false); + for (const [command, drained] of [["drain", true], ["status", true], ["resume", false]]) { + const answer = await hostCommand(f.env, command); + assert.equal(answer.code, 0, answer.stderr); + assert.equal(JSON.parse(answer.stdout).drained, drained); } + const duplicate = await hostCommand(f.env); + assert.equal(duplicate.code, 1, duplicate.stderr); + assert.match(duplicate.stderr, /already running/); + // Windows terminates without running handlers: the descriptor stays, but nothing answers on its pipe. + daemon.child.kill(); + await daemon.closed; + assert.equal((await hostCommand(f.env, "status")).code, 1, "status must not start a replacement daemon"); + const restarted = launchHost(t, f.env); + status = await controlReady(f.env); + assert.equal(status.pid, restarted.child.pid, "a stale descriptor is replaced by the next daemon"); }); -test("worker maintenance startup is drained before linking and can be explicitly resumed", unixControl, async (t) => { +test("worker maintenance startup is drained before linking and can be explicitly resumed", async (t) => { const f = controlFixture(t); const daemon = launchHost(t, { ...f.env, OMP_WEB_HOST_DRAINED: "1" }); - const { hostControlPath } = await import("../lib/hosts/host-control.ts"); - t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); + if (process.platform !== "win32") { + const { hostControlPath } = await import("../lib/hosts/host-control.ts"); + t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); + } const status = await controlReady(f.env); assert.equal(status.pid, daemon.child.pid); assert.equal(status.drained, true); 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/capacity.test.mjs b/lib/hosts/capacity.test.mjs index cf4a8e800..d8fcffdf2 100644 --- a/lib/hosts/capacity.test.mjs +++ b/lib/hosts/capacity.test.mjs @@ -331,3 +331,45 @@ test("the sampler combines leaf and ancestor limits using each ancestor's own me }, ]); }); + +test("Windows samples OS CPU times and available memory without /proc, cgroups or a load average", () => { + const cpu = (busy, idle) => ({ times: { user: busy - 10, nice: 0, sys: 6, irq: 4, idle } }); + const steps = [ + { cpus: [cpu(100, 900), cpu(100, 900)], free: 8 * GiB }, + { cpus: [cpu(160, 940), cpu(140, 960)], free: 6 * GiB, activeSessions: 1 }, + { cpus: [], free: 6 * GiB }, + { cpus: [cpu(200, 1000), cpu(200, 1000)], free: 5 * GiB }, + { cpus: [cpu(230, 1070), cpu(230, 1070)], free: 5 * GiB, activeSessions: 4 }, + ]; + const script = ` + const os = require("node:os"); + const fs = require("node:fs"); + const { syncBuiltinESMExports } = require("node:module"); + const steps = ${JSON.stringify(steps)}; + let step; + Object.defineProperty(process, "platform", { value: "win32" }); + const readFileSync = fs.readFileSync; + fs.readFileSync = (path, ...args) => { + if (typeof path === "string" && (path.startsWith("/proc/") || path.startsWith("/sys/"))) throw new Error("Windows must not read " + path); + return readFileSync(path, ...args); + }; + os.cpus = () => step.cpus; + os.freemem = () => step.free; + os.availableParallelism = () => 2; + os.loadavg = () => { throw new Error("Windows has no load average"); }; + syncBuiltinESMExports(); + const { sampleHostCapacity } = await import(${JSON.stringify(new URL("./capacity.ts", import.meta.url).href)}); + const samples = []; + for (step of steps) samples.push(sampleHostCapacity(step.activeSessions ?? 0)); + console.log(JSON.stringify(samples)); + `; + const child = spawnSync(process.execPath, ["--eval", script], { encoding: "utf8", timeout: 10_000 }); + assert.equal(child.status, 0, child.stderr || child.error?.message); + assert.deepEqual(JSON.parse(child.stdout), [ + null, + { effectiveCpus: 2, load1: 0, busyFraction: 0.5, stealFraction: 0, availableMemoryBytes: 6 * GiB, activeSessions: 1 }, + null, + null, + { effectiveCpus: 2, load1: 0, busyFraction: 0.3, stealFraction: 0, availableMemoryBytes: 5 * GiB, activeSessions: 4 }, + ]); +}); diff --git a/lib/hosts/capacity.ts b/lib/hosts/capacity.ts index b6366c5e1..dc53ff335 100644 --- a/lib/hosts/capacity.ts +++ b/lib/hosts/capacity.ts @@ -1,5 +1,5 @@ import { readFileSync } from "node:fs"; -import { availableParallelism, loadavg } from "node:os"; +import { availableParallelism, cpus, freemem, loadavg } from "node:os"; import { posix } from "node:path"; export interface HostCapacity { @@ -163,8 +163,28 @@ function readOptional(path: string): string | undefined { let previousCounters: CpuCounters | null = null; +/** Windows has no /proc or cgroups: Node reads per-CPU times and available physical memory from the OS. + * shortcut: Job Object CPU/memory limits are not applied; read them if Windows workers ever run inside a job. */ +function windowsSample(): { current: CpuCounters; resources: EffectiveResources } | null { + let busy = 0, idle = 0; + for (const { times } of cpus()) { + busy += times.user + times.nice + times.sys + times.irq; + idle += times.idle; + } + const available = freemem(); + if (!Number.isSafeInteger(busy) || !Number.isSafeInteger(idle) || busy + idle <= 0 || !Number.isSafeInteger(available)) return null; + return { current: { busy, idle, steal: 0 }, resources: { effectiveCpus: availableParallelism(), availableMemoryBytes: available } }; +} + /** Samples shared host counters; callers supply active turns, not saved sessions. */ export function sampleHostCapacity(activeSessions: number): HostCapacity | null { + if (process.platform === "win32") { + const sample = windowsSample(); + // Windows reports no load average; busyFraction carries the CPU pressure there. + const capacity = sample ? capacityFromInterval(previousCounters, sample.current, sample.resources, 0, activeSessions) : null; + previousCounters = sample?.current ?? null; + return capacity; + } if (process.platform !== "linux") return null; try { const current = parseProcStat(readFileSync("/proc/stat", "utf8")); 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/host-cli.ts b/lib/hosts/host-cli.ts index 5e5464b45..5a5e7c507 100644 --- a/lib/hosts/host-cli.ts +++ b/lib/hosts/host-cli.ts @@ -71,8 +71,7 @@ async function main(argv: string[]): Promise { // Login/logout need none of the daemon, which jiti would otherwise transpile on every run. const { runHostDaemon } = await import("./daemon"); let daemon: HostDaemon | undefined; - // Windows ordinary standalone hosts retain their existing startup path. - const endpoint = process.platform === "win32" ? null : await createHostControlServer((command) => { + const endpoint = await createHostControlServer((command) => { if (!daemon) throw new Error("The host daemon is starting"); return daemon.control(command); }); diff --git a/lib/hosts/host-control.test.mjs b/lib/hosts/host-control.test.mjs index c0d063f1f..106383825 100644 --- a/lib/hosts/host-control.test.mjs +++ b/lib/hosts/host-control.test.mjs @@ -6,10 +6,11 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; -import { createHostControlServer, hostControlPath, requestHostControl } from "./host-control.ts"; +import { createHostControlServer, hostControlDescriptorPath, hostControlPath, requestHostControl } from "./host-control.ts"; import { runHostDaemon } from "./daemon.ts"; -const unixOnly = { skip: process.platform === "win32" && "Local worker control is Unix-only; ordinary Windows hosts remain supported" }; +const unixOnly = { skip: process.platform === "win32" && "Unix socket ownership and permissions; Windows uses the named-pipe tests below" }; +const windowsOnly = { skip: process.platform !== "win32" && "Windows named-pipe control" }; async function until(check, label) { const deadline = Date.now() + 10_000; @@ -22,7 +23,7 @@ async function until(check, label) { function fixture(t) { const scratch = mkdtempSync(join(tmpdir(), "ompweb-host-control-")); const agent = join(scratch, "agent"); - const path = hostControlPath(agent); + const path = process.platform === "win32" ? null : hostControlPath(agent); const saved = { agent: process.env.PI_CODING_AGENT_DIR, omp: process.env.OMP_WEB_OMP_BIN }; process.env.PI_CODING_AGENT_DIR = agent; process.env.OMP_WEB_OMP_BIN = join(scratch, "missing-omp"); @@ -34,7 +35,7 @@ function fixture(t) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } - rmSync(dirname(path), { recursive: true, force: true }); + if (path) rmSync(dirname(path), { recursive: true, force: true }); rmSync(scratch, { recursive: true, force: true }); }); return { scratch, agent, path, daemon }; @@ -46,7 +47,8 @@ async function rawRequest(path, input) { let text = ""; socket.setTimeout(2000, () => socket.destroy(new Error("local control response timed out"))); socket.on("error", reject); - socket.on("connect", () => socket.end(input)); + // Write, not end: Windows named pipes cannot half-close, which drops the reply. + socket.on("connect", () => socket.write(input)); socket.on("data", (chunk) => { text += chunk; }); socket.on("end", () => resolve(text)); }); @@ -210,3 +212,68 @@ test("losing a real resume response does not undo admission or permit the caller await until(() => !f.daemon.control("status").drained, "the real resume despite its lost response"); assert.equal((await requestHostControl("status", f.agent)).drained, false); }); + +test("Windows: a real daemon is controlled through a random named pipe and a per-start token", windowsOnly, async (t) => { + const f = fixture(t); + const server = await createHostControlServer(f.daemon.control, f.agent); + t.after(() => server.close()); + assert.match(server.path, /^\\\\\.\\pipe\\ompweb-host-[0-9a-f]{32}$/); + const descriptor = JSON.parse(readFileSync(hostControlDescriptorPath(f.agent), "utf8")); + assert.equal(descriptor.pipe, server.path); + assert.match(descriptor.token, /^[A-Za-z0-9_-]{43}$/); + const status = await requestHostControl("status", f.agent); + assert.equal(status.pid, process.pid); + assert.equal(JSON.stringify(status).includes("must-not-appear-in-status"), false); + assert.equal((await requestHostControl("drain", f.agent)).drained, true); + assert.equal(f.daemon.control("status").drained, true, "the pipe changes the actual daemon, not an echo fixture"); + assert.equal((await requestHostControl("resume", f.agent)).drained, false); + await server.close(); + assert.equal(existsSync(hostControlDescriptorPath(f.agent)), false); + await assert.rejects(rawRequest(descriptor.pipe, '{"command":"status"}\n'), (error) => error.code === "ENOENT"); +}); + +test("Windows: requests without the current token cannot change daemon admission", windowsOnly, async (t) => { + const f = fixture(t); + const server = await createHostControlServer(f.daemon.control, f.agent); + t.after(() => server.close()); + const { token } = JSON.parse(readFileSync(hostControlDescriptorPath(f.agent), "utf8")); + const wrong = (token[0] === "A" ? "B" : "A") + token.slice(1); + for (const line of ['{"command":"drain"}\n', `{"command":"drain","token":"${wrong}"}\n`, `{"command":"drain","token":"${token}","extra":1}\n`, '{"command":"drain","token":7}\n']) { + const reply = JSON.parse(await rawRequest(server.path, line)); + assert.equal(reply.ok, false, line); + assert.equal(f.daemon.control("status").drained, false, line); + } + assert.equal(JSON.parse(await rawRequest(server.path, `{"command":"drain","token":"${token}"}\n`)).status.drained, true); +}); + +test("Windows: a second start refuses the live pipe and keeps its descriptor; a stale descriptor is replaced", windowsOnly, async (t) => { + const f = fixture(t); + const file = hostControlDescriptorPath(f.agent); + const server = await createHostControlServer(f.daemon.control, f.agent); + const live = readFileSync(file, "utf8"); + await assert.rejects(createHostControlServer(f.daemon.control, f.agent), /already running/); + assert.equal(readFileSync(file, "utf8"), live); + assert.equal((await requestHostControl("status", f.agent)).pid, process.pid); + await server.close(); + // A crashed daemon leaves its descriptor behind; nothing answers on its pipe. + writeFileSync(file, live); + const replacement = await createHostControlServer(f.daemon.control, f.agent); + t.after(() => replacement.close()); + assert.notEqual(replacement.path, JSON.parse(live).pipe); + assert.equal((await requestHostControl("status", f.agent)).pid, process.pid); +}); + +test("Windows: clients never connect to a pipe outside the descriptor contract", windowsOnly, async (t) => { + const f = fixture(t); + const file = hostControlDescriptorPath(f.agent); + await assert.rejects(requestHostControl("status", f.agent), /No host daemon is running/); + const decoy = createServer((socket) => { socket.destroy(); assert.fail("the client connected to a decoy pipe"); }); + const listened = Promise.withResolvers(); + decoy.listen("\\\\.\\pipe\\decoy-" + process.pid, listened.resolve); + await listened.promise; + t.after(() => decoy.close()); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify({ pipe: "\\\\.\\pipe\\decoy-" + process.pid, token: "x".repeat(43) })); + await assert.rejects(requestHostControl("drain", f.agent), /Invalid host control descriptor/); + assert.equal(f.daemon.control("status").drained, false); +}); diff --git a/lib/hosts/host-control.ts b/lib/hosts/host-control.ts index 1903f4bce..6e6d363c3 100644 --- a/lib/hosts/host-control.ts +++ b/lib/hosts/host-control.ts @@ -1,7 +1,10 @@ // Private local maintenance on the existing host process; no web credentials or TCP listener. -import { createHash, randomBytes } from "node:crypto"; -import { chmodSync, linkSync, lstatSync, mkdirSync, realpathSync, unlinkSync, type Stats } from "node:fs"; -import { createConnection, createServer } from "node:net"; +// Unix: an owned 0600 socket in a 0700 directory. Windows: a named pipe, whose default DACL lets other +// local users connect and whose name anyone may claim first, so the pipe name is random per start and every +// request carries a per-start token; both live only in a descriptor file in this user's agent directory. +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { chmodSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, type Stats } from "node:fs"; +import { createConnection, createServer, type Server } from "node:net"; import { basename, dirname, join, resolve } from "node:path"; import { getAgentDir } from "../omp/paths"; @@ -19,6 +22,41 @@ const MAX_MESSAGE = 4096; const errno = (error: unknown) => (error as NodeJS.ErrnoException)?.code; const unix = () => { if (process.platform === "win32") throw new Error("Local host control is Unix-only; it is not supported on Windows"); }; const command = (value: unknown): value is HostControlCommand => value === "status" || value === "drain" || value === "resume"; +const PIPE_RE = /^\\\\\.\\pipe\\ompweb-host-[0-9a-f]{32}$/; +const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/; +const digest = (value: string) => createHash("sha256").update(value).digest(); + +/** The Windows endpoint descriptor: the current pipe name and token, in this user's agent directory. */ +export function hostControlDescriptorPath(agentDir = getAgentDir()): string { + return join(agentDir, "omp-web", "host-control.json"); +} + +function readDescriptor(file: string): { pipe: string; token: string } | null { + let text: string; + try { + const stat = lstatSync(file); + if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("Unsafe host control descriptor: not a regular file"); + text = readFileSync(file, "utf8"); + } catch (error) { + if (errno(error) === "ENOENT") return null; + throw error; + } + const value: unknown = JSON.parse(text); + if (!value || typeof value !== "object" || !("pipe" in value) || !("token" in value) + || typeof value.pipe !== "string" || typeof value.token !== "string" || !PIPE_RE.test(value.pipe) || !TOKEN_RE.test(value.token)) { + throw new Error("Invalid host control descriptor"); + } + return { pipe: value.pipe, token: value.token }; +} + +/** True when something answers on `pipe`; a missing pipe means its daemon is gone. */ +function answering(pipe: string): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const socket = createConnection(pipe); + socket.once("connect", () => { socket.destroy(); resolve(true); }); + socket.once("error", (error) => errno(error) === "ENOENT" ? resolve(false) : reject(error)); + return promise; +} /** Resolve existing prefixes so /var and /private/var name the same agent, even before it is created. */ function canonical(path: string): string { @@ -65,20 +103,9 @@ async function refused(path: string): Promise { }); } -export async function createHostControlServer(control: (command: HostControlCommand) => HostControlStatus, agentDir = getAgentDir()): Promise<{ path: string; close(): Promise }> { - const path = hostControlPath(agentDir); - const dir = dirname(path); - try { mkdirSync(dir, { mode: 0o700 }); } catch (error) { if (errno(error) !== "EEXIST") throw error; } - owned(dir, "directory", 0o700); - try { - const stale = owned(path, "socket", 0o600); - await refused(path); - const current = owned(path, "socket", 0o600); - if (!same(stale, current)) throw new Error("Host control endpoint changed during stale recovery"); - unlinkSync(path); - } catch (error) { if (errno(error) !== "ENOENT") throw error; } - - const server = createServer((socket) => { +/** One newline-terminated JSON request, one reply. With `token`, the request must carry exactly that token. */ +function controlServer(control: (command: HostControlCommand) => HostControlStatus, token?: string): Server { + return createServer((socket) => { let input = ""; let answered = false; socket.setTimeout(3000, () => socket.destroy()); @@ -91,13 +118,78 @@ export async function createHostControlServer(control: (command: HostControlComm answered = true; try { const request: unknown = JSON.parse(input.trim()); - if (!request || typeof request !== "object" || Array.isArray(request) || Object.keys(request).length !== 1 || !("command" in request) || !command(request.command)) throw new Error("Invalid host control command"); + if (!request || typeof request !== "object" || Array.isArray(request) || !("command" in request) || !command(request.command) + || Object.keys(request).length !== (token === undefined ? 1 : 2)) throw new Error("Invalid host control command"); + if (token !== undefined && !("token" in request && typeof request.token === "string" && timingSafeEqual(digest(request.token), digest(token)))) { + throw new Error("Invalid host control token"); + } socket.end(JSON.stringify({ ok: true, status: control(request.command) }) + "\n"); } catch (error) { socket.end(JSON.stringify({ ok: false, error: { code: errno(error) || "invalid_control", message: error instanceof Error ? error.message : "Host control failed" } }) + "\n"); } }); }); +} + +async function createWindowsHostControlServer(control: (command: HostControlCommand) => HostControlStatus, agentDir: string): Promise<{ path: string; close(): Promise }> { + const file = hostControlDescriptorPath(agentDir); + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const previous = readDescriptor(file); + if (previous) { + if (await answering(previous.pipe)) throw new Error("A host daemon is already running"); + // Remove only the stale descriptor just inspected; another starter's replacement is never touched. + if (readDescriptor(file)?.token === previous.token) unlinkSync(file); + } + const pipe = `\\\\.\\pipe\\ompweb-host-${randomBytes(16).toString("hex")}`; + const token = randomBytes(32).toString("base64url"); + const server = controlServer(control, token); + const listened = Promise.withResolvers(); + server.once("error", listened.reject); + server.listen(pipe, listened.resolve); + await listened.promise; + // Publish by exclusive hard link so readers never see a partial file and two starters cannot both win. + const temporary = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`; + try { + writeFileSync(temporary, JSON.stringify({ pipe, token }) + "\n", { flag: "wx", mode: 0o600 }); + try { linkSync(temporary, file); } + catch (error) { throw errno(error) === "EEXIST" ? new Error("A host daemon is already running") : error; } + } catch (error) { + const closed = Promise.withResolvers(); + server.close(() => closed.resolve()); + await closed.promise; + throw error; + } finally { + try { unlinkSync(temporary); } catch (error) { if (errno(error) !== "ENOENT") throw error; } + } + let closing: Promise | undefined; + return { + path: pipe, + close: () => { + if (closing) return closing; + const { promise, resolve, reject } = Promise.withResolvers(); + closing = promise; + try { if (readDescriptor(file)?.token === token) unlinkSync(file); } catch (error) { if (errno(error) !== "ENOENT") reject(error); } + server.close(() => resolve()); + return promise; + }, + }; +} + +export async function createHostControlServer(control: (command: HostControlCommand) => HostControlStatus, agentDir = getAgentDir()): Promise<{ path: string; close(): Promise }> { + if (process.platform === "win32") return createWindowsHostControlServer(control, agentDir); + const path = hostControlPath(agentDir); + const dir = dirname(path); + try { mkdirSync(dir, { mode: 0o700 }); } catch (error) { if (errno(error) !== "EEXIST") throw error; } + owned(dir, "directory", 0o700); + try { + const stale = owned(path, "socket", 0o600); + await refused(path); + const current = owned(path, "socket", 0o600); + if (!same(stale, current)) throw new Error("Host control endpoint changed during stale recovery"); + unlinkSync(path); + } catch (error) { if (errno(error) !== "ENOENT") throw error; } + + const server = controlServer(control); // Bind privately, then publish an exclusive hard link. libuv unlinks its bind name on close; // it must never own the public name, which another process could replace before cleanup. const temporary = join(dir, `bind-${randomBytes(6).toString("hex")}.sock`); @@ -124,15 +216,26 @@ export async function createHostControlServer(control: (command: HostControlComm export async function requestHostControl(value: HostControlCommand, agentDir = getAgentDir()): Promise { if (!command(value)) throw new Error("Invalid host control command"); - const path = hostControlPath(agentDir); - owned(dirname(path), "directory", 0o700); - owned(path, "socket", 0o600); + let path: string; + let request: string; + if (process.platform === "win32") { + // Only a pipe named in this user's descriptor; never a guessed or caller-supplied one. + const descriptor = readDescriptor(hostControlDescriptorPath(agentDir)); + if (!descriptor) throw Object.assign(new Error("No host daemon is running for this agent directory"), { code: "ENOENT" }); + path = descriptor.pipe; + request = JSON.stringify({ command: value, token: descriptor.token }); + } else { + path = hostControlPath(agentDir); + owned(dirname(path), "directory", 0o700); + owned(path, "socket", 0o600); + request = JSON.stringify({ command: value }); + } return new Promise((resolve, reject) => { const socket = createConnection(path); let text = ""; socket.setTimeout(3000, () => socket.destroy(new Error("Host control response timed out"))); socket.once("error", reject); - socket.once("connect", () => socket.write(JSON.stringify({ command: value }) + "\n")); + socket.once("connect", () => socket.write(request + "\n")); socket.on("data", (bytes) => { text += bytes.toString("utf8"); if (Buffer.byteLength(text) > MAX_MESSAGE) socket.destroy(new Error("Host control response is too large")); 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, {