diff --git a/README.md b/README.md index 230c3f4f..635050a9 100644 --- a/README.md +++ b/README.md @@ -1298,6 +1298,41 @@ arrive together, it takes a third; a repeated Ctrl-C, which Just does not forward, kills at the second. There is no timeout except `--quick`'s: any other command waits its turn for as long as the host stays busy. +### Record each run + +A process that starts an agent, such as a job runner or a CPU audit, can read +back what the agent's gated commands waited for by setting `QUEST_GATE_RECORD` +in the agent's environment to an absolute path. Every outermost `quest gate` +run on Linux or macOS, including those the agent's parallel shells and +subagents start, then appends one JSON line to that file, however the run ends: + +```json +{"command":["cargo","test"],"directory":"/home/me/src/app","started":"2026-11-12T19:40:01.120Z","admitted":"2026-11-12T19:40:31.452Z","unit":"quest-gate-0d6c3f9e-5a51-4c1b-9d0e-2f4b8a7c6e10.scope","exit":0,"cancelled":false,"error":null} +``` + +- `started` and `admitted` give the wait. A run cancelled before admission has + a null `admitted`. +- `unit` is the command's systemd user scope, null where the gate owns it + another way, such as on macOS. Once the scope ends, systemd logs + `: Consumed 1.386s CPU time over 1.357s wall clock time, 8.1M memory + peak.` to the user journal (`journalctl --user -u `) at info level when + the scope used a notable amount, such as a second of CPU, and at debug level + otherwise. The memory peak needs systemd 255 and Linux 5.19. +- `exit` is the status the gate returns, `cancelled` whether it was cancelled, + and `error` the gate's own failure, such as a scope it cannot confirm + stopped. + +Each line is one write to a file opened for appending, so concurrent gates +leave only whole lines; give each agent its own file to tell them apart. Nested +gates write nothing, since their command runs inside their outermost gate's. +An unset or empty variable writes nothing, a relative path or a symlink is +refused, and a file the gate cannot open fails it before the command runs. A +new file is readable only by its user. A line it cannot write fails the gate +too, except that a cancelled run exits as it would have without the record. +Windows refuses the variable, since it cannot refuse a symlink atomically. +The agent's own processes write the file, so a record is only as trustworthy +as the agent. + ## Route work by size `quest` ranks the harnesses, models, and efforts that write work of each size, diff --git a/quest/m0/gate-record.md b/quest/m0/gate-record.md deleted file mode 100644 index 81064006..00000000 --- a/quest/m0/gate-record.md +++ /dev/null @@ -1,112 +0,0 @@ -# [M] The gate records each run for the process that started the agent - -## Goal - -When `QUEST_GATE_RECORD` names a file, every outermost `quest gate` run -on Linux or macOS appends one JSON line to it, however the run ends, -with the command, its directory, how long it waited for admission, its -CPU time, wall time, peak memory, and exit status. When it is unset, the -gate writes nothing. - -A process that starts an agent, such as a job runner or a CPU audit, -sets the variable in that agent's environment and reads back what the -agent's gated commands waited for and cost, including those its parallel -shells and subagents ran. Today that takes matching agent transcripts -against systemd journal lines, which hold no wait time and exist only on -Linux. - -Non-goals: how the gate admits commands; Windows, which -[its own quest](/quest/m1/gate-record-windows.md) covers; and any view of -the record in Quest itself. - -## Plan - -Decided 2026-11-12 (maintainer, `/quest-plan`): - -- ✅ An environment variable names the file, and the reader owns it - (rejected: every gate always appending to a per-host log under - Quest's cache directory, tagged with an ID the reader filters by, - which needs rotation and retention for history nothing reads). A - reader that wants each agent apart gives each agent its own file. -- ✅ Linux and macOS here, Windows in m1 (rejected: Windows here too, - since m0 leaves native Windows and its suite to m1; recording only - wait, wall time, and exit status on Windows with no plan for the - rest). The first answer was every platform; review found Windows - conflicts with m0's scope and needs a new channel out of the job stub, - so the maintainer split it. -- ✅ Where the gate owns the command only as a process group (macOS, and - Linux without a systemd user manager), record a labeled lower bound: - the CPU of the processes the gate reaped, and the largest single - process's peak memory (rejected: sampling the group every few seconds, - which costs more code and still misses short-lived processes). The - README says these exclude processes the gate kills at the end, such as - a leftover background server. -- ✅ Only outermost runs are recorded. A gate inside an admitted command - (`QUEST_GATE_ADMITTED`) runs at once and is measured as part of it, - so recording it too would count its CPU twice. -- ✅ m0 (rejected: m1), with the rest of the gate's work. - -Agent's choices, for the implementer to revisit: - -- One line per run: `command` (argv), `directory` (absolute), `started`, - `admitted` (null when the run never was), and `ended` as ISO - timestamps, `cpuMs`, `peakMemory` in bytes (null when the host cannot - say), `measured` (`cgroup` or `children`, naming the source above; the - Windows quest adds `job`), - `exit` (the status the gate returns, 128 plus the signal's number for - a signalled command, as the owners already map it), `cancelled`, and - `error` (the gate's own failure, such as a command that cannot start - or a scope it cannot confirm stopped). Wait and wall time follow from - the timestamps. Nothing is in production, so the format carries no - version. -- `ended` is when the command's own process exits, before the gate stops - descendants it left behind, so cleanup does not count as wall time. -- On Linux with a systemd scope, the counters must outlive the command: - the scope runs with `--collect`, and `vacated` in - `src/cli/supervise.ts` already succeeds when systemd has removed the - emptied cgroup, so a read after the command's tree exits can find - nothing, and the 5-second CPU samples miss a short command and the - last interval. Recommended: the handshake shell stays in the scope as - a holder instead of becoming the command, and runs the command in a - child cgroup of the scope, which is delegated (`Delegate=yes`) with no - controllers enabled below it, so the scope's own `cpu.stat` - `usage_usec` and `memory.peak` cover everything the command started. - The owner stops the command's leftovers with the child's - `cgroup.kill`, reads the scope's counters while the holder keeps it - populated, then releases the holder and returns the counters with the - exit status. The holder writes the command's exit status and the time - it exited to the handshake's report pipe as soon as the command exits, - since the owner otherwise sees only the holder's exit, after cleanup. An implementer may prove another way instead, such as - holding a D-Bus reference to the unit and reading systemd's - `CPUUsageNSec` and `MemoryPeak`; the short-command test below decides. - `memory.peak` needs Linux 5.19, so on 5.14 to 5.18 `peakMemory` is - null. -- On a process group, `cpuMs` and `peakMemory` come from the command's - rusage at exit, which `wait4` reports for it and the descendants it - waited for. Node's `child_process` exposes none; Bun's - `Subprocess.resourceUsage()` does, so the group owner may need to - start its command through `Bun.spawn`. -- Append each line in one write to a file opened for append, since an - agent's parallel shells and subagents share it. -- A cancelled run, including one cancelled while waiting for admission, - still writes its line. A line that cannot be written fails the gate: - it names the file on stderr and exits nonzero, keeping a cancellation's - status when the run was cancelled. -- The record holds what the agent's own processes wrote. The agent's - shell already has the variable and can write the file directly, so - removing it from gated commands' environment would protect nothing; - the README says a record is as trustworthy as the agent. -- Document the variable, the line format, and what each platform counts - in the README's gate section. - -Tests: an outermost run under the variable appends one line whose wait, -CPU, wall time, and exit match a stub command's, including one that ends -before the first CPU sample; a nested gate adds none; an unset variable -writes nothing; a run cancelled while queued for admission is recorded -with no admission; an unwritable file fails the gate; a process group's -line is labeled `children`; and concurrent gates leave only whole lines. - -## Hosts - -- linux - the systemd scope's cgroup accounting -- macos - the process group's rusage diff --git a/quest/m0/review-login-flake.md b/quest/m0/review-login-flake.md new file mode 100644 index 00000000..5f4d5678 --- /dev/null +++ b/quest/m0/review-login-flake.md @@ -0,0 +1,11 @@ +# [S] Fix the flaky logged-out review test + +## Goal + +`test/review.test.ts`'s "a login the API rejects fails as logged out" passes on every run, with the flake's root cause fixed rather than retried or skipped. + +## Plan + +- Known: during validation of [#685](https://github.com/moq-dev/quest/pull/685), a full `just test` run failed this test once; it then passed three reruns. #685 does not touch the code it covers. +- Reproduce it first, such as by running the test in a loop or under the full suite's load, then fix the cause in the test or the code it exercises. +- The maintainer chose: ✅ add a quest to reproduce the flake and fix it at the root cause (rejected: plan it only if it recurs). diff --git a/quest/m1/gate-record-windows.md b/quest/m1/gate-record-windows.md deleted file mode 100644 index 5565b6fb..00000000 --- a/quest/m1/gate-record-windows.md +++ /dev/null @@ -1,37 +0,0 @@ -# [M] The gate's run record on Windows - -## Goal - -On Windows, `QUEST_GATE_RECORD` works as it does on Linux and macOS: each -outermost `quest gate` run appends one line, with CPU time and peak -memory taken from the Job Object that owns the command and everything it -starts. - -## Plan - -Decided 2026-11-12 (maintainer, `/quest-plan`): split from the -[gate run record](/quest/m0/gate-record.md), since m0 leaves native -Windows and its suite to m1. - -The Job Object lives in the Bun stub that `src/cli/job.ts` runs, and it -ends with the stub, so the gate never holds it. The stub reads the job's -basic accounting (total user and kernel time) and its peak job memory -once the command exits, before it closes the handle, and passes them to -the gate over a channel of its own, such as an extra pipe, keeping the -command's stdio untouched. Its line's `measured` is `job`, since the -job covers everything the command started. Without a job, which the stub -only warns about today, the line carries `children` from the stub's own -child, as on a process group. - -Tests, in the native Windows suite: a stub command's line carries its -CPU and peak memory, a grandchild's CPU counts toward it, and a run -without a job is labeled `children`. - -## Hosts - -- windows - the Job Object accounting - -## Required - -- [Gate run record](/quest/m0/gate-record.md) - the variable, the line - format, and the Linux and macOS measurement this extends diff --git a/src/cli/gate.ts b/src/cli/gate.ts index 4e20fa73..7ee4c2c5 100644 --- a/src/cli/gate.ts +++ b/src/cli/gate.ts @@ -3,9 +3,22 @@ // the command's descendants until they stop, and holds nothing else while it runs. import { spawn, spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { + closeSync, + constants as fs, + linkSync, + lstatSync, + mkdirSync, + openSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, + writeSync, +} from "node:fs"; import { availableParallelism, constants, cpus, hostname, loadavg, totalmem, userInfo } from "node:os"; -import { dirname, join, relative, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import type { Readable } from "node:stream"; import { setTimeout as sleep } from "node:timers/promises"; import { type Cancellation, cancelled, follow, forwards, GROUP, interrupts, received, requested } from "./interrupt"; @@ -819,59 +832,163 @@ const notices: Record = { queue: "quest gate: waiting for commands queued earlier to start", }; +/** + * Names a file to which every outermost gate appends one JSON line describing its run, however it + * ends (see `gate`). A nested gate runs inside a command its outermost gate already covers. + */ +const RECORD = "QUEST_GATE_RECORD"; + +/** Open the file `RECORD` names for appending, before anything runs; undefined while it is unset or empty. */ +function recordFile(env: NodeJS.ProcessEnv): { path: string; fd: number } | undefined { + const path = env[RECORD]; + if (!path) return undefined; + // Windows has no O_NOFOLLOW, and no reader there yet. + if (process.platform === "win32") throw new Error(`gate cannot record its run on Windows (${RECORD})`); + // The command's shells change directory, so a relative path would scatter one reader's lines. + if (!isAbsolute(path)) throw new Error(`${RECORD} must be an absolute path: ${path}`); + try { + // Private to the user, and never through a symlink someone else planted at a shared path. + const flags = fs.O_WRONLY | fs.O_APPEND | fs.O_CREAT | fs.O_NOFOLLOW; + return { path, fd: openSync(path, flags, 0o600) }; + } catch (error) { + throw new Error(`gate cannot record its run in ${path}: ${message(error)}`); + } +} + +const message = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +/** How `gate` admits its command. */ +export interface GateOptions { + /** Wait at most QUICK_MS (see `Precedence`). */ + quick?: boolean; + /** The admission ledger and host measures; this user's on this host when omitted. */ + host?: Host; +} + +/** What one gate observed of its run, for its record. */ +interface Observed { + /** Wall-clock milliseconds when the command was admitted. */ + admitted?: number; + /** The systemd scope the command ran in, whose journal lines hold its CPU time and peak memory. */ + unit?: string; +} + /** * Run from the CLI. A failure to measure the command is fatal even when the command succeeded, * since every other gate on the host relies on that accounting; a cancelled command still - * reports its cancellation. + * reports its cancellation. With `RECORD` set, an outermost gate appends its run's line in one + * write, so concurrent gates leave only whole lines; a line it cannot write fails the gate, except + * that a cancelled run keeps its cancelled status. */ -export async function gate(command: string[], options: { quick?: boolean } = {}): Promise { +export async function gate(command: string[], options: GateOptions = {}): Promise { + const outermost = process.env[ADMITTED] !== "1"; + const record = outermost ? recordFile(process.env) : undefined; + const started = Date.now(); + // Read now: the command may remove its own directory. + const directory = record ? process.cwd() : ""; const cancel = interrupts(); + const observed: Observed = {}; try { - const { run, unit } = owner(); - let admitted: { host: Host; id: string } | undefined; - // A nested invocation executes inside the already admitted command. - if (process.env[ADMITTED] !== "1") { - const shown = new Set(); - try { - const notice = (reason: Waiting) => { - if (shown.has(reason)) return; - shown.add(reason); - process.stderr.write(`${notices[reason]}\n`); - }; - const precedence = { - priority: process.env[PRIORITY] === "1", - quick: options.quick, - }; - const host = fileHost(claimDirectory()); - admitted = { host, id: await admit(hostLimits(), host, cancel.signal, notice, precedence) }; - } catch (error) { - if (cancel.signal.aborted) return cancelled(cancel.signal); - throw error; - } + let status: number; + let failure: unknown; + try { + status = await gated(command, options, outermost, cancel, observed); + } catch (error) { + failure = error; + // The status the CLI exits with for a gate's own failure. + status = 1; + } + if (!record) { + if (failure !== undefined) throw failure; + return status; } - const stop = new AbortController(); - // Held as a value until the command ends, so a failure never goes unhandled meanwhile. - const measuring = - admitted !== undefined && unit !== undefined - ? measure(admitted.host, { id: admitted.id, unit }, stop.signal).then( - () => undefined, - (error: unknown) => ({ error }), - ) - : undefined; - let result: number; - const env: NodeJS.ProcessEnv = { ...process.env, [ADMITTED]: "1" }; - // mbx otherwise takes its configured priority, which agents' hosts may lower. - if (process.env[PRIORITY] === "1") env.MBX_SCHEDULER_PRIORITY ??= "normal"; + const iso = (ms: number) => new Date(ms).toISOString(); + const line = Buffer.from( + `${JSON.stringify({ + command, + directory, + started: iso(started), + admitted: observed.admitted === undefined ? null : iso(observed.admitted), + unit: observed.unit ?? null, + exit: status, + cancelled: cancel.signal.aborted, + error: failure === undefined ? null : message(failure), + })}\n`, + ); try { - result = await run(command, env, cancel); + const written = writeSync(record.fd, line); + if (written !== line.length) throw new Error(`wrote ${written} of ${line.length} bytes`); + } catch (error) { + const unrecorded = `gate cannot record its run in ${record.path}: ${message(error)}`; + // A cancelled run exits as it would have, recorded or not. + if (cancel.signal.aborted) { + process.stderr.write(`quest ${unrecorded}\n`); + if (failure !== undefined) throw failure; + return status; + } + throw new Error(failure === undefined ? unrecorded : `${message(failure)}; ${unrecorded}`); } finally { - stop.abort(); + closeSync(record.fd); } - const failed = await measuring; - if (cancel.signal.aborted) return cancelled(cancel.signal); - if (failed) throw failed.error; - return result; + if (failure !== undefined) throw failure; + return status; } finally { cancel.close(); } } + +/** Admit the command unless nested, then run it, noting what the record needs in `observed`. */ +async function gated( + command: string[], + options: GateOptions, + outermost: boolean, + cancel: ReturnType, + observed: Observed, +): Promise { + const { run, unit } = owner(); + let admitted: { host: Host; id: string } | undefined; + // A nested invocation executes inside the already admitted command. + if (outermost) { + const shown = new Set(); + try { + const notice = (reason: Waiting) => { + if (shown.has(reason)) return; + shown.add(reason); + process.stderr.write(`${notices[reason]}\n`); + }; + const precedence = { + priority: process.env[PRIORITY] === "1", + quick: options.quick, + }; + const host = options.host ?? fileHost(claimDirectory()); + admitted = { host, id: await admit(hostLimits(), host, cancel.signal, notice, precedence) }; + observed.admitted = Date.now(); + } catch (error) { + if (cancel.signal.aborted) return cancelled(cancel.signal); + throw error; + } + } + const stop = new AbortController(); + // Held as a value until the command ends, so a failure never goes unhandled meanwhile. + const measuring = + admitted !== undefined && unit !== undefined + ? measure(admitted.host, { id: admitted.id, unit }, stop.signal).then( + () => undefined, + (error: unknown) => ({ error }), + ) + : undefined; + const env: NodeJS.ProcessEnv = { ...process.env, [ADMITTED]: "1" }; + // mbx otherwise takes its configured priority, which agents' hosts may lower. + if (process.env[PRIORITY] === "1") env.MBX_SCHEDULER_PRIORITY ??= "normal"; + observed.unit = unit; + let result: number; + try { + result = await run(command, env, cancel); + } finally { + stop.abort(); + } + const failed = await measuring; + if (cancel.signal.aborted) return cancelled(cancel.signal); + if (failed) throw failed.error; + return result; +} diff --git a/src/cli/main.ts b/src/cli/main.ts index bbfc2115..8a681772 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -154,11 +154,15 @@ export function main(argv: string[], out: Output): number | Promise { "MBX_SCHEDULER_PRIORITY=normal unless it sets its own.\n\n" + "Once the command exits, or is cancelled and exits, its remaining descendants are killed; a second " + "signal kills them all at once. Linux with a systemd 254+ user manager owns every descendant through " + - "a systemd user scope, or inside a Quest scope through a child cgroup of its own. macOS, and Linux " + + "a systemd user scope, inside a Quest scope one bound to it. macOS, and Linux " + "without one, own the command's process group in a new session without a controlling terminal, so a " + "descendant that leaves the group or session escapes. Windows owns every descendant through a " + "kill-on-close Job Object. Exits with the command's status, or 128 plus the signal's number once " + - "cancelled.", + "cancelled.\n\n" + + "With QUEST_GATE_RECORD naming an absolute path, an outermost gate on Linux or macOS appends one JSON " + + "line per run to that file, however the run ends: its command, directory, when it started and was " + + "admitted, its systemd scope, whose journal holds its CPU time and peak memory, and its exit status. " + + "A file it cannot write fails the gate.", ) .option("--quick", `Start a cheap command after at most ${QUICK_MS / 1000} seconds of waiting`) .argument("", "Executable to run") @@ -913,8 +917,8 @@ export function main(argv: string[], out: Output): number | Promise { .description( "Run a command in the checkout, restoring it first when released, without the repository-location " + "variables, such as GIT_DIR, that a Git hook exports. The command and its descendants " + - "run in a new, delegated systemd user scope; once the command exits, descendants still in the scope " + - "are killed. A `quest gate` inside it owns its command through a child cgroup of the scope. " + + "run in a new systemd user scope; once the command exits, descendants still in the scope " + + "are killed. A `quest gate` inside it runs its command in a scope of its own, bound to this one. " + "When no other supervised run remains, the scratch declared at creation is pruned. Put the whole job, " + "such as an agent session or a script that installs, builds, and tests, in one run.\n\n" + "A supervisor that crashes leaves its run recorded; the next worktree command drops it once its scope " + diff --git a/test/gate.test.ts b/test/gate.test.ts index 13726f79..e67a4d94 100644 --- a/test/gate.test.ts +++ b/test/gate.test.ts @@ -1503,3 +1503,149 @@ test("gate rejects unknown options before the executable and forwards flags afte expect(gateBoundary(["gate", "--unknown", "ls"])).toEqual(["gate", "--unknown", "ls"]); expect(gateBoundary(["gate", "--", "-command"])).toEqual(["gate", "--", "-command"]); }); + +describe.skipIf(process.platform === "win32")("the run record", () => { + /** A ledger of the test's own that admits at once, or never when `full`. */ + const ledger = (full = false): Host => ({ + ...fileHost(tempDir()), + load: () => 0, + memory: () => (full ? 0 : Infinity), + }); + + /** An outermost gate recording to `file`. */ + function outermost(file: string) { + vi.stubEnv("QUEST_GATE_ADMITTED", undefined); + vi.stubEnv("QUEST_GATE_PRIORITY", undefined); + vi.stubEnv("QUEST_GATE_RECORD", file); + } + + const lines = (file: string) => + readFileSync(file, "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line)); + + /** Cancel the newest gate with `name`, as its own signal handler would on receiving it. */ + function interrupt(name: NodeJS.Signals) { + (process.listeners(name).at(-1) as () => void)(); + } + + test("an outermost run appends one line with its wait, scope, and exit", async () => { + const dir = tempDir(); + const file = join(dir, "record.jsonl"); + const cgroup = join(dir, "cgroup"); + outermost(file); + const scoped = owner(process.env).unit !== undefined; + const command = ["/bin/sh", "-c", `cat /proc/self/cgroup > ${quote(cgroup)} 2>/dev/null; exit 3`]; + const before = Date.now(); + expect(await gate(command, { host: ledger() })).toBe(3); + const after = Date.now(); + const [line, ...rest] = lines(file); + expect(rest).toEqual([]); + expect(statSync(file).mode & 0o777).toBe(0o600); + expect(line).toMatchObject({ command, directory: process.cwd(), exit: 3, cancelled: false, error: null }); + const times = [before, Date.parse(line.started), Date.parse(line.admitted), after]; + expect(times).toEqual([...times].sort((a, b) => a - b)); + // The unit names the scope the command actually ran in, so a reader can find its journal lines. + if (scoped) + expect(readFileSync(cgroup, "utf8").trim()).toMatch(new RegExp(`/${line.unit.replaceAll(".", "\\.")}$`)); + else expect(line.unit).toBeNull(); + }); + + test("a nested gate records nothing, and an empty variable is unset", async () => { + const dir = tempDir(); + const file = join(dir, "record.jsonl"); + vi.stubEnv("QUEST_GATE_RECORD", file); + vi.stubEnv("QUEST_GATE_ADMITTED", "1"); + expect(await gate([process.execPath, "-e", "process.exit(5)"])).toBe(5); + expect(existsSync(file)).toBe(false); + outermost(""); + expect(await gate([process.execPath, "-e", "process.exit(6)"], { host: ledger() })).toBe(6); + expect(readdirSync(dir)).toEqual([]); + }); + + test("a run cancelled while queued is recorded with no admission or scope", async () => { + const dir = tempDir(); + const file = join(dir, "record.jsonl"); + const ran = join(dir, "ran"); + outermost(file); + const host = ledger(true); + const result = gate(["/bin/sh", "-c", `: > ${quote(ran)}`], { host }); + await until(() => host.ledger().admissions.length > 0); + interrupt("SIGHUP"); + expect(await result).toBe(128 + constants.signals.SIGHUP); + expect(existsSync(ran)).toBe(false); + expect(lines(file)).toEqual([ + expect.objectContaining({ + admitted: null, + unit: null, + exit: 128 + constants.signals.SIGHUP, + cancelled: true, + error: null, + }), + ]); + }); + + test("a record it cannot open refuses to run the command", async () => { + const dir = tempDir(); + const ran = join(dir, "ran"); + const command = ["/bin/sh", "-c", `: > ${quote(ran)}`]; + outermost(join(dir, "missing", "record.jsonl")); + await expect(gate(command, { host: ledger() })).rejects.toThrow(/cannot record its run in .*missing/); + outermost("record.jsonl"); + await expect(gate(command, { host: ledger() })).rejects.toThrow("must be an absolute path"); + const link = join(dir, "link.jsonl"); + symlinkSync(join(dir, "target.jsonl"), link); + outermost(link); + await expect(gate(command, { host: ledger() })).rejects.toThrow(/cannot record its run in .*link\.jsonl/); + expect(existsSync(join(dir, "target.jsonl"))).toBe(false); + expect(existsSync(ran)).toBe(false); + }); + + // /dev/full opens for appending, then fails every write. + test.runIf(process.platform === "linux")( + "a line it cannot write fails the gate, and a cancelled one keeps its status", + async () => { + outermost("/dev/full"); + await expect(gate(["true"], { host: ledger() })).rejects.toThrow("cannot record its run in /dev/full"); + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + const host = ledger(true); + const result = gate(["true"], { host }); + await until(() => host.ledger().admissions.length > 0); + interrupt("SIGINT"); + expect(await result).toBe(128 + constants.signals.SIGINT); + expect(stderr).toHaveBeenCalledWith(expect.stringContaining("cannot record its run in /dev/full")); + } finally { + stderr.mockRestore(); + } + }, + ); + + test("concurrent gates leave only whole lines", async () => { + const dir = tempDir(); + const file = join(dir, "record.jsonl"); + const script = join(dir, "gates.ts"); + const gatePath = fileURLToPath(new URL("../src/cli/gate.ts", import.meta.url)); + // Long arguments make each line span many pages, so an interleaved write would show. + writeFileSync( + script, + `import { fileHost, gate } from ${JSON.stringify(gatePath)}; + const host = { ...fileHost(process.argv[2]), load: () => 0, memory: () => Infinity }; + process.exit(await gate(["true", process.argv[3].repeat(64 * 1024)], { host }));`, + ); + const env: NodeJS.ProcessEnv = { ...process.env, QUEST_GATE_RECORD: file }; + delete env.QUEST_GATE_ADMITTED; + const gates = "abcdefgh".split("").map((letter) => { + const child = spawn(process.execPath, [config, script, join(dir, `ledger-${letter}`), letter], { + env, + stdio: "inherit", + }); + return once(child, "exit"); + }); + expect((await Promise.all(gates)).map(([code]) => code)).toEqual(Array(8).fill(0)); + const recorded = lines(file).map((line) => line.command[1]); + expect(recorded.map((argument: string) => argument[0]).sort()).toEqual("abcdefgh".split("")); + for (const argument of recorded) expect(argument).toBe(argument[0].repeat(64 * 1024)); + }); +});