// #1873 triage-host: the Triage session's host and its relay. The relay answers only a message to // the person; the session sees its own run directory and the health snapshots and nothing else of // the data root; its environment is a fixed list; nothing launches without a model route or over // the cap. The session runs the stub adapter (tests/fixtures/triage-adapter.mjs); no model is called. import { test } from "node:test"; import assert from "node:assert/strict"; import { connect } from "node:net"; 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 { 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, 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; const skip = sandboxProblem() ?? false; const scratch = () => mkdtempSync(join(process.env.TMPDIR, "th-")); const CAP = "a".repeat(64); const SNAPSHOT = { snapshotVersion: 1, at: "2026-11-16T12:00:00.000Z", console: { state: "answering", at: "2026-11-16T12:00:00.000Z" }, proxy: "not read", systemConfig: { valid: true, exit: 0, code: null }, organizations: { count: 1, list: [{ id: "alpha", bus: { state: "stopped", lastStart: null }, processing: "not read", config: { valid: true, exit: 0, code: null } }] }, }; // What the Console's own environment might hold: none of it but the allowed names may reach the session. const CONSOLE_ENV = { PATH: "/should/not/pass", LANG: "C.UTF-8", TZ: "UTC", HOME: "/home/someone", MOSAIC_CONFIG: "/x/config.json", MOSAIC_BUS_CONSOLE_SOCKET: "/x/bus.sock", MOSAIC_GITEA_CREDENTIAL_FILE: "/x/cred", GITEA_TOKEN: "t", SSH_AUTH_SOCK: "/x/agent", ANTHROPIC_API_KEY: "from-the-console", XDG_CONFIG_HOME: "/x", MOSAIC_DATA_ROOT: "/x", }; const raw = (socket, line) => new Promise((resolve, reject) => { const c = connect(socket); let input = ""; c.on("connect", () => c.write(line + "\n")); c.on("data", (b) => { input += b; }); c.on("end", () => resolve(JSON.parse(input))); c.on("error", reject); }); test("triageEnv keeps the fixed names and the route's proxy variables, and nothing else", () => { const env = triageEnv(CONSOLE_ENV, { ANTHROPIC_BASE_URL: "http://127.0.0.1:1", ANTHROPIC_AUTH_TOKEN: "k", MOSAIC_CONFIG: "/y", OTHER: "z" }, { node: "/opt/node/bin/node" }); assert.deepEqual(Object.keys(env).sort(), ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "LANG", "PATH", "TZ"]); assert.equal(env.PATH, "/opt/node/bin:/usr/bin:/bin"); assert.deepEqual(SPAWN_ENV_ALLOW, ["PATH", "LANG", "LC_ALL", "TZ", "TERM"]); assert.deepEqual(ROUTE_ENV_ALLOW, ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]); assert.equal(triageEnv(CONSOLE_ENV, { ANTHROPIC_API_KEY: "from-the-route" }).ANTHROPIC_API_KEY, undefined, "the session gets no key, only the proxy's token"); assert.equal(triageEnv(CONSOLE_ENV).ANTHROPIC_API_KEY, undefined, "a key in the Console's environment is not the route's"); }); test("the relay refuses every verb but a message to the person, and any call without the capability", async (t) => { const dir = scratch(); const socket = join(dir, "relay.sock"); const sent = []; const queue = [{ id: "owner-0123456789ab", from_role: "human", class: "REQUEST", body: "hello", at: "2026-11-16T12:00:00.000Z" }]; const read = []; const server = await createRelay({ socket, cap: CAP, take: () => queue.splice(0), read: (id) => read.push(id), onSend: (m) => sent.push(m) }); t.after(() => server.close()); const client = new Client({ path: socket, cap: CAP }); assert.deepEqual(await client.call("role.claim"), { library: false }); assert.deepEqual(await client.call("processing.status"), { halted: false, invalid: false }); assert.deepEqual((await client.call("state")).tasks, { open: [], total: 0, cap: 0 }); 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", 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 ["", "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, result: false }], bad.slice(0, 24)); } const refused = [ ["decision.raise", { kind: "hire", body: "x" }], ["event.emit", { kind: "action.allowed", body: {} }], ["message.send", { to: "chief", body: "x", class: "INFO" }], ["message.send", { to: "pm", body: "x" }], ["message.send", { to: "human" }], ["task.create", { title: "x" }], ["launch", { instance: "chief" }], ["plugin.tool", {}], ["toString", {}], ["__proto__", {}], ["constructor", {}], ]; for (const [verb, args] of refused) { await assert.rejects(client.call(verb, args), (e) => e.code === RELAY_REFUSED, verb); } await assert.rejects(new Client({ path: socket, cap: "b".repeat(64) }).call("message.send", { to: "human", body: "x" }), (e) => e.code === RELAY_REFUSED); await assert.rejects(new Client({ path: socket, human: "jason" }).call("message.receive"), (e) => e.code === RELAY_REFUSED); assert.deepEqual(await raw(socket, "not json"), { ok: false, error: RELAY_REFUSED, reason: "the Triage host answers only a message to the person" }); assert.equal((await raw(socket, JSON.stringify({ cap: CAP.toUpperCase(), verb: "role.claim" }))).error, RELAY_REFUSED); assert.equal(sent.length, 1, "no refused call reached the transcript"); assert.equal(lstatSync(socket).mode & 0o777, 0o600); }); test("the prompt names the snapshot inside the session and the card form, after the role's contract", () => { const text = hostPrompt("# Triage\n\nContract.\n", { snapshotPath: "/r/work/health/snapshot.json", steps: ["bus-start"] }); assert.match(text, /^# Triage\n\nContract\.\n\n## This host/); assert.match(text, /\/r\/work\/health\/snapshot\.json/); 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 /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"); 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"); await assert.rejects(h.message("hello"), (e) => e.code === "triage-no-route" && /no model route is set/.test(e.message)); assert.equal(h.running, false); assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); assert.deepEqual((await h.state()).transcript, []); }); test("over the cap: the message is refused until the next day and nothing launches", async (t) => { let clock = Date.parse("2026-11-16T15:00:00.000Z"), asked = 0, answer = { ok: false, code: "triage-over-cap", until: "2026-11-17T00:00:00.000Z" }; const route = { admit: async () => { asked++; return answer; } }; const { h, dataRoot } = host(t, scratch(), { route, now: () => new Date(clock) }); assert.equal((await h.state()).route, "set"); assert.equal((await h.state()).overCapUntil, null); await assert.rejects(h.message("hello"), (e) => e.code === "triage-over-cap" && e.until === "2026-11-17T00:00:00.000Z"); assert.equal(h.running, false); assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); assert.equal((await h.state()).overCapUntil, "2026-11-17T00:00:00.000Z"); // Held: a later route answer cannot reopen the day; the route is not asked again before the time. answer = { ok: false, code: "triage-no-route" }; clock = Date.parse("2026-11-16T23:59:59.000Z"); await assert.rejects(h.message("hello"), (e) => e.code === "triage-over-cap" && e.until === "2026-11-17T00:00:00.000Z"); assert.equal(asked, 1); // At the time, the hold ends and the route is asked again. clock = Date.parse("2026-11-17T00:00:00.000Z"); assert.equal((await h.state()).overCapUntil, null); await assert.rejects(h.message("hello"), (e) => e.code === "triage-no-route"); assert.equal(asked, 2); assert.deepEqual((await h.state()).transcript, [], "a refused message is never written"); // An over-cap answer whose time is not usable (past, too far, not an ISO time) refuses without a hold. for (const until of ["2026-11-17T00:00:00.000Z", "2026-11-20T00:00:00.000Z", "Tue, 17 Nov 2026 12:00:00 GMT", "tomorrow", 5]) { let n = 0; const r = { admit: async () => { n++; return { ok: false, code: "triage-over-cap", until }; } }; const later = host(t, scratch(), { route: r, now: () => new Date("2026-11-17T01:00:00.000Z") }).h; await assert.rejects(later.message("a"), (e) => e.code === "triage-over-cap" && e.until === undefined, String(until)); await assert.rejects(later.message("b"), (e) => e.code === "triage-over-cap"); assert.equal(n, 2, `${until}: not held`); assert.equal((await later.state()).overCapUntil, null); } const odd = { admit: async () => ({ ok: false, code: "rm -rf", until: 5 }) }; const other = host(t, scratch(), { route: odd }).h; await assert.rejects(other.message("hello"), (e) => e.code === "triage-route-refused" && e.until === undefined); }); // #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://user@127.0.0.1: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) => { let reads = 0, release; const gate = new Promise((r) => { release = r; }); const { h } = host(t, scratch(), { readSnapshot: async () => { reads++; await gate; return SNAPSHOT; } }); const both = Promise.all([h.refresh(), h.refresh()]); release(); const [a, b] = await both; assert.equal(reads, 1); assert.equal(a, b); await h.refresh(); assert.equal(reads, 2, "a later refresh reads again"); }); test("a Triage directory that is a link is refused", async (t) => { const root = scratch(); const dataRoot = join(root, "data"); mkdirSync(join(root, "elsewhere"), { recursive: true }); mkdirSync(dataRoot); symlinkSync(join(root, "elsewhere"), join(dataRoot, "triage")); const route = { admit: async () => ({ ok: true }) }; const { h } = host(t, root, { route }); await assert.rejects(h.message("hello"), (e) => e.code === "triage-dir-unsafe"); assert.deepEqual(readdirSync(join(root, "elsewhere")), []); }); async function waitFor(fn, ms = 30000) { const end = Date.now() + ms; while (Date.now() < end) { const v = await fn(); if (v) return v; await new Promise((r) => setTimeout(r, 50)); } throw new Error("timed out"); } test("end to end under the sandbox: the first message starts the session, which sees only its two directories and answers into the transcript", { skip, timeout: 120000 }, async (t) => { const root = scratch(); const dataRoot = join(root, "data"); // What the session must not see: an org root, a config, a secrets file, the host's transcript. mkdirSync(join(dataRoot, "orgs", "alpha"), { recursive: true }); writeFileSync(join(dataRoot, "orgs", "alpha", "org.json"), "{}"); mkdirSync(join(root, "config")); writeFileSync(join(root, "config", "config.json"), "{}"); mkdirSync(join(root, "secrets")); writeFileSync(join(root, "secrets", "token"), "secret"); // 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")); 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"), join(dataRoot, "triage", "host", "transcript.jsonl"), join(dataRoot, "triage", "host"), 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" } }; } }; 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); const replies = async (n) => waitFor(async () => { const list = (await h.state()).transcript.filter((e) => e.from === "triage"); return list.length >= n ? list : null; }); await h.message("PROBE"); assert.equal(h.running, true); const probed = JSON.parse((await replies(1))[0].text.replace(/\n\n.*$/s, "")); const allowed = new Set([ "PATH", "LANG", "TZ", "HOME", "TMPDIR", "ANTHROPIC_BASE_URL", "TRIAGE_PROBE", "PWD", "SHLVL", "_", "OLDPWD", "MOSAIC_REQUEST", "MOSAIC_SYSTEM_PROMPT_FILE", "MOSAIC_WORKSPACE", "MOSAIC_SESSION_DIR", "MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", "MOSAIC_TOOL_SOCKET", "MOSAIC_TURN_MARKER", "MOSAIC_PROVIDER", "MOSAIC_MODEL", "MOSAIC_MODEL_ACTIVITY_DIR", "MOSAIC_UNSLOP_LOG", ]); for (const name of probed.env) assert.ok(allowed.has(name), `the session's environment holds ${name}`); for (const name of ["MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "GITEA_TOKEN", "SSH_AUTH_SOCK", "ANTHROPIC_API_KEY", "OTHER", "MOSAIC_DATA_ROOT"]) assert.ok(!probed.env.includes(name), name); assert.deepEqual(probed.seen, Object.fromEntries(probe.map((p) => [p, p.endsWith(join("work", "health", "snapshot.json"))]))); assert.equal(probed.snapshot, 1); assert.equal(probed.writeHealth, "EROFS"); assert.equal(probed.writeBundle, "EROFS"); assert.equal(probed.writeWork, "written"); assert.deepEqual(readdirSync(join(dataRoot, "orgs")), ["alpha"], "the planted link's target is untouched"); assert.equal(lstatSync(join(dataRoot, "triage", "agent", "work")).isDirectory(), true); assert.deepEqual(readdirSync(join(dataRoot, "triage", "health")), ["snapshot.json"]); await h.message("CARDS"); const cards = (await replies(2))[1]; assert.deepEqual(cards.cards, [{ step: "bus-start", org: "alpha", command: "mosaic bus start alpha --detach" }]); assert.equal(cards.dropped, 1); assert.match(cards.text, /^The alpha bus is stopped\./); await h.message("TOOL chief"); assert.match((await replies(3))[2].text, new RegExp(RELAY_REFUSED)); await h.message("TOOL human"); const last = await replies(5); const texts = last.slice(3).map((e) => e.text); assert.ok(texts.includes("from the tool"), "the session's own send to the person reaches the transcript"); assert.ok(texts.some((x) => /"ok":true/.test(x)), "and the tool call was answered"); assert.equal(admits, 4, "each message is admitted by the route"); const tr = join(dataRoot, "triage", "host", "transcript.jsonl"); assert.equal(lstatSync(tr).mode & 0o777, 0o600); for (const d of ["", "health", "agent", "host"]) assert.equal(lstatSync(join(dataRoot, "triage", d)).mode & 0o777, 0o700, d); const owner = readFileSync(tr, "utf8").trim().split("\n").map((l) => JSON.parse(l)).filter((e) => e.from === "owner").map((e) => e.text); assert.deepEqual(owner, ["PROBE", "CARDS", "TOOL chief", "TOOL human"]); const tools = JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "bundle", "tools.json"), "utf8")); assert.deepEqual(tools.map((x) => x.name), ["send_message"]); const policy = JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "bundle", "policy.json"), "utf8")); assert.deepEqual([policy.tools, policy.typed, policy.network, policy.needs, policy.credentials], [["read", "grep", "find", "ls"], ["send_message"], "none", [], []]); await h.stop(); assert.equal(h.running, false); assert.equal(existsSync(join(dataRoot, "triage", "agent", "relay.sock")), false); }); // A route answer that runs the stub adapter under the sandbox. function stubRoute(root) { 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: { 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); return list.length >= n ? list : null; }); test("a second start on the same data root answers too: the last run's turns do not stop the next", { skip, timeout: 120000 }, async (t) => { const root = scratch(); const route = stubRoute(root); const first = host(t, root, { route }).h; const one = await first.message("one"); assert.deepEqual((await repliesOf(first, 1)).map((e) => [e.text.replace(/\n\n.*$/s, ""), e.in_reply_to]), [["echo: one", one.id]]); await first.stop(); assert.equal(first.running, false); const { h: second, dataRoot } = host(t, root, { route }); const two = await second.message("two"); const list = await repliesOf(second, 2); assert.deepEqual(list.map((e) => [e.text.replace(/\n\n.*$/s, ""), e.in_reply_to]), [["echo: one", one.id], ["echo: two", two.id]]); assert.equal((await second.state()).transcript.filter((e) => e.from === "host").length, 0); assert.equal(existsSync(join(dataRoot, "triage", "agent", "turns")), true); }); test("a session that ends mid-turn: the message it took is answered by the host, leaves the queue, and the next message is answered", { skip, timeout: 120000 }, async (t) => { const root = scratch(); const { h, dataRoot } = host(t, root, { route: stubRoute(root) }); const slept = await h.message("SLEEP"); // The turn has started once the runner made its turns directory. await waitFor(() => { try { return readdirSync(join(dataRoot, "triage", "agent", "turns")).length > 0; } catch { return false; } }); const pid = h.pid; assert.ok(Number.isInteger(pid)); process.kill(-pid, "SIGKILL"); const [note] = await repliesOf(h, 1, "host"); assert.deepEqual([note.in_reply_to, note.text], [slept.id, UNANSWERED]); await waitFor(() => !h.running); assert.equal((await h.state()).lastExit.signal, "SIGKILL"); const next = await h.message("after"); const [reply] = await repliesOf(h, 1); assert.deepEqual([reply.text.replace(/\n\n.*$/s, ""), reply.in_reply_to], ["echo: after", next.id]); assert.equal((await h.state()).transcript.filter((e) => e.from === "host").length, 1, "the killed message is answered once and not taken again"); }); 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 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); assert.equal(h.running, false, text); } const lines = (await h.state()).transcript.map((e) => [e.from, e.text]); assert.deepEqual(lines, [["owner", "one"], ["host", NOT_STARTED], ["owner", "two"], ["host", NOT_STARTED]]); assert.equal(existsSync(join(dataRoot, "triage", "agent", "relay.sock")), false); }); test("a reply that names its message answers it: a session killed after replying leaves no unanswered line", { skip, timeout: 120000 }, async (t) => { const root = scratch(); const { h } = host(t, root, { route: stubRoute(root) }); const sent = await h.message("REPLY-SLEEP"); const [reply] = await repliesOf(h, 1); assert.deepEqual([reply.text.replace(/\n\n.*$/s, ""), reply.in_reply_to], ["answered early", sent.id]); process.kill(-h.pid, "SIGKILL"); await waitFor(() => !h.running); 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) }); const slept = await h.message("SLEEP"); await waitFor(() => { try { return readdirSync(join(dataRoot, "triage", "agent", "turns")).length > 0; } catch { return false; } }); // The runner takes one message per turn and is held in SLEEP, so this one is queued and never taken. const waiting = await h.message("waiting"); process.kill(-h.pid, "SIGKILL"); await waitFor(() => !h.running); const notes = (await repliesOf(h, 2, "host")).map((e) => [e.in_reply_to, e.text]).sort((a, b) => a[1].localeCompare(b[1])); assert.deepEqual(notes, [[waiting.id, NOT_TAKEN], [slept.id, UNANSWERED]].sort((a, b) => a[1].localeCompare(b[1]))); }); test("with devOwner set, a card's bus start carries the dev-owner flag", { skip, timeout: 120000 }, async (t) => { const root = scratch(); const { h } = host(t, root, { route: stubRoute(root), devOwner: true }); await h.message("CARDS"); const [reply] = await repliesOf(h, 1); assert.deepEqual(reply.cards, [{ step: "bus-start", org: "alpha", command: "mosaic bus start alpha --dev-local-owner --detach" }]); });