feat(triage): the owner-only route store and mosaic triage route show|set

<dataRoot>/triage/route.json holds Triage's model route and daily cap as names only:
a catalogue model key, a harness name and a daily-quota cap leaf, with no env value
and no key. The directory is 0700 and the file 0600, 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,
atomic (temp file, fsync, rename, directory fsync), and appends one receipt line.
The reset is 00:00 in a zone the owner gives, with no default. The file location,
field names and reset rule each live in one place.

mosaic triage route show|set are human verbs and refuse an agent run before any read.
Nothing is wired into the Triage host: the Console keeps route: null. Held for
Jason's ruling on the design's four questions (#1873, lane triage-route-store).
This commit is contained in:
jason.woltje committed 2026-11-18 12:05:07 -06:00
1 parent 2d44750b96
commit 4c8527fcd3
7 files changed
+906 -1

No files matched your search

+23
View File
@@ -1425,3 +1425,26 @@ installer writes `<dataRoot>/.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 `<dataRoot>/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.
+4
View File
@@ -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`);
+101
View File
@@ -0,0 +1,101 @@
// #1873 triage-route-store: the owner's terminal verbs for the Triage route file,
// <dataRoot>/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`);
}
+149
View File
@@ -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);
});