Compare commits

...
Author SHA1 Message Date
jason.woltje 9a3004cba4 test(webui): the agents.js export pin names the restart chain SP19 adds for the agent drawer (#1873, lane sp19-drawer-restart) 2026-11-18 13:15:20 -06:00
jason.woltje 4b833d23e9 fix(webui): drawer restart review round: each restart keeps its own state per agent, so another drawer's Stop or question no longer drops its line or its running state, with a two-drawer test; once the agent was ended (a refused launch, a thread ended, a restart done) the drawer repaints from a fresh instances read and focus goes to its heading, so an agent with no run no longer offers Stop and Restart; a refusal before the end keeps focus on Restart; an archived or unavailable organization says so instead of outcome unknown, with a test (#1873, lane sp19-drawer-restart) 2026-11-18 12:51:38 -06:00
jason.woltje 05be6c62bd feat(webui): Restart in the agent drawer: beside Stop and only where Stop is offered, in Stop's confirm step and status line, it ends the agent through its own organization's /agent/terminate with the reason restart from the agent drawer, waits for the request to close and its runs to reach 0, then launches it through /agent/launch; a conversation agent is ended and not launched; it never regenerates; not owner, bus stopped, end refused, launch refused and runs never reaching 0 each say so in one line and leave the buttons usable; a second click while it runs does nothing. The agents.js restart chain takes org, reason, a text callback and a status callback; the Routing receipt's Restart now keeps its reason and words, pinned by two new tests (#1873, lane sp19-drawer-restart) 2026-11-18 12:35:34 -06:00
jason.woltje c9fad00d25 fix(triage): review round for the route store
The file owner check has its own test through a file-owner seam, for
route.json on read and write and for route-receipts.jsonl on write. The
directory, temp file and a new receipts file get their modes on the open
descriptor, so a narrow umask cannot leave a route the next read refuses;
an existing receipts file is never repaired. A failed temp write refuses
and removes the temp file. A failure after the rename refuses as
triage-route-unrecorded and names the new revision. The input zone check
uses the stored cap's rule, so +05:00 refuses as an unknown zone. A
changed cap keeps its since, as an organization's token limits do, so
lowering the cap never drops tokens already counted (#1873, lane
triage-route-store).
2026-11-18 12:05:07 -06:00
jason.woltje 4c8527fcd3 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).
2026-11-18 12:05:07 -06:00
jason.woltje 2d44750b96 fix(webui): drawer polish review round 3 notes: with the runs not read and no claim, Last activity names the agents and claims reads, with a test for chief; the Project scroll test waits for the Projects page heading; a test comment matches the one of its runs wording (#1873, lane sp18-drawer-polish) 2026-11-18 11:26:45 -06:00
jason.woltje 9343baffff fix(webui): drawer polish review round 2: the kept scroll place is dropped as soon as the address leaves the page under the sheet, so a project or Assistant page that bus.js draws without afterPaint no longer leaves it for a later page; the scroll tests make every page long first and wait for the linked page's own content; Last activity says one of its N runs, and a run when the runs were not read (#1873, lane sp18-drawer-polish) 2026-11-18 11:18:18 -06:00
jason.woltje 38ea639d70 fix(webui): drawer polish review round: at 390 the page under the sheet goes back to its place only when the drawer closes onto that same page, so a link in the sheet opens its page at the top and a later page does not jump; Last activity counts a role or conversation claim only when the instances read lists its run as running, says when a running run holds nothing yet, and names the latest of several runs (#1873, lane sp18-drawer-polish) 2026-11-18 11:18:18 -06:00
jason.woltje fc558df31a fix(webui): drawer and page polish: at 390 the open agent sheet is the whole screen and the page under it no longer scrolls behind it, and Close puts the page back where it was; the drawer's Last activity is when the agent's current run took its role or conversation, from the claim time the workspace read already carries; the Dashboard's two columns line up with its tile row; the organization page's left column holds Autonomy and Starter packs; the workflows section() stub and its duplicate stopped panel are gone (#1873, lane sp18-drawer-polish) 2026-11-18 11:18:18 -06:00
jason.woltje 56cc7b59dd fix(seat,unslop-hook): review round: the linked fixed path test puts the stand-in's real path outside HOME so only its own guard refuses the source; the Stop hook's notes name the late-fallback turn a later Stop can check again and say a second Stop after a blocking hook waits and logs one late entry; the plugins README names the Perl, Ruby, less and resolver hooks and points to REFUSED_NAMES (#1873, lane triage-p3s) 2026-11-18 11:05:35 -06:00
jason.woltje c641dbfbc9 fix(webui): the triage snapshot reads every organization's bus and processing sockets at once and limits only the config checks, which start node children; the deadline tests count reads and use the injected clock instead of tight wall-clock margins (#1873, lane triage-p3s) 2026-11-18 10:52:53 -06:00
jason.woltje eb1146ebad fix(webui): a triage reply settles its entry only when it is the runner's RESULT answer; a progress note that names the message leaves it queued, so a session that dies after the note still reports it unanswered (#1873, lane triage-p3s) 2026-11-18 10:52:53 -06:00
jason.woltje 4b5d027361 fix(seat): hosted route fences P3s: realOr runs once per fixed path, a test hook adds a stand-in fixed path so a linked one is tested, the refuse list adds LUA_INIT, CURL_HOME and SSLKEYLOGFILE, and the plugins README names every refused suffix and hook (#1873, lane triage-p3s) 2026-11-18 10:52:53 -06:00
jason.woltje 80ce06851d fix(unslop-hook): the Stop hook records the last prompt it checked per session in <log>.stop.json and waits while the transcript still ends with that turn, so a Stop with no last_assistant_message, or one whose reply has the last turn's text, no longer checks the last turn as this one; the 2 s wait stays (#1873, lane triage-p3s) 2026-11-18 10:52:53 -06:00
jason.woltje b39d5e2ff3 fix(unslop-hook): review round, the Stop fallback logs late: true and the comment names the two stale cases left: an input with no last_assistant_message, and a reply whose text equals the last turn's last reply; cli.mjs notes that the packs-http read is the tested gate for system-only templates (#1873, lane triage-followups) 2026-11-16 16:05:43 -06:00
jason.woltje c85c768a4a fix(webui): the first render's heading focus leaves an open drawer or dialog alone: a reader who opened the Triage drawer, an agent drawer, the narrow-screen menu or a dialog before the first render ended keeps focus there; on load a second render can draw the agents rows while the first still reads, so the agent drawer had the same fault (#1873, lane triage-followups) 2026-11-16 15:54:12 -06:00
jason.woltje b7649ecd73 fix(webui): the workflows read leaves out system-only templates
The workflows read listed the triage template, which only the client hid.
The read handler now drops every template the organization vocabulary marks
system-only, and the Console's read supplier in cli.mjs drops them too. The
client filter stays. (#1873, lane triage-followups)
2026-11-16 15:46:57 -06:00
jason.woltje 0354452971 fix(unslop-hook): the Claude Stop hook waits for the turn to reach the transcript
Claude Code 2.1.319, 2.1.322 and 2.1.325 can run the Stop hook before they
write the turn to the transcript. The hook then read the last turn's reply,
logged it a second time, and missed this turn's reply. That made
claude-session.test.mjs row 66 red in most runs.

The hook now reads the transcript again, for up to 2 s, until its last reply
matches last_assistant_message. If it never does, it checks
last_assistant_message alone with an empty entryId, never the last turn
again. (#1873, lane triage-followups)
2026-11-16 15:45:09 -06:00
jason.woltje bbbefb3f28 fix(webui): triage fences re-check, only HOME may hold the stack's code: the code root names its holder, which must be a protected path, and no other protected path sets a source aside; a code root in or around the run dir or a fixed path is refused in either path's real spelling too; the mount, install root and protected lists are copied once so a changing list cannot pass one check and feed another; the refuse list adds PERLLIB, LESSOPEN, LESSCLOSE, HOSTALIASES and names ending _ASKPASS, _CA_BUNDLE or _BASE_URL (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
jason.woltje 2f91ff5bea fix(webui): triage fences review, HOME is not counted against the stack's own code: a caller's protected path that holds the code root sets aside a source whose named and real paths both lie in it, never the run dir or a fixed path, so pi starts from a copy or worktree under HOME; a refusal at the binds answers triage-route-invalid and removes what the start wrote; each mount field is read once and no dest lies in or around another; values refuse every C0 and C1 control and U+2028/U+2029; the token shape drops the m flag; the refuse list adds MALLOC_, NPM_CONFIG_, XDG_, names ending _DIR, _CONF or _CONFIG, and the libc, shell, OpenSSL and Java hooks (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
jason.woltje 1ca3a38f86 feat(webui): triage fences, the host checks a copy of the route's answer before anything is written or spawned: harnessEnv names must be declared by the harness module and are refused outright when MOSAIC_, NODE_, LD_, DYLD_, PYTHON, BASH_, GIT_, PATH, HOME, TMPDIR, ENV, a founder or a provider name; values are short clean strings; route env holds only the proxy's two names with a loopback base URL, and the host's port and token shape when given; the adapter and at most 8 mounts resolve inside the module's install roots and never in or around the data root, the config dir, HOME, /srv/mosaic or a secrets path, with dests clear of /tmp, the run dir and the system binds, checked again in hostedBinds; a refused answer answers triage-route-invalid and leaves a host line (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
37 changed files with 2665 additions and 184 deletions

No files matched your search

+27
View File
@@ -1425,3 +1425,30 @@ 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 first cap counts from the time it is
set; a later change keeps that `since`, as an organization's token limits do,
so lowering the cap never drops tokens already spent. 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.
If the route changed but its receipt line could not be written, the write
refuses with `triage-route-unrecorded` (exit 3) and names the new revision.
`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);
});
+22
View File
@@ -258,6 +258,28 @@ export returns:
`gateTimeout`, `bundle`, `env`, `turnEnd`, `outputPolicy` and `transcript` give its
sandbox binds, web, tool names, S0 lines, bundle files, adapter variables,
how a turn ends and where its transcripts land.
- `envNames` and `installRoots({env})` (#1873 triage-fences) are optional and
outside `kinds.mjs`. A session the Console hosts with no organization
(Triage) reads them; organization launches do not. `envNames` lists the
names `env()` returns, less the provider's. The host takes a route's
`harnessEnv` name only when it is listed here and is not one the host
always refuses: `MOSAIC_*`, `NODE_*`, `LD_*`, `DYLD_*`, `PYTHON*`, `BASH_*`,
`GIT_*`, `MALLOC_*`, `NPM_CONFIG_*`, `XDG_*`, any name ending in `_DIR`,
`_CONF`, `_CONFIG`, `_ASKPASS`, `_CA_BUNDLE` or `_BASE_URL`, PATH, HOME,
TMPDIR, ENV, the founder's and the provider's names, and named shell,
proxy, resolver, libc, OpenSSL and Java hooks, Perl and Ruby start
options and library paths, less's input filters, Lua's start code,
curl's config home and a TLS key log. The full list is
`REFUSED_NAMES` in `packages/webui/src/triage-host.mjs`. `installRoots` lists the directories
where the adapter and the mounts live. A hosted adapter or mount source
must resolve inside one of them, and never in or around the data root,
the config directory, HOME, `/srv/mosaic` or a path with a `secret`
segment. HOME does not count against a source inside the stack's own
code, so a copy or a worktree under HOME still passes. Every claude-code
name is `MOSAIC_*`, so a hosted session cannot run Claude Code yet. pi's
`MOSAIC_TOOLS`, `MOSAIC_EXTENSIONS` and `MOSAIC_THINKING` are refused the
same way, so a hosted pi gets no tools and no extension until the host
sets those names itself.
- `compactions({store, cursors, budget, streams, first})` reads a thread
session's native store for row 270's compaction count (row 307). Core keeps
the ledger (`packages/seat/src/compactions.mjs`) and passes `store` as
+11 -1
View File
@@ -6,7 +6,7 @@
// session.json. packages/plugins/README.md lists the interface.
import { spawnSync } from "node:child_process";
import { accessSync, constants, realpathSync, statSync } from "node:fs";
import { delimiter, isAbsolute, join } from "node:path";
import { delimiter, dirname, isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { claudeBuiltins, MCP_PREFIX } from "../../../harness/src/gate.mjs";
import { hasSessionCredential, SESSION_CREDENTIALS } from "../../../seat/src/session.mjs";
@@ -145,6 +145,16 @@ export function env({ files, policy, session, proxy = null }) {
};
}
// #1873 triage-fences: the names env() returns, less the proxy's, and the directories its adapter
// and mounts live in: the pinned binary's when MOSAIC_CLAUDE_BIN is set. A hosted session's host
// (Triage) takes harnessEnv names and mount sources only from these; launches don't read them.
export const envNames = Object.freeze(["MOSAIC_TOOLS", "MOSAIC_CLAUDE_SETTINGS", "MOSAIC_CLAUDE_MCP_CONFIG", "MOSAIC_THINKING", "MOSAIC_MODEL_ACTIVITY_SOURCE"]);
export function installRoots({ env = {} } = {}) {
const roots = [join(REPO, "adapters", "claude"), join(REPO, "tools", "unslop-hook")];
if (env.MOSAIC_CLAUDE_BIN) roots.push(dirname(realpathSync(env.MOSAIC_CLAUDE_BIN)));
return roots;
}
// A turn ends when claude exits; there is no marker.
export const turnEnd = () => "exit";
export const transcript = ({ runDir, store = null }) => (store ? store.projects : join(runDir, "home", ".claude", "projects"));
+8
View File
@@ -118,6 +118,14 @@ export function env({ policy, tools, session, proxy = null }) {
};
}
// #1873 triage-fences: the names env() returns, less the provider key, and the directories its
// adapter and mounts live in. A hosted session's host (Triage) takes harnessEnv names and mount
// sources only from these; launches don't read them. The host refuses every MOSAIC_* name from a
// route, so MOSAIC_TOOLS, MOSAIC_EXTENSIONS and MOSAIC_THINKING are listed only to say what env()
// hands a session: a hosted pi needs the host to set them itself (a later slice).
export const envNames = Object.freeze(["PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]);
export const installRoots = () => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), realpathSync(join(REPO, "node_modules")), join(REPO, "tools", "unslop-hook")];
// The extension writes the turn marker at agent_end; an exit without it is a failed turn.
export const turnEnd = () => "marker";
export const transcript = ({ runDir, store = null }) => (store ? store.session : join(runDir, "session"));
+118 -4
View File
@@ -34,7 +34,7 @@
// the launch (sandbox-unavailable).
import { spawnSync } from "node:child_process";
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync } from "node:fs";
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
@@ -193,6 +193,117 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR
return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", ...identity, "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command];
}
// #1873 triage-fences: what a model route may hand a hosted session, checked before the host
// writes anything and again in hostedBinds. The adapter and each mount's source must be a clean
// absolute path whose real path lies under one of the harness module's install roots, named under
// that same root, and outside every protected path: the data root, the config directory and HOME
// the caller passes, the run directory, ALWAYS_PROTECTED, and any path with a segment that
// contains "secret" in any case. A protected path counts in its own spelling and its real path, and
// a source may neither lie inside one nor contain one. The bind's source is the real path, so a
// link swapped after the check cannot steer it. A mount's dest (its source when it names none) is
// never /tmp, the run directory or a system bind's dest, nor inside or around one, never a parent
// of or equal to a runner file, the adapter or node, and never in or around another mount's dest.
// At most HOSTED_MOUNTS_MAX mounts. A refusal is a HostedRouteError naming its fence, never a path.
// `codeRoot` is the stack's own code and `codeHolder` the one protected path that may hold it:
// HOME, when the stack runs from a copy or a worktree under it. That path does not refuse a source
// whose named and real paths both lie in the code root. Every other check still applies to it, and
// no other protected path, the run directory or ALWAYS_PROTECTED is ever set aside. A code root in
// or around the run directory or ALWAYS_PROTECTED, in either path's spelling or real path, is refused.
export const HOSTED_MOUNTS_MAX = 8;
const ROOTS_MAX = 16;
const PATH_MAX = 4096;
const ALWAYS_PROTECTED = Object.freeze(["/srv/mosaic", "/proc", "/sys", "/dev", "/run", "/root", "/boot"]);
const MOUNT_KEYS = Object.freeze(["src", "dest", "why"]);
export class HostedRouteError extends Error {
constructor(fence, message) {
super(`hosted binds: ${message}`);
this.code = "hosted-binds-refused";
this.fence = fence;
}
}
const refuseRoute = (fence, message) => { throw new HostedRouteError(fence, message); };
// Absolute, already normal (no "..", ".", "//" or trailing slash), not "/", no NUL.
const cleanPath = (p) => typeof p === "string" && p.length > 1 && p.length <= PATH_MAX && !p.includes("\0") && isAbsolute(p) && resolve(p) === p;
const within = (child, parent) => child === parent || child.startsWith(parent + "/");
const overlaps = (a, b) => within(a, b) || within(b, a);
const secretPath = (p) => p.split("/").some((seg) => /secret/i.test(seg));
const realOr = (p) => { try { return realpathSync(p); } catch { return p; } };
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
// `alsoFixed` is a test hook: it adds stand-in fixed paths and never removes a shipped one.
export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = null, codeHolder = null, runDir, node = process.execPath, alsoFixed = [] }) {
if (!cleanPath(runDir)) refuseRoute("protected", "the run directory is not a clean absolute path");
if (!Array.isArray(protectedPaths)) refuseRoute("protected", "no protected paths were given");
if (!Array.isArray(alsoFixed)) refuseRoute("protected", "the added fixed paths are not a list");
// Lists are copied once, so a Proxy cannot answer one length to a check and another to the map.
protectedPaths = Array.from(protectedPaths);
// Each guarded entry: its spellings, and whether a source in the code root is clear of it. The
// fixed paths and the run dir never hold the code. Their spellings are looked up once, here, and
// serve both the code-root check and their guards, so the two always see the same real path.
const fixed = [...ALWAYS_PROTECTED, ...Array.from(alsoFixed), runDir].map((p) => {
if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path");
return { spellings: [p, realOr(p)], holdsCode: false };
});
let code = null;
if (codeRoot !== null) {
if (!cleanPath(codeRoot)) refuseRoute("protected", "the code root is not a clean absolute path");
if (!protectedPaths.includes(codeHolder)) refuseRoute("protected", "the code root's holder is not a protected path");
code = [codeRoot, realOr(codeRoot)];
if (code.some((c) => fixed.some((g) => g.spellings.some((s) => overlaps(c, s))))) refuseRoute("protected", "the code root is in or around a path that is never set aside");
}
const guarded = [...fixed];
for (const p of protectedPaths) {
if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path");
const spellings = [p, realOr(p)];
const holdsCode = p === codeHolder && code !== null && spellings.some((g) => code.some((c) => c !== g && within(c, g)));
guarded.push({ spellings, holdsCode });
}
if (!Array.isArray(installRoots)) refuseRoute("roots", "the harness module declares no usable install roots");
installRoots = Array.from(installRoots);
if (installRoots.length === 0 || installRoots.length > ROOTS_MAX) refuseRoute("roots", "the harness module declares no usable install roots");
const roots = installRoots.map((r) => {
if (!cleanPath(r)) refuseRoute("roots", "an install root is not a clean absolute path");
let real;
try { real = realpathSync(r); } catch { refuseRoute("roots", "an install root is missing"); }
if (real === "/" || !statSync(real).isDirectory()) refuseRoute("roots", "an install root is not a directory");
return { named: r, real };
});
const source = (src, fence, what) => {
if (!cleanPath(src)) refuseRoute(fence, `${what} is not a clean absolute path`);
let real;
try { real = realpathSync(src); } catch { refuseRoute(fence, `${what} is missing`); }
if (!roots.some((r) => (within(src, r.named) || within(src, r.real)) && within(real, r.real))) refuseRoute(fence, `${what} is not under an install root`);
const inCode = code !== null && code.some((c) => within(src, c)) && within(real, code[1]);
if (guarded.some((g) => !(g.holdsCode && inCode) && [src, real].some((p) => g.spellings.some((s) => overlaps(p, s))))) refuseRoute(fence, `${what} is in or around a protected path`);
if ([src, real].some(secretPath)) refuseRoute(fence, `${what} is in a secrets path`);
return real;
};
const adapterReal = source(adapter, "adapter", "the adapter");
if (!statSync(adapterReal).isFile()) refuseRoute("adapter", "the adapter is not a file");
if (!Array.isArray(harnessMounts)) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
harnessMounts = Array.from(harnessMounts);
if (harnessMounts.length > HOSTED_MOUNTS_MAX) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
const apart = ["/tmp", runDir, ...systemBinds(node).map((b) => b.dest ?? b.src)];
const kept = [...RUNNER_FILES, adapter, node];
const dests = [];
const mounts = harnessMounts.map((m, i) => {
const what = `harness mount ${i + 1}`;
if (!plainObject(m) || Object.keys(m).some((k) => !MOUNT_KEYS.includes(k))) refuseRoute("mounts", `${what} is not { src, dest, why }`);
// Each field is read once, so a getter cannot answer one value to a check and another to the bind.
const { src, dest: named, why } = m;
if (typeof why !== "string" || !why || why.length > 256) refuseRoute("mounts", `${what} is not { src, dest, why }`);
if (named !== undefined && !cleanPath(named)) refuseRoute("mount-dest", `${what}'s dest is not a clean absolute path`);
const real = source(src, "mount-src", what);
const dest = named ?? src;
if (apart.some((p) => overlaps(dest, p)) || kept.some((p) => within(p, dest)) || dests.some((d) => overlaps(dest, d))) refuseRoute("mount-dest", `${what}'s dest would cover a path the session needs`);
dests.push(dest);
return { src: real, dest, why };
});
return { adapter: { src: adapterReal, dest: adapter }, mounts };
}
// #1873 triage-host: the binds for a session the Console hosts in no organization (Triage). It
// gets the system part, the runner's files, the adapter and the harness module's mounts like any
// session, and from the data root exactly two directories: its own `runDir` read-write, and
@@ -200,7 +311,9 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR
// calls through stay read-only inside it, and its tmp/ is /tmp. There is no workspace, broker,
// launch or git socket, thread store or org root. Each source inside runDir must be what the host
// just made there, never a link the session left: bwrap resolves a bind's source on the host.
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], relaySocket, node = process.execPath, readOnly = [] }) {
// The adapter and the mounts pass checkHostedRoute against `installRoots`, `protectedPaths` and
// `codeRoot` with its `codeHolder` here too; without install roots nothing binds.
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, relaySocket, node = process.execPath, readOnly = [] }) {
if (relaySocket !== join(runDir, "relay.sock")) throw new Error("hosted binds: the relay socket must be the run directory's relay.sock");
const healthDest = join(runDir, "work", "health");
for (const p of [runDir, healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work"), healthDest]) {
@@ -213,10 +326,11 @@ export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], re
try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${relative(runDir, p)} is missing`); }
if (!ok(st)) throw new Error(`hosted binds: ${relative(runDir, p)} is not what the host made`);
}
const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, codeHolder, runDir, node });
const out = systemBinds(node);
for (const f of RUNNER_FILES) out.push({ kind: "ro", src: f, why: "a repository file the runner loads" });
out.push({ kind: "ro", src: adapter, why: "the harness adapter the runner starts each turn" });
for (const m of harnessMounts) out.push({ kind: "ro", src: m.src, ...(m.dest ? { dest: m.dest } : {}), why: m.why });
out.push({ kind: "ro", src: route.adapter.src, ...(route.adapter.src !== adapter ? { dest: adapter } : {}), why: "the harness adapter the runner starts each turn" });
for (const m of route.mounts) out.push({ kind: "ro", src: m.src, ...(m.dest !== m.src ? { dest: m.dest } : {}), why: m.why });
for (const f of readOnly) out.push({ kind: "ro", src: f, why: "a test fixture" });
out.push(
{ kind: "rw", src: runDir, why: "the session's own state: turns/, session/, work/, tools.sock, turn.done, home/, tmp/" },
+169 -7
View File
@@ -5,8 +5,8 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:net";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { RUNNER_FILES, hostedArgv, hostedBinds } from "../src/sandbox.mjs";
import { dirname, join } from "node:path";
import { HOSTED_MOUNTS_MAX, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../src/sandbox.mjs";
function layout(t) {
const root = mkdtempSync(join(process.env.TMPDIR, "hb-"));
@@ -15,19 +15,21 @@ function layout(t) {
const healthDir = join(dataRoot, "triage", "health");
for (const d of [join(dataRoot, "orgs"), join(dataRoot, "triage", "host"), healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work", "health")]) mkdirSync(d, { recursive: true });
writeFileSync(join(runDir, "session.json"), "{}");
const adapter = join(root, "adapter.sh");
const install = join(root, "install");
mkdirSync(install);
const adapter = join(install, "adapter.sh");
writeFileSync(adapter, "exit 0\n");
return new Promise((resolve) => {
const server = createServer().listen(join(runDir, "relay.sock"), () => {
t.after(() => server.close());
resolve({ root, dataRoot, runDir, healthDir, adapter, relaySocket: join(runDir, "relay.sock") });
resolve({ root, dataRoot, runDir, healthDir, adapter, install, relaySocket: join(runDir, "relay.sock"), installRoots: [install], protectedPaths: [dataRoot] });
});
});
}
test("hosted binds hold the run directory and the health directory of the data root, and nothing else of it", async (t) => {
const p = await layout(t);
const list = hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket });
const list = hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths });
const fromData = list.filter((b) => typeof b.src === "string" && b.src.startsWith(p.dataRoot + "/"));
assert.deepEqual(fromData.map((b) => [b.kind, b.src, b.dest ?? null]), [
["rw", p.runDir, null],
@@ -46,7 +48,7 @@ test("hosted binds hold the run directory and the health directory of the data r
test("hosted binds refuse a relay socket elsewhere, and any source in the run directory that the host did not make", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket };
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
assert.throws(() => hostedBinds({ ...base, relaySocket: join(p.root, "bus.sock") }), /relay socket must be the run directory's relay\.sock/);
// A link in place of each directory the binds read: bwrap would follow it on the host.
for (const d of ["bundle", "tmp", "work"]) {
@@ -72,7 +74,7 @@ test("hosted binds refuse a relay socket elsewhere, and any source in the run di
test("the hosted command line sets no git identity and runs the command under the namespaces", async (t) => {
const p = await layout(t);
const argv = hostedArgv(hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket }), p.runDir, ["node", "runner.mjs", p.runDir], { bwrap: "/b/bwrap" });
const argv = hostedArgv(hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths }), p.runDir, ["node", "runner.mjs", p.runDir], { bwrap: "/b/bwrap" });
assert.equal(argv[0], "/b/bwrap");
assert.deepEqual(argv.slice(1, 5), ["--unshare-user", "--unshare-pid", "--unshare-ipc", "--as-pid-1"]);
assert.deepEqual(argv.slice(-3), ["node", "runner.mjs", p.runDir]);
@@ -81,3 +83,163 @@ test("the hosted command line sets no git identity and runs the command under th
assert.equal(argv[home + 1], join(p.runDir, "home"));
assert.ok(argv.includes("--remount-ro"));
});
// #1873 triage-fences: hostedBinds checks the adapter and the mounts again, so a caller that skips
// the host's own check still binds nothing outside the install roots.
test("hosted binds refuse without install roots or protected paths, and refuse an adapter or a mount source outside the roots or in a protected path", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
refused({ installRoots: undefined }, "roots", "no roots");
refused({ installRoots: [] }, "roots", "empty roots");
refused({ installRoots: ["/"] }, "roots", "root /");
refused({ installRoots: [join(p.root, "absent")] }, "roots", "missing root");
refused({ installRoots: [p.adapter] }, "roots", "a file as root");
refused({ protectedPaths: undefined }, "protected", "no protected paths");
refused({ protectedPaths: ["relative"] }, "protected", "relative protected path");
writeFileSync(join(p.root, "out.sh"), "x");
refused({ adapter: join(p.root, "out.sh") }, "adapter", "adapter outside");
symlinkSync(join(p.root, "out.sh"), join(p.install, "link.sh"));
refused({ adapter: join(p.install, "link.sh") }, "adapter", "adapter link out");
refused({ adapter: p.install }, "adapter", "adapter is a directory");
refused({ harnessMounts: [{ src: join(p.install, "link.sh"), why: "w" }] }, "mount-src", "mount link out");
refused({ harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }], installRoots: [p.root] }, "mount-src", "mount in the data root");
refused({ harnessMounts: [{ src: p.root, why: "w" }], installRoots: [p.root] }, "mount-src", "mount around the data root");
mkdirSync(join(p.install, "secrets"));
writeFileSync(join(p.install, "secrets", "k"), "x");
refused({ harnessMounts: [{ src: join(p.install, "secrets", "k"), why: "w" }] }, "mount-src", "mount in secrets");
writeFileSync(join(p.install, "m"), "x");
refused({ harnessMounts: Array.from({ length: HOSTED_MOUNTS_MAX + 1 }, (_, i) => ({ src: join(p.install, "m"), dest: `/opt/m${i}`, why: "w" })) }, "mounts", "too many");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/tmp/m", why: "w" }] }, "mount-dest", "dest under /tmp");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: p.runDir, why: "w" }] }, "mount-dest", "dest is the run dir");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: join(p.runDir, "session.json"), why: "w" }] }, "mount-dest", "dest is session.json");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/usr", why: "w" }] }, "mount-dest", "dest is a system bind");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: dirname(RUNNER_FILES[0]), why: "w" }] }, "mount-dest", "dest holds a runner file");
refused({ harnessMounts: [{ src: join(p.install, "m"), why: "w", kind: "rw" }] }, "mounts", "a kind of its own");
});
test("hosted binds bind the real file of a link that stays inside the install root, at the path the route named", async (t) => {
const p = await layout(t);
writeFileSync(join(p.install, "real.mjs"), "x");
symlinkSync(join(p.install, "real.mjs"), join(p.install, "named.mjs"));
symlinkSync(p.adapter, join(p.install, "adapter-link.sh"));
const list = hostedBinds({
runDir: p.runDir, healthDir: p.healthDir, adapter: join(p.install, "adapter-link.sh"), relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths,
harnessMounts: [{ src: join(p.install, "named.mjs"), why: "w" }, { src: join(p.install, "real.mjs"), dest: "/opt/real.mjs", why: "w2" }],
});
assert.ok(list.some((b) => b.kind === "ro" && b.src === p.adapter && b.dest === join(p.install, "adapter-link.sh")));
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === join(p.install, "named.mjs") && b.why === "w"));
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === "/opt/real.mjs" && b.why === "w2"));
assert.ok(!list.some((b) => b.src === join(p.install, "named.mjs")));
});
test("a protected path that holds the code root (HOME over a copy or a worktree) does not refuse a source inside the code root; everything else still holds", async (t) => {
const p = await layout(t);
// home/ holds the code root code/, which holds the install root.
const home = join(p.root, "home");
const code = join(home, "code");
const inst = join(code, "inst");
mkdirSync(join(inst, "secrets"), { recursive: true });
for (const f of ["adapter.sh", "m", join("secrets", "k")]) writeFileSync(join(inst, f), "x");
writeFileSync(join(home, "outside"), "x");
mkdirSync(join(code, "data"));
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: join(inst, "adapter.sh"), relaySocket: p.relaySocket, installRoots: [inst], protectedPaths: [p.dataRoot, home], codeRoot: code, codeHolder: home };
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(inst, "m"), dest: "/opt/m", why: "w" }] });
assert.ok(list.some((b) => b.src === join(inst, "adapter.sh")) && list.some((b) => b.src === join(inst, "m") && b.dest === "/opt/m"));
// Without the code root, HOME refuses the same adapter.
refused({ codeRoot: null }, "adapter", "no code root");
// A code root that is HOME itself sets nothing aside.
refused({ codeRoot: home }, "adapter", "code root is HOME");
// A source under HOME outside the code root, even inside an install root.
refused({ installRoots: [home], adapter: join(home, "outside") }, "adapter", "outside the code root");
// A link inside the code root to a file outside it.
symlinkSync(join(home, "outside"), join(inst, "out"));
refused({ installRoots: [inst, home], harnessMounts: [{ src: join(inst, "out"), why: "w" }] }, "mount-src", "link out of the code root");
// A protected path inside the code root still refuses.
writeFileSync(join(code, "data", "f"), "x");
refused({ installRoots: [code], protectedPaths: [p.dataRoot, home, join(code, "data")], harnessMounts: [{ src: join(code, "data", "f"), why: "w" }] }, "mount-src", "protected path in the code root");
// The secrets check still holds inside the code root.
refused({ harnessMounts: [{ src: join(inst, "secrets", "k"), why: "w" }] }, "mount-src", "secrets in the code root");
// The run directory and the fixed list are never set aside, and a code root around them is refused.
refused({ codeRoot: p.root, installRoots: [p.root], harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }] }, "protected", "code root holds the run dir");
refused({ codeRoot: "/srv/mosaic/x" }, "protected", "code root in a fixed path");
refused({ codeRoot: "relative" }, "protected", "relative code root");
// Only the named holder sets the code aside: another protected path that holds the code still refuses.
refused({ protectedPaths: [p.dataRoot, home, p.root] }, "adapter", "a second protected path holds the code");
refused({ codeHolder: null }, "protected", "no holder");
refused({ codeHolder: join(p.root, "elsewhere") }, "protected", "a holder that is not a protected path");
// A run directory named through a link: a code root in its real path is refused before any check.
const realRun = join(home, "run");
mkdirSync(join(realRun, "code", "inst"), { recursive: true });
writeFileSync(join(realRun, "code", "inst", "a.sh"), "x");
symlinkSync(realRun, join(p.root, "runlink"));
assert.throws(() => checkHostedRoute({ adapter: join(realRun, "code", "inst", "a.sh"), harnessMounts: [], installRoots: [join(realRun, "code", "inst")], protectedPaths: [p.dataRoot, home], codeRoot: join(realRun, "code"), codeHolder: home, runDir: join(p.root, "runlink") }), (e) => e.fence === "protected", "code root in the run dir's real path");
});
test("a fixed path named through a link: a code root in its real path is refused before any guard, and a source there is refused by its guard", async (t) => {
const p = await layout(t);
// None of the shipped fixed paths is a link on a test host, so the test hook adds a stand-in.
const home = join(p.root, "home");
// The real path lies outside HOME and the data root, so only the stand-in's own guard can refuse
// a source there.
const real = join(p.root, "fixedreal");
const inst = join(real, "code", "inst");
mkdirSync(inst, { recursive: true });
writeFileSync(join(inst, "a.sh"), "x");
const link = join(p.root, "fixedlink");
symlinkSync(real, link);
const base = { adapter: join(inst, "a.sh"), harnessMounts: [], installRoots: [inst], protectedPaths: [p.dataRoot, home], codeHolder: home, runDir: p.runDir, alsoFixed: [link] };
const refused = (opts, fence, message, label) => assert.throws(() => checkHostedRoute({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence && message.test(e.message), label);
// The code root lies in the stand-in's real path, not under the name the list gives.
refused({ codeRoot: join(real, "code") }, "protected", /never set aside/, "code root in a fixed path's real path");
// With the code root in HOME, the source in the stand-in's real path is refused by the stand-in's
// guard, which holds the same real spelling. No other guard holds that path.
mkdirSync(join(home, "code"), { recursive: true });
refused({ codeRoot: join(home, "code") }, "adapter", /protected path/, "source in a fixed path's real path");
// The same source passes without the stand-in: only the stand-in refused it.
assert.equal(checkHostedRoute({ ...base, alsoFixed: [], codeRoot: join(home, "code") }).adapter.src, join(inst, "a.sh"));
// The hook adds fixed paths and never removes one, and takes only a list of clean absolute paths.
refused({ alsoFixed: [], codeRoot: "/srv/mosaic/x" }, "protected", /never set aside/, "shipped fixed path with an empty hook");
refused({ alsoFixed: ["relative"], codeRoot: join(real, "code") }, "protected", /clean absolute/, "relative stand-in");
refused({ alsoFixed: "/x", codeRoot: join(real, "code") }, "protected", /clean absolute|list/, "a hook that is not a list");
});
test("a list that answers one length to the check and another later is read once", async (t) => {
const p = await layout(t);
const items = [];
for (let i = 0; i <= HOSTED_MOUNTS_MAX; i++) { writeFileSync(join(p.install, `m${i}`), "x"); items.push({ src: join(p.install, `m${i}`), dest: `/opt/m${i}`, why: "w" }); }
let reads = 0;
const mounts = new Proxy(items, { get: (o, k) => (k === "length" ? (reads++ === 0 ? 1 : o.length) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: mounts, installRoots: p.installRoots, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "mounts");
// Install roots: two short answers pass the count, then a long one would add roots the count never saw.
const roots = [];
for (let i = 0; i <= 16; i++) { roots.push(join(p.root, `r${i}`)); mkdirSync(roots[i]); }
writeFileSync(join(roots[16], "a.sh"), "x");
let rootReads = 0;
const rootList = new Proxy(roots, { get: (o, k) => (k === "length" ? (rootReads++ < 2 ? 1 : o.length) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: join(roots[16], "a.sh"), harnessMounts: [], installRoots: rootList, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "adapter");
// Protected paths: the holder check sees HOME, then a shorter answer would leave HOME unguarded.
const home = join(p.root, "home");
mkdirSync(join(home, "code"), { recursive: true });
writeFileSync(join(home, "f"), "x");
let guardReads = 0;
const guards = new Proxy([p.dataRoot, home], { get: (o, k) => (k === "length" ? (guardReads++ === 0 ? 2 : 1) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: [{ src: join(home, "f"), dest: "/opt/f", why: "w" }], installRoots: [p.install, home], protectedPaths: guards, codeRoot: join(home, "code"), codeHolder: home, runDir: p.runDir }), (e) => e.fence === "protected" || e.fence === "mount-src");
});
test("each mount field is read once, and no mount's dest lies in or around another's", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
writeFileSync(join(p.install, "m"), "x");
writeFileSync(join(p.install, "n"), "x");
let reads = 0;
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), why: "w", get dest() { return reads++ === 0 ? undefined : "/opt/../tmp"; } }] });
assert.equal(reads, 1);
assert.ok(list.some((b) => b.src === join(p.install, "m") && b.dest === undefined));
assert.ok(!list.some((b) => b.dest === "/opt/../tmp"));
for (const [a, b] of [["/opt/x", "/opt/x/f"], ["/opt/x/f", "/opt/x"], ["/opt/x", "/opt/x"]]) {
assert.throws(() => hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: a, why: "w" }, { src: join(p.install, "n"), dest: b, why: "w" }] }), (e) => e.fence === "mount-dest", `${a} then ${b}`);
}
assert.equal(hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: "/opt/x", why: "w" }, { src: join(p.install, "n"), dest: "/opt/xy", why: "w" }] }).filter((b) => b.dest?.startsWith("/opt/")).length, 2);
});
+4 -3
View File
@@ -39,7 +39,7 @@ import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snaps
import { busesStopped } from '../../cli/src/proxy-admin-host.mjs';
import { agentLevelsWriteRoutes } from './agent-levels-write.mjs';
import { RESTART_EXIT } from '../../cli/src/org-console.mjs';
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs';
import { selectorScope } from '../../organization/src/selector.mjs';
// The bus verifies the Console's exact same-tree script in /proc, whose argv preserves a
// relative shell argument even though Node's process.argv resolves it. Re-exec the same
@@ -204,8 +204,9 @@ try {
// and the preview are reads over requestRead.
templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
// Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names.
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template) }) : null,
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names
// less the system-only ones. packs-http's workflowsRead drops them again and is the tested gate.
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template).filter(t => !systemOnly(t)) }) : null,
reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }),
};
},
+4 -1
View File
@@ -24,6 +24,8 @@
// console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows`
// (SP6) is the owner's read of the organization file as the writer reads it ({document, revision,
// templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it.
import { systemOnly } from '../../organization/src/vocabulary.mjs';
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|board|workflows(?:\/([^/]+))?)$/;
// Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task
// board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405).
@@ -171,7 +173,8 @@ async function workflowsRead(res, { workflows, live, session, writable }) {
}
const roles = {
definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(),
templates: current.templates.filter(n => typeof n === 'string').sort(),
// #1873 triage-followups: a system-only template (organization vocabulary SYSTEM_ONLY) is never offered.
templates: current.templates.filter(n => typeof n === 'string' && !systemOnly(n)).sort(),
};
return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable });
}
+30 -22
View File
@@ -193,7 +193,7 @@
catch { return { unknown: true }; }
if (res.type === 'opaqueredirect') return { signedOut: true };
try { result = await res.json(); } catch { return { unknown: true }; }
return { ok: res.ok, result };
return { ok: res.ok, status: res.status, result };
}
// The request's closing read, or a reason the chain stops.
async function closing(request, org) {
@@ -215,31 +215,39 @@
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
} catch { return null; }
}
async function restartAgent(name, thread) {
const org = window.MosaicOrg?.id ?? null;
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
const paint = () => paintRestart(name, org);
const stop = text => { r.busy = false; r.text = text; paint(); };
paint();
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
if (asked.signedOut) return stop('Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
// SP19 (#1873): the agent drawer's Restart runs this same chain. `org` is the agent's own organization
// (on #/agents the page has none), `reason` goes with the terminate, `text(step, detail)` may give the
// words for a step (nothing keeps the route-change words below), and `onStatus({ step, busy, text })`
// takes each line in place of the Routing receipt's button. The chain never regenerates.
async function restartAgent(name, thread, { org = window.MosaicOrg?.id ?? null, reason = 'route change', text, onStatus } = {}) {
const r = { busy: true, text: '' };
if (!onStatus) restarts[name] = r;
const paint = step => onStatus ? onStatus({ step, busy: r.busy, text: r.text }) : paintRestart(name, org);
const words = (step, detail, own) => (typeof text === 'function' ? text(step, detail) : undefined) ?? own;
const say = (step, detail, own) => { r.text = words(step, detail, own); paint(step); };
const stop = (step, detail, own) => { r.busy = false; say(step, detail, own); };
say('ending', {}, `Terminating ${name}…`);
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason });
if (asked.signedOut) return stop('signedOut', {}, 'Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return asked.ok || asked.unknown ? stop('endUnknown', {}, UNKNOWN) : stop('endRefused', { status: asked.status, result: asked.result }, refused(asked.result));
const ended = await closing(asked.result.request, org);
if (ended.stop) return stop(ended.stop);
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
if (ended.stop) return stop('endOpen', { stop: ended.stop }, ended.stop);
if (ended.done.reason) return stop('endClosed', { reason: ended.done.reason }, `${name}: ${ended.done.reason}. It was not restarted.`);
say('ended', {}, `Terminated ${name}. Waiting for its session to end…`);
let left = false;
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
r.text = `Launching ${name}…`; paint();
if (!left) return stop('stillRunning', {}, `${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
const time = new Date().toLocaleTimeString();
if (thread) return stop('threadEnded', { time }, `Terminated ${name} at ${time}. Its next message starts it on the new route.`);
say('launching', {}, `Launching ${name}…`);
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
if (launch.signedOut) return stop('launchSignedOut', {}, 'Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return launch.ok || launch.unknown ? stop('launchUnknown', {}, `${UNKNOWN} It was terminated.`) : stop('launchRefused', { status: launch.status, result: launch.result }, `${refused(launch.result)} It was terminated and not launched.`);
const started = await closing(launch.result.request, org);
if (started.stop) return stop(started.stop);
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
if (started.stop) return stop('launchOpen', { stop: started.stop }, started.stop);
if (started.done.reason) return stop('launchClosed', { reason: started.done.reason }, `${name}: ${started.done.reason}. It was terminated and not launched.`);
const run = started.done.done?.run ?? null;
return stop('restarted', { run }, `Restarted ${name} on the new route${run ? ` (run ${run})` : ''}.`);
}
document.addEventListener('click', e => {
const b = e.target.closest?.('[data-agent-restart]');
@@ -247,7 +255,7 @@
restartAgent(b.dataset.agentRestart, b.dataset.agentThread === 'yes');
});
window.MosaicAgents = Object.freeze({ section, restartMarkup, isThread: definition => threadDefinitions.has(definition) });
window.MosaicAgents = Object.freeze({ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions.has(definition) });
})();
/* #1873 A2: Settings > Agents, the root and project agent levels. bus.js awaits section() for the
+5 -1
View File
@@ -2246,5 +2246,9 @@
window.addEventListener('hashchange', e => render(!agentOnly(e.oldURL, e.newURL)));
$('refresh').addEventListener('click', () => render(false));
$('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed
render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
// #1873 triage-followups: the first render ends by focusing the page's heading. A drawer or dialog the
// reader opened before then keeps its focus: the Triage drawer, an agent drawer, the narrow-screen
// menu or any open dialog.
const holdsFocus = () => { const a = document.activeElement; return !!a && (!!a.closest('.ws-drawer:not([hidden]), [data-ws-drawer], dialog[open], [role="dialog"], [role="alertdialog"]') || (drawerOpen && nav.contains(a))); };
render(false).then(() => { if (!$('bus-view').hidden && !holdsFocus()) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
})();
+1 -1
View File
@@ -1,4 +1,4 @@
[data-packs],[data-workflows]{margin-top:16px}
[data-packs]{margin-top:16px}
.pack-list,.pack-hires{list-style:none;margin:8px 0;padding:0}
.pack-row,.pack-hire{border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere}
.pack-preview{border:1px solid var(--border);border-radius:var(--r);padding:12px;margin:12px 0;overflow-wrap:anywhere}
+13
View File
@@ -631,6 +631,14 @@ html[data-organizations] .ws-orgcard .at{grid-column:3;grid-row:1;font:500 11.5p
html[data-organizations] .ws-orgcard .why{grid-column:1/-1;font-size:12px;color:var(--muted)}
html[data-organizations] .ws-orgcard.off a{border-style:dashed}
html[data-organizations] .ws-home-split{margin-top:4px}
/* SP18: the Dashboard's columns line up with its tile row. Three equal tracks with the tiles' gap, the left
column spanning two, end on a tile edge whether the row holds six tiles (after the fourth) or three
(after the second). Below 760 px the split is one column. */
html[data-organizations] .ws-home>.ws-tiles{gap:var(--gap)}
@media (min-width:760px){
html[data-organizations] .ws-home-split{grid-template-columns:repeat(3,minmax(0,1fr));gap:var(--gap)}
html[data-organizations] .ws-home-split>:first-child{grid-column:span 2}
}
html[data-organizations] .ws-trail{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;background:var(--surface)}
html[data-organizations] .ws-trail li{display:grid;grid-template-columns:48px 20px minmax(0,1fr);gap:10px;padding:7px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent);font-size:13px;align-items:center}
html[data-organizations] .ws-trail li:last-child{border-bottom:0}
@@ -770,6 +778,11 @@ html[data-organizations] .ws-drawer-acts .note{flex-basis:100%}
@media (min-width:1200px){html[data-organizations] body:has(.ws-drawer) .content{padding-right:calc(420px + 22px)}}
@media (max-width:700px){
html[data-organizations] .ws-drawer{top:0;left:0;right:0;width:auto;border-left:0;box-shadow:none}
/* SP18: the sheet covers the screen, so the page under it is held to one screen and does not scroll; it
kept its own height before, and the sheet showed over a long blank area. workspace.js puts the page's
place back on Close. */
html[data-organizations]:has(#bus-view .ws-drawer){overflow:hidden}
html[data-organizations]:has(#bus-view .ws-drawer) body{height:100dvh;overflow:hidden}
}
@media (max-width:1100px){
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(3,minmax(0,1fr))}
+3 -5
View File
@@ -40,8 +40,8 @@
return value;
}
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
// #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The read may still
// list them; a step role never resolves to one and the picker never offers one.
// #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The server leaves
// them out of the read; this filter stays so a step role never resolves to one and the picker never offers one.
const SYSTEM_ONLY = ['triage'];
const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r));
async function read(org, s) {
@@ -823,7 +823,5 @@
window.matchMedia(NARROW).addEventListener('change', () => {
if (document.querySelector('[data-wfg-graph]')) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
});
// section(): the organization page's old form editor is gone (SP17); workspace.js still asks for it.
const section = () => '';
window.MosaicWorkflows = { load, section, page, card, hasDraft, forget, landed };
window.MosaicWorkflows = { load, page, card, hasDraft, forget, landed };
})();
+148 -34
View File
@@ -367,21 +367,20 @@
${orgTiles}
${docrow}
<div class="ws-split">
<section aria-label="Sessions and workflows">
<section aria-label="Sessions, workflows, autonomy and starter packs">
${secH('Active agent sessions', live ? (noRuns ? 'running not read' : live.length ? `${live.length} running${tileAgents ? `, ${liveWorking} working` : ', working not read'}` : 'none running') : '', `<a href="#/agents?${oq}" data-focus-key="agents-all">This organization's agents</a>`)}
${sessions}
${window.MosaicWorkflows?.card?.(id, { stopped, label: label(org) }) ?? ''}
<div class="ws-wide">
${stopped ? stoppedPanel('data-autonomy', 'Autonomy') : window.MosaicAutonomy?.section(id) ?? ''}
${stopped ? stoppedPanel('data-packs', 'Starter packs') : window.MosaicPacks?.section(id) ?? ''}
</div>
</section>
<section aria-label="Settings">
${secH('Settings', 'every setting, with where its value comes from')}
${settingsList(org, { business, settings, instances, noRuns, orgCount: list ? list.length : null })}
</section>
</div>
<div class="ws-wide">
${stopped ? stoppedPanel('data-autonomy', 'Autonomy') : window.MosaicAutonomy?.section(id) ?? ''}
${stopped ? stoppedPanel('data-packs', 'Starter packs') : window.MosaicPacks?.section(id) ?? ''}
${stopped ? stoppedPanel('data-workflows', 'Workflows') : window.MosaicWorkflows?.section(id) ?? ''}
</div>
${await drawerRead}
</article>`;
}
@@ -1119,8 +1118,16 @@
const DRAWER_LIMIT = 5, STOP_REASON = 'Stopped from the agent drawer.';
const STOP_UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.';
// The Stop state of the drawer's agent survives repaints: `confirm` while it asks, `busy` while the
// request is open, then the result in words beside the button.
let stopState = null; // { id, confirm, busy, text }
// request is open, then the result in words beside the button. SP19: `kind` says whether Stop or
// Restart asks (no kind is Stop). While either asks or runs, both buttons wait.
let stopState = null; // { id, kind, confirm, busy, text }
// SP19: each drawer agent's restart, kept per agent so several can run at once and none loses its
// line when another drawer asks or stops: `busy` while it runs, then its outcome in words. An entry
// goes when a new question starts on that agent, or when the drawer closes after it finished.
const restarts = new Map(); // id -> { busy, text }
// The state a drawer draws: its own question or Stop first, else its restart.
const actState = id => stopState?.id === id ? stopState : restarts.has(id) ? { id, kind: 'restart', ...restarts.get(id) } : null;
const RESTART_REASON = 'restart from the agent drawer';
let drawerFocus = false, drawerShown = null;
// The drawer holds at most one history entry. A row opened from the page without a drawer pushes one
// entry marked in history.state; switching rows replaces it. Close goes Back only from that marked
@@ -1133,11 +1140,16 @@
const sansAgent = () => { const n = queryOf(); n.delete('agent'); const s = n.toString(); return `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`; };
// The row's name as a link that opens the drawer: a native link, so Tab reaches it and Enter opens it.
const drawerLink = (q, a) => `<a class="ws-drawer-open" href="${esc(drawerHref(q, `${a.org}:${a.key}`))}" data-ws-drawer-open="${esc(`${a.org}:${a.key}`)}" data-focus-key="${esc(`agent:${a.org}:${a.key}`)}">${esc(a.name)}</a>`;
const stopConfirm = (name, who) => `<span class="ws-drawer-confirm" data-drawer-stop-confirm>Stop ${esc(who)}? <button type="button" class="ws-btn danger" data-drawer-stop-yes data-focus-key="drawer-stop-yes">Stop ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-stop-no data-focus-key="drawer-stop-no">Cancel</button></span>`;
function stopActions(pick, a, orgName) {
const st = stopState?.id === pick.id ? stopState : null;
const who = `${a.name} in ${orgName}`;
return `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${st?.busy || st?.confirm ? ' disabled' : ''}>${st?.busy ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm ? stopConfirm(a.name, who) : ''}`;
// SP19: Stop and Restart ask in the same confirm step, each under its own data attributes.
const actConfirm = (kind, name, question) => `<span class="ws-drawer-confirm" data-drawer-${kind}-confirm>${esc(question)} <button type="button" class="ws-btn danger" data-drawer-${kind}-yes data-focus-key="drawer-${kind}-yes">${kind === 'stop' ? 'Stop' : 'Restart'} ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-${kind}-no data-focus-key="drawer-${kind}-no">Cancel</button></span>`;
const stopConfirm = (name, who) => actConfirm('stop', name, `Stop ${who}?`);
const restartConfirm = (name, who, thread) => actConfirm('restart', name, `Restart ${who}? ${thread ? 'It ends its session; its next message starts it again.' : 'It ends its session and launches it again.'}`);
function stopActions(pick, a, orgName, thread) {
const st = actState(pick.id), kind = st?.kind || 'stop';
const who = `${a.name} in ${orgName}`, hold = st?.busy || st?.confirm ? ' disabled' : '';
const stop = `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${hold}>${st?.busy && kind === 'stop' ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'stop' ? stopConfirm(a.name, who) : ''}`;
if (!window.MosaicAgents?.restart) return stop;
return `${stop} <button type="button" class="ws-btn" data-drawer-restart data-drawer-thread="${thread ? 'yes' : 'no'}" data-focus-key="drawer-restart"${hold}>${st?.busy && kind === 'restart' ? 'Restarting…' : 'Restart'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'restart' ? restartConfirm(a.name, who, thread) : ''}`;
}
// SP13 (#1873): the drawer's instances read gives the agent's state. The drawer does not hold the
// page for it: once the page's own reads have answered (`opts.page`), a drawer whose instances read
@@ -1336,7 +1348,8 @@
: a.level !== 'org' ? 'No Message: a copy is not messaged from here.'
: 'No Message: this Console messages only conversation agents, such as the Assistant.'}</p>`);
else if (change) acts.push(`<p class="note" data-drawer-nomessage>No Message: this Console does not send chat in ${esc(orgName)}.</p>`);
if (change && a.level === 'org' && !a.keep && running(item) > 0) acts.push(stopActions(pick, a, orgName));
// SP19: a restart that is running keeps its buttons even when a repaint reads no run between its end and its launch.
if (change && a.level === 'org' && !a.keep && (running(item) > 0 || restarts.get(id)?.busy)) acts.push(stopActions(pick, a, orgName, !!window.MosaicAgents?.isThread?.(def)));
// Why Stop is not offered, in words, where this Console could otherwise change the organization's agents.
// SP13: "not running" is a reason only once the instances read has given the agent's runs.
else if (change) acts.push(`<p class="note" data-drawer-nostop>${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.'
@@ -1344,10 +1357,25 @@
: a.level !== 'org' ? 'A copy is not stopped from here.'
: a.keep ? `${esc(a.name)} is one of ${esc(orgName)}’s protected agents, so it is not stopped from here.`
: 'It is not running, so there is nothing to stop.'}</p>`);
const st = stopState?.id === id ? stopState : null;
const st = actState(id);
const actions = chat || change
? `<div class="ws-drawer-acts" data-drawer-actions>${acts.join(' ')}<p class="ws-drawer-status" id="ws-drawer-status" role="status" data-drawer-status>${esc(st?.text || '')}</p></div>`
: `<p class="note" data-drawer-readonly>This Console only reads ${esc(orgName)}. It can not message or stop its agents.</p>`;
// SP18: the agents read lists only roles a run holds now, and thread.claims only conversations a run
// holds now; each row carries that run and when it took the role or the conversation. A claim counts
// only when the instances read lists its run as running, so a claim left by a run that ended does not
// date a stopped agent. Last activity is the latest such time. No read keeps when a run ended or when
// the agent last sent a message (a thread's messages read pages from the oldest message), so neither is shown.
const runs = !unknown && runsRead(item) ? item.running : null;
const claims = [a.s ? { ...a.s, what: 'the role' } : null, ...arr(body?.sessions).filter(x => x?.kind === 'thread' && x.org === org && x.instance === key).map(x => ({ ...x, what: 'the conversation' }))]
.filter(c => c && msOf(c.claimedAt) !== null && (!runs || runs.includes(c.run))).sort((x, y) => msOf(y.claimedAt) - msOf(x.claimedAt));
const last = claims[0], claimWhy = notRead(['agents', 'claims']);
// With the runs not read, nothing checked the claim against a live run, so the line says "a run".
const activity = last ? `${!runs ? 'a run' : runs.length > 1 ? `one of its ${runs.length} runs` : 'its run'} took ${last.what} <time datetime="${esc(last.claimedAt)}" title="${esc(new Date(msOf(last.claimedAt)).toLocaleString())}">${esc(ago(last.claimedAt))}</time>`
: `<span class="muted">${claimWhy ? `not read: ${esc(claimWhy)}`
: runs?.length ? `not recorded: ${runs.length > 1 ? 'its runs hold' : 'its run holds'} no role or conversation yet`
: !runs ? 'not recorded: the agents and claims reads show no run holding its role or a conversation, and its runs were not read'
: 'not recorded: no run holds it now, and no read keeps when its last run ended'}</span>`;
const fields = [
field('org', 'Organization', orgChip(o, org)),
// A pack hire's pack is named once, in Hired from; the Role row says only that it was hired.
@@ -1358,11 +1386,7 @@
model ? field('model', 'Model', `<span class="mono">${esc(model)}</span>`) : '',
project ? field('project', 'Project', `<a href="${esc(`${orgHref(org)}/projects/${enc(project.id)}`)}">${esc(project.name || project.key || project.id)}</a>${project.from ? ` <span class="t2">${project.from}</span>` : ''}`) : '',
task ? field('task', 'Task', `<a href="${esc(taskHref(task.ref))}">${esc(task.title || task.ref)}</a>${task.title ? ` <span class="t2 mono">${esc(task.ref)}</span>` : ''}`) : '',
// SP16: no read the Console makes carries the time of a role agent's last message or run. The agents
// read's time is when it took the role and `since` is when its present state began, so neither is shown.
// An agent holding a conversation has its messages in that thread's messages read, but that read pages
// from the oldest message, so its last message is a walk of every page away; the drawer does not make it.
field('activity', 'Last activity', `<span class="muted">${thread?.thread ? 'not shown: reading it means reading the whole conversation' : 'not recorded'}</span>`),
field('activity', 'Last activity', activity),
].join('');
return shell(a.name, `<dl class="ws-drawer-fields">${fields}</dl>
<section class="ws-drawer-sec" data-drawer-tasks aria-label="Open tasks assigned to ${esc(a.name)}"><h3>Open tasks</h3>${tasksBody}${tasksAll}</section>
@@ -1373,10 +1397,21 @@
// `agent` from the address in place. Either way the page repaints without it and focus returns to the row.
function closeDrawer() {
if (!stopState?.busy) stopState = null;
for (const [k, r] of restarts) if (!r.busy) restarts.delete(k);
if (stateOf()?.[DRAWER_MARK] && queryOf().has('agent')) { history.back(); return; }
history.replaceState(unmarked(), '', sansAgent());
document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
}
// SP18: below 701 px the open drawer is a sheet and shell.css holds the page under it to one screen, which
// scrolls the page to the top. The page's place is kept while no drawer is open, with the page the sheet
// opened over. It is put back only when the drawer closes onto that same page (Close, Escape or Back); a
// link in the sheet goes to another page, which starts at its top, and the kept place is dropped. Some
// pages a link opens (a project, the Assistant) are drawn without afterPaint, so the place is dropped as
// soon as the address leaves the page under the sheet.
const SHEET = window.matchMedia('(max-width:700px)');
let pageY = 0, sheetOver = null;
window.addEventListener('scroll', () => { if (!document.querySelector('#bus-view [data-ws-drawer]')) pageY = window.scrollY; }, { passive: true });
window.addEventListener('hashchange', () => { if (sheetOver !== null && sansAgent() !== sheetOver) { sheetOver = null; pageY = 0; } });
// bus.js calls this after each paint: focus moves into a drawer a row opened, and back to the row
// when the drawer has closed and focus was left nowhere.
function afterPaint() {
@@ -1384,8 +1419,13 @@
const view = document.getElementById('bus-view'), d = view?.querySelector('[data-ws-drawer]');
const now = d?.dataset.wsDrawer || null, was = drawerShown;
drawerShown = now;
if (now) sheetOver = sansAgent();
if (d && drawerFocus) { drawerFocus = false; d.querySelector('h2')?.focus({ preventScroll: true }); return; }
drawerFocus = false;
if (!now && sheetOver !== null) {
if (SHEET.matches && pageY && sheetOver === sansAgent()) window.scrollTo(0, pageY);
sheetOver = null; pageY = window.scrollY;
}
if (!now && was) {
const a = document.activeElement;
if (!a || a === document.body || !view?.contains(a)) view?.querySelector(`[data-focus-key="${CSS.escape(`agent:${was}`)}"]`)?.focus({ preventScroll: true });
@@ -1395,7 +1435,7 @@
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
stopState = { id, busy: true, text: `Stopping ${name}…` };
const repaint = () => document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } const rb = now.querySelector('[data-drawer-restart]'); if (rb) rb.disabled = !!stopState.busy; now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
const finish = text => { stopState = { id, text }; paint(); const b = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-stop]`); b?.focus({ preventScroll: true }); };
paint();
let res, body = null;
@@ -1423,6 +1463,72 @@
}
finish(`Request ${request} is still open. Read the agents again later.`);
}
// SP19: the drawer's Restart. The agents.js chain ends the agent through its own organization's routes
// (the drawer's, which on #/agents is not the page's), waits for the request to close and its runs to
// reach 0, then launches it; a conversation agent is not launched. It never regenerates. Each step is
// painted in place; a refusal before the end leaves both buttons usable and focus on Restart.
const refusedWhy = (d, orgName) => {
const e = d?.result?.error, m = d?.result?.message;
if (d?.status === 403 && e === 'read-only') return `this Console only reads agents in ${orgName} (read-only).`;
if (d?.status === 403 && (e === 'unavailable' || e === 'owner-only')) return `this Console is not the owner of ${orgName}, so it does not restart its agents.`;
if (e === 'no-bus-host') return `the bus of ${orgName} is not running. Nothing changed.`;
if (e === 'org-archived') return `${orgName} is archived, so its agents are not changed. Nothing changed.`;
if (e === 'org-unavailable') return `${orgName} is not available to this Console. Nothing changed.`;
if (d?.result?.sent === false && typeof m === 'string' && m) return m;
if (d?.result?.sent === false && typeof e === 'string') return `the bus refused (${e}).`;
return STOP_UNKNOWN;
};
const restartWords = (name, orgName) => (step, d) => ({
ending: `Restarting ${name}: asking it to end…`,
signedOut: 'Not restarted: sign in again, then read the agents.',
endUnknown: `Not restarted: ${STOP_UNKNOWN}`,
endRefused: `Not restarted: ${refusedWhy(d, orgName)}`,
endOpen: `Not restarted: ${d?.stop}`,
endClosed: `Not restarted: ${name} was not ended (${d?.reason}).`,
ended: `${name} was asked to end. Waiting for its session to end…`,
stillRunning: `Not restarted: ${name} was asked to end, but its session is still running. Read the agents again before trying.`,
threadEnded: `Ended ${name} at ${d?.time}. Its next message starts it.`,
launching: `${name} has ended. Launching it…`,
launchSignedOut: `${name} was ended and not launched: sign in again, then read the agents.`,
launchUnknown: `${name} was ended. The launch outcome is unknown; read the agents again before trying. Nothing was retried.`,
launchRefused: `${name} was ended and not launched: ${refusedWhy(d, orgName)}`,
launchOpen: `${name} was ended. ${d?.stop}`,
launchClosed: `${name} was ended and not launched: ${d?.reason}.`,
restarted: `Restarted ${name}${d?.run ? ` (run ${d.run})` : ''}.`,
})[step];
async function restartAgent(d) {
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
const thread = d.querySelector('[data-drawer-restart]')?.dataset.drawerThread === 'yes';
if (restarts.get(id)?.busy) return;
// The question is answered: from now on this agent's drawer draws its restart.
if (stopState?.id === id) stopState = null;
restarts.set(id, { busy: true, text: '' });
// Paint this agent's drawer in place, when it is on screen and no question of its own holds it.
const paint = () => {
const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), r = restarts.get(id); if (!now || !r || stopState?.id === id) return;
const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = r.text;
const rb = now.querySelector('[data-drawer-restart]'), sb = now.querySelector('[data-drawer-stop]');
if (rb) { rb.disabled = r.busy; rb.firstChild.textContent = r.busy ? 'Restarting…' : 'Restart'; }
if (sb) sb.disabled = r.busy;
now.querySelector('.ws-drawer-confirm')?.remove();
};
// The finished line stays in the entry. A refusal before the end changed nothing, so focus goes back
// to Restart. Once the agent was ended its runs changed: the repaint reads the instances again, so the
// buttons follow them (after a refused launch it has none, so Stop and Restart go), and focus goes to
// the drawer's heading, which every repaint keeps.
const after = new Set(['restarted', 'threadEnded', 'launchSignedOut', 'launchUnknown', 'launchRefused', 'launchOpen', 'launchClosed']);
const done = step => {
document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`)?.querySelector(after.has(step) ? '[data-focus-key="drawer-h"]' : '[data-drawer-restart]')?.focus({ preventScroll: true });
if (after.has(step)) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
};
const onStatus = ({ step, busy, text }) => {
restarts.set(id, { busy: !!busy, text });
paint();
if (!busy) done(step);
};
try { await window.MosaicAgents.restart(name, thread, { org, reason: RESTART_REASON, text: restartWords(name, orgName), onStatus }); }
catch { restarts.set(id, { busy: false, text: `Not restarted: ${STOP_UNKNOWN}` }); paint(); done('endUnknown'); }
}
document.addEventListener('click', e => {
const link = e.target.closest?.('[data-ws-drawer-open]');
if (link) {
@@ -1441,33 +1547,41 @@
if (!d) return;
if (e.target.closest('[data-drawer-close]')) { closeDrawer(); return; }
const id = d.dataset.wsDrawer;
if (e.target.closest('[data-drawer-stop]') && !(stopState?.id === id && stopState.busy)) {
const b = d.querySelector('[data-drawer-stop]'), name = d.dataset.drawerName;
stopState = { id, confirm: true, text: '' };
d.querySelector('[data-drawer-stop-confirm]')?.remove();
b.insertAdjacentHTML('afterend', stopConfirm(name, `${name} in ${d.dataset.drawerOrgName}`));
b.disabled = true;
// SP19: nothing starts while this agent's Stop or Restart runs.
const held = (stopState?.id === id && stopState.busy) || !!restarts.get(id)?.busy;
const ask = e.target.closest('[data-drawer-stop]') ? 'stop' : e.target.closest('[data-drawer-restart]') ? 'restart' : null;
if (ask && !held) {
const b = d.querySelector(`[data-drawer-${ask}]`), name = d.dataset.drawerName, who = `${name} in ${d.dataset.drawerOrgName}`;
stopState = { id, kind: ask, confirm: true, text: '' }; restarts.delete(id);
d.querySelector('.ws-drawer-confirm')?.remove();
b.insertAdjacentHTML('afterend', ask === 'stop' ? stopConfirm(name, who) : restartConfirm(name, who, b.dataset.drawerThread === 'yes'));
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = true;
const s = d.querySelector('[data-drawer-status]'); if (s) s.textContent = '';
d.querySelector('[data-drawer-stop-no]')?.focus({ preventScroll: true });
d.querySelector(`[data-drawer-${ask}-no]`)?.focus({ preventScroll: true });
return;
}
if (e.target.closest('[data-drawer-stop-no]')) { cancelStop(d); return; }
if (ask) return;
if (e.target.closest('[data-drawer-stop-no], [data-drawer-restart-no]')) { cancelStop(d); return; }
if (held) return;
if (e.target.closest('[data-drawer-stop-yes]')) stopAgent(d);
else if (e.target.closest('[data-drawer-restart-yes]')) restartAgent(d);
});
// Cancel the Stop question: nothing sent, Stop enabled again and focused.
// Cancel the Stop or Restart question: nothing sent, both buttons enabled again, focus on the one that asked.
function cancelStop(d) {
const kind = d.querySelector('[data-drawer-restart-confirm]') ? 'restart' : 'stop';
stopState = null;
d.querySelector('[data-drawer-stop-confirm]')?.remove();
const b = d.querySelector('[data-drawer-stop]'); if (b) { b.disabled = false; b.focus({ preventScroll: true }); }
d.querySelector('.ws-drawer-confirm')?.remove();
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = false;
d.querySelector(`[data-drawer-${kind}]`)?.focus({ preventScroll: true });
}
// Escape cancels the Stop question while it asks, else closes the drawer, unless a dialog is open
// Escape cancels the Stop or Restart question while it asks, else closes the drawer, unless a dialog is open
// or something else took the key.
document.addEventListener('keydown', e => {
if (e.key !== 'Escape' || e.defaultPrevented || document.querySelector('dialog[open]')) return;
const d = document.querySelector('#bus-view [data-ws-drawer]');
if (!d) return;
e.preventDefault();
if (d.querySelector('[data-drawer-stop-confirm]')) cancelStop(d); else closeDrawer();
if (d.querySelector('.ws-drawer-confirm')) cancelStop(d); else closeDrawer();
});
// ---- controls: filters write the hash query and repaint in place ----
+120 -21
View File
@@ -22,13 +22,27 @@
// state says so. The route's answer names the harness: adapter, its mounts, harnessEnv, turnEnd,
// model and provider, and the proxy variables for the spawn. Over the cap the route refuses until
// the next day, and the message is refused with its code.
//
// #1873 triage-fences: the host checks a copy of the route's answer before it writes anything, and
// uses only that copy. harnessEnv names must be in the harness module's envNames and pass
// refusedHarnessName; values are clean strings. env holds only ROUTE_ENV_ALLOW names, with
// ANTHROPIC_BASE_URL loopback http on a port (the host's proxyPort when it names one) and the
// token matching the host's tokenPattern when it names one. The adapter and the mounts pass
// checkHostedRoute (sandbox.mjs) against the module's installRoots and the data root, the config
// directory and HOME (HOME not counted against the stack's own code), here and again in
// hostedBinds. A refused answer reaches no spawn, answers triage-route-invalid, and writes
// ROUTE_REFUSED to the transcript; a refusal at the binds also removes what the start wrote.
import { spawn } from "node:child_process";
import { randomBytes, timingSafeEqual } from "node:crypto";
import { appendFileSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, chmodSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { BWRAP, REPO, RUNNER_FILES, hostedArgv, hostedBinds } from "../../seat/src/sandbox.mjs";
import { pathToFileURL } from "node:url";
import { BWRAP, REPO, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../../seat/src/sandbox.mjs";
import { isProviderVariable } from "../../seat/src/session.mjs";
import { configDir as systemConfigDir } from "../../organization/src/organization-config.mjs";
import { typedTools } from "../../harness/src/tools.mjs";
import { builtinTools } from "../../harness/src/bundle.mjs";
import { FOUNDER_ENV } from "../../harness/src/runner.mjs";
@@ -43,6 +57,7 @@ export const QUEUE_MAX = 20;
export const UNANSWERED = "Triage stopped before it answered this message. Send it again.";
export const NOT_STARTED = "Triage did not start, so this message was not delivered.";
export const NOT_TAKEN = "Triage stopped before it read this message. Send it again.";
export const ROUTE_REFUSED = "Triage did not start: the model route's answer did not pass the host's checks, so this message was not delivered.";
// An over-cap answer is held for at most this long; a later time is not taken.
export const CAP_HOLD_MAX_MS = 48 * 3600 * 1000;
const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
@@ -56,7 +71,36 @@ const CAP = /^[0-9a-f]{64}$/;
export const SPAWN_ENV_ALLOW = Object.freeze(["PATH", "LANG", "LC_ALL", "TZ", "TERM"]);
export const ROUTE_ENV_ALLOW = Object.freeze(["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]);
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
const deniedHarnessName = (k) => !ENV_NAME.test(k) || k === "MOSAIC_CONFIG" || k.startsWith("MOSAIC_BUS_") || FOUNDER_ENV.includes(k) || k === "SSH_AUTH_SOCK";
const ENV_VALUE_MAX = 4096;
const HARNESS_ENV_MAX = 64;
// Refused in harnessEnv even when the harness module declares them: the runner's own MOSAIC_*
// values, loader, libc and interpreter hooks, the shell's start files, a tool's config directory
// and the founder's, an askpass program, a CA bundle or a base URL, Lua's start code, curl's config
// home and a TLS key log. A provider name (every ANTHROPIC_* among them) goes through route env or nowhere.
const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_|MALLOC_|NPM_CONFIG_|XDG_)/;
const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG|ASKPASS|CA_BUNDLE|BASE_URL)$/;
const REFUSED_NAMES = new Set([
"PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK", "SHELL", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "CDPATH",
"GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"GCONV_PATH", "GLIBC_TUNABLES", "LOCPATH", "OPENSSL_CONF", "OPENSSL_ENGINES", "OPENSSL_MODULES", "SSL_CERT_FILE", "SSL_CERT_DIR",
"JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS", "LUA_INIT", "CURL_HOME", "SSLKEYLOGFILE",
...FOUNDER_ENV,
]);
export const refusedHarnessName = (k) => typeof k !== "string" || !ENV_NAME.test(k) || REFUSED_PREFIX.test(k) || REFUSED_SUFFIX.test(k) || REFUSED_NAMES.has(k) || isProviderVariable(k);
// No control character of any kind (C0, DEL, C1) and no line or paragraph separator.
const cleanValue = (v) => typeof v === "string" && v.length <= ENV_VALUE_MAX && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(v);
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
// The proxy is on this machine: http, 127.0.0.1, a port, nothing after it.
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/;
const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/;
// The harness module a route names, from the repository's own tree; null when there is none.
async function repoHarnessModule(name) {
if (!HARNESS_NAME.test(name)) return null;
const file = join(REPO, "packages", "plugins", "harness", name, "index.mjs");
try { if (!lstatSync(file).isFile()) return null; } catch { return null; }
return import(pathToFileURL(file).href);
}
export function triageEnv(source, routeEnv = {}, { node = process.execPath } = {}) {
const env = { PATH: `${dirname(node)}:/usr/bin:/bin` };
@@ -132,8 +176,9 @@ function sameCap(a, b) {
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
// The relay server. `onSend(body)` keeps a human-bound send; `take()` returns the queued owner
// messages; `read(id)` drops one that was answered.
// The relay server. `onSend({ body, in_reply_to, result })` keeps a human-bound send, `result` true
// only for class RESULT, the class the runner gives its answer to a turn; `take()` returns the
// queued owner messages; `read(id)` drops one that was answered.
export function createRelay({ socket, cap, take, read, onSend, log = () => {} }) {
const answer = (conn, value) => { try { conn.end(JSON.stringify(value) + "\n"); } catch {} };
const refuse = (conn) => answer(conn, { ok: false, error: RELAY_REFUSED, reason: "the Triage host answers only a message to the person" });
@@ -160,7 +205,7 @@ export function createRelay({ socket, cap, take, read, onSend, log = () => {} })
if (verb === "message.read") { read(args.id); return answer(conn, { ok: true, result: {} }); }
if (verb === "message.send" && args.to === "human" && typeof args.body === "string" && args.body.length <= 32768) {
// Only an id the host issued is kept. The model writes this field, and the transcript serves it.
onSend({ body: args.body, in_reply_to: typeof args.in_reply_to === "string" && OWNER_ID.test(args.in_reply_to) ? args.in_reply_to : null });
onSend({ body: args.body, in_reply_to: typeof args.in_reply_to === "string" && OWNER_ID.test(args.in_reply_to) ? args.in_reply_to : null, result: args.class === "RESULT" });
return answer(conn, { ok: true, result: { id: `triage-${randomBytes(6).toString("hex")}` } });
}
} catch (e) {
@@ -185,8 +230,21 @@ export function createRelay({ socket, cap, take, read, onSend, log = () => {} })
// provider, env } | { ok: false, code, until? } } or null for no route
// readSnapshot async () -> the snapshot (triage-snapshot.mjs composeSnapshot), written to health/
// pollInterval the runner's receive interval in ms, for tests; the runner's default otherwise
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null }) {
// proxyPort the port ANTHROPIC_BASE_URL must name, or null for any port
// tokenPattern a RegExp the whole ANTHROPIC_AUTH_TOKEN must match, or null for no shape check
// harnessModule async (name) -> the harness module (envNames, installRoots) or null; the
// repository's packages/plugins/harness/<name> by default
// home HOME, which no mount may reach outside the stack's own code; the Console user's by default
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir() }) {
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root");
if (proxyPort !== null && !(Number.isInteger(proxyPort) && proxyPort > 0 && proxyPort <= 65535)) throw new TypeError("proxyPort must be a port number or null");
if (tokenPattern !== null && !(tokenPattern instanceof RegExp)) throw new TypeError("tokenPattern must be a RegExp or null");
if (typeof harnessModule !== "function") throw new TypeError("harnessModule must be a function");
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gmy]/g, ""));
// What no mount source may lie in or around, besides the run directory and the fixed list. HOME
// does not refuse the stack's own code when the stack runs from under it (a copy or a worktree).
const protectedPaths = [dataRoot, systemConfigDir(env), home];
const codeRoot = REPO;
const paths = triagePaths(dataRoot);
const role = JSON.parse(readFileSync(join(roleDir, "triage.json"), "utf8"));
const contract = readFileSync(join(roleDir, role.contract), "utf8");
@@ -272,17 +330,44 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
writeFileSync(join(a, "session.json"), JSON.stringify(session, null, 2) + "\n", { mode: 0o600, flag: "wx" });
};
const checkAdmitted = (a) => {
if (!a || typeof a !== "object" || typeof a.adapter !== "string" || !a.adapter.startsWith("/")
|| !["marker", "exit"].includes(a.turnEnd) || typeof a.model !== "string" || !a.model
|| typeof a.harness !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(a.harness)
|| !a.harnessEnv || typeof a.harnessEnv !== "object" || Array.isArray(a.harnessEnv)
|| Object.entries(a.harnessEnv).some(([k, v]) => typeof v !== "string" || deniedHarnessName(k))
|| !Array.isArray(a.harnessMounts ?? [])) throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
// The route's answer, checked. It returns a copy taken once, so a getter or a later change to
// the route's object cannot hand the bundle or the binds anything the checks did not see, and
// the module's install roots, for hostedBinds. The log names the fence, never a value.
const checkAdmitted = async (answer) => {
const refuse = (fence) => {
log(`triage host: route refused: ${fence}`);
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
};
let a;
try { a = structuredClone(answer); } catch { refuse("shape"); }
if (!plainObject(a) || typeof a.adapter !== "string" || !["marker", "exit"].includes(a.turnEnd)
|| typeof a.model !== "string" || !a.model || typeof a.harness !== "string" || !HARNESS_NAME.test(a.harness)
|| (a.provider !== undefined && typeof a.provider !== "string")) refuse("shape");
let mod = null;
try { mod = await harnessModule(a.harness); } catch { mod = null; }
const declared = mod?.envNames;
if (!Array.isArray(declared) || typeof mod.installRoots !== "function") refuse("module");
const he = a.harnessEnv;
if (!plainObject(he) || Object.keys(he).length > HARNESS_ENV_MAX) refuse("harness-env");
for (const [k, v] of Object.entries(he)) if (refusedHarnessName(k) || !declared.includes(k) || !cleanValue(v)) refuse("harness-env");
const re = a.env ?? {};
if (!plainObject(re) || Object.entries(re).some(([k, v]) => !ROUTE_ENV_ALLOW.includes(k) || !cleanValue(v))) refuse("route-env");
const url = LOOPBACK_URL.exec(re.ANTHROPIC_BASE_URL ?? "");
if (!url || Number(url[1]) > 65535 || (proxyPort !== null && Number(url[1]) !== proxyPort)) refuse("route-env");
if (tokenShape && !(typeof re.ANTHROPIC_AUTH_TOKEN === "string" && tokenShape.test(re.ANTHROPIC_AUTH_TOKEN))) refuse("route-env");
let installRoots;
try { installRoots = structuredClone(mod.installRoots({ env })); } catch { refuse("module"); }
try {
checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, runDir: paths.agent, node });
} catch (e) {
if (e?.code === "hosted-binds-refused") refuse(e.fence);
throw e;
}
return { admitted: a, installRoots };
};
const start = async (admitted) => {
checkAdmitted(admitted);
const start = async (answer) => {
const { admitted, installRoots } = await checkAdmitted(answer);
ensureDirs();
writeBundle(admitted);
cap = randomBytes(32).toString("hex");
@@ -297,17 +382,31 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
const i = queue.findIndex((m) => m.id === id);
if (i >= 0) queue.splice(i, 1);
},
// A reply that names a queued message answers it: the message leaves the queue here, so a
// session that ends before its message.read leaves no "unanswered" line under an answer.
onSend: ({ body, in_reply_to }) => {
// An answer (class RESULT) that names a queued message answers it: the message leaves the queue
// here, so a session that ends before its message.read leaves no "unanswered" line under an
// answer. A note in any other class stays in the transcript but leaves the message queued, so
// a session that ends after a progress note still gets the "unanswered" line. The model's tool
// can also pick class RESULT; such a note settles the message as the runner's answer would.
onSend: ({ body, in_reply_to, result }) => {
const { text, cards, dropped } = extractCards(body, orgIds(), { devOwner: devOwner === true });
append({ at: now().toISOString(), from: "triage", text, cards, dropped, ...(in_reply_to ? { in_reply_to } : {}) });
const i = in_reply_to ? queue.findIndex((m) => m.id === in_reply_to) : -1;
const i = in_reply_to && result === true ? queue.findIndex((m) => m.id === in_reply_to) : -1;
if (i >= 0) queue.splice(i, 1);
},
log,
});
const list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], relaySocket: join(paths.agent, "relay.sock"), node, readOnly });
let list;
try {
list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly });
} catch (e) {
if (e?.code !== "hosted-binds-refused") throw e;
log(`triage host: route refused at the binds: ${e.fence}`);
// Nothing of the refused start stays: the relay, its socket, the bundle and session.json go.
relay?.close();
relay = null;
for (const f of ["relay.sock", "session.json", "bundle"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
}
const argv = hostedArgv(list, paths.agent, [node, RUNNER, paths.agent], { bwrap });
const out = openSync(paths.log, "a", 0o600);
try {
@@ -406,7 +505,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
catch (e) {
const i = queue.findIndex((m) => m.id === id);
if (i >= 0) queue.splice(i, 1);
try { append({ at: now().toISOString(), from: "host", in_reply_to: id, text: NOT_STARTED }); } catch {}
try { append({ at: now().toISOString(), from: "host", in_reply_to: id, text: e?.code === "triage-route-invalid" ? ROUTE_REFUSED : NOT_STARTED }); } catch {}
relay?.close();
relay = null;
log(`triage host: start failed: ${e.code ?? "error"}`);
+271
View File
@@ -0,0 +1,271 @@
// #1873 triage-route-store: the owner-only file that holds Triage's model route and daily cap,
// <dataRoot>/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. Files and the directory the store makes get their modes set on the open
// descriptor, so the owner's umask cannot leave them unreadable. 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, fchmodSync, 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 first cap counts from now; a changed cap keeps its stored `since`, as an organization's token
// limits do (packages/organization/src/launch-settings.mjs stamp), so lowering the cap never drops
// the tokens already spent today. Only a reset would move it, and this slice has no reset verb.
export function capFor({ limit, timeZone, previous, now }) {
return { limit, since: previous ? previous.since : now, reset: "00:00", 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;
// The same zone rule the stored cap is held to (isDailyModelQuota: its zone shape, then Intl).
const knownZone = (zone) => typeof zone === "string"
&& isDailyModelQuota(LEAF_KEY, { limit: 0, since: "2000-01-01T00:00:00.000Z", reset: "00:00", timeZone: zone });
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 owner the files are held to: the same user, unless a test checks the file owner alone.
const fileUidOf = (opts) => opts.fileUid ?? uidOf(opts);
// 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"); }
// The umask may have narrowed the mode; set it on the directory just made, never through a link.
try {
const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
try { fchmodSync(fd, 0o700); } finally { closeSync(fd); }
} 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);
if (!checkDir(dir, uidOf(opts), { create: false })) return null;
return readFile(file, fileUidOf(opts));
}
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. An
// existing file is held to its checks as it is; only a file made here gets its mode set.
function openReceipts(receipts, uid) {
const flags = constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK;
let fd;
try { fd = openSync(receipts, flags); }
catch (e) {
if (e.code === "ELOOP") throw unreadable("route-receipts.jsonl is a link");
if (e.code !== "ENOENT") throw unreadable("route-receipts.jsonl cannot be opened");
try { fd = openSync(receipts, flags | constants.O_CREAT | constants.O_EXCL, 0o600); }
catch { throw unreadable("route-receipts.jsonl cannot be made"); }
try { fchmodSync(fd, 0o600); } catch { closeSync(fd); throw unreadable("route-receipts.jsonl cannot be made"); }
}
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, opts.uid and opts.fileUid are for tests; opts.hook(stage) is a test seam at "write"
// (inside the temp write), "crash" (after the temp file is written), "before-rename" and
// "after-rename" (before the receipt line). A failure after the rename refuses as
// triage-route-unrecorded: the route did change, and its receipt line is missing.
export function writeRoute(dataRoot, input, opts = {}) {
checkInput(input);
const { dir, file, receipts, lock } = routePaths(dataRoot);
const uid = uidOf(opts);
const fileUid = fileUidOf(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, fileUid);
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, fileUid);
try {
const temp = join(dir, `.route.json.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
let tfd;
try { tfd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
catch { throw unreadable("route.json cannot be written"); }
try {
try {
fchmodSync(tfd, 0o600);
hook("write");
writeSync(tfd, `${JSON.stringify(next, null, 2)}\n`);
fsyncSync(tfd);
} finally { closeSync(tfd); }
} catch { try { unlinkSync(temp); } catch {} throw unreadable("route.json cannot be written"); }
hook("crash");
hook("before-rename");
try { renameSync(temp, file); } catch (e) { try { unlinkSync(temp); } catch {} throw unreadable("route.json cannot be replaced"); }
try {
hook("after-rename");
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);
} catch {
throw new RouteStoreError("triage-route-unrecorded", `the Triage route changed to revision ${next.revision}, but its receipt line was not written`);
}
} finally { closeSync(receiptFd); }
return next;
} finally { dropLock(lock, held); }
}
+25 -17
View File
@@ -39,7 +39,7 @@ export const BUS_STATES = Object.freeze(["running", "not-answering", "stopped",
const UNIT_ACTIVE = Object.freeze(["active", "inactive", "failed", "activating", "deactivating", "reloading", "unknown"]);
export const READ_TIMEOUT_MS = 5000;
export const MAX_ORGS = 200;
// At most this many organizations are read at once; each read can start a node child for its config check.
// At most this many organizations' config checks run at once; each starts a node child.
export const ORG_READS_AT_ONCE = 4;
// What a failed system config check may say. Each refusal code the validator prints as its first
@@ -190,8 +190,11 @@ async function mapLimit(items, limit, fn) {
}
// The organization stage runs under one deadline, `timeoutMs` from its start, however many
// organizations there are: an organization whose reads have not finished by then is "not read", and
// one not yet begun is not read at all. A whole snapshot takes at most about two timeouts.
// organizations there are: a read that has not finished by then is "not read", and one not yet
// begun is not read at all. The bus and processing reads are socket reads and begin for every
// organization at once. Only the config checks, a node child each, wait for one of
// ORG_READS_AT_ONCE slots, so a hung check holds back other checks but never another
// organization's socket reads. A whole snapshot takes at most about two timeouts.
export async function composeSnapshot(readers = {}, { now = () => new Date(), timeoutMs = READ_TIMEOUT_MS, clock = Date.now } = {}) {
const at = now().toISOString();
const read = (name, ...args) => (typeof readers[name] === "function" ? bounded(() => readers[name](...args), timeoutMs) : Promise.resolve(NOT_READ));
@@ -200,21 +203,26 @@ export async function composeSnapshot(readers = {}, { now = () => new Date(), ti
if (Array.isArray(orgsRaw)) {
const active = orgsRaw.filter((o) => o && typeof o === "object" && o.state === "active" && typeof o.id === "string" && ID_PATTERN.test(o.id)).slice(0, MAX_ORGS);
const deadline = clock() + timeoutMs;
const list = await mapLimit(active, ORG_READS_AT_ONCE, async ({ id }) => {
// fn bounded by what is left of the deadline, or NOT_READ once nothing is.
const inTime = (fn) => {
const left = deadline - clock();
if (left <= 0) return { id, bus: NOT_READ, processing: NOT_READ, config: NOT_READ };
const readOrg = (name) => (typeof readers[name] === "function" ? bounded(() => readers[name](id), left) : NOT_READ);
const [bus, processing, config] = await Promise.all([
typeof readers.busStatus === "function"
? bounded(async () => {
try { return busFields(await readers.busStatus(id)); }
catch (e) { return e?.name === "CliError" || e?.dead === true ? busFields(null, true) : NOT_READ; }
}, left)
: NOT_READ,
readOrg("processing"),
readOrg("orgConfig"),
]);
return { id, bus: bus === NOT_READ ? NOT_READ : bus, processing: processingFields(processing), config: configFields(config, ORG_CONFIG_CODES) };
return left > 0 ? bounded(fn, left) : Promise.resolve(NOT_READ);
};
const readOrg = (name, id) => (typeof readers[name] === "function" ? inTime(() => readers[name](id)) : Promise.resolve(NOT_READ));
const sockets = Promise.all(active.map(({ id }) => Promise.all([
typeof readers.busStatus === "function"
? inTime(async () => {
try { return busFields(await readers.busStatus(id)); }
catch (e) { return e?.name === "CliError" || e?.dead === true ? busFields(null, true) : NOT_READ; }
})
: NOT_READ,
readOrg("processing", id),
])));
const configs = await mapLimit(active, ORG_READS_AT_ONCE, ({ id }) => readOrg("orgConfig", id));
const socketReads = await sockets;
const list = active.map(({ id }, i) => {
const [bus, processing] = socketReads[i];
return { id, bus: bus === NOT_READ ? NOT_READ : bus, processing: processingFields(processing), config: configFields(configs[i], ORG_CONFIG_CODES) };
});
organizations = { count: list.length, list };
}
@@ -18,7 +18,7 @@ const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString()
const HIRE = '0f3c1a2b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
const THREAD = '7b1e2c3d-4f50-4a61-8b72-9c83d4e5f6a7';
function fixture() {
function fixture(tweak) {
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt' },
{ id: 'beta', label: 'Beta Works', theme: 'grove' },
@@ -52,6 +52,7 @@ function fixture() {
model: {},
},
};
tweak?.(DATA);
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = id => ({
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
@@ -107,16 +108,26 @@ const STUB = `(() => {
if (window.__packsBody) return new Response(window.__packsBody, { status: 200, headers: { 'content-type': 'text/html' } });
return answer(200, { writable: false, applied: [{ id: 'coding', origin: 'shipped', project: null, hired: ['research-2'], open: [] }], packs: packs[1] === 'beta' ? [{ id: 'coding', origin: 'shipped', pack: { id: 'coding', label: 'Coding', version: 2, hires: [{ name: 'research-2', definition: 'researcher', reason: 'Research.' }], definitions: { researcher: { template: 'researcher', sha256: '${'a'.repeat(64)}' } } } }] : [] });
}
// SP19: a test may set __runs[org][name] to the runs the instances read lists for that agent.
const inst = u.match(/^\\/api\\/orgs\\/([^/]+)\\/bus\\/instances$/);
if (inst && window.__runs?.[inst[1]]) {
const got = await real(url, init), v = await got.json();
for (const [n, runs] of Object.entries(window.__runs[inst[1]])) if (v?.rows?.[0]?.instances?.[n]) v.rows[0].instances[n].running = runs;
return answer(got.status, v);
}
if (!/\\/agent\\//.test(u) || (init.method || 'GET') === 'GET' && !u.includes('/agent/request')) return real(url, init);
window.__posts.push({ url: u, method: init.method || 'GET', body: init.body ?? null });
const a = window.__answers.shift();
if (!a) throw new TypeError('no answer queued');
// SP19: an answer may wait on a promise (\`hold\`) and run a step once it is given (\`then\`).
if (a.hold) await a.hold;
a.then?.();
return answer(a.status ?? 200, a.body);
};
})();`;
async function setup(t, { viewport = [1440, 900], hash = '#/agents', stub = true, scripts = [] } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture(), log: () => {} });
async function setup(t, { viewport = [1440, 900], hash = '#/agents', stub = true, scripts = [], data } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture(data), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
@@ -185,9 +196,12 @@ test('the drawer shows each field from its read: name, organization, role and so
// Decisions waiting on a human that it raised, each into the Inbox. Chief's is not its own.
const decisions = await b.evaluate(`[...document.querySelectorAll('${d} [data-drawer-decisions] li a')].map(a => [a.textContent.trim(), a.getAttribute("href")])`);
assert.deepEqual(decisions, [['Ship the hero copy?', '#/inbox?d=acme%3Adec-1']]);
// SP16: no read gives the time of an agent's last activity. The agents read's time (when it took the
// role) and `since` (when its present state began) are not that, so the drawer says not recorded.
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded');
// SP18: the agents read lists only roles a run holds now, and its time is when that run took the role,
// so Last activity is when coder's running run took the role, 40 minutes before the read, with the time itself.
assert.match(await text(`${d} [data-drawer-activity]`), /^its run took the role 4[01] min ago$/);
const started = await attr(`${d} [data-drawer-activity] time`, 'datetime');
assert.ok(Math.abs(Date.now() - Date.parse(started) - 40 * 60000) < 90000, started);
assert.match(await attr(`${d} [data-drawer-activity] time`, 'title'), /\d/);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-activity]').closest('.ws-drawer-f').querySelector('dt').textContent`), 'Last activity');
// Not a pack hire: no packs read, and no Hired from line.
assert.equal(await has(`${d} [data-drawer-hired]`), false);
@@ -209,6 +223,53 @@ test('a hired agent shows where its role came from; a not-running agent says not
assert.match(await text(`${d} [data-drawer-source]`), new RegExp(`hire decision ${HIRE}`));
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)not running$/);
assert.equal(await has(`${d} [data-drawer-model]`), false);
// SP18: no run holds it, and no read keeps the time of a run that ended: one plain line, no time.
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded: no run holds it now, and no read keeps when its last run ended');
assert.equal(await has(`${d} [data-drawer-activity] time`), false);
});
// SP18 review: a claim dates the agent only when the instances read lists its run as running.
test('SP18 review: Last activity counts only a claim whose run is running', async t => {
// Coder runs run-2, but the role is still held by run-1, whose process ended: nothing dates run-2 yet.
{
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', data: d => { d.acme.instances.coder.running = ['run-2']; } });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && /running$/.test(document.querySelector('${d} [data-drawer-state]')?.textContent ?? '')`);
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded: its run holds no role or conversation yet');
assert.equal(await has(`${d} [data-drawer-activity] time`), false);
}
// Coder runs nothing, and a claim from three days ago is left: not running, and no time from that claim.
{
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', data: d => { d.acme.instances.coder.running = []; d.acme.agents[0].at = at(3 * 24 * 60); d.acme.agents[0].working = null; } });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && /not running$/.test(document.querySelector('${d} [data-drawer-state]')?.textContent ?? '')`);
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded: no run holds it now, and no read keeps when its last run ended');
assert.equal(await has(`${d} [data-drawer-activity] time`), false);
}
// Two runs, one holding the role: no read says which run is newer, so the line says one of them.
{
const { wait, text } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', data: d => { d.acme.instances.coder.running = ['run-1', 'run-2']; } });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && !!document.querySelector('${d} [data-drawer-activity] time')`);
assert.match(await text(`${d} [data-drawer-activity]`), /^one of its 2 runs took the role 4[01] min ago$/);
}
// The instances read fails: nothing checked the claim against a live run, so the line says "a run".
{
const fail = `(() => { const f = window.fetch; window.fetch = (u, i) => /\\/api\\/orgs\\/acme\\/bus\\/instances$/.test(String(u)) ? Promise.resolve(new Response('{}', { status: 503 })) : f(u, i); })();`;
const { wait, text } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [fail] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && /^State not read/.test(document.querySelector('${d} [data-drawer-state]')?.textContent ?? '')`);
assert.match(await text(`${d} [data-drawer-activity]`), /^a run took the role 4[01] min ago$/);
}
// The same failed read for chief, which holds no role and no conversation: the line names both gaps.
{
const fail = `(() => { const f = window.fetch; window.fetch = (u, i) => /\\/api\\/orgs\\/acme\\/bus\\/instances$/.test(String(u)) ? Promise.resolve(new Response('{}', { status: 503 })) : f(u, i); })();`;
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=acme%3Achief', scripts: [fail] });
const d = '[data-ws-drawer="acme:chief"]';
await wait(`${open('acme:chief')} && /^State not read/.test(document.querySelector('${d} [data-drawer-state]')?.textContent ?? '')`);
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded: the agents and claims reads show no run holding its role or a conversation, and its runs were not read');
assert.equal(await has(`${d} [data-drawer-activity] time`), false);
}
});
test('SP16: a pack hire names its pack and the template the packs read gives; a refused read says so', async t => {
@@ -501,8 +562,8 @@ test('Message opens the agent\'s thread in an Assistant pane; Stop asks first an
assert.equal(await attr('[data-ws-drawer="acme:assistant"] [data-drawer-message]', 'href'), `#/assistant?add=acme%3A${THREAD}`);
// SP16: Message is offered, so no line says why it is not.
assert.equal(await has('[data-ws-drawer="acme:assistant"] [data-drawer-nomessage]'), false);
// It holds a conversation, whose messages read pages from the oldest message: the drawer says it does not read it.
assert.equal(await text('[data-ws-drawer="acme:assistant"] [data-drawer-activity]'), 'not shown: reading it means reading the whole conversation');
// SP18: a conversation agent's run took its conversation 5 minutes before the read (thread.claims' time).
assert.match(await text('[data-ws-drawer="acme:assistant"] [data-drawer-activity]'), /^its run took the conversation [56] min ago$/);
// A role agent holds no thread to open, so it has no Message; it can still be stopped.
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('[data-ws-drawer="acme:coder"] [data-drawer-stop]')`);
@@ -577,3 +638,275 @@ test('at 390 wide the drawer is a full-width sheet', async t => {
assert.equal(box[1], box[2]);
assert.ok(box[3] <= box[2], `no horizontal page scroll: ${box[3]} > ${box[2]}`);
});
// SP18: the sheet is fixed to the screen, but the page under it kept its own height, so the page still
// scrolled behind the sheet and a full-page shot showed the sheet stretched down a long blank area. With the
// sheet open the page is one screen tall; Close puts the page back where the reader left it.
test('SP18: at 390 wide the open sheet is the whole screen, the page under it does not scroll, and Close keeps the place', async t => {
const { b, wait } = await setup(t, { viewport: [390, 844], hash: '#/orgs/acme/organization' });
const link = JSON.stringify(sessionLink('acme:coder'));
await wait(`document.querySelector(${link}) && document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 10`);
await b.evaluate(`document.querySelector(${link}).scrollIntoView({ block: 'center' })`);
const at = await b.evaluate('Math.round(scrollY)');
assert.ok(at > 100, `the row is down the page: ${at}`);
await b.evaluate(`document.querySelector(${link}).click()`);
await wait(open('acme:coder'));
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
const m = await b.evaluate(`(() => { const r = ${drawer('acme:coder')}.getBoundingClientRect(), e = document.documentElement; return { top: Math.round(r.top), bottom: Math.round(r.bottom), left: Math.round(r.left), width: Math.round(r.width), vh: innerHeight, vw: e.clientWidth, docH: e.scrollHeight, bodyH: Math.round(document.body.getBoundingClientRect().height), sw: e.scrollWidth }; })()`);
assert.equal(m.top, 0, JSON.stringify(m));
assert.equal(m.bottom, m.vh, `the sheet ends at the screen's foot: ${JSON.stringify(m)}`);
assert.equal(m.left, 0); assert.equal(m.width, m.vw);
assert.ok(m.docH <= m.vh && m.bodyH <= m.vh, `the page under the sheet is one screen tall, nothing below to scroll to: ${JSON.stringify(m)}`);
assert.ok(m.sw <= m.vw, 'no sideways scroll');
// A scroll on the page does nothing while the sheet is open.
await b.evaluate('window.scrollTo(0, 2000)');
assert.equal(await b.evaluate('Math.round(scrollY)'), 0);
await b.evaluate(`${drawer('acme:coder')}.querySelector("[data-drawer-close]").click()`);
await wait(noDrawer);
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
assert.ok(Math.abs(await b.evaluate('Math.round(scrollY)') - at) <= 1, `Close puts the page back at ${at}: ${await b.evaluate('Math.round(scrollY)')}`);
assert.ok(await b.evaluate('document.documentElement.scrollHeight') > 844, 'the page is its full height again');
// At 1440 the drawer is a side panel: the page keeps its height and scrolls.
await b.viewport(1440, 900);
await b.evaluate(`document.querySelector(${link}).click()`);
await wait(open('acme:coder'));
assert.ok(await b.evaluate('document.documentElement.scrollHeight') > 900, 'at 1440 the page beside the drawer keeps its height');
});
// SP18 review: only Close (or Back to the same page) puts the page back. A link in the sheet goes to a new
// page, which starts at its top, and the place kept for the page under the sheet is not used later either.
// The Task page is drawn through afterPaint; a project address is drawn by bus.js's chat branch without it
// (this fixture has no chat backend, so that page is the Projects list saying the route is invalid).
for (const [label, sel, hashStart, ready] of [
['Task', '[data-drawer-task] a', '#/orgs/acme/tasks?task=', 'document.querySelector("[data-tasks-board]")'],
['Project', '[data-drawer-project] a', '#/orgs/acme/projects/p-site', 'document.querySelector("#bus-view h1")?.textContent.trim() === "Projects"'],
]) test(`SP18 review: at 390 the sheet's ${label} link opens its page at the top, and a later page does not jump`, async t => {
const { b, wait } = await setup(t, { viewport: [390, 844], hash: '#/orgs/acme/organization' });
const link = JSON.stringify(sessionLink('acme:coder'));
await wait(`document.querySelector(${link}) && document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 10`);
// Every page is long, so a jump to the kept place would show wherever it lands.
await b.evaluate('document.head.insertAdjacentHTML("beforeend", "<style>#bus-view{padding-bottom:4000px}</style>")');
await b.evaluate(`document.querySelector(${link}).scrollIntoView({ block: 'center' })`);
const at = await b.evaluate('Math.round(scrollY)');
assert.ok(at > 100, `the row is down the page: ${at}`);
await b.evaluate(`document.querySelector(${link}).click()`);
await wait(open('acme:coder'));
await b.evaluate(`${drawer('acme:coder')}.querySelector(${JSON.stringify(sel)}).click()`);
await wait(`${noDrawer} && location.hash.startsWith(${JSON.stringify(hashStart)}) && ${ready}`);
await b.evaluate('new Promise(r => setTimeout(r, 500))');
const y = await b.evaluate('Math.round(scrollY)');
assert.ok(y <= 1, `the ${label} page is at its top, not at ${at}: ${y}`);
// The next page with no drawer does not take the kept place either.
await b.evaluate('location.hash = "#/orgs/acme/organization"');
await wait('document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 10');
await b.evaluate('new Promise(r => setTimeout(r, 500))');
const later = await b.evaluate('Math.round(scrollY)');
assert.ok(later <= 1, `the organization page opens at its top: ${later}`);
});
// #1873 triage-followups: the page focuses its heading when its first render ends. On load the page
// starts a second render that reads GET /api/workspace again, so when the first render's read is slow
// the second draws the rows first and a reader can open a drawer before the first render ends. Its late
// end must not take the drawer's focus. The page holds the first GET /api/workspace until __go.
const HOLD_FIRST = `(() => { const f = window.fetch; let first = true; window.__firstDone = false; window.fetch = (u, o) => { if (first && String(u?.url ?? u).includes('/api/workspace')) { first = false; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o).finally(() => setTimeout(() => { window.__firstDone = true; }, 0))); } }, 20); }); } return f(u, o); }; })()`;
test('triage-followups: a drawer opened before the first render ends keeps focus when that render ends', async t => {
const { b, wait } = await setup(t, { scripts: [HOLD_FIRST] });
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
assert.notEqual(await b.evaluate('document.activeElement?.tagName'), 'H1', 'the first render has not ended');
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
await wait(`${open('acme:coder')} && ${drawer('acme:coder')}.contains(document.activeElement)`);
await b.evaluate('window.__go = true');
await wait('window.__firstDone');
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate(`${drawer('acme:coder')}.contains(document.activeElement)`), true, `focus stays in the drawer, not on ${await b.evaluate('document.activeElement?.tagName')}`);
});
// SP19 (#1873): Restart in the drawer, offered only where Stop is. It reuses Stop's confirm step and
// status line, ends the agent through its own organization's /agent/terminate, waits for the request to
// close and for its runs to reach 0, then launches it through /agent/launch. It never regenerates. A
// conversation agent is ended and not launched. The page's 2 s poll steps run every 20 ms here.
const FAST = `(() => { const st = window.setTimeout.bind(window); window.setTimeout = (f, ms, ...a) => st(f, ms === 2000 ? 20 : ms, ...a); })()`;
const END = '5e000000-0000-4000-8000-0000000000e1', LAUNCH = '5e000000-0000-4000-8000-0000000000a1';
const closed = (request, action, extra = {}) => ({ request, instance: 'coder', action, state: 'closed', done: { run: null, transaction: null, refusal: null }, cancelled: null, ...extra });
// Every distinct state of the drawer's actions, from now on: [status, Restart's label, Restart disabled, Stop disabled].
const WATCH = id => `(() => { window.__seen = []; const snap = () => { const d = document.querySelector('[data-ws-drawer="${id}"]'); if (!d) return; const r = d.querySelector('[data-drawer-restart]'), s = d.querySelector('[data-drawer-stop]'); const v = [d.querySelector('[data-drawer-status]')?.textContent ?? '', r ? r.firstChild.textContent : null, !!r?.disabled, !!s?.disabled]; const l = window.__seen.at(-1); if (!l || l.join('|') !== v.join('|')) window.__seen.push(v); }; snap(); new MutationObserver(snap).observe(document.getElementById('bus-view'), { subtree: true, childList: true, characterData: true, attributes: true }); return true; })()`;
const status = d => `(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`;
const usable = d => `document.querySelector('${d} [data-drawer-restart]')?.disabled === false && document.querySelector('${d} [data-drawer-stop]')?.disabled === false && !document.querySelector('${d} .ws-drawer-confirm')`;
test('SP19: Restart asks first, then ends and launches the agent in its own organization, and never regenerates', async t => {
// The reader was last on Beta Works, so the Console's chosen organization is beta. #/agents shows every
// organization's agents; the drawer's own organization is used, not the chosen one.
const { b, wait, text } = await setup(t, { hash: '#/orgs/beta/organization', scripts: [FAST] });
await wait(`window.MosaicOrg?.id === 'beta' && document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 0`);
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
assert.equal(await b.evaluate('window.MosaicOrg?.id ?? null'), 'beta');
// Beside Stop, in the same action group as the status line.
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').closest('[data-drawer-actions]') === document.querySelector('${d} [data-drawer-stop]').closest('[data-drawer-actions]')`), true);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').textContent`), 'Restart coder in Acme Studio');
// It asks first, in Stop's confirm step. Cancel sends nothing and puts focus back on Restart.
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
assert.match(await text(`${d} [data-drawer-restart-confirm]`), /^Restart coder in Acme Studio\? It ends its session and launches it again\. Restart coder Cancel$/);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').classList.contains('ws-drawer-confirm')`), true);
assert.deepEqual(await b.evaluate(`[document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`), [true, true]);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-no]').click()`);
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
// Escape cancels the question too, and the drawer stays.
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-no]') === document.activeElement`);
await b.key('Escape');
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
assert.equal(await b.evaluate(agentParam), 'acme:coder');
assert.deepEqual(await b.evaluate('window.__posts'), []);
// Yes: one terminate, its request followed until it closes, the runs read until none is left, one launch.
await b.evaluate(`window.__answers.push(
{ body: { request: '${END}', runs: ['run-1'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { coder: [] } }; } },
{ body: ${JSON.stringify(closed(END, 'end'))} },
{ body: { request: '${LAUNCH}' }, then: () => { window.__runs = { acme: { coder: ['run-2'] } }; } },
{ body: ${JSON.stringify(closed(LAUNCH, 'launch', { done: { run: 'run-2', transaction: null, refusal: null } }))} })`);
await b.evaluate(WATCH('acme:coder'));
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
await wait(`/^Restarted coder \\(run run-2\\)\\.$/.test(${status(d)}) && ${usable(d)}`);
const posts = await b.evaluate('window.__posts');
assert.deepEqual(posts.map(p => [p.url, p.method]), [
['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET'],
['/api/orgs/acme/agent/launch', 'POST'], [`/api/orgs/acme/agent/request?id=${LAUNCH}`, 'GET'],
]);
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'coder', reason: 'restart from the agent drawer' });
assert.deepEqual(JSON.parse(posts[2].body), { instance: 'coder' });
assert.equal(posts.some(p => /regenerate/.test(p.url)), false, 'Restart never regenerates');
// The status line names each step; while it runs, Restart reads Restarting… and both buttons wait.
const seen = await b.evaluate('window.__seen');
const steps = seen.map(s => s[0]).filter((s, i, all) => s && s !== all[i - 1]);
assert.deepEqual(steps, ['Restarting coder: asking it to end…', 'coder was asked to end. Waiting for its session to end…', 'coder has ended. Launching it…', 'Restarted coder (run run-2).']);
for (const [s, label, rd, sd] of seen.filter(s => steps.slice(0, 3).includes(s[0]))) assert.deepEqual([label, rd, sd], ['Restarting…', true, true], s);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').firstChild.textContent`), 'Restart');
});
// The Assistant is a protected agent, so it has no Stop and no Restart; ideas is a conversation agent that is not.
test('SP19: a conversation agent is ended and not launched; its next message starts it', async t => {
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Aideas', scripts: [FAST], data });
const d = '[data-ws-drawer="acme:ideas"]';
await wait(`${open('acme:ideas')} && document.querySelector('${d} [data-drawer-restart]')`);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').dataset.drawerThread`), 'yes');
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
assert.match(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').textContent`), /^Restart ideas in Acme Studio\? It ends its session; its next message starts it again\./);
await b.evaluate(`window.__answers.push(
{ body: { request: '${END}', runs: ['run-4'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { ideas: [] } }; } },
{ body: ${JSON.stringify({ ...closed(END, 'end'), instance: 'ideas' })} })`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
await wait(`/^Ended ideas at .+\\. Its next message starts it\\.$/.test(${status(d)})`);
const posts = await b.evaluate('window.__posts');
assert.deepEqual(posts.map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET']]);
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'ideas', reason: 'restart from the agent drawer' });
});
test('SP19: a second click while a restart runs does nothing', async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
// The terminate's answer is held, so the restart is still running while the page is clicked again.
await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
await wait(`window.__posts.length === 1 && document.querySelector('${d} [data-drawer-restart]').disabled`);
// Even a Restart button made clickable again starts nothing: no second question, no second request.
await b.evaluate(`(() => { const r = document.querySelector('${d} [data-drawer-restart]'), s = document.querySelector('${d} [data-drawer-stop]'); r.disabled = false; s.disabled = false; r.click(); s.click(); return true; })()`);
await b.evaluate('new Promise(r => setTimeout(r, 300))');
assert.equal(await b.evaluate(`!!document.querySelector('${d} .ws-drawer-confirm')`), false);
assert.equal(await b.evaluate('window.__posts.length'), 1);
await b.evaluate('window.__release()');
await wait(`/^Not restarted:/.test(${status(d)}) && ${usable(d)}`);
assert.equal(await b.evaluate('window.__posts.length'), 1);
});
// SP19 review: a restart keeps its own state, so another drawer's question or Stop does not lose its
// line, and its drawer still shows it running when the reader comes back.
test('SP19: a restart keeps its line and its running state across another drawer\'s Stop', async t => {
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST], data });
const d = '[data-ws-drawer="acme:coder"]', i = '[data-ws-drawer="acme:ideas"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
await wait(`window.__posts.length === 1`);
// Ideas asks to stop and is cancelled; back on coder, its restart still shows as running.
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-no]').click()`);
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
assert.deepEqual(await b.evaluate(`[${status(d)}, document.querySelector('${d} [data-drawer-restart]').firstChild.textContent, document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`),
['Restarting coder: asking it to end…', 'Restarting…', true, true]);
// Ideas' Stop question is open when coder's restart is refused; coder's drawer still says so after.
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
await b.evaluate('window.__release()');
await b.evaluate('new Promise(r => setTimeout(r, 300))');
assert.equal(await b.evaluate(`!!document.querySelector('${i} [data-drawer-stop-confirm]')`), true, 'the other drawer keeps its question');
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-no]').click()`);
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
await wait(`${status(d)} === 'Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents.' && ${usable(d)}`);
assert.equal(await b.evaluate('window.__posts.length'), 1);
});
// Each refusal the two routes can give says so in one plain line. Where the agent still runs, both
// buttons are usable again and focus is on Restart; after a refused launch it has no run, so the
// repaint drops Stop and Restart, keeps the line and puts focus on the drawer's heading.
const ENDED = [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] }, runs: [] }, { body: closed(END, 'end') }];
for (const [label, answers, line] of [
['not the owner', [{ status: 403, body: { error: 'unavailable', sent: false } }],
/^Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents\.$/],
['the organization is archived', [{ status: 409, body: { error: 'org-archived', message: 'organization is archived' } }],
/^Not restarted: Acme Studio is archived, so its agents are not changed\. Nothing changed\.$/],
['the bus is stopped', [{ status: 503, body: { error: 'no-bus-host', message: 'no-bus-host: no-bus-host. Nothing changed.', sent: false } }],
/^Not restarted: the bus of Acme Studio is not running\. Nothing changed\.$/],
['the end is refused', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: { ...closed(END, 'end', { done: { run: null, transaction: null, refusal: 'instance-kept' } }), reason: 'the instance is kept; unkeep it first' } }],
/^Not restarted: coder was not ended \(the instance is kept; unkeep it first\)\.$/],
['the launch is refused', [...ENDED, { status: 409, body: { error: 'capacity-full', message: 'capacity-full: a launch limit is reached. Nothing changed.', sent: false } }],
/^coder was ended and not launched: capacity-full: a launch limit is reached\. Nothing changed\.$/],
['the launch request closes refused', [...ENDED, { body: { request: LAUNCH } }, { body: { ...closed(LAUNCH, 'launch', { done: { run: null, transaction: null, refusal: 'no-route' } }), reason: 'the instance has no harness, model and thinking yet; set its route first' } }],
/^coder was ended and not launched: the instance has no harness, model and thinking yet; set its route first\.$/],
['its runs never reach 0', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: closed(END, 'end') }],
/^Not restarted: coder was asked to end, but its session is still running\. Read the agents again before trying\.$/],
]) test(`SP19: a refusal says so in the drawer: ${label}`, async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
const queued = JSON.stringify(answers);
await b.evaluate(`window.__answers.push(...${queued}.map(a => a.runs ? { ...a, then: () => { window.__runs = { acme: { coder: a.runs } }; } } : a))`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
const launched = label.startsWith('the launch');
await wait(launched ? `/ was ended and not launched: /.test(${status(d)}) && !document.querySelector('${d} [data-drawer-restart]')`
: `/^Not restarted: /.test(${status(d)}) && document.querySelector('${d} [data-drawer-restart]')?.disabled === false`);
await b.evaluate('new Promise(r => setTimeout(r, 300))');
assert.match(await b.evaluate(status(d)), line);
if (launched) {
assert.deepEqual(await b.evaluate(`[!!document.querySelector('${d} [data-drawer-stop]'), document.querySelector('${d} [data-drawer-nostop]')?.textContent]`), [false, 'It is not running, so there is nothing to stop.']);
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} h2')`), true, `focus is on the drawer heading, not ${await b.evaluate('document.activeElement?.outerHTML.slice(0, 80)')}`);
} else {
assert.equal(await b.evaluate(usable(d)), true, 'both buttons are usable again');
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-restart]')`), true, 'focus is back on Restart');
}
const posts = await b.evaluate('window.__posts');
assert.equal(posts.some(p => /regenerate/.test(p.url)), false);
assert.equal(posts.filter(p => p.url.endsWith('/agent/launch')).length, launched ? 1 : 0);
assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
});
+3 -2
View File
@@ -218,8 +218,9 @@ test('row 194 N5: agents.js is served as JavaScript and index.html loads it once
const s = await setup(t);
const js = await get(s, '/agents.js');
assert.equal(js.status, 200); assert.match(js.type, /^text\/javascript/);
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses.
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses; SP19 the
// restart chain the agent drawer calls.
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
assert.match(js.text, /Agent actions are unavailable here\. Use mosaic org instance from the instance CLI\./);
const html = await get(s, '/');
assert.equal(html.text.match(/<script src="\/agents\.js" defer><\/script>/g)?.length, 1);
+7 -2
View File
@@ -6,7 +6,8 @@
// CARDS answer a reply with a cards fence: one valid card, one unknown step
// TOOL <to> call send_message to <to> through the tool socket and answer the raw reply
// SLEEP hang until killed
// REPLY-SLEEP send the person an answer to this message through the tool socket, then hang until killed
// REPLY-SLEEP send the person an answer (class RESULT) to this message through the tool socket, then hang until killed
// NOTE-SLEEP send the person a progress note (class INFO) on this message through the tool socket, then hang until killed
// anything else answer "echo: <body>"
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { connect } from "node:net";
@@ -57,7 +58,11 @@ if (body === "PROBE") {
process.stdout.write(await toolCall("send_message", { to: body.slice(5), body: "from the tool", class: "INFO" }));
} else if (body === "REPLY-SLEEP") {
const id = request.match(/^Message (\S+) from /m)?.[1];
await toolCall("send_message", { to: "human", body: "answered early", class: "INFO", in_reply_to: id });
await toolCall("send_message", { to: "human", body: "answered early", class: "RESULT", in_reply_to: id });
setInterval(() => {}, 1000);
} else if (body === "NOTE-SLEEP") {
const id = request.match(/^Message (\S+) from /m)?.[1];
await toolCall("send_message", { to: "human", body: "still looking", class: "INFO", in_reply_to: id });
setInterval(() => {}, 1000);
} else if (body === "SLEEP") {
setInterval(() => {}, 1000);
@@ -279,3 +279,24 @@ test('At 390 wide the tiles sit two to a row with no sideways scroll, on the Das
assert.equal(await cols('[data-org-tiles]'), 2);
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'organization page');
});
test('SP18: at 1440 and 1024 the Dashboard\'s two columns line up with the tile row above them', async t => {
const { b, wait } = await setup(t, { viewport: [1440, 1000] });
await wait(homeReady);
// The left column ends where a tile ends and the right column starts where the next tile starts: the fourth
// and fifth of six at 1440, the second and third of three a row at 1024.
const edges = () => b.evaluate(`(() => {
const tiles = [...document.querySelectorAll('[data-ws-home] [data-ws-tile]')].map(e => e.getBoundingClientRect());
const cols = [...document.querySelectorAll('[data-ws-home] .ws-home-split>*')].map(e => e.getBoundingClientRect());
return { rights: tiles.map(r => Math.round(r.right)), lefts: tiles.map(r => Math.round(r.left)), left: cols[0] && [Math.round(cols[0].left), Math.round(cols[0].right)], right: cols[1] && [Math.round(cols[1].left), Math.round(cols[1].right)] };
})()`);
for (const [w, nth] of [[1440, 4], [1024, 2]]) {
await b.viewport(w, 1000);
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
const e = await edges();
assert.ok(e.left && e.right && e.right[0] > e.left[1], `two columns side by side at ${w}: ${JSON.stringify(e)}`);
assert.ok(Math.abs(e.left[1] - e.rights[nth - 1]) <= 1, `at ${w} the left column ends with tile ${nth}: ${JSON.stringify(e)}`);
assert.ok(Math.abs(e.right[0] - e.lefts[nth]) <= 1, `at ${w} the right column starts with tile ${nth + 1}: ${JSON.stringify(e)}`);
assert.ok(Math.abs(e.right[1] - Math.max(...e.rights)) <= 1, `at ${w} the right column ends with the row`);
}
});
@@ -180,6 +180,20 @@ test('the Settings card fits at 1440 with the drawer open, at 735 and 390 withou
assert.deepEqual(cols[1].heads, ['Settings']);
const gap = await b.evaluate(`(() => { const left = document.querySelector('#bus-view .ws-dash>.ws-split>section'), card = left.querySelector('[data-wfg-card]'), above = card.previousElementSibling; return Math.round(card.getBoundingClientRect().top - above.getBoundingClientRect().bottom); })()`);
assert.ok(gap >= 0 && gap <= 40, `the Workflows card follows the sessions directly: ${gap}px`);
// SP18: Autonomy and Starter packs follow the Workflows card in the left column, so the left column is not
// empty beside the long Settings card and nothing runs full width below it.
const left = await b.evaluate(`(() => { const s = [...document.querySelectorAll('#bus-view .ws-dash>.ws-split>section')]; return { autonomy: !!s[0].querySelector('[data-autonomy]'), packs: !!s[0].querySelector('[data-packs]'), after: !!document.querySelector('#bus-view .ws-dash>.ws-split ~ :is(div,section):not([data-ws-drawer])'), ends: s.map(x => Math.round(x.getBoundingClientRect().bottom)) }; })()`);
assert.equal(left.autonomy && left.packs, true, `Autonomy and Starter packs are in the left column: ${JSON.stringify(left)}`);
assert.equal(left.after, false, 'no full-width block under the split');
// How near level the two end depends on the data: in this fixture Autonomy is a one-line refusal and no pack
// is installed, so the Settings card is still the taller. The left column ends with Starter packs.
assert.ok(await b.evaluate(`Math.abs(document.querySelector('#bus-view .ws-dash>.ws-split>section [data-packs]').getBoundingClientRect().bottom - document.querySelector('#bus-view .ws-dash>.ws-split>section').getBoundingClientRect().bottom) <= 1`), `the left column ends with Starter packs: ${JSON.stringify(left.ends)}`);
// At 390 the page is one column: sessions, Workflows, Autonomy, Starter packs, then Settings.
await b.viewport(390, 844);
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
const order = await b.evaluate(`[...document.querySelectorAll('#bus-view .ws-dash>.ws-split h2, #bus-view .ws-dash>.ws-split h3')].map(h => h.textContent.trim()).filter(x => ['Active agent sessions', 'Workflows', 'Autonomy', 'Starter packs', 'Settings'].includes(x))`);
assert.deepEqual(order, ['Active agent sessions', 'Workflows', 'Autonomy', 'Starter packs', 'Settings']);
assert.ok(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), 'no sideways scroll at 390');
});
test('the bare organization address with a query is the organization page, query kept; ?agent= opens the drawer', async t => {
+5 -3
View File
@@ -262,8 +262,10 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na
assert.deepEqual(body.projects, Object.fromEntries(Object.entries(doc.projects).map(([id, p]) => [id, p.workflows ?? {}])));
assert.deepEqual(body.projects.stack, doc.projects.stack.workflows);
assert.deepEqual(body.roles.definitions, ['triage']);
assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).sort());
assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost'));
// #1873 triage-followups: the shipped triage template is system-only, so the read leaves it out.
assert.ok(templateHashes(join(f.root, 'roles')).some(x => x.template === 'triage'), 'the fixture ships the triage template');
assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).filter(n => n !== 'triage').sort());
assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost') && !body.roles.templates.includes('triage'));
assert.equal(body.revision, createHash('sha256').update(readFileSync(f.file)).digest('hex'), 'the revision is the writer\'s: the hash of the file bytes');
assert.equal(body.writable, true);
assert.equal(JSON.stringify(body).includes(f.root), false, 'no host path leaves');
@@ -283,7 +285,7 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na
test('SP6 GET /workflows leaves out a library project and answers outcome-unknown for a read it cannot trust', async t => {
const REV = 'a'.repeat(64);
const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7] };
const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7, 'triage'] };
const f = await fixture(t, { workflows: () => read });
const [status, body] = await call(f, `${ORG}/workflows`);
assert.equal(status, 200, JSON.stringify(body));
@@ -20,7 +20,8 @@ const END = '10000000-0000-4000-8000-0000000000e1', LAUNCH = '10000000-0000-4000
const DEV = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner', name: 'Local operator' };
const route = thinking => ({ harness: 'claude', model: 'opus', thinking, fallback: null });
test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
// A real server with the stub bus, on Settings > Routing. `refusal` closes coder's end request with that code.
async function stage(t, { refusal = null } = {}) {
const root = mkdtempSync(join(tmpdir(), 'f3r-')); t.after(() => rmSync(root, { recursive: true, force: true }));
const entry = (definition, extra) => ({ definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: [], alive: [], ...extra });
const instances = {
@@ -52,7 +53,7 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
if (verb === 'instance.launch') { requests.set(LAUNCH, { instance: args.instance, action: 'launch' }); instances[args.instance].running = ['run-2']; return { request: LAUNCH }; }
if (verb === 'instance.request') {
const r = requests.get(args.request);
return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: null }, cancelled: null };
return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: r.action === 'end' && r.instance === 'coder' ? refusal : null }, cancelled: null };
}
throw Error(`unexpected ${verb}`);
};
@@ -72,6 +73,11 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
for (const name of ['chief', 'coder', 'assistant', 'reviewer']) await b.evaluate(`(()=>{const s=${cell(name, 'thinking')};s.value='low';s.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`);
await b.evaluate(`document.getElementById('routes-form').requestSubmit();true`);
await wait(`document.querySelector('.routes-apply')`);
return { b, wait, asked, items, dir };
}
test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
const { b, wait, asked, items, dir } = await stage(t);
assert.deepEqual(asked, [['routes.set', { revision: REV, routes: { chief: route('low'), coder: route('low'), assistant: route('low'), reviewer: route('low') } }]]);
assert.equal(await b.evaluate(`document.getElementById('routes-receipt').textContent`), 'Routes saved for chief, coder, assistant, reviewer. The next launch of each uses the new route.');
assert.deepEqual(await items(), [
@@ -103,3 +109,29 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
await b.viewport(390, 844);
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=390`), true, 'no sideways scroll at phone width');
});
// SP19 (#1873): the drawer's Restart shares this chain. The route-change flow keeps its reason, its
// unprefixed routes and every line it shows, step by step, and its refusal line.
const WATCH = name => `(()=>{window.__seen=[];const snap=()=>{const s=document.querySelector('[data-agent-restart-status="${name}"]')?.textContent??'';if(s&&s!==window.__seen.at(-1))window.__seen.push(s);};new MutationObserver(snap).observe(document.body,{subtree:true,childList:true,characterData:true});return true;})()`;
test('SP19: Restart now keeps its reason and its words', { timeout: 120000 }, async t => {
const { b, wait, asked } = await stage(t);
const posts = [];
await b.evaluate(`(()=>{const f=window.fetch;window.__urls=[];window.fetch=(u,o)=>{window.__urls.push(String(u));return f(u,o);};return true;})()`);
await b.evaluate(WATCH('coder'));
await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
await wait(`document.querySelector('[data-agent-restart-status="coder"]')?.textContent==='Restarted coder on the new route (run run-2).'`, 30000);
assert.deepEqual(await b.evaluate('window.__seen'), ['Terminating coder…', 'Terminated coder. Waiting for its session to end…', 'Launching coder…', 'Restarted coder on the new route (run run-2).']);
assert.deepEqual(asked.filter(([v]) => v === 'instance.end'), [['instance.end', { instance: 'coder', reason: 'route change' }]]);
posts.push(...(await b.evaluate('window.__urls')).filter(u => /\/api\/agent\/(terminate|launch|regenerate)/.test(u)));
assert.deepEqual(posts, ['/api/agent/terminate', '/api/agent/launch']);
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').textContent`), 'Restart coder now');
});
test('SP19: Restart now says when the end is refused, in its own words', { timeout: 120000 }, async t => {
const { b, wait, asked } = await stage(t, { refusal: 'instance-kept' });
await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
await wait(`/It was not restarted/.test(document.querySelector('[data-agent-restart-status="coder"]')?.textContent??'')`, 30000);
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart-status="coder"]').textContent`), 'coder: the instance is kept; unkeep it first. It was not restarted.');
assert.equal(asked.filter(([v]) => v === 'instance.launch').length, 0);
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').disabled`), false);
});
@@ -409,3 +409,31 @@ test('item 5: markup and control characters in every field stay text: no element
await sleep(500);
assert.equal(await f.b.evaluate('window.__pwned ?? null'), null);
});
// #1873 triage-followups: the page focuses its heading when its first render ends. A reader who opened
// the drawer before then keeps focus in the drawer. The page holds GET /api/workspace, which the first
// render waits on, until the drawer has opened and taken focus.
const HOLD_WORKSPACE = `(() => { const f = window.fetch; window.__held = 0; window.fetch = (u, o) => { if (String(u?.url ?? u).includes('/api/workspace') && !window.__go) { window.__held += 1; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o)); } }, 20); }); } return f(u, o); }; })()`;
test('triage-followups: a drawer opened before the first render ends keeps focus when the render ends', async t => {
const f = await setup(t, { init: HOLD_WORKSPACE });
await f.wait('document.querySelector("#triage-open") && window.__held > 0');
const heading = () => f.b.evaluate('document.querySelector("#bus-view h1")?.textContent ?? null');
await sleep(300);
assert.equal(await heading(), 'Reading…', 'the first render has not ended');
await f.click('#triage-open');
await f.wait('document.querySelector("#triage-drawer")?.contains(document.activeElement)');
await f.b.evaluate('window.__go = true');
await f.wait('document.querySelector("#bus-view h1")?.textContent === "Dashboard"');
await sleep(400);
assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer").contains(document.activeElement)'), true, `focus stays in the drawer, not on ${await f.b.evaluate('document.activeElement?.tagName')}`);
// Escape still closes it and puts focus back on the entry.
await f.b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await f.wait('document.querySelector("#triage-drawer").hidden');
assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-open');
});
test('triage-followups: with no drawer open the first render still focuses the heading', async t => {
const f = await setup(t);
await f.wait('document.activeElement?.tagName === "H1"');
});
+331 -27
View File
@@ -5,12 +5,14 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { connect } from "node:net";
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { Client } from "../../bus/src/client.mjs";
import { sandboxProblem } from "../../seat/src/sandbox.mjs";
import { REPO, RUNNER_FILES, checkHostedRoute, sandboxProblem } from "../../seat/src/sandbox.mjs";
import { isProviderVariable } from "../../seat/src/session.mjs";
import {
NOT_STARTED, NOT_TAKEN, RELAY_REFUSED, ROUTE_ENV_ALLOW, SPAWN_ENV_ALLOW, UNANSWERED, createRelay, createTriageHost, hostPrompt, triageEnv,
NOT_STARTED, NOT_TAKEN, RELAY_REFUSED, ROUTE_ENV_ALLOW, ROUTE_REFUSED, SPAWN_ENV_ALLOW, UNANSWERED, createRelay, createTriageHost, hostPrompt,
refusedHarnessName, triageEnv,
} from "../src/triage-host.mjs";
const FIXTURE = new URL("./fixtures/triage-adapter.mjs", import.meta.url).pathname;
@@ -63,13 +65,20 @@ test("the relay refuses every verb but a message to the person, and any call wit
assert.deepEqual(await client.call("message.receive"), [{ id: "owner-0123456789ab", from_role: "human", class: "REQUEST", body: "hello", at: "2026-11-16T12:00:00.000Z" }]);
assert.match((await client.call("message.send", { to: "human", body: "answer", class: "RESULT", in_reply_to: "owner-0123456789ab" })).id, /^triage-/);
await client.call("message.read", { id: "owner-0123456789ab" });
assert.deepEqual(sent, [{ body: "answer", in_reply_to: "owner-0123456789ab" }]);
assert.deepEqual(sent, [{ body: "answer", in_reply_to: "owner-0123456789ab", result: true }]);
assert.deepEqual(read, ["owner-0123456789ab"]);
// Only the class RESULT send, the runner's answer to its turn, says the message is answered. A note
// in any other class, or with no class, is kept but does not.
for (const cls of ["INFO", "REQUEST", "result", undefined, 7]) {
sent.length = 0;
await client.call("message.send", { to: "human", body: "note", class: cls, in_reply_to: "owner-0123456789ab" });
assert.deepEqual(sent, [{ body: "note", in_reply_to: "owner-0123456789ab", result: false }], String(cls));
}
// The model writes in_reply_to. Anything but an id the host issued is dropped, never stored.
for (const bad of ["<img src=x onerror=1>", "owner-1", "owner-0123456789ab\u202e", "owner-0123456789abc", "x".repeat(60000)]) {
sent.length = 0;
await client.call("message.send", { to: "human", body: "b", in_reply_to: bad });
assert.deepEqual(sent, [{ body: "b", in_reply_to: null }], bad.slice(0, 24));
assert.deepEqual(sent, [{ body: "b", in_reply_to: null, result: false }], bad.slice(0, 24));
}
const refused = [
["decision.raise", { kind: "hire", body: "x" }], ["event.emit", { kind: "action.allowed", body: {} }],
@@ -95,13 +104,67 @@ test("the prompt names the snapshot inside the session and the card form, after
assert.match(text, /```cards\n\[\{"step": "bus-start", "org": "alpha"\}\]\n```/);
});
// Names the route may try in harnessEnv that the host refuses even when the module declares them.
const REFUSED_TRIED = [
"MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", "MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "NODE_OPTIONS", "NODE_PATH", "LD_PRELOAD",
"LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "PYTHONPATH", "PYTHONSTARTUP", "PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK",
"GITEA_TOKEN", "GH_TOKEN", "GIT_ASKPASS", "GIT_CONFIG_PARAMETERS", "VIKUNJA_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "GLIBC_TUNABLES", "PI_CODING_AGENT_DIR", "XDG_CONFIG_HOME",
];
// The fake harness module: it declares the probe names and every refused one, so only the host's
// own refusal stops those. Its one install root is <root>/install.
const DECLARED = Object.freeze(["TRIAGE_PROBE", "FAKE_OK", "FAKE_TWO", ...REFUSED_TRIED]);
const fakeModule = (roots, names = DECLARED) => async (name) => name === "fake" ? { envNames: names, installRoots: () => roots } : null;
function host(t, root, opts = {}) {
const dataRoot = join(root, "data");
const h = createTriageHost({ dataRoot, readSnapshot: async () => SNAPSHOT, env: CONSOLE_ENV, readOnly: [FIXTURE], pollInterval: 100, ...opts });
mkdirSync(join(root, "install"), { recursive: true });
if (!existsSync(join(root, "install", "adapter.sh"))) writeFileSync(join(root, "install", "adapter.sh"), "exit 0\n");
const h = createTriageHost({ dataRoot, readSnapshot: async () => SNAPSHOT, env: CONSOLE_ENV, readOnly: [FIXTURE], pollInterval: 100, harnessModule: fakeModule([join(root, "install")]), ...opts });
t.after(() => h.stop());
return { h, dataRoot };
}
// A launcher that only leaves a mark: a spawn is proved by the mark, no spawn by its absence.
function spy(root) {
const f = join(root, "spy");
writeFileSync(f, `#!/bin/sh\n: > '${join(root, "spawned")}'\nexit 0\n`, { mode: 0o755 });
return f;
}
const answer = (root, over = {}) => ({
ok: true, adapter: join(root, "install", "adapter.sh"), harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit",
model: "m", provider: "p", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" }, ...over,
});
// One route answer through a fresh host: refused before anything is written or spawned, with the
// one code, the owner-readable line, and a log line that names the fence.
async function refusedRoute(t, label, make, opts = {}) {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
const logs = [];
const over = await make(root);
const route = { admit: async () => (typeof over === "function" ? over() : answer(root, over)) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), log: (l) => logs.push(l), ...(typeof opts === "function" ? opts(root) : opts) });
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid" && e.message === "the model route's answer is not usable", label);
assert.equal(existsSync(join(root, "spawned")), false, `${label}: nothing spawned`);
assert.equal(h.running, false, label);
assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false, `${label}: no bundle`);
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0], label);
assert.ok(logs.some((l) => /^triage host: route refused: [a-z-]+$/.test(l)), `${label}: ${logs.join(" | ")}`);
return logs;
}
// One route answer through a fresh host that must reach the launcher; the session.json it wrote.
async function admittedRoute(t, label, make, opts = {}) {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
const over = await make(root);
const route = { admit: async () => (typeof over === "function" ? over() : answer(root, over)) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), ...(typeof opts === "function" ? opts(root) : opts) });
await h.message("hello");
await waitFor(() => existsSync(join(root, "spawned")));
return JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "session.json"), "utf8"));
}
test("no model route: nothing launches, the message is refused, and the state says the route is not set", async (t) => {
const { h, dataRoot } = host(t, scratch());
assert.equal((await h.state()).route, "not set");
@@ -147,20 +210,250 @@ test("over the cap: the message is refused until the next day and nothing launch
await assert.rejects(other.message("hello"), (e) => e.code === "triage-route-refused" && e.until === undefined);
});
test("a route whose answer carries a config, bus or founder variable is refused before anything starts", async (t) => {
for (const name of ["MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "GITEA_TOKEN", "SSH_AUTH_SOCK", "lower"]) {
const root = scratch();
const adapter = join(root, "adapter.sh");
writeFileSync(adapter, "exit 0\n");
const route = { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: { [name]: "x" }, harnessMounts: [], turnEnd: "exit", model: "m", provider: "p", env: {} }) };
const { h, dataRoot } = host(t, root, { route });
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid", name);
assert.equal(h.running, false);
assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false);
// The owner's line is written before the start; the transcript then says it was not delivered.
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, owner.text, note.from, note.in_reply_to, note.text, rest.length], ["owner", "hello", "host", owner.id, NOT_STARTED, 0], name);
// #1873 triage-fences, design section 4. Every refused answer reaches no spawn (the spy launcher
// leaves no mark), writes no bundle, answers triage-route-invalid and leaves ROUTE_REFUSED under
// the owner's line.
test("fence 1: a harnessEnv name the host refuses is refused even when the harness module declares it", async (t) => {
for (const name of REFUSED_TRIED) {
assert.ok(DECLARED.includes(name));
await refusedRoute(t, name, () => ({ harnessEnv: { [name]: "x" } }));
assert.equal(refusedHarnessName(name), true, name);
}
// Names that are not one plain upper-case name: lower or mixed case, an equals sign, a NUL.
for (const name of ["lower", "Mosaic_policy_file", "mosaic_policy_file", "FAKE_OK=x", "A=B", "FAKE_OK\0", " FAKE_OK", "fake_ok"]) {
await refusedRoute(t, JSON.stringify(name), () => ({ harnessEnv: { [name]: "x" } }), (root) => ({ harnessModule: fakeModule([join(root, "install")], [...DECLARED, name]) }));
}
for (const name of [
"GIT_DIR", "BASH_FUNC_x%%", "LD_AUDIT", "SHELLOPTS", "PS4", "IFS", "HTTPS_PROXY", "NODE_EXTRA_CA_CERTS", "PYTHONHOME", "MOSAIC_X", "GCONV_PATH",
"LOCPATH", "MALLOC_CHECK_", "OPENSSL_CONF", "SSL_CERT_FILE", "ZDOTDIR", "PROMPT_COMMAND", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "NPM_CONFIG_PREFIX",
"CLAUDE_CONFIG_DIR", "XDG_DATA_HOME", "ANY_CONF", "ANY_CONFIG", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES",
"SSH_ASKPASS", "SUDO_ASKPASS", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "OPENAI_BASE_URL", "ANY_BASE_URL",
"LUA_INIT", "CURL_HOME", "SSLKEYLOGFILE",
]) assert.equal(refusedHarnessName(name), true, name);
for (const name of ["FAKE_OK", "PI_MODEL", "TRIAGE_PROBE"]) assert.equal(refusedHarnessName(name), false, name);
});
test("fence 1: values are strings of at most 4096 characters with no control character or line separator, and at most 64 names", async (t) => {
for (const [label, v] of [
["newline", "x\ny"], ["nul", "x\0"], ["cr", "x\ry"], ["tab", "x\ty"], ["escape", "x\u001by"], ["del", "x\u007f"], ["c1 next line", "x\u0085y"],
["line separator", "x\u2028y"], ["paragraph separator", "x\u2029y"], ["4097", "a".repeat(4097)], ["number", 5], ["null", null], ["object", {}], ["array", ["x"]],
]) {
await refusedRoute(t, label, () => ({ harnessEnv: { FAKE_OK: v } }));
}
const many = Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`FAKE_N${i}`, "x"]));
await refusedRoute(t, "65 names", () => ({ harnessEnv: many }), (root) => ({ harnessModule: fakeModule([join(root, "install")], Object.keys(many)) }));
await admittedRoute(t, "64 names", () => ({ harnessEnv: Object.fromEntries(Object.entries(many).slice(0, 64)) }), (root) => ({ harnessModule: fakeModule([join(root, "install")], Object.keys(many)) }));
await refusedRoute(t, "array harnessEnv", () => ({ harnessEnv: ["FAKE_OK"] }));
await refusedRoute(t, "no harnessEnv", () => ({ harnessEnv: undefined }));
const s = await admittedRoute(t, "4096", () => ({ harnessEnv: { FAKE_OK: "a".repeat(4096), FAKE_TWO: "" } }));
assert.deepEqual(Object.keys(s.harnessEnv), ["FAKE_OK", "FAKE_TWO"]);
});
test("fence 1: a name the harness module does not declare is refused; a declared one reaches the session's bundle", async (t) => {
await refusedRoute(t, "undeclared", () => ({ harnessEnv: { FAKE_UNDECLARED: "x" } }));
await refusedRoute(t, "no such module", () => ({ harness: "nope" }));
await refusedRoute(t, "module without envNames", () => ({}), (root) => ({ harnessModule: async () => ({ installRoots: () => [join(root, "install")] }) }));
await refusedRoute(t, "module without installRoots", () => ({}), { harnessModule: async () => ({ envNames: DECLARED }) });
await refusedRoute(t, "module that throws", () => ({}), { harnessModule: async () => { throw new Error("x"); } });
await refusedRoute(t, "installRoots that throws", () => ({}), { harnessModule: async () => ({ envNames: DECLARED, installRoots: () => { throw new Error("x"); } }) });
const s = await admittedRoute(t, "declared", () => ({ harnessEnv: { FAKE_OK: "yes" } }));
assert.deepEqual(s.harnessEnv, { FAKE_OK: "yes" });
});
test("fence 1: the bundle holds the copy the host checked; no MOSAIC_ name reaches session.json, even from a getter", async (t) => {
let reads = 0;
const s = await admittedRoute(t, "getter", (root) => () => {
const a = answer(root);
delete a.harnessEnv;
Object.defineProperty(a, "harnessEnv", { enumerable: true, get: () => (reads++ === 0 ? { FAKE_OK: "checked" } : { MOSAIC_POLICY_FILE: "/evil", FAKE_OK: "swapped" }) });
return a;
});
assert.equal(reads, 1, "the answer is read once");
assert.deepEqual(s.harnessEnv, { FAKE_OK: "checked" });
assert.ok(!Object.keys(s.harnessEnv).some((k) => k.startsWith("MOSAIC_")));
// An answer that cannot be copied (a function in it) is refused.
await refusedRoute(t, "function", (root) => ({ harnessEnv: { FAKE_OK: "x" }, extra: () => 1 }));
});
test("fence 2: route env holds only the proxy's two names, the base URL is http on 127.0.0.1 with a port, and the host's port and token shape hold when given", async (t) => {
const bad = [
undefined, "", "http://localhost:9", "http://[::1]:9", "https://127.0.0.1:9", "http://127.0.0.1", "http://127.0.0.1:", "http://127.0.0.1:9/",
"http://127.0.0.1:9/v1", "http://127.0.0.1:09", "http://127.0.0.1:0", "http://127.0.0.1:65536", "http://127.0.0.1:99999", "http://127.0.0.2:9",
"http://[email protected]:9", "HTTP://127.0.0.1:9", "http://127.0.0.1:9\n", "http://127.0.0.1:9 ", "http://127.1:9", "http://2130706433:9",
"http://127.0.0.1:9#x", "http://127.0.0.1:9?x", "http://10.0.0.1:9", 9,
];
for (const url of bad) await refusedRoute(t, `url ${JSON.stringify(url)}`, () => ({ env: url === undefined ? {} : { ANTHROPIC_BASE_URL: url } }));
for (const extra of ["OTHER", "MOSAIC_CONFIG", "ANTHROPIC_API_KEY", "PATH", "anthropic_base_url"]) {
await refusedRoute(t, `env ${extra}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", [extra]: "x" } }));
}
for (const token of ["a\nb", "a\u2028b", "a\u0000b", "a\u007fb"]) await refusedRoute(t, `token ${JSON.stringify(token)}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: token } }));
await refusedRoute(t, "env array", () => ({ env: ["ANTHROPIC_BASE_URL"] }));
await admittedRoute(t, "port 65535", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:65535" } }));
// The host's port.
await refusedRoute(t, "other port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }), { proxyPort: 9001 });
await admittedRoute(t, "its port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9001" } }), { proxyPort: 9001 });
// The host's token shape: the whole token, never a part of it.
const tokenPattern = /mst-[0-9a-f]{8}/g;
for (const token of [undefined, "xmst-deadbeef", "mst-deadbeefx", "mst-DEADBEEF", "", "mst-deadbee"]) {
await refusedRoute(t, `token ${token}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ...(token === undefined ? {} : { ANTHROPIC_AUTH_TOKEN: token }) } }), { tokenPattern });
}
await admittedRoute(t, "token", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: "mst-deadbeef" } }), { tokenPattern });
await admittedRoute(t, "token twice", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: "mst-deadbeef" } }), { tokenPattern });
for (const p of [0, 65536, "9", 1.5]) assert.throws(() => createTriageHost({ dataRoot: "/x", proxyPort: p }), /proxyPort/);
assert.throws(() => createTriageHost({ dataRoot: "/x", tokenPattern: "mst-" }), /tokenPattern/);
});
test("fence 3: a mount source outside the install roots, through a link out of them, or in the data root, the config directory, HOME or a secrets path is refused", async (t) => {
const file = (p) => { mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, "x"); return p; };
const mount = (src, extra = {}) => ({ harnessMounts: [{ src, why: "w", ...extra }] });
await refusedRoute(t, "outside", (root) => mount(file(join(root, "elsewhere", "f"))));
await refusedRoute(t, "link out", (root) => { file(join(root, "elsewhere", "f")); symlinkSync(join(root, "elsewhere", "f"), join(root, "install", "out")); return mount(join(root, "install", "out")); });
await refusedRoute(t, "dir link out", (root) => { file(join(root, "elsewhere", "f")); symlinkSync(join(root, "elsewhere"), join(root, "install", "d")); return mount(join(root, "install", "d", "f")); });
await refusedRoute(t, "dotdot", (root) => { file(join(root, "elsewhere", "f")); return mount(`${root}/install/../elsewhere/f`); });
await refusedRoute(t, "dotdot in root", (root) => { file(join(root, "install", "f")); return mount(`${root}/install/x/../f`); });
await refusedRoute(t, "trailing slash", (root) => { mkdirSync(join(root, "install", "d")); return mount(join(root, "install", "d") + "/"); });
await refusedRoute(t, "double slash", (root) => { file(join(root, "install", "f")); return mount(root + "//install/f"); });
await refusedRoute(t, "relative", () => mount("install/adapter.sh"));
await refusedRoute(t, "missing", (root) => mount(join(root, "install", "absent")));
await refusedRoute(t, "case", (root) => { file(join(root, "install", "f")); return mount(join(root, "INSTALL", "f")); });
// With the whole scratch root as the install root, only the protected-path fence stands.
const wide = (root) => ({ harnessModule: fakeModule([root]) });
await refusedRoute(t, "data root", (root) => mount(file(join(root, "data", "f"))), wide);
await refusedRoute(t, "parent of data root", (root) => { mkdirSync(join(root, "data"), { recursive: true }); return mount(join(root)); }, wide);
await refusedRoute(t, "alias of data root", (root) => { file(join(root, "data", "f")); symlinkSync(join(root, "data"), join(root, "alias")); return mount(join(root, "alias", "f")); }, wide);
await refusedRoute(t, "config dir", (root) => mount(file(join(root, "cfg", "f"))), (root) => ({ ...wide(root), env: { ...CONSOLE_ENV, MOSAIC_CONFIG: join(root, "cfg", "config.json") } }));
await refusedRoute(t, "home", (root) => mount(file(join(root, "h", "f"))), (root) => ({ ...wide(root), home: join(root, "h") }));
await refusedRoute(t, "parent of home", (root) => { file(join(root, "p", "h", "f")); return mount(join(root, "p")); }, (root) => ({ ...wide(root), home: join(root, "p", "h") }));
for (const seg of ["secrets", "Secrets", "SECRET", "my-secret-store"]) {
await refusedRoute(t, seg, (root) => mount(file(join(root, "install", seg, "token"))));
}
await refusedRoute(t, "link into secrets", (root) => { file(join(root, "install", "secrets", "token")); symlinkSync(join(root, "install", "secrets", "token"), join(root, "install", "t")); return mount(join(root, "install", "t")); });
await refusedRoute(t, "9 mounts", (root) => ({ harnessMounts: Array.from({ length: 9 }, (_, i) => ({ src: file(join(root, "install", `m${i}`)), dest: `/opt/m${i}`, why: "w" })) }));
await refusedRoute(t, "mounts not a list", (root) => ({ harnessMounts: { src: file(join(root, "install", "f")) } }));
await refusedRoute(t, "extra key", (root) => mount(file(join(root, "install", "f")), { mode: "rw" }));
await refusedRoute(t, "no why", (root) => ({ harnessMounts: [{ src: file(join(root, "install", "f")) }] }));
await refusedRoute(t, "string mount", (root) => ({ harnessMounts: [file(join(root, "install", "f"))] }));
await refusedRoute(t, "install root is /", () => ({}), { harnessModule: fakeModule(["/"]) });
await refusedRoute(t, "install root not a list", (root) => ({}), (root) => ({ harnessModule: fakeModule(join(root, "install")) }));
await refusedRoute(t, "no install roots", () => ({}), { harnessModule: fakeModule([]) });
await admittedRoute(t, "8 mounts", (root) => ({ harnessMounts: Array.from({ length: 8 }, (_, i) => ({ src: file(join(root, "install", `m${i}`)), dest: `/opt/m${i}`, why: "w" })) }));
});
test("fence 3: a mount dest that is or holds /tmp, the run directory, the relay socket, the bundle, session.json, the health dest, a system bind or a runner file is refused", async (t) => {
const withDest = (dest) => (root) => {
writeFileSync(join(root, "install", "f"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: typeof dest === "function" ? dest(root) : dest, why: "w" }] };
};
const run = (root, ...p) => join(root, "data", "triage", "agent", ...p);
const dests = [
["/tmp", "/tmp"], ["under /tmp", "/tmp/x"], ["/tmp/", "/tmp/"], ["root", "/"], ["/usr/bin/sh", "/usr/bin/sh"], ["/usr", "/usr"], ["/etc", "/etc"],
["/etc/hosts", "/etc/hosts"], ["relative", "opt/x"], ["dotdot", "/opt/../tmp"], ["empty", ""], ["number", 5],
["run dir", (r) => run(r)], ["in run dir", (r) => run(r, "x")], ["relay", (r) => run(r, "relay.sock")], ["bundle", (r) => run(r, "bundle")],
["session.json", (r) => run(r, "session.json")], ["health dest", (r) => run(r, "work", "health")], ["parent of run dir", (r) => dirname(run(r))],
["parent of data root", (r) => r], ["runner file", RUNNER_FILES[0]], ["holds runner files", join(REPO, "packages")], ["repo", REPO],
["node", process.execPath], ["holds node", dirname(process.execPath)], ["adapter", (r) => join(r, "install", "adapter.sh")],
["holds adapter", (r) => join(r, "install")],
];
for (const [label, dest] of dests) await refusedRoute(t, `dest ${label}`, withDest(dest));
await refusedRoute(t, "same dest twice", (root) => {
writeFileSync(join(root, "install", "f"), "x");
writeFileSync(join(root, "install", "g"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: "/opt/x", why: "w" }, { src: join(root, "install", "g"), dest: "/opt/x", why: "w" }] };
});
for (const [label, a, b] of [["nested dest", "/opt/x", "/opt/x/f"], ["parent dest", "/opt/x/f", "/opt/x"]]) {
await refusedRoute(t, label, (root) => {
writeFileSync(join(root, "install", "f"), "x");
writeFileSync(join(root, "install", "g"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: a, why: "w" }, { src: join(root, "install", "g"), dest: b, why: "w" }] };
});
}
await admittedRoute(t, "dest /opt/x", withDest("/opt/x"));
});
test("fence 3: the adapter takes the same checks: inside an install root, a file, not through a link out, not in a protected path", async (t) => {
await refusedRoute(t, "outside", (root) => { writeFileSync(join(root, "a.sh"), "exit 0\n"); return { adapter: join(root, "a.sh") }; });
await refusedRoute(t, "link out", (root) => { writeFileSync(join(root, "a.sh"), "exit 0\n"); symlinkSync(join(root, "a.sh"), join(root, "install", "a.sh")); return { adapter: join(root, "install", "a.sh") }; });
await refusedRoute(t, "directory", (root) => { mkdirSync(join(root, "install", "d")); return { adapter: join(root, "install", "d") }; });
await refusedRoute(t, "relative", () => ({ adapter: "install/adapter.sh" }));
await refusedRoute(t, "dotdot", (root) => ({ adapter: `${root}/install/../install/adapter.sh` }));
await refusedRoute(t, "missing", (root) => ({ adapter: join(root, "install", "absent.sh") }));
await refusedRoute(t, "secrets", (root) => { mkdirSync(join(root, "install", "secrets")); writeFileSync(join(root, "install", "secrets", "a.sh"), "x"); return { adapter: join(root, "install", "secrets", "a.sh") }; });
await refusedRoute(t, "data root", (root) => { mkdirSync(join(root, "data"), { recursive: true }); writeFileSync(join(root, "data", "a.sh"), "x"); return { adapter: join(root, "data", "a.sh") }; }, (root) => ({ harnessModule: fakeModule([root]) }));
await refusedRoute(t, "not a string", () => ({ adapter: 5 }));
// A link that stays inside the root is followed: the bind's source is the file itself.
await admittedRoute(t, "link inside", (root) => { writeFileSync(join(root, "install", "real.sh"), "exit 0\n"); symlinkSync(join(root, "install", "real.sh"), join(root, "install", "a.sh")); return { adapter: join(root, "install", "a.sh") }; });
});
test("the shipped harness modules declare what their own env() and mounts() hand a session, and their adapter and mounts pass the host's checks", async () => {
const dir = scratch();
for (const name of ["pi", "claude-code"]) {
const mod = await import(new URL(`../../plugins/harness/${name}/index.mjs`, import.meta.url).href);
assert.ok(Array.isArray(mod.envNames) && Object.isFrozen(mod.envNames), name);
const keys = Object.keys(mod.env({
files: { settings: "/s", mcp: "/m" }, policy: { tools: ["read"] }, tools: [], session: { model: "m", thinking: "off", provider: "p" },
}));
assert.deepEqual(keys.filter((k) => !isProviderVariable(k)).sort(), [...mod.envNames].sort(), name);
const roots = mod.installRoots({ env: {} });
const route = { adapter: mod.adapter(), harnessMounts: mod.mounts({ env: {} }), installRoots: roots, runDir: join(dir, "data", "triage", "agent") };
const got = checkHostedRoute({ ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), join(dir, "home")] });
assert.equal(got.adapter.dest, mod.adapter(), name);
// A stack that runs from under HOME (a copy or a worktree): HOME holds the repository, and the
// code root keeps HOME from refusing the stack's own files. Without it, HOME refuses them.
const underHome = { ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), dirname(REPO)] };
assert.equal(checkHostedRoute({ ...underHome, codeRoot: REPO, codeHolder: dirname(REPO) }).adapter.dest, mod.adapter(), name);
assert.throws(() => checkHostedRoute(underHome), (e) => e.fence === "adapter", name);
}
});
test("a host whose HOME holds the repository starts the shipped pi harness's own route; a source under HOME outside the repository is still refused", async (t) => {
const pi = await import(new URL("../../plugins/harness/pi/index.mjs", import.meta.url).href);
const home = dirname(REPO);
const opts = { home, harnessModule: async (name) => (name === "pi" ? pi : null) };
const piRoute = (root) => answer(root, { harness: "pi", adapter: pi.adapter(), harnessMounts: pi.mounts({ env: {} }), harnessEnv: { PI_MODEL: "m", PI_OFFLINE: "1" } });
const s = await admittedRoute(t, "pi under HOME", (root) => () => piRoute(root), opts);
assert.equal(s.adapter, pi.adapter());
assert.deepEqual(s.harnessEnv, { PI_MODEL: "m", PI_OFFLINE: "1" });
// The same host and module, with HOME's own directory (which holds the repository) as an extra
// install root and mount: it is under HOME and not in the code, so it is refused.
const wide = { ...pi, installRoots: (o) => [...pi.installRoots(o), home] };
const logs = await refusedRoute(t, "under HOME, outside the repository", (root) => () => ({ ...piRoute(root), harnessMounts: [...pi.mounts({ env: {} }), { src: home, dest: "/opt/home", why: "w" }] }), { home, harnessModule: async (name) => (name === "pi" ? wide : null) });
assert.ok(logs.includes("triage host: route refused: mount-src"), logs.join(" | "));
});
test("a route that changes after the first check is refused at the binds: nothing spawns, what the start wrote is removed, and the next message starts", async (t) => {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
writeFileSync(join(root, "outside.sh"), "exit 0\n");
const logs = [];
let checked = false;
let swapped = false;
const harnessModule = async (name) => (name === "fake" ? { envNames: DECLARED, installRoots: () => { checked = true; return [join(root, "install")]; } } : null);
// The run id in session.json reads the clock after the first check: the adapter becomes a link
// out of the install root then, so only hostedBinds' own check can see it.
const now = () => {
if (checked && !swapped) {
swapped = true;
rmSync(join(root, "install", "adapter.sh"));
symlinkSync(join(root, "outside.sh"), join(root, "install", "adapter.sh"));
}
return new Date("2026-11-16T12:00:00.000Z");
};
const route = { admit: async () => answer(root) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), log: (l) => logs.push(l), harnessModule, now });
const agent = join(dataRoot, "triage", "agent");
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid" && e.message === "the model route's answer is not usable");
assert.ok(swapped, "the swap happened between the checks");
assert.ok(logs.includes("triage host: route refused at the binds: adapter"), logs.join(" | "));
assert.equal(existsSync(join(root, "spawned")), false);
assert.equal(h.running, false);
for (const f of ["session.json", "relay.sock", "bundle"]) assert.equal(existsSync(join(agent, f)), false, f);
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0]);
rmSync(join(root, "install", "adapter.sh"));
writeFileSync(join(root, "install", "adapter.sh"), "exit 0\n");
await h.message("again");
await waitFor(() => existsSync(join(root, "spawned")));
});
test("a read and a message that arrive together share one snapshot read", async (t) => {
@@ -211,7 +504,8 @@ test("end to end under the sandbox: the first message starts the session, which
// A link left where the host makes its work directory must not steer the bind.
mkdirSync(join(dataRoot, "triage", "agent"), { recursive: true, mode: 0o700 });
symlinkSync(join(dataRoot, "orgs"), join(dataRoot, "triage", "agent", "work"));
const adapter = join(root, "adapter.sh");
mkdirSync(join(root, "install"));
const adapter = join(root, "install", "adapter.sh");
writeFileSync(adapter, `exec '${process.execPath}' '${FIXTURE}'\n`, { mode: 0o644 });
const probe = [
join(dataRoot, "orgs", "alpha", "org.json"), join(root, "config", "config.json"), join(root, "secrets", "token"),
@@ -219,7 +513,7 @@ test("end to end under the sandbox: the first message starts the session, which
join(dataRoot, "triage", "health", "snapshot.json"), join(dataRoot, "triage", "agent", "work", "health", "snapshot.json"),
];
let admits = 0;
const route = { admit: async () => { admits += 1; return { ok: true, adapter, harness: "fake", harnessEnv: { TRIAGE_PROBE: JSON.stringify(probe) }, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", OTHER: "x" } }; } };
const route = { admit: async () => { admits += 1; return { ok: true, adapter, harness: "fake", harnessEnv: { TRIAGE_PROBE: JSON.stringify(probe) }, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }; } };
const { h } = host(t, root, { route });
assert.equal(h.running, false, "nothing starts before the owner's first message");
assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false);
@@ -280,9 +574,10 @@ test("end to end under the sandbox: the first message starts the session, which
// A route answer that runs the stub adapter under the sandbox.
function stubRoute(root) {
const adapter = join(root, "adapter.sh");
mkdirSync(join(root, "install"), { recursive: true });
const adapter = join(root, "install", "adapter.sh");
writeFileSync(adapter, `exec '${process.execPath}' '${FIXTURE}'\n`, { mode: 0o644 });
return { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: {} }) };
return { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }) };
}
const repliesOf = (h, n, from = "triage") => waitFor(async () => {
const list = (await h.state()).transcript.filter((e) => e.from === from);
@@ -326,9 +621,7 @@ test("a session that ends mid-turn: the message it took is answered by the host,
test("a launcher that cannot run is a failed start: the message is not delivered, nothing reports running, and the next message is refused the same way", async (t) => {
const root = scratch();
const adapter = join(root, "adapter.sh");
writeFileSync(adapter, "exit 0\n");
const route = { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "m", provider: "p", env: {} }) };
const route = { admit: async () => answer(root) };
const { h, dataRoot } = host(t, root, { route, bwrap: join(root, "no-such-launcher") });
for (const text of ["one", "two"]) {
await assert.rejects(h.message(text), (e) => e.code === "triage-start-failed", text);
@@ -350,6 +643,17 @@ test("a reply that names its message answers it: a session killed after replying
assert.deepEqual((await h.state()).transcript.filter((e) => e.from === "host"), []);
});
test("a progress note that names its message does not answer it: a session killed after the note leaves an unanswered line", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h } = host(t, root, { route: stubRoute(root) });
const sent = await h.message("NOTE-SLEEP");
const [noted] = await repliesOf(h, 1);
assert.deepEqual([noted.text.replace(/\n\n.*$/s, ""), noted.in_reply_to], ["still looking", sent.id]);
process.kill(-h.pid, "SIGKILL");
const [note] = await repliesOf(h, 1, "host");
assert.deepEqual([note.in_reply_to, note.text], [sent.id, UNANSWERED]);
});
test("a message the session never read gets a host line when it ends and leaves the queue", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h, dataRoot } = host(t, root, { route: stubRoute(root) });
@@ -0,0 +1,424 @@
// #1873 triage-route-store: the owner-only file that holds Triage's model route and daily cap,
// <dataRoot>/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" });
// A later cap keeps its since, changed or not, as an organization's token limits do: lowering
// the cap never drops the tokens already counted.
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: 2, timeZone: "UTC", previous: prev, now: LATER }).since, NOW);
assert.equal(capFor({ limit: 5, timeZone: "Europe/Berlin", previous: prev, now: LATER }).since, NOW);
});
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, NOW);
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, timeZone: "+05:00" }, /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;
// The files alone owned by someone else: route.json on read and write, the receipts on write.
assert.throws(() => readRoute(d, { fileUid: other }), unreadableFor(/route\.json is not owned by this user/));
assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(NOW), fileUid: other }), unreadableFor(/route\.json is not owned by this user/));
const e = root(t);
writeRoute(e, INPUT, { now: at(NOW) });
unlinkSync(routePaths(e).file);
assert.throws(() => writeRoute(e, INPUT, { now: at(NOW), fileUid: other }), unreadableFor(/route-receipts\.jsonl is not owned by this user/));
assert.equal(existsSync(routePaths(e).file), false);
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("a write under a narrow umask still leaves 0700 and 0600, so the next read works", (t) => {
const d = root(t);
const old = process.umask(0o277);
let written;
try { written = writeRoute(d, INPUT, { now: at(NOW) }); } finally { process.umask(old); }
const { dir, file, receipts: r } = routePaths(d);
assert.equal(lstatSync(dir).mode & 0o777, 0o700);
assert.equal(lstatSync(file).mode & 0o777, 0o600);
assert.equal(lstatSync(r).mode & 0o777, 0o600);
assert.deepEqual(readRoute(d), written);
// An existing receipts file is never repaired: a wrong mode still refuses.
chmodSync(r, 0o644);
assert.throws(() => writeRoute(d, { ...INPUT, revision: 1 }, { now: at(LATER) }), unreadableFor(/route-receipts\.jsonl mode is not 0600/));
});
test("a failed temp write refuses and leaves the route; a failed receipt after the rename says so", (t) => {
const d = root(t);
writeRoute(d, INPUT, { now: at(NOW) });
const before = readFileSync(routePaths(d).file, "utf8");
const fail = (stage) => (s) => { if (s === stage) throw Object.assign(new Error("no space"), { code: "ENOSPC" }); };
assert.throws(() => writeRoute(d, { ...INPUT, limit: 1, revision: 1 }, { now: at(LATER), hook: fail("write") }), unreadableFor(/route\.json cannot be written/));
assert.equal(readFileSync(routePaths(d).file, "utf8"), before);
assert.deepEqual(readdirSync(routePaths(d).dir).sort(), ["route-receipts.jsonl", "route.json"]);
assert.equal(receipts(d).length, 1);
// After the rename the route has changed; the refusal names the new revision and the missing line.
assert.throws(() => writeRoute(d, { ...INPUT, limit: 1, revision: 1 }, { now: at(LATER), hook: fail("after-rename") }),
(e) => code("triage-route-unrecorded")(e) && /changed to revision 2, but its receipt line was not written/.test(e.message));
assert.equal(readRoute(d).revision, 2);
assert.equal(receipts(d).length, 1);
assert.deepEqual(readdirSync(routePaths(d).dir).sort(), ["route-receipts.jsonl", "route.json"]);
});
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);
});
+38 -10
View File
@@ -156,7 +156,7 @@ test("the snapshot file is one 0600 file, replaced whole", () => {
assert.equal(JSON.parse(readFileSync(file, "utf8")).n, 2);
});
test("organizations are read at most ORG_READS_AT_ONCE at a time and listed in registry order", async () => {
test("config checks run at most ORG_READS_AT_ONCE at a time and organizations are listed in registry order", async () => {
let live = 0, most = 0;
const ids = Array.from({ length: 10 }, (_, i) => `org${i}`);
const slow = async () => { live++; most = Math.max(most, live); await new Promise((r) => setTimeout(r, 5)); live--; return { valid: true, exit: 0, code: null }; };
@@ -167,15 +167,19 @@ test("organizations are read at most ORG_READS_AT_ONCE at a time and listed in r
assert.equal(snap.organizations.count, 10);
});
// The timing tests below assert what was read, which no load changes, and a time bound far
// above the one deadline they prove; the "begun late" test moves the deadline's clock by hand.
test("the organization reads share one deadline: forty hung organizations take one timeout, not ten", async () => {
let calls = 0;
const calls = { busStatus: 0, processing: 0, orgConfig: 0 };
const ids = Array.from({ length: 40 }, (_, i) => `org${i}`);
const hang = () => { calls++; return new Promise(() => {}); };
const hang = (name) => () => { calls[name]++; return new Promise(() => {}); };
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), busStatus: hang, processing: hang, orgConfig: hang }, { timeoutMs: 200 });
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), busStatus: hang("busStatus"), processing: hang("processing"), orgConfig: hang("orgConfig") }, { timeoutMs: 200 });
const took = Date.now() - began;
assert.ok(took < 800, `took ${took} ms`);
assert.ok(calls < ids.length, `${calls} reads began`);
// Ten timeouts would be 2000 ms; one is 200.
assert.ok(took < 1500, `took ${took} ms`);
// The config checks behind the first four hang to the deadline, and no later one begins.
assert.ok(calls.orgConfig < ids.length, `${calls.orgConfig} config checks began`);
assert.equal(snap.organizations.count, 40);
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
for (const o of snap.organizations.list) assert.deepEqual([o.bus, o.processing, o.config], [NOT_READ, NOT_READ, NOT_READ], o.id);
@@ -184,11 +188,35 @@ test("the organization reads share one deadline: forty hung organizations take o
test("an organization begun late gets only what is left of the deadline", async () => {
const ids = ["a0", "a1", "a2", "a3", "a4"];
const hang = () => new Promise(() => {});
// Three readers hang; a3 answers after 300 ms, and the worker that read it starts a4 with 100 ms left.
const orgConfig = (id) => (id === "a3" ? new Promise((r) => setTimeout(() => r({ valid: true, exit: 0, code: null }), 300)) : hang());
// The deadline's clock moves only by hand. Three readers hang; a3 answers at once and moves the
// clock 300 ms, so the worker that read it starts a4 with 100 ms left. a4 answers after 250 ms:
// inside a whole timeout, outside what is left.
let t = 0;
const answer = { valid: true, exit: 0, code: null };
const orgConfig = (id) => {
if (id === "a3") { t += 300; return answer; }
if (id === "a4") return new Promise((r) => setTimeout(() => r(answer), 250));
return hang();
};
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig }, { timeoutMs: 400 });
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig }, { timeoutMs: 400, clock: () => t });
const took = Date.now() - began;
assert.ok(took < 600, `took ${took} ms`);
assert.ok(took < 1500, `took ${took} ms`);
assert.deepEqual(snap.organizations.list.map((o) => [o.id, o.config === NOT_READ ? "not read" : "read"]), [["a0", "not read"], ["a1", "not read"], ["a2", "not read"], ["a3", "read"], ["a4", "not read"]]);
});
test("the bus and processing reads are not held behind the config checks: every organization's sockets are read", async () => {
const ids = Array.from({ length: 10 }, (_, i) => `org${i}`);
const hang = () => new Promise(() => {});
// The first four config checks hang to the deadline and hold every config slot; the socket reads answer at once.
const orgConfig = (id) => (ids.indexOf(id) < ORG_READS_AT_ONCE ? hang() : { valid: true, exit: 0, code: null });
const snap = await composeSnapshot({
orgs: async () => ids.map((id) => ({ id, state: "active" })),
busStatus: async () => ({ healthy: true, pid: 1 }),
processing: async () => ({ halted: false, invalid: false }),
orgConfig,
}, { timeoutMs: 300 });
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
for (const o of snap.organizations.list) assert.deepEqual([o.bus.state, o.processing], ["running", { halted: false, invalid: false }], o.id);
for (const o of snap.organizations.list.slice(0, ORG_READS_AT_ONCE)) assert.equal(o.config, NOT_READ, o.id);
});
@@ -302,8 +302,9 @@ test('keyboard focus follows visual order and survives a data refresh', async t
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`);
await wait('document.querySelectorAll("[data-org-dashboard] .ws-doc").length > 0 && document.querySelectorAll("#workspace-nav .ws-proj").length === 3');
const wide = await tabStops(b, 'document.querySelector("#sections a")');
// The left column holds the sessions and, below them, the Workflows card (SP16); the right holds Settings.
const regions = ['nav', 'head', 'Sessions and workflows', 'Settings'];
// The left column holds the sessions and, below them, the Workflows card (SP16), then Autonomy and Starter
// packs (SP18); the right holds Settings.
const regions = ['nav', 'head', 'Sessions, workflows, autonomy and starter packs', 'Settings'];
assert.deepEqual([...new Set(wide.map(s => s.region))].filter(r => r !== 'other'), regions);
assertVisualOrder(wide.filter(s => s.region !== 'other'), regions, '1440');
const keys = wide.map(s => s.key);
@@ -312,6 +312,9 @@ test('a stopped organization is not read: the page and card say the bus is stopp
await wait(`document.querySelector('[data-org-dashboard] [data-wfg-card][data-bus-stopped]')`, 'stopped card');
assert.match(await b.evaluate(`document.querySelector('[data-wfg-card]').textContent`), /Not read: the bus is stopped\./);
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-none]')`), null);
// SP18: the card is the page's one Workflows block; the old stopped panel under it said the same thing twice.
assert.equal(await b.evaluate(`[...document.querySelectorAll('[data-org-dashboard] h2, [data-org-dashboard] h3')].filter(h => h.textContent.trim() === 'Workflows').length`), 1, 'one Workflows heading on a stopped organization page');
assert.equal(await b.evaluate(`document.querySelector('[data-workflows]')`), null);
assert.equal(reads.filter(id => id === 'gamma').length, 0, 'a stopped organization is not read');
});
+1 -1
View File
@@ -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" "$@"
+20 -3
View File
@@ -113,9 +113,26 @@ lists.
can write. The counts are the session's own report, not host evidence.
- The extension's per-reply dedupe is in memory. After a restart the same
reply can get a second notice.
- On the first turn of a new Claude Code session the transcript may not
hold the reply when Stop runs; the hook then checks
`last_assistant_message` and logs an empty `entryId`.
- Claude Code can run the Stop hook before it writes the turn to the
transcript (seen on 2.1.319 to 2.1.325, on any turn). The Stop hook keeps,
per session id, the uuid of the last prompt whose turn it checked, in
`<log>.stop.json` next to its log. A transcript is stale while its last
prompt has that uuid, or while its last reply does not match
`last_assistant_message`. The hook reads it again until it is not, for up
to 2 s. If it never catches up, the hook checks `last_assistant_message`
alone, logs an empty `entryId` and `late: true`, and the turn's earlier
replies go unchecked; with no `last_assistant_message` it checks nothing.
Two cases are left. First, a late fallback records no prompt, because
the hook never saw the turn. When that turn lands in the transcript, a
later Stop can take it for its own: one with no
`last_assistant_message`, or one whose reply has the same text as the
late turn's last reply. That Stop checks the late turn's replies again.
Second, a Stop hook that blocks makes Claude go on with no new prompt,
so a second Stop in that turn finds the transcript stale by its prompt.
It waits 2 s and checks `last_assistant_message` alone, late. Managed
sessions do not reach this case: their only Stop hook never blocks. The
state file sits in the run directory with the log, so it is the
session's own record too.
- The word/phrase lists are the mechanical subset of ms-unslop only, keyed to
pattern ids in lists.json. Style judgments (voice, rhythm, structure) stay in
the skill, not the gate.
+73 -7
View File
@@ -77,20 +77,86 @@ function check(text, at) {
}
}
function stop(input) {
const list = entries(input.transcript_path);
// The transcript's last prompt (its uuid, or null) and the assistant messages with text since it.
function lastTurn(path) {
const list = entries(path);
let start = -1;
list.forEach((e, i) => { if (isPrompt(e)) start = i; });
const turn = replies(list.slice(start + 1));
if (!turn.length && typeof input.last_assistant_message === "string" && input.last_assistant_message.trim()) {
turn.push({ id: "", text: input.last_assistant_message });
const uuid = start >= 0 && typeof list[start].uuid === "string" && list[start].uuid ? list[start].uuid : null;
return { prompt: uuid, replies: replies(list.slice(start + 1)) };
}
// The Stop hook's own state, next to its log: per session id, the uuid of the last prompt whose
// turn it checked. At most STATE_MAX sessions are kept, the latest last.
const STATE = LOG ? `${LOG}.stop.json` : null;
const STATE_MAX = 64;
function stopState() {
if (!STATE) return {};
try {
const value = JSON.parse(fs.readFileSync(STATE, "utf8"));
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
} catch { return {}; }
}
function recordStop(session, prompt) {
if (!STATE) return;
const state = stopState();
delete state[session];
state[session] = prompt;
const keys = Object.keys(state);
for (const k of keys.slice(0, Math.max(0, keys.length - STATE_MAX))) delete state[k];
const tmp = `${STATE}.${process.pid}`;
try {
fs.writeFileSync(tmp, JSON.stringify(state) + "\n");
fs.renameSync(tmp, STATE);
} catch {
try { fs.rmSync(tmp, { force: true }); } catch {}
}
}
// Claude Code can run the Stop hook before it writes the turn to the transcript, so the
// transcript may still end with the last turn. It is stale while its last prompt is the one the
// hook last checked for this session, or while its last reply is not the one the hook input
// names in last_assistant_message. Read it again until it is not, for up to STOP_WAIT_MS (the
// hook's own limit is 10 s). A transcript that never catches up gives last_assistant_message
// alone, logged with late: true so a release where it never matches shows in the log; with no
// last_assistant_message there is no reply to check, and nothing is logged.
// Two cases are left. A late fallback records no prompt uuid, since the hook never saw the turn.
// Once that turn lands, a later Stop with no last_assistant_message, or with a reply whose text
// equals the late turn's last reply, takes it for its own and logs its replies again. And a Stop
// hook that blocks makes Claude go on with no new prompt, so a second Stop in that turn finds the
// transcript stale by the uuid rule, waits, and logs only last_assistant_message, late. Managed
// sessions never reach the second case: their only Stop hook never blocks.
const STOP_WAIT_MS = 2000;
const flat = (s) => s.replace(/\s+/g, "");
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
function stop(input) {
const told = typeof input.last_assistant_message === "string" && input.last_assistant_message.trim() ? input.last_assistant_message : null;
const session = typeof input.session_id === "string" ? input.session_id : "";
const state = stopState();
const seen = Object.hasOwn(state, session) && typeof state[session] === "string" ? state[session] : null;
const stale = (t) => (t.prompt !== null && t.prompt === seen) || (told !== null && !(t.replies.length && flat(t.replies.at(-1).text) === flat(told)));
const deadline = Date.now() + STOP_WAIT_MS;
let t = lastTurn(input.transcript_path);
let turn = t.replies, late = false;
while (stale(t)) {
if (Date.now() >= deadline) {
turn = told === null ? [] : [{ id: "", text: told }];
late = true;
break;
}
pause(25);
t = lastTurn(input.transcript_path);
turn = t.replies;
}
for (const r of turn) {
const result = check(r.text, "stop");
if (result === null) return;
if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked });
else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings });
const extra = late ? { late: true } : {};
if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked, ...extra });
else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings, ...extra });
}
if (!late && t.prompt !== null) recordStop(session, t.prompt);
}
// The entry ids the log already holds a notice for.
+86
View File
@@ -302,6 +302,92 @@ t("claude-hook: a broken lists.json logs broken_lists and no verdict; bad input
assert.deepStrictEqual(events(bad).map((e) => e.ev), ["hook_failed"]);
});
// Claude Code can run the Stop hook before it writes the turn to the transcript (seen on 2.1.319,
// 2.1.322 and 2.1.325). The hook then saw the last turn's reply and logged it again.
const jsonl = (list) => list.map((x) => JSON.stringify(x)).join("\n") + "\n";
const lastTurn = [
{ type: "user", uuid: "p1", message: { role: "user", content: "status?" } },
line("assistant", "m1", "a1", [{ type: "text", text: "The build is green." }]),
];
const TELL_REPLY = "Let me delve into it. A pivotal step.";
t("claude-hook: Stop waits for a late transcript and checks this turn's reply, not the last turn's", () => {
const transcript = writeTmp("transcript-late.jsonl", jsonl(lastTurn));
const late = writeTmp("transcript-late-tail.jsonl", jsonl([
{ type: "user", uuid: "p2", message: { role: "user", content: "and now?" } },
line("assistant", "m2", "a2", [{ type: "text", text: TELL_REPLY }]),
]));
const log = tmp("hook-late.jsonl");
// The writer runs on its own while the hook blocks, as claude's transcript writer does.
const writer = require("node:child_process").spawn("sh", ["-c", 'sleep 0.3; cat "$1" >> "$2"', "sh", late, transcript], { stdio: "ignore" });
const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log });
writer.kill();
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["flagged", "a2"]]);
});
t("claude-hook: Stop with a transcript that never catches up checks last_assistant_message alone", () => {
const transcript = writeTmp("transcript-stale.jsonl", jsonl(lastTurn));
const log = tmp("hook-stale.jsonl");
const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log });
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId, e.late]), [["flagged", "", true]]);
// A turn already in the transcript is checked at once, with its entry id.
const now = tmp("hook-current.jsonl");
const started = Date.now();
hook("stop", { transcript_path: transcript, last_assistant_message: "The build is green." }, { MOSAIC_UNSLOP_LOG: now });
assert.ok(Date.now() - started < 1500, "no wait when the transcript is current");
assert.deepStrictEqual(events(now).map((e) => [e.ev, e.entryId, e.late]), [["checked", "a1", undefined]]);
});
// The Stop hook keeps, per session and next to its log, the last prompt whose turn it checked. A
// transcript that still ends with that prompt is stale, even with no last_assistant_message or
// with a reply whose text equals the last turn's.
const appendLater = (from, to) => require("node:child_process").spawn("sh", ["-c", 'sleep 0.3; cat "$1" >> "$2"', "sh", from, to], { stdio: "ignore" });
t("claude-hook: Stop with no last_assistant_message does not check a turn it checked again, and waits for the late tail", () => {
const transcript = writeTmp("transcript-untold.jsonl", jsonl(lastTurn));
const log = tmp("hook-untold.jsonl");
const env = { MOSAIC_UNSLOP_LOG: log };
assert.strictEqual(hook("stop", { session_id: "s1", transcript_path: transcript }, env).status, 0);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["checked", "a1"]]);
// The next turn's Stop runs before its turn reaches the transcript.
const writer = appendLater(writeTmp("transcript-untold-tail.jsonl", jsonl([
{ type: "user", uuid: "p2", message: { role: "user", content: "and now?" } },
line("assistant", "m2", "a2", [{ type: "text", text: TELL_REPLY }]),
])), transcript);
const r = hook("stop", { session_id: "s1", transcript_path: transcript }, env);
writer.kill();
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["checked", "a1"], ["flagged", "a2"]]);
// A transcript that never catches up gives nothing to check: nothing is logged.
assert.strictEqual(hook("stop", { session_id: "s1", transcript_path: transcript }, env).status, 0);
assert.strictEqual(events(log).length, 2);
// The state is per session: another session on the same log has checked nothing yet.
hook("stop", { session_id: "s2", transcript_path: transcript }, env);
assert.deepStrictEqual(events(log).slice(2).map((e) => [e.ev, e.entryId]), [["flagged", "a2"]]);
});
t("claude-hook: Stop whose reply has the last turn's text does not take the stale transcript for this turn", () => {
const transcript = writeTmp("transcript-same.jsonl", jsonl(lastTurn));
const log = tmp("hook-same.jsonl");
const env = { MOSAIC_UNSLOP_LOG: log };
const told = { session_id: "s1", transcript_path: transcript, last_assistant_message: "The build is green." };
assert.strictEqual(hook("stop", told, env).status, 0);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["checked", "a1"]]);
const writer = appendLater(writeTmp("transcript-same-tail.jsonl", jsonl([
{ type: "user", uuid: "p2", message: { role: "user", content: "still?" } },
line("assistant", "m2", "a2", [{ type: "text", text: "The build is green." }]),
])), transcript);
const r = hook("stop", told, env);
writer.kill();
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["checked", "a1"], ["checked", "a2"]]);
// A transcript that never catches up gives last_assistant_message alone, late.
hook("stop", told, env);
assert.deepStrictEqual(events(log).slice(2).map((e) => [e.ev, e.entryId, e.late]), [["checked", "", true]]);
});
let failed = 0;
for (const [name, ok] of results) { console.log(`${ok ? "PASS" : "FAIL"} ${name}`); if (!ok) failed++; }
console.log(`${results.length - failed}/${results.length} passed`);