diff --git a/packages/cli/README.md b/packages/cli/README.md index 91df5ca53..8b5f30401 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -1425,3 +1425,26 @@ installer writes `/.deployed` as mode 0444 naming the instance. `webui-service.sh` refuses accounts and deployed instances because its user manager runs under a human or development seat uid. The receipt uid identifies the invoking process; it does not attribute a human or resist tampering by that uid. + +## Triage route (#1873, held for Jason's ruling) + +`mosaic triage route show` prints the Triage route the instance owner set, or +`triage route: not set` (exit 0). `mosaic triage route set --model KEY +--harness NAME --cap TOKENS --time-zone ZONE [--revision N]` writes it. Both +refuse inside an agent run before anything is read (exit 3). + +The file is `/triage/route.json` +(packages/webui/src/triage-route-store.mjs): a catalogue model key, a harness +name and a daily cap leaf `{limit, since, reset, timeZone}`. It holds no env +value and no key. The day resets at 00:00 in the zone given, which has no +default; an unknown zone refuses. The directory is 0700 and the file 0600, +owned by the running user; a link, a non-file, a wrong mode or owner, or an +unknown field refuses (exit 3). A write is compare-and-set on `revision` +(`--revision 0`: only when nothing is set), atomic, and appends one line with +the old and new values to `route-receipts.jsonl`. A write that died leaves +`route.lock`; the next write refuses and names it, and you remove it by hand. +`set` checks the harness against packages/plugins/harness/; it does not check +the model key against a catalogue yet. + +The Console does not read this file: the Triage host keeps `route: null` until +the wiring slice. diff --git a/packages/cli/src/cli.mjs b/packages/cli/src/cli.mjs index f589107a9..8a94d2a11 100644 --- a/packages/cli/src/cli.mjs +++ b/packages/cli/src/cli.mjs @@ -56,6 +56,7 @@ import { ORG_CONFIG, runConfigCommand } from "../../organization/src/config-comm import { devCommand, DEV_USAGE, fixtureLaunchEnv, fixtureLauncherOptions } from "./dev-fixture.mjs"; import { runCommand, RUN_USAGE } from "./run-evidence.mjs"; import { tasksWriteCommand, TASKS_WRITE_OPS, TASKS_WRITE_USAGE } from "./tasks-write.mjs"; +import { triageCommand, TRIAGE_USAGE } from "./triage.mjs"; export const USAGE = `usage: ${ACCOUNTS_USAGE} @@ -103,6 +104,7 @@ export const USAGE = `usage: mosaic console start [--dev-local-owner [--dev-insecure-bind ADDR --dev-allow-host NAME[,NAME...]]] [--detach] [--port auto|N] mosaic console stop|status mosaic console restart + ${TRIAGE_USAGE} ${DEV_USAGE} ${RUN_USAGE}`; @@ -818,6 +820,8 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin, if (verb === "launches") return launches(rest, io, deps); if (verb === "bus") return bus(rest, io, deps); if (verb === "console") return consoleCommand(rest, io, deps); + // triage-route-store (#1873): the owner's Triage route file, read and written as the person. + if (verb === "triage") return triageCommand(rest, io, deps); if (verb === "dev") return devCommand(rest, io, { system: deps.system }); if (verb === "run") return runCommand(rest, io, { system: deps.system, callFor: (p) => channelCallFor(p, io, deps) }); if (verb === "-h" || verb === "--help") return io.stdout.write(`${USAGE}\n`); diff --git a/packages/cli/src/triage.mjs b/packages/cli/src/triage.mjs new file mode 100644 index 000000000..9af0210d9 --- /dev/null +++ b/packages/cli/src/triage.mjs @@ -0,0 +1,101 @@ +// #1873 triage-route-store: the owner's terminal verbs for the Triage route file, +// /triage/route.json (packages/webui/src/triage-route-store.mjs). +// +// mosaic triage route show +// mosaic triage route set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N] +// +// Both are human verbs: an agent run is refused before anything is read (exit 3), from this +// process's environment and the one the command was given, as the bus and Console lifecycle verbs +// refuse it. `show` with no file prints "not set" and exits 0. Without --revision a write +// compares with the revision read under the store's lock; pass --revision from `show` to make the +// write conditional on what was shown (0: only when no route is set yet). +// +// Nothing here wires the route into the Triage host: the Console keeps `route: null` until the +// wiring slice. `set` checks the harness against the repository's harness modules; it does not +// check the model key against a catalogue, since none exists outside an organization's bus yet. +import { lstatSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { readRoute, RouteStoreError, writeRoute } from "../../webui/src/triage-route-store.mjs"; +import { loadSystem } from "./config.mjs"; +import { CliError } from "./errors.mjs"; +import { refuseInsideAgent } from "./transport.mjs"; + +export const TRIAGE_USAGE = "mosaic triage route show | set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N]"; +const HARNESS_ROOT = fileURLToPath(new URL("../../plugins/harness/", import.meta.url)); +const VALUES = ["--model", "--harness", "--cap", "--time-zone", "--revision"]; +const WHOLE = /^(0|[1-9][0-9]*)$/; +// The actor every terminal write records: the instance owner, the only person who runs this verb. +const ACTOR = "owner"; + +const usage = (why) => new CliError(`${why}\nusage: ${TRIAGE_USAGE}`, 4); + +// Option names, never values, in a refusal. +function parse(args) { + const values = {}, positional = []; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (VALUES.includes(a)) { + if (i + 1 >= args.length) throw usage(`${a} needs one value`); + if (Object.hasOwn(values, a)) throw usage(`${a} is given twice`); + values[a] = args[++i]; + } else if (a.startsWith("--")) throw usage("unknown option"); + else positional.push(a); + } + return { values, positional }; +} + +function whole(text, name) { + if (!WHOLE.test(text)) throw new CliError(`triage-route-invalid: ${name} must be a whole number`, 2); + return Number(text); +} + +function knownHarness(name) { + if (!/^[a-z][a-z0-9-]{0,31}$/.test(name)) return false; + try { return lstatSync(join(HARNESS_ROOT, name, "index.mjs")).isFile(); } catch { return false; } +} + +function storeError(error) { + if (!(error instanceof RouteStoreError)) throw error; + return new CliError(`${error.code}: ${error.message}`, error.code === "triage-route-invalid" ? 2 : 3); +} + +function show(route) { + if (!route) return "triage route: not set\n"; + const { cap } = route; + return [ + `triage route: revision ${route.revision}`, + `model: ${route.model}`, + `harness: ${route.harness}`, + `cap: ${cap.limit} tokens a day, resets ${cap.reset} ${cap.timeZone}, counted since ${cap.since}`, + `updated: ${route.updatedAt} by ${route.updatedBy}`, + "", + ].join("\n"); +} + +export function triageCommand(rest, io, deps = {}) { + refuseInsideAgent(process.env); + refuseInsideAgent(io.env); + const [noun, sub, ...args] = rest; + if (noun !== "route" || !["show", "set"].includes(sub)) throw usage("unknown triage command"); + const { values, positional } = parse(args); + if (positional.length) throw usage("unexpected argument"); + const dataRoot = () => (deps.system ?? loadSystem({ env: io.env })).dataRoot; + if (sub === "show") { + if (Object.keys(values).length) throw usage("show takes no options"); + let route; + try { route = readRoute(dataRoot()); } catch (e) { throw storeError(e); } + io.stdout.write(show(route)); + return; + } + for (const name of ["--model", "--harness", "--cap", "--time-zone"]) if (!Object.hasOwn(values, name)) throw usage(`set needs ${name}`); + if (!knownHarness(values["--harness"])) throw new CliError("triage-route-invalid: no harness module has that name", 2); + const input = { + model: values["--model"], harness: values["--harness"], limit: whole(values["--cap"], "--cap"), + timeZone: values["--time-zone"], by: ACTOR, + ...(Object.hasOwn(values, "--revision") ? { revision: whole(values["--revision"], "--revision") } : {}), + }; + let route; + try { route = writeRoute(dataRoot(), input, deps.now ? { now: deps.now } : {}); } catch (e) { throw storeError(e); } + io.stdout.write(`triage route set: revision ${route.revision}\n`); +} diff --git a/packages/cli/tests/triage-route.test.mjs b/packages/cli/tests/triage-route.test.mjs new file mode 100644 index 000000000..325c80f6a --- /dev/null +++ b/packages/cli/tests/triage-route.test.mjs @@ -0,0 +1,149 @@ +// #1873 triage-route-store: `mosaic triage route show|set`, the owner's terminal verbs for the +// Triage route file (packages/webui/src/triage-route-store.mjs). Human verbs: an agent run is +// refused before anything is read (exit 3), as the other human verbs refuse it. `show` with no +// file says the route is not set and exits 0. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { run } from "../src/cli.mjs"; +import { AGENT_MARKERS } from "../src/transport.mjs"; +import { routePaths } from "../../webui/src/triage-route-store.mjs"; +import { humanEnv, io } from "./helpers.mjs"; + +const REPO = new URL("../../../", import.meta.url).pathname; +const MOSAIC = join(REPO, "scripts/mosaic"); +const NOW = new Date("2026-11-18T12:00:00.000Z"); +const SET = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "200000", "--time-zone", "America/Chicago"]; + +function dataRoot(t) { + const d = mkdtempSync(join(tmpdir(), "tr-")); + t.after(() => rmSync(d, { recursive: true, force: true })); + return d; +} +async function cli(argv, d, env = humanEnv()) { + const s = io(env); + const code = await run(argv, s, { system: { dataRoot: d }, now: () => NOW }); + return { code, stdout: s.out.text, stderr: s.err.text }; +} + +test("show with no route says it is not set and exits 0", async (t) => { + const d = dataRoot(t); + assert.deepEqual(await cli(["triage", "route", "show"], d), { code: 0, stdout: "triage route: not set\n", stderr: "" }); + assert.equal(existsSync(routePaths(d).dir), false); +}); + +test("set writes the route; show reads it back", async (t) => { + const d = dataRoot(t); + const set = await cli(SET, d); + assert.equal(set.code, 0, set.stderr); + assert.equal(set.stdout, "triage route set: revision 1\n"); + const shown = await cli(["triage", "route", "show"], d); + assert.equal(shown.code, 0); + assert.equal(shown.stdout, [ + "triage route: revision 1", + "model: glm-5", + "harness: claude-code", + "cap: 200000 tokens a day, resets 00:00 America/Chicago, counted since 2026-11-18T12:00:00.000Z", + "updated: 2026-11-18T12:00:00.000Z by owner", + "", + ].join("\n")); + const doc = JSON.parse(readFileSync(routePaths(d).file, "utf8")); + assert.equal(doc.updatedBy, "owner"); + // --revision makes the write conditional on what show printed. + const five = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "5", "--time-zone", "America/Chicago", "--revision", "1"]; + assert.equal((await cli(five, d)).code, 0); + assert.equal(JSON.parse(readFileSync(routePaths(d).file, "utf8")).cap.limit, 5); + const stale = await cli([...SET, "--revision", "1"], d); + assert.equal(stale.code, 3); + assert.match(stale.stderr, /^mosaic: triage-route-stale: /); +}); + +test("refused input exits 2 or 4 and writes nothing", async (t) => { + const d = dataRoot(t); + const without = (flag) => { const a = [...SET]; const i = a.indexOf(flag); a.splice(i, 2); return a; }; + const swap = (flag, value) => { const a = [...SET]; a[a.indexOf(flag) + 1] = value; return a; }; + const cases = [ + [without("--model"), 4], [without("--harness"), 4], [without("--cap"), 4], [without("--time-zone"), 4], + [swap("--cap", "-1"), 2], [swap("--cap", "1e3"), 2], [swap("--cap", "01"), 2], [swap("--cap", "9007199254740993"), 2], + [swap("--time-zone", "Atlantis/Lost"), 2], [swap("--model", "Has Space"), 2], + [swap("--harness", "nonesuch"), 2], [swap("--harness", "../pi"), 2], + [[...SET, "--revision", "x"], 2], [[...SET, "--revision", "-1"], 2], + [[...SET, "--cap", "5"], 4], [[...SET, "--unknown", "1"], 4], [[...SET, "extra"], 4], + [["triage", "route", "show", "--model", "x"], 4], [["triage", "route", "show", "extra"], 4], + [["triage", "route"], 4], [["triage", "route", "remove"], 4], [["triage"], 4], [["triage", "key"], 4], + ]; + for (const [argv, want] of cases) { + const r = await cli(argv, d); + assert.equal(r.code, want, `${argv.join(" ")}: ${r.stderr}`); + assert.equal(r.stdout, ""); + } + // An unknown option is named as one, and its value never reaches the message. + const unknown = await cli([...SET, "--unknown", "secret-value"], d); + assert.equal(unknown.code, 4); + assert.match(unknown.stderr, /^mosaic: unknown option\n/); + assert.doesNotMatch(unknown.stderr, /secret-value/); + assert.equal(existsSync(routePaths(d).file), false); +}); + +test("an unreadable store exits 3 on show and on set", async (t) => { + const d = dataRoot(t); + assert.equal((await cli(SET, d)).code, 0); + chmodSync(routePaths(d).file, 0o644); + for (const argv of [["triage", "route", "show"], [...SET, "--revision", "1"]]) { + const r = await cli(argv, d); + assert.equal(r.code, 3); + assert.match(r.stderr, /^mosaic: triage-route-unreadable: the Triage route store is unreadable: route\.json mode is not 0600\n$/); + } +}); + +test("an agent caller is refused before anything is read, for show and set", async (t) => { + const d = dataRoot(t); + for (const marker of AGENT_MARKERS) { + for (const argv of [["triage", "route", "show"], SET]) { + const r = await cli(argv, d, { ...humanEnv(), [marker]: "1" }); + assert.equal(r.code, 3, marker); + assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`); + } + } + assert.equal(existsSync(routePaths(d).dir), false); +}); + +test("scripts/mosaic routes triage to the verb; a marker in the process env refuses", (t) => { + const home = mkdtempSync(join(tmpdir(), "trm-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-trtest/config.json") }); + const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "trtest"], { env, encoding: "utf8" }); + assert.equal(setup.status, 0, setup.stderr); + const mosaic = (args, extra = {}) => spawnSync(MOSAIC, args, { env: { ...env, ...extra }, encoding: "utf8", timeout: 60000 }); + const shown = mosaic(["triage", "route", "show"]); + assert.equal(shown.status, 0, shown.stderr); + assert.equal(shown.stdout, "triage route: not set\n"); + const set = mosaic(SET.slice(0)); + assert.equal(set.status, 0, set.stderr); + assert.equal(set.stdout, "triage route set: revision 1\n"); + const dataDir = join(home, ".mosaic-trtest"); + assert.equal(JSON.parse(readFileSync(routePaths(dataDir).file, "utf8")).model, "glm-5"); + const refused = mosaic(["triage", "route", "show"], { CLAUDECODE: "1" }); + assert.equal(refused.status, 3); + assert.match(refused.stderr, /found CLAUDECODE in the environment/); + assert.equal(refused.stdout, ""); +}); + +test("a marker in this process's own environment refuses even when the command's env is clean", async (t) => { + const d = dataRoot(t); + for (const marker of AGENT_MARKERS) { + const saved = process.env[marker]; + process.env[marker] = "1"; + try { + for (const argv of [["triage", "route", "show"], SET]) { + const r = await cli(argv, d, humanEnv()); + assert.equal(r.code, 3, marker); + assert.match(r.stderr, new RegExp(`found ${marker} in the environment`)); + } + } finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; } + } + assert.equal(existsSync(routePaths(d).dir), false); +}); diff --git a/packages/webui/src/triage-route-store.mjs b/packages/webui/src/triage-route-store.mjs new file mode 100644 index 000000000..801b8775f --- /dev/null +++ b/packages/webui/src/triage-route-store.mjs @@ -0,0 +1,246 @@ +// #1873 triage-route-store: the owner-only file that holds Triage's model route and daily cap, +// /triage/route.json (design report reports/triage-route-design.md section 1, option C). +// +// { version, revision, model, harness, cap: { limit, since, reset, timeZone }, updatedAt, updatedBy } +// +// Names only: a catalogue model key and a harness name. No env value and no key ever enter this +// file; the host derives env, mounts and the adapter itself (a later slice). Nothing here is wired +// into the Triage host or the Console yet: the Console keeps `route: null`. +// +// Fail closed. The triage directory is 0700 and route.json 0600, both owned by the running user; +// a link, a hard link, a non-file, a wrong mode or owner, an unknown field or an unknown time zone +// refuses. A write is compare-and-set on `revision` under an exclusive lock file, atomic (a 0600 +// temp file in the same directory, fsync, rename, fsync of the directory), and appends one line +// to route-receipts.jsonl. A writer that dies leaves its lock; the next write refuses and names +// it, and the person removes it by hand, as with the organization lifecycle fence. +// +// Choices Jason may still reverse each live in one place: the file location (routePaths), the +// field names (ROUTE_FIELDS, CAP_FIELDS) and the reset rule (capFor). +import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { join } from "node:path"; +import { isDailyModelQuota } from "../../plugins/src/model-quota.mjs"; +import { processState } from "../../seat/src/process-state.mjs"; + +export const ROUTE_VERSION = 1; +export const ROUTE_FIELDS = Object.freeze(["version", "revision", "model", "harness", "cap", "updatedAt", "updatedBy"]); +export const CAP_FIELDS = Object.freeze(["limit", "since", "reset", "timeZone"]); +// The catalogue's model key shape (packages/bus/src/model-catalogue.mjs validId) and the Triage +// host's harness name shape (packages/webui/src/triage-host.mjs HARNESS_NAME). +const MODEL_KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/; +const ACTOR = /^[a-z][a-z0-9-]{0,31}$/; +const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; +// isDailyModelQuota checks one leaf under a twelve-hex key; the Triage cap has no key of its own. +const LEAF_KEY = "000000000000"; +const MAX_BYTES = 64 * 1024; +const INPUT_FIELDS = Object.freeze(["model", "harness", "limit", "timeZone", "by", "revision"]); + +export class RouteStoreError extends Error { + constructor(code, message) { + super(message); + this.name = "RouteStoreError"; + this.code = code; + } +} +const unreadable = (why) => new RouteStoreError("triage-route-unreadable", `the Triage route store is unreadable: ${why}`); +const invalid = (why) => new RouteStoreError("triage-route-invalid", `the Triage route is invalid: ${why}`); + +// The file location, in one place. +export function routePaths(dataRoot) { + const dir = join(dataRoot, "triage"); + return { dir, file: join(dir, "route.json"), receipts: join(dir, "route-receipts.jsonl"), lock: join(dir, "route.lock") }; +} + +// The reset rule, in one place: the day resets at 00:00 in the owner's zone, which has no default. +// A cap whose limit, reset and zone are unchanged keeps its `since`; any other cap counts from now. +export function capFor({ limit, timeZone, previous, now }) { + const reset = "00:00"; + const same = previous && previous.limit === limit && previous.reset === reset && previous.timeZone === timeZone; + return { limit, since: same ? previous.since : now, reset, timeZone }; +} + +const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype; +const exactKeys = (v, keys) => plain(v) && Object.keys(v).length === keys.length && keys.every((k) => Object.hasOwn(v, k)); +const canonicalTime = (s) => typeof s === "string" && ISO.test(s) && !Number.isNaN(Date.parse(s)) && new Date(s).toISOString() === s; +const knownZone = (zone) => { + if (typeof zone !== "string" || zone === "") return false; + try { new Intl.DateTimeFormat("en-US", { timeZone: zone }); return true; } catch { return false; } +}; + +export function validRoute(doc) { + return exactKeys(doc, ROUTE_FIELDS) + && doc.version === ROUTE_VERSION + && Number.isSafeInteger(doc.revision) && doc.revision >= 1 + && typeof doc.model === "string" && MODEL_KEY.test(doc.model) + && typeof doc.harness === "string" && HARNESS_NAME.test(doc.harness) + // isDailyModelQuota also checks that the zone is one Intl knows. + && exactKeys(doc.cap, CAP_FIELDS) && isDailyModelQuota(LEAF_KEY, doc.cap) + && canonicalTime(doc.updatedAt) + && typeof doc.updatedBy === "string" && ACTOR.test(doc.updatedBy); +} + +const uidOf = (opts) => opts.uid ?? process.getuid(); + +// The triage directory: a real directory, the running user's, mode 0700. Returns false when it is +// missing and `create` is off; with `create` it makes it (never the data root above it). +function checkDir(dir, uid, { create }) { + let st; + try { st = lstatSync(dir); } + catch (e) { + if (e.code !== "ENOENT") throw unreadable("the triage directory cannot be read"); + if (!create) return false; + try { mkdirSync(dir, { mode: 0o700 }); } catch { throw unreadable("the triage directory cannot be made"); } + st = lstatSync(dir); + } + if (st.isSymbolicLink()) throw unreadable("the triage directory is a link"); + if (!st.isDirectory()) throw unreadable("the triage directory is not a directory"); + if (st.uid !== uid) throw unreadable("the triage directory is not owned by this user"); + if ((st.mode & 0o777) !== 0o700) throw unreadable("the triage directory mode is not 0700"); + return true; +} + +// An opened file's own checks: a regular file, one link, the running user's, mode 0600. +function checkFile(fd, uid, what) { + const st = fstatSync(fd); + if (!st.isFile()) throw unreadable(`${what} is not a regular file`); + if (st.nlink !== 1) throw unreadable(`${what} has more than one link`); + if (st.uid !== uid) throw unreadable(`${what} is not owned by this user`); + if ((st.mode & 0o777) !== 0o600) throw unreadable(`${what} mode is not 0600`); + return st; +} + +function readFile(file, uid) { + let fd; + try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } + catch (e) { + if (e.code === "ENOENT") return null; + if (e.code === "ELOOP") throw unreadable("route.json is a link"); + throw unreadable("route.json cannot be opened"); + } + try { + const st = checkFile(fd, uid, "route.json"); + if (st.size > MAX_BYTES) throw unreadable("route.json is too large"); + let doc; + try { doc = JSON.parse(readFileSync(fd, "utf8")); } catch { throw unreadable("route.json is not JSON"); } + if (!validRoute(doc)) throw unreadable("route.json does not match the route shape"); + return doc; + } finally { closeSync(fd); } +} + +// The stored route, or null when none is set. Throws triage-route-unreadable on anything unsafe. +export function readRoute(dataRoot, opts = {}) { + const { dir, file } = routePaths(dataRoot); + const uid = uidOf(opts); + if (!checkDir(dir, uid, { create: false })) return null; + return readFile(file, uid); +} + +function checkInput(input) { + if (!plain(input)) throw invalid("the input is not an object"); + for (const k of Object.keys(input)) if (!INPUT_FIELDS.includes(k)) throw invalid(`unknown field ${k}`); + if (typeof input.model !== "string" || !MODEL_KEY.test(input.model)) throw invalid("model must be a catalogue model key"); + if (typeof input.harness !== "string" || !HARNESS_NAME.test(input.harness)) throw invalid("harness must be a harness name"); + if (!Number.isSafeInteger(input.limit) || input.limit < 0) throw invalid("the cap must be a whole number of tokens, 0 or more"); + if (input.timeZone === undefined) throw invalid("a time zone is required"); + if (!knownZone(input.timeZone)) throw invalid("the time zone is unknown"); + if (typeof input.by !== "string" || !ACTOR.test(input.by)) throw invalid("the actor name is invalid"); + if (input.revision !== undefined && (!Number.isSafeInteger(input.revision) || input.revision < 0)) throw invalid("revision must be a whole number, 0 or more"); +} + +function holderLine(lock) { + let holder = null; + try { + const fd = openSync(lock, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { holder = JSON.parse(readFileSync(fd, "utf8")); } finally { closeSync(fd); } + } catch { holder = null; } + if (!Number.isSafeInteger(holder?.pid) || holder.pid <= 0) return `another write holds ${lock}, or a writer left it; remove it by hand once no write is running`; + let alive; + try { alive = processState(holder.pid).alive; } catch { alive = null; } + if (alive === false) return `a writer that is not running (pid ${holder.pid}) left ${lock}; remove it by hand`; + return `another write (pid ${holder.pid}) holds ${lock}; try again when it ends`; +} + +function takeLock(lock) { + let fd; + try { fd = openSync(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); } + catch (e) { + if (e.code === "EEXIST") throw new RouteStoreError("triage-route-busy", `the Triage route is busy: ${holderLine(lock)}`); + throw unreadable("the lock cannot be made"); + } + try { + writeSync(fd, `${JSON.stringify({ pid: process.pid, at: new Date().toISOString() })}\n`); + return { fd, st: fstatSync(fd) }; + } catch (e) { + closeSync(fd); + try { unlinkSync(lock); } catch {} + throw unreadable("the lock cannot be written"); + } +} + +function dropLock(lock, held) { + try { + const now = lstatSync(lock); + if (now.dev === held.st.dev && now.ino === held.st.ino) unlinkSync(lock); + } catch {} + closeSync(held.fd); +} + +// The receipts file, opened for append before the route changes, so a bad one refuses first. +function openReceipts(receipts, uid) { + let fd; + try { fd = openSync(receipts, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600); } + catch (e) { + if (e.code === "ELOOP") throw unreadable("route-receipts.jsonl is a link"); + throw unreadable("route-receipts.jsonl cannot be opened"); + } + try { checkFile(fd, uid, "route-receipts.jsonl"); } catch (e) { closeSync(fd); throw e; } + return fd; +} + +const summary = (doc) => (doc ? { model: doc.model, harness: doc.harness, cap: doc.cap } : null); + +// Set the route. input: { model, harness, limit, timeZone, by, revision? }. With `revision` the +// write happens only if the stored revision equals it (0: only when no route is set yet); without +// it, the revision read under the lock. Returns the new route. +// opts.now and opts.uid are for tests; opts.hook(stage) is a test seam at "crash" (after the temp +// file is written) and "before-rename". +export function writeRoute(dataRoot, input, opts = {}) { + checkInput(input); + const { dir, file, receipts, lock } = routePaths(dataRoot); + const uid = uidOf(opts); + const now = (opts.now ?? (() => new Date()))().toISOString(); + const hook = opts.hook ?? (() => {}); + checkDir(dir, uid, { create: true }); + const held = takeLock(lock); + try { + const current = readFile(file, uid); + const stored = current?.revision ?? 0; + if (input.revision !== undefined && input.revision !== stored) { + throw new RouteStoreError("triage-route-stale", `the Triage route changed: the stored revision is ${stored}, not ${input.revision}`); + } + const next = { + version: ROUTE_VERSION, revision: stored + 1, model: input.model, harness: input.harness, + cap: capFor({ limit: input.limit, timeZone: input.timeZone, previous: current?.cap ?? null, now }), + updatedAt: now, updatedBy: input.by, + }; + if (!validRoute(next)) throw invalid("the new route does not match the route shape"); + const receiptFd = openReceipts(receipts, uid); + try { + const temp = join(dir, `.route.json.${process.pid}.${randomBytes(6).toString("hex")}.tmp`); + const tfd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); + try { + writeSync(tfd, `${JSON.stringify(next, null, 2)}\n`); + fsyncSync(tfd); + } finally { closeSync(tfd); } + hook("crash"); + hook("before-rename"); + try { renameSync(temp, file); } catch (e) { try { unlinkSync(temp); } catch {} throw unreadable("route.json cannot be replaced"); } + const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY); + try { fsyncSync(dfd); } finally { closeSync(dfd); } + writeSync(receiptFd, `${JSON.stringify({ at: now, by: input.by, revision: next.revision, from: summary(current), to: summary(next) })}\n`); + fsyncSync(receiptFd); + } finally { closeSync(receiptFd); } + return next; + } finally { dropLock(lock, held); } +} diff --git a/packages/webui/tests/triage-route-store.test.mjs b/packages/webui/tests/triage-route-store.test.mjs new file mode 100644 index 000000000..0732484f8 --- /dev/null +++ b/packages/webui/tests/triage-route-store.test.mjs @@ -0,0 +1,382 @@ +// #1873 triage-route-store: the owner-only file that holds Triage's model route and daily cap, +// /triage/route.json (design report section 1, option C). Names only: no env value and +// no key. The directory is 0700 and the file 0600, both the running user's; a link, a non-file, +// a wrong mode or owner refuses. A write is compare-and-set on revision, atomic (temp file plus +// rename in the same directory), and appends one receipt line. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + CAP_FIELDS, ROUTE_FIELDS, ROUTE_VERSION, RouteStoreError, capFor, readRoute, routePaths, validRoute, writeRoute, +} from "../src/triage-route-store.mjs"; + +const MODULE = new URL("../src/triage-route-store.mjs", import.meta.url).pathname; +const NOW = "2026-11-18T12:00:00.000Z"; +const LATER = "2026-11-18T13:00:00.000Z"; +const at = (iso) => () => new Date(iso); +const INPUT = { model: "glm-5", harness: "claude-code", limit: 200000, timeZone: "America/Chicago", by: "owner" }; + +function root(t) { + const dir = mkdtempSync(join(process.env.TMPDIR, "trs-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} +const code = (c) => (e) => e instanceof RouteStoreError && e.code === c; +// Unreadable with a given reason, so each check is shown to refuse on its own. +const unreadableFor = (re) => (e) => code("triage-route-unreadable")(e) && re.test(e.message); +const receipts = (dataRoot) => readFileSync(routePaths(dataRoot).receipts, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)); +const good = () => ({ + version: 1, revision: 1, model: "glm-5", harness: "claude-code", + cap: { limit: 200000, since: NOW, reset: "00:00", timeZone: "America/Chicago" }, updatedAt: NOW, updatedBy: "owner", +}); +// Write a doc straight to route.json at the right modes, to test the loader alone. +function plant(dataRoot, doc) { + const { dir, file } = routePaths(dataRoot); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + chmodSync(dir, 0o700); + writeFileSync(file, typeof doc === "string" ? doc : JSON.stringify(doc), { mode: 0o600 }); + chmodSync(file, 0o600); +} + +test("paths, field names and the reset rule each live in one place", () => { + const p = routePaths("/d"); + assert.deepEqual(p, { dir: "/d/triage", file: "/d/triage/route.json", receipts: "/d/triage/route-receipts.jsonl", lock: "/d/triage/route.lock" }); + assert.deepEqual([...ROUTE_FIELDS].sort(), ["cap", "harness", "model", "revision", "updatedAt", "updatedBy", "version"]); + assert.deepEqual([...CAP_FIELDS].sort(), ["limit", "reset", "since", "timeZone"]); + assert.equal(ROUTE_VERSION, 1); + // A new cap starts its count now and resets at 00:00 in the owner's zone. + assert.deepEqual(capFor({ limit: 5, timeZone: "UTC", previous: null, now: NOW }), { limit: 5, since: NOW, reset: "00:00", timeZone: "UTC" }); + // The same cap keeps its since; a changed limit or zone starts again. + const prev = { limit: 5, since: NOW, reset: "00:00", timeZone: "UTC" }; + assert.equal(capFor({ limit: 5, timeZone: "UTC", previous: prev, now: LATER }).since, NOW); + assert.equal(capFor({ limit: 6, timeZone: "UTC", previous: prev, now: LATER }).since, LATER); + assert.equal(capFor({ limit: 5, timeZone: "Europe/Berlin", previous: prev, now: LATER }).since, LATER); +}); + +test("no file reads as not set; a write then reads back the same route", (t) => { + const d = root(t); + assert.equal(readRoute(d), null); + const written = writeRoute(d, INPUT, { now: at(NOW) }); + assert.deepEqual(written, good()); + assert.deepEqual(readRoute(d), good()); + const { dir, file } = routePaths(d); + assert.equal(lstatSync(dir).mode & 0o777, 0o700); + assert.equal(lstatSync(file).mode & 0o777, 0o600); + // The store holds names only: nothing shaped like an env value or a key. + const text = readFileSync(file, "utf8"); + assert.doesNotMatch(text, /ANTHROPIC|_KEY|TOKEN|mst-|msk-|env/i); + // A second write bumps the revision and keeps the cap's since when the cap is the same. + const second = writeRoute(d, { ...INPUT, model: "glm-5.3-flash", revision: 1 }, { now: at(LATER) }); + assert.equal(second.revision, 2); + assert.equal(second.model, "glm-5.3-flash"); + assert.equal(second.cap.since, NOW); + assert.equal(second.updatedAt, LATER); + assert.deepEqual(readRoute(d), second); + // No temp file or lock is left behind. + assert.deepEqual(readdirSync(dir).sort(), ["route-receipts.jsonl", "route.json"]); +}); + +test("each write appends one receipt line with the old and the new value", (t) => { + const d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + writeRoute(d, { ...INPUT, limit: 1000 }, { now: at(LATER) }); + const lines = receipts(d); + assert.equal(lines.length, 2); + assert.deepEqual(lines[0], { at: NOW, by: "owner", revision: 1, from: null, to: { model: "glm-5", harness: "claude-code", cap: good().cap } }); + assert.equal(lines[1].revision, 2); + assert.deepEqual(lines[1].from, { model: "glm-5", harness: "claude-code", cap: good().cap }); + assert.equal(lines[1].to.cap.limit, 1000); + assert.equal(lines[1].to.cap.since, LATER); + assert.equal(lstatSync(routePaths(d).receipts).mode & 0o777, 0o600); + // A refused write appends nothing. + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }), code("triage-route-stale")); + assert.equal(receipts(d).length, 2); +}); + +test("a stale revision refuses and leaves the file alone", (t) => { + const d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + writeRoute(d, { ...INPUT, limit: 7, revision: 1 }, { now: at(NOW) }); + const before = readFileSync(routePaths(d).file, "utf8"); + assert.throws(() => writeRoute(d, { ...INPUT, limit: 9, revision: 1 }, { now: at(LATER) }), code("triage-route-stale")); + assert.throws(() => writeRoute(d, { ...INPUT, limit: 9, revision: 3 }, { now: at(LATER) }), code("triage-route-stale")); + assert.equal(readFileSync(routePaths(d).file, "utf8"), before); + // Revision 0 means "only if there is no route yet". + assert.throws(() => writeRoute(d, { ...INPUT, revision: 0 }, { now: at(LATER) }), code("triage-route-stale")); + const e = root(t); + assert.equal(writeRoute(e, { ...INPUT, revision: 0 }, { now: at(NOW) }).revision, 1); +}); + +test("refused input shapes on a write", (t) => { + const d = root(t); + // Each input check refuses with its own message, so none rests only on the final shape check. + const bad = [ + [{ ...INPUT, model: "" }, /model must be/], [{ ...INPUT, model: "Has Space" }, /model must be/], + [{ ...INPUT, model: "x".repeat(65) }, /model must be/], [{ ...INPUT, model: 5 }, /model must be/], + [{ ...INPUT, harness: "" }, /harness must be/], [{ ...INPUT, harness: "Claude" }, /harness must be/], + [{ ...INPUT, harness: "../pi" }, /harness must be/], [{ ...INPUT, harness: "x".repeat(33) }, /harness must be/], + [{ ...INPUT, limit: -1 }, /the cap must be/], [{ ...INPUT, limit: 1.5 }, /the cap must be/], + [{ ...INPUT, limit: "100" }, /the cap must be/], [{ ...INPUT, limit: 2 ** 53 }, /the cap must be/], + [{ ...INPUT, timeZone: undefined }, /a time zone is required/], [{ ...INPUT, timeZone: "" }, /time zone is unknown/], + [{ ...INPUT, timeZone: "Mars/Olympus_Mons" }, /time zone is unknown/], [{ ...INPUT, timeZone: "../etc" }, /time zone is unknown/], + [{ ...INPUT, by: "" }, /actor name/], [{ ...INPUT, by: "Owner Person" }, /actor name/], + [{ ...INPUT, revision: -1 }, /revision must be/], [{ ...INPUT, revision: "1" }, /revision must be/], [{ ...INPUT, revision: 1.5 }, /revision must be/], + [{ ...INPUT, env: { A: "b" } }, /unknown field env/], [{ ...INPUT, key: "mst-x" }, /unknown field key/], + [null, /not an object/], [[INPUT], /not an object/], + ]; + for (const [input, message] of bad) { + assert.throws(() => writeRoute(d, input, { now: at(NOW) }), (e) => code("triage-route-invalid")(e) && message.test(e.message), JSON.stringify(input)); + } + // No time zone default: leaving it out refuses. + const { timeZone, ...noZone } = INPUT; + assert.throws(() => writeRoute(d, noZone, { now: at(NOW) }), (e) => code("triage-route-invalid")(e) && /a time zone is required/.test(e.message)); + assert.equal(readRoute(d), null); +}); + +test("an unknown time zone refuses on write and on read", (t) => { + const d = root(t); + assert.throws(() => writeRoute(d, { ...INPUT, timeZone: "Atlantis/Lost" }, { now: at(NOW) }), code("triage-route-invalid")); + plant(d, { ...good(), cap: { ...good().cap, timeZone: "Atlantis/Lost" } }); + assert.throws(() => readRoute(d), code("triage-route-unreadable")); +}); + +test("each refused stored shape reads as unreadable", (t) => { + const g = good(); + const shapes = { + "not json": "{", + "an array": [g], + "null": null, + "unknown field": { ...g, env: {} }, + "unknown cap field": { ...g, cap: { ...g.cap, perTurn: 5 } }, + "missing version": (({ version, ...r }) => r)(g), + "missing revision": (({ revision, ...r }) => r)(g), + "missing model": (({ model, ...r }) => r)(g), + "missing harness": (({ harness, ...r }) => r)(g), + "missing cap": (({ cap, ...r }) => r)(g), + "missing updatedAt": (({ updatedAt, ...r }) => r)(g), + "missing updatedBy": (({ updatedBy, ...r }) => r)(g), + "missing cap.limit": { ...g, cap: (({ limit, ...r }) => r)(g.cap) }, + "missing cap.since": { ...g, cap: (({ since, ...r }) => r)(g.cap) }, + "missing cap.reset": { ...g, cap: (({ reset, ...r }) => r)(g.cap) }, + "missing cap.timeZone": { ...g, cap: (({ timeZone, ...r }) => r)(g.cap) }, + "version 2": { ...g, version: 2 }, + "revision 0": { ...g, revision: 0 }, + "revision text": { ...g, revision: "1" }, + "bad model": { ...g, model: "A B" }, + "bad harness": { ...g, harness: "A/B" }, + "cap an array": { ...g, cap: [1] }, + "negative limit": { ...g, cap: { ...g.cap, limit: -1 } }, + "bad reset": { ...g, cap: { ...g.cap, reset: "24:00" } }, + "bad since": { ...g, cap: { ...g.cap, since: "2026-11-18" } }, + "bad updatedAt": { ...g, updatedAt: "yesterday" }, + "bad updatedBy": { ...g, updatedBy: "A B" }, + }; + for (const [name, doc] of Object.entries(shapes)) { + const d = root(t); + plant(d, doc); + assert.throws(() => readRoute(d), code("triage-route-unreadable"), name); + if (typeof doc !== "string") assert.equal(validRoute(doc), false, name); + } + assert.equal(validRoute(g), true); + // A write over an unreadable file refuses too; it never replaces what it could not read. + const d = root(t); + plant(d, { ...g, env: {} }); + assert.throws(() => writeRoute(d, INPUT, { now: at(NOW) }), code("triage-route-unreadable")); +}); + +test("an oversized file is refused before it is parsed", (t) => { + const d = root(t); + plant(d, JSON.stringify(good()) + " ".repeat(70000)); + assert.throws(() => readRoute(d), code("triage-route-unreadable")); +}); + +test("a wrong mode on the directory or the file refuses", (t) => { + for (const mode of [0o755, 0o750, 0o711, 0o500]) { + const d = root(t); + plant(d, good()); + chmodSync(routePaths(d).dir, mode); + assert.throws(() => readRoute(d), code("triage-route-unreadable"), `dir ${mode.toString(8)}`); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(NOW) }), code("triage-route-unreadable"), `dir ${mode.toString(8)}`); + chmodSync(routePaths(d).dir, 0o700); + } + for (const mode of [0o644, 0o640, 0o604, 0o400, 0o700]) { + const d = root(t); + plant(d, good()); + chmodSync(routePaths(d).file, mode); + assert.throws(() => readRoute(d), code("triage-route-unreadable"), `file ${mode.toString(8)}`); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(NOW) }), code("triage-route-unreadable"), `file ${mode.toString(8)}`); + } + // A receipts file with the wrong mode refuses the write before the route changes. + const d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + chmodSync(routePaths(d).receipts, 0o644); + assert.throws(() => writeRoute(d, { ...INPUT, limit: 1, revision: 1 }, { now: at(LATER) }), code("triage-route-unreadable")); + assert.equal(readRoute(d).revision, 1); +}); + +test("a wrong owner refuses on the directory and the file", (t) => { + const d = root(t); + plant(d, good()); + // Pretend to be another user: the store compares with the uid it is given. + const other = process.getuid() + 1; + assert.throws(() => readRoute(d, { uid: other }), unreadableFor(/the triage directory is not owned by this user/)); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(NOW), uid: other }), unreadableFor(/the triage directory is not owned by this user/)); + assert.equal(readRoute(d, { uid: process.getuid() }).revision, 1); +}); + +test("a link at the file, the directory or the receipts refuses; so does a non-file", (t) => { + // Symlink at route.json, to a valid route elsewhere. + let d = root(t); + plant(d, good()); + const elsewhere = join(d, "elsewhere.json"); + renameSync(routePaths(d).file, elsewhere); + symlinkSync(elsewhere, routePaths(d).file); + assert.throws(() => readRoute(d), code("triage-route-unreadable")); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(NOW) }), code("triage-route-unreadable")); + // A hard link at route.json. + d = root(t); + plant(d, good()); + linkSync(routePaths(d).file, join(d, "hard.json")); + assert.throws(() => readRoute(d), code("triage-route-unreadable")); + // Symlink at the triage directory, to a real 0700 directory holding a valid route. + d = root(t); + const real = join(d, "real"); + mkdirSync(real, { mode: 0o700 }); + writeFileSync(join(real, "route.json"), JSON.stringify(good()), { mode: 0o600 }); + symlinkSync(real, routePaths(d).dir); + assert.throws(() => readRoute(d), unreadableFor(/the triage directory is a link/)); + assert.throws(() => writeRoute(d, INPUT, { now: at(NOW) }), unreadableFor(/the triage directory is a link/)); + // A directory where route.json should be. + d = root(t); + mkdirSync(routePaths(d).file, { recursive: true, mode: 0o700 }); + chmodSync(routePaths(d).dir, 0o700); + assert.throws(() => readRoute(d), unreadableFor(/route\.json is not a regular file/)); + // A file where the triage directory should be, at 0700 so only the directory check refuses it. + d = root(t); + writeFileSync(routePaths(d).dir, "x", { mode: 0o700 }); + chmodSync(routePaths(d).dir, 0o700); + assert.throws(() => readRoute(d), unreadableFor(/the triage directory is not a directory/)); + assert.throws(() => writeRoute(d, INPUT, { now: at(NOW) }), unreadableFor(/the triage directory is not a directory/)); + // A symlink at the receipts file refuses the write and never follows it. + d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + const target = join(d, "target.jsonl"); + writeFileSync(target, "", { mode: 0o600 }); + unlinkSync(routePaths(d).receipts); + symlinkSync(target, routePaths(d).receipts); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }), code("triage-route-unreadable")); + assert.equal(readFileSync(target, "utf8"), ""); + assert.equal(readRoute(d).revision, 1); + // A symlink at the lock path is not followed: the write refuses as busy. + d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + symlinkSync(join(d, "nowhere"), routePaths(d).lock); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }), code("triage-route-busy")); + assert.equal(existsSync(join(d, "nowhere")), false); +}); + +test("the store makes its directory 0700 but never the data root", (t) => { + const d = root(t); + assert.throws(() => writeRoute(join(d, "missing"), INPUT, { now: at(NOW) }), code("triage-route-unreadable")); + assert.equal(existsSync(join(d, "missing")), false); +}); + +test("two writers in one process: the second, while the first holds the lock, refuses busy", (t) => { + const d = root(t); + writeRoute(d, INPUT, { now: at(NOW) }); + let inner = null; + const won = writeRoute(d, { ...INPUT, limit: 1, revision: 1 }, { + now: at(LATER), + hook: (stage) => { + if (stage !== "before-rename") return; + try { writeRoute(d, { ...INPUT, limit: 2, revision: 1 }, { now: at(LATER) }); } catch (e) { inner = e; } + }, + }); + assert.equal(won.cap.limit, 1); + assert.ok(code("triage-route-busy")(inner), String(inner)); + assert.equal(readRoute(d).cap.limit, 1); + assert.equal(receipts(d).length, 2); +}); + +// A child process that loads the store and writes once; prints {ok, code}. `wait` makes it hold +// at the given stage until the file `go` appears, so two children overlap for real. +const CHILD = ` +import { writeRoute } from ${JSON.stringify(MODULE)}; +import { existsSync, writeFileSync } from "node:fs"; +const [dataRoot, limit, revision, wait, go, ready] = process.argv.slice(1); +try { + const r = writeRoute(dataRoot, { model: "glm-5", harness: "claude-code", limit: Number(limit), timeZone: "UTC", by: "owner", revision: Number(revision) }, { + hook: (stage) => { + if (stage === "crash") { if (wait === "crash") process.kill(process.pid, "SIGKILL"); return; } + if (stage !== wait) return; + writeFileSync(ready, ""); + const end = Date.now() + 20000; + while (!existsSync(go) && Date.now() < end) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); + }, + }); + console.log(JSON.stringify({ ok: true, limit: r.cap.limit })); +} catch (e) { console.log(JSON.stringify({ ok: false, code: e.code ?? String(e) })); } +`; +function child(args) { + return new Promise((resolve, reject) => { + const p = spawn(process.execPath, ["--input-type=module", "-e", CHILD, ...args], { stdio: ["ignore", "pipe", "pipe"] }); + let out = "", err = ""; + p.stdout.setEncoding("utf8").on("data", (c) => { out += c; }); + p.stderr.setEncoding("utf8").on("data", (c) => { err += c; }); + p.on("error", reject); + p.on("close", (status, signal) => resolve({ status, signal, out: out.trim(), err })); + }); +} +async function until(path) { + const end = Date.now() + 20000; + while (!existsSync(path)) { + if (Date.now() > end) throw new Error(`timed out waiting for ${path}`); + await new Promise((r) => setTimeout(r, 20)); + } +} + +test("two writer processes racing on one revision: one wins, one refuses", async (t) => { + const d = root(t); + writeRoute(d, { ...INPUT, timeZone: "UTC" }, { now: at(NOW) }); + const go = join(d, "go"), ready = join(d, "ready"); + // The first holds just before its rename; the second starts then, with the same revision. + const first = child([d, "11", "1", "before-rename", go, ready]); + await until(ready); + const second = await child([d, "22", "1", "none", join(d, "unused"), join(d, "unused-ready")]); + writeFileSync(go, ""); + const a = JSON.parse((await first).out), b = JSON.parse(second.out); + assert.deepEqual(a, { ok: true, limit: 11 }); + assert.equal(b.ok, false); + assert.equal(b.code, "triage-route-busy"); + assert.equal(readRoute(d).cap.limit, 11); + assert.equal(readRoute(d).revision, 2); + // After the winner, the loser's revision is stale. + const again = JSON.parse((await child([d, "22", "1", "none", join(d, "u2"), join(d, "u3")])).out); + assert.deepEqual(again, { ok: false, code: "triage-route-stale" }); + // Started together with no pause, exactly one of two wins. + const both = await Promise.all([child([d, "33", "2", "none", join(d, "u4"), join(d, "u5")]), child([d, "44", "2", "none", join(d, "u6"), join(d, "u7")])]); + const results = both.map((r) => JSON.parse(r.out)); + assert.equal(results.filter((r) => r.ok).length, 1, JSON.stringify(results)); + assert.ok(results.filter((r) => !r.ok).every((r) => ["triage-route-busy", "triage-route-stale"].includes(r.code)), JSON.stringify(results)); + assert.equal(readRoute(d).revision, 3); + assert.equal(receipts(d).length, 3); +}); + +test("a crash between the temp write and the rename leaves the old file", async (t) => { + const d = root(t); + const old = writeRoute(d, { ...INPUT, timeZone: "UTC" }, { now: at(NOW) }); + const r = await child([d, "99", "1", "crash", join(d, "go"), join(d, "ready")]); + assert.equal(r.signal, "SIGKILL", r.err); + assert.deepEqual(readRoute(d), old); + assert.equal(receipts(d).length, 1); + // The temp file is still there, and the dead writer's lock refuses the next write, naming it. + const { dir, lock } = routePaths(d); + assert.ok(readdirSync(dir).some((n) => n.endsWith(".tmp")), readdirSync(dir).join(",")); + assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }), (e) => code("triage-route-busy")(e) && /not running/.test(e.message) && /route\.lock/.test(e.message)); + // The person removes the lock by hand; the next write works and the read ignores the temp file. + unlinkSync(lock); + assert.equal(writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }).revision, 2); + assert.equal(readRoute(d).revision, 2); +}); diff --git a/scripts/mosaic b/scripts/mosaic index 49a299d73..5efee52db 100755 --- a/scripts/mosaic +++ b/scripts/mosaic @@ -46,6 +46,6 @@ if [ "${1:-}" = library ] && [ "${2:-}" = survey ]; then exec node "$REPO/packages/library/src/survey.mjs" "$@" fi case "${1:-}" in - org|proxy|halt|resume|processing|usage|project|limits|inbox|decide|tasks|agents|trail|talk|stop|launches|bus|console|plugins|credentials|hosts|grants|name|names|follow|threads|thread|access|dev|run) exec node "$REPO/packages/cli/src/cli.mjs" "$@" ;; + org|proxy|halt|resume|processing|usage|project|limits|inbox|decide|tasks|agents|trail|talk|stop|launches|bus|console|plugins|credentials|hosts|grants|name|names|follow|threads|thread|access|dev|run|triage) exec node "$REPO/packages/cli/src/cli.mjs" "$@" ;; esac exec node "$REPO/packages/seat/src/cli.mjs" "$@"