salvage: uncommitted work from dewey-r165-wt2 (disk cleanup #824, 2026-11-06)

This commit is contained in:
mos committed 2026-11-06 10:00:46 -06:00
1 parent 70c9131f0d
commit bb04a92930
24 files changed
+1343 -18

No files matched your search

+51
View File
@@ -854,6 +854,57 @@ mappings refuse. Every held role must map too. A migrated file prints unchanged.
Jason installs the output himself in Mos's window with the PM run idle, and
the re-pin follows in the same window (decision 145).
## Role instances
Row 165 (#1662, Q171, REQ-ROLE-3).
```
mosaic business instances BUSINESS [--json]
mosaic business instance add BUSINESS INSTANCE --definition DEF [--vars FILE] [--launch] --revision REV
mosaic business instance set BUSINESS INSTANCE [--definition DEF] [--vars FILE] [--launch | --no-launch] --revision REV
```
`scripts/mosaic` sends `business instances` and `business instance` here and
every other `business` command to `packages/business`. `instances` prints the
file's revision, each instance with its definition and its marks (`launcher`,
`launched`, `protected`), the definitions `add` and `set` accept, and the
definitions that declare credentials. `add` and `set` send the bus's
human-only `instances.set` verb. `set` needs at least one of `--definition`,
`--vars` and a launch flag. `--vars FILE` is a JSON object that replaces the
instance's vars whole. `--launch` and `--no-launch` add the instance to
`launch.instances` or remove it.
The business package's instance writer runs the checks `mosaic business
validate` runs before it writes, and logs the change in `changes.jsonl` with
the human as actor. It refuses, and the file keeps its bytes:
| Code | When |
|---|---|
| `organization-credentials-out-of-scope` | the definition declares credentials, or a definition change on an instance that holds them |
| `organization-instance-exists` | `add` names an instance the file has |
| `organization-unknown-instance` | `set` names an instance the file lacks |
| `organization-definition-refused` | an assistant definition or instance; those change through `mosaic limits set` |
| `organization-launch-not-configured` | a launch flag when the file has no launch block |
| `organization-no-change` | the file already says that |
| `organization-project-mismatch`, `organization-unresolvable-instance` | the change would fail `mosaic business validate` against a project file |
| `revision-conflict` | the file changed since `--revision` |
The bus sends a refusal's code alone, so the command adds the reason. A
refusal exits 2; an agent session or a non-human transport exits 3; a usage
error exits 4 before any bus call.
The commands bind no credentials. A definition that declares them needs
`credentials` and a `tracker` bot in the instance, and those, with `holder`,
stay hand edits of the business file. A vars or launch change on an instance
that holds credentials succeeds and leaves them as they are. There is no
delete.
An add or a definition change prints `restart needed`: the running bus keeps
the roles it loaded at start; this command does not restart it. The output
names no one; the restart itself needs Mos's go or Jason's hand. A vars or launch change
prints `no restart`, because the launcher reads it at its next launch check.
The Console Settings page has the same read and write (`packages/webui`).
## Token usage
`mosaic usage [--business ID] [--json]` reads the bus's accounting, without
+4
View File
@@ -17,6 +17,7 @@ import { projectBusCommand, projectCommand, PROJECT_BUS_USAGE, PROJECT_USAGE } f
import { resolveThread, threadCommand, threadMembers, threadsCommand, THREAD_TALK_USAGE, THREAD_USAGE, THREADS_USAGE } from "./thread.mjs";
import { limitsCommand, LIMITS_USAGE } from "./limits.mjs";
import { pluginsCommand, PLUGINS_USAGE } from "./plugins.mjs";
import { instancesCommand, INSTANCES_USAGE } from "./instances.mjs";
import { createChannelCaller } from "../../plugins/src/channel.mjs";
import { PluginError } from "../../plugins/src/kinds.mjs";
import { CliError } from "./errors.mjs";
@@ -37,6 +38,7 @@ export const USAGE = `usage:
${USAGE_USAGE}
${LIMITS_USAGE}
${PLUGINS_USAGE}
${INSTANCES_USAGE}
${PROJECT_USAGE}
${PROJECT_BUS_USAGE}
${THREADS_USAGE}
@@ -568,6 +570,8 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
if (verb === "limits") return limitsCommand(rest,io,p=>callFor(p,io,deps));
if (verb === "usage") return usageCommand(rest, io, p => callFor(p, io, deps));
if (verb === "plugins") return pluginsCommand(rest, io, (p) => callFor(p, io, deps));
// Row 165 (#1662): scripts/mosaic sends only `business instances` and `business instance` here.
if (verb === "business") return instancesCommand(rest, io, (p) => callFor(p, io, deps));
if (verb === "talk") return talk(rest, io, deps);
if (verb === "follow") return talk(rest, io, deps, true);
if (verb === "name" || verb === "names") return names(verb, rest, io, deps);
+121
View File
@@ -0,0 +1,121 @@
// `mosaic business instances` and `mosaic business instance add|set` (row 165, #1662, Q171,
// REQ-ROLE-3): the human reads, adds and changes role instances through the broker's human-only
// instances and instances.set verbs. The broker refuses an agent, a reader and a tester; the
// business package's instance writer refuses a stale revision and every document
// `mosaic business validate` would refuse, and logs the change with its actor.
import { readFileSync } from "node:fs";
import { CliError } from "./errors.mjs";
export const INSTANCES_USAGE = "mosaic business instances BUSINESS [--json] | " +
"business instance add BUSINESS INSTANCE --definition DEF [--vars FILE] [--launch] --revision REV | " +
"business instance set BUSINESS INSTANCE [--definition DEF] [--vars FILE] [--launch | --no-launch] --revision REV";
// The bus answers a refusal with its code alone, so the reason a human reads is here.
export const REASONS = {
"organization-credentials-out-of-scope": "this command binds no credentials, so it refuses a definition that declares them " +
"and a definition change on an instance that holds them; that stays a hand edit of the business file",
"organization-instance-exists": "the business already has that instance; change it with `mosaic business instance set`",
"organization-unknown-instance": "the business has no such instance; add it with `mosaic business instance add`",
"organization-definition-refused": "this command neither adds nor changes an assistant, and moves no instance to the assistant " +
"definition; an assistant changes only through `mosaic limits set` with an assistants patch",
"organization-launch-not-configured": "the business file has no launch block, so launch membership can't change",
"organization-no-change": "the business file already says that",
"organization-project-mismatch": "a project file's id differs from its key in the business file; `mosaic business validate` shows it",
"organization-unresolvable-instance": "an instance wouldn't resolve against a project file; `mosaic business validate` shows why",
"revision-conflict": "the business file changed since that revision; read it again with `mosaic business instances`",
};
export const RESTART_NEEDED = "restart needed: the running bus keeps the roles it loaded at start; this command does not restart it";
const NO_RESTART = "no restart: the launcher reads the change at its next launch check";
function parse(args) {
const out = { positional: [], flags: new Set(), values: {} };
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (["--json", "--launch", "--no-launch"].includes(arg)) {
if (out.flags.has(arg)) throw new CliError(INSTANCES_USAGE, 4);
out.flags.add(arg);
} else if (["--definition", "--vars", "--revision"].includes(arg)) {
if (!args[i + 1] || Object.hasOwn(out.values, arg)) throw new CliError(INSTANCES_USAGE, 4);
out.values[arg] = args[++i];
} else if (arg.startsWith("--")) throw new CliError(INSTANCES_USAGE, 4);
else out.positional.push(arg);
}
return out;
}
// The args instances.set takes, from `instance add|set`. A usage error is exit 4 before any call.
function setArgs(parsed) {
const [, op, , instance] = parsed.positional;
const { values, flags } = parsed;
const launch = flags.has("--launch") ? true : flags.has("--no-launch") ? false : undefined;
if (parsed.positional.length !== 4 || !["add", "set"].includes(op) || !values["--revision"] || flags.has("--json") ||
(flags.has("--launch") && flags.has("--no-launch")) || (op === "add" && (!values["--definition"] || launch === false)) ||
(op === "set" && !values["--definition"] && !values["--vars"] && launch === undefined)) {
throw new CliError(INSTANCES_USAGE, 4);
}
const args = { revision: values["--revision"], instance, op: op === "add" ? "add" : "change" };
if (values["--definition"]) args.definition = values["--definition"];
if (values["--vars"]) {
try {
args.vars = JSON.parse(readFileSync(values["--vars"], "utf8"));
} catch (error) {
throw new CliError(`--vars ${values["--vars"]}: ${error.message}`, 4);
}
}
if (launch !== undefined) args.launch = launch;
return args;
}
export function formatInstances(view) {
const lines = [`business ${view.business}, revision ${view.revision}`];
for (const [name, entry] of Object.entries(view.instances)) {
const marks = [entry.launcher && "launcher", entry.launched && "launched", entry.protected && "protected"].filter(Boolean);
const vars = Object.keys(entry.vars).length ? ` vars ${JSON.stringify(entry.vars)}` : "";
lines.push(` ${name}: ${entry.definition}${marks.length ? ` (${marks.join(", ")})` : ""}${vars}`);
}
const definitions = Object.entries(view.definitions);
const accepted = definitions.filter(([, d]) => d.accepted).map(([name]) => name);
const bound = definitions.filter(([, d]) => d.services.length).map(([name, d]) => `${name} (${d.services.join(", ")})`);
lines.push(`definitions add and set accept: ${accepted.join(", ") || "none"}`);
if (bound.length) lines.push(`definitions that declare credentials, a hand edit: ${bound.join(", ")}`);
return `${lines.join("\n")}\n`;
}
// args are the words after `mosaic business`. callFor(parsed) returns the human's call(verb, args).
export async function instancesCommand(args, io, callFor) {
const parsed = parse(args);
const sub = parsed.positional[0];
const business = parsed.positional[sub === "instances" ? 1 : 2];
if (!["instances", "instance"].includes(sub) || !business) throw new CliError(INSTANCES_USAGE, 4);
let request;
if (sub === "instances") {
if (parsed.positional.length !== 2 || Object.keys(parsed.values).length || parsed.flags.has("--launch") || parsed.flags.has("--no-launch")) {
throw new CliError(INSTANCES_USAGE, 4);
}
} else request = setArgs(parsed);
try {
const call = callFor({ positional: parsed.positional, flags: parsed.flags, values: { "--business": business } });
if (!request) {
const view = await call("instances", {});
return io.stdout.write(parsed.flags.has("--json") ? `${JSON.stringify(view, null, 2)}\n` : formatInstances(view));
}
const result = await call("instances.set", request);
const entry = result.instances[request.instance];
io.stdout.write([
`business ${result.business}: ${request.op === "add" ? "added" : "changed"} ${request.instance} (${entry.definition}${entry.launched ? ", launched" : ""})`,
`revision ${result.revision}`,
`transaction ${result.transaction}`,
result.restart ? RESTART_NEEDED : NO_RESTART,
].join("\n") + "\n");
} catch (error) {
const code = error.code;
if (Object.hasOwn(REASONS, code)) {
const refused = new CliError(`${code}: ${REASONS[code]}`, error.exitCode ?? 2);
refused.code = code;
throw refused;
}
if (error instanceof CliError) throw error;
throw new CliError(error.message, 2);
}
}
+154
View File
@@ -0,0 +1,154 @@
// Row 165 (#1662, Q171, REQ-ROLE-3): `mosaic business instances` and `mosaic business instance
// add|set` reach the broker's human-only verbs, which write through the business package's
// instance writer. The bus here is a real startBroker over a temporary organization directory.
import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { BusError } from "../../bus/src/broker.mjs";
import { startBroker } from "../../bus/src/runtime.mjs";
import { systemFor, writeJson } from "../../business/tests/helpers.mjs";
import { main, run } from "../src/cli.mjs";
import { RESTART_NEEDED } from "../src/instances.mjs";
import { fixture, io, tmp } from "./helpers.mjs";
const BUSINESS_CLI = fileURLToPath(new URL("../../business/src/cli.mjs", import.meta.url));
const MOSAIC = fileURLToPath(new URL("../../../scripts/mosaic", import.meta.url));
async function setup(t) {
const root = tmp(t, "mosaic-cli-instances-");
const f = fixture(root, "acme");
mkdirSync(f.dataRoot, { mode: 0o700 });
const dir = join(root, "config");
const bus = await startBroker({
dataRoot: f.dataRoot,
businesses: { acme: { id: "acme", human: "jason", arbiters: { technical: "coder", delivery: "coder" }, roles: { coder: { authority: { withinRole: [], crossRole: [] } } } } },
organization: { dir, rolesDir: f.roles, system: systemFor(root) },
});
t.after(() => bus.close());
const human = bus.broker.bindHuman({ business: "acme", human: "jason", via: "cli", outsideAgent: true });
const calls = [];
const deps = {
system: { dataRoot: f.dataRoot },
transport: (business) => async (verb, args = {}) => {
calls.push({ business, verb, args });
try {
return structuredClone(bus.broker.request(human, { verb, args }));
} catch (e) {
if (!(e instanceof BusError)) throw e;
const error = new Error(e.code);
error.code = e.code;
throw error;
}
},
};
const file = join(dir, "businesses", "acme.json");
const log = () => readFileSync(join(dir, "businesses", ".history", "acme", "changes.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l));
const validate = () => spawnSync(process.execPath, [BUSINESS_CLI, "validate", "acme"], {
env: { PATH: process.env.PATH, HOME: join(root, "home"), MOSAIC_CONFIG: f.config, MOSAIC_ROLES_DIR: f.roles }, encoding: "utf8",
});
const mosaic = async (args, env = f.env) => {
const x = io(env);
const code = await run(["business", ...args], x, deps);
return { code, out: x.out.text, err: x.err.text };
};
const revision = async () => JSON.parse((await mosaic(["instances", "acme", "--json"])).out).revision;
return { root, f, file, log, validate, mosaic, revision, calls };
}
test("row 165 CLI: instance add puts an instance in the file, validate exits 0, and the log names the human", async (t) => {
const s = await setup(t);
const view = await s.mosaic(["instances", "acme"]);
assert.equal(view.code, 0, view.err);
assert.match(view.out, /^business acme, revision [a-f0-9]{64}$/m);
assert.match(view.out, /^ {2}chief: chief-of-staff \(launcher\)$/m);
assert.match(view.out, /^definitions add and set accept: .*\bmerge-gate\b.*\bsecurity-reviewer\b/m);
assert.match(view.out, /^definitions that declare credentials, a hand edit: .*\breviewer \(gitea, vikunja\)/m);
const added = await s.mosaic(["instance", "add", "acme", "sec-1", "--definition", "security-reviewer", "--launch", "--revision", await s.revision()]);
assert.equal(added.code, 0, added.err);
const entry = s.log().at(-1);
const now = await s.revision();
assert.deepEqual(added.out.split("\n"), [
"business acme: added sec-1 (security-reviewer, launched)", `revision ${now}`, `transaction ${entry.transaction}`, RESTART_NEEDED, "",
]);
assert.equal(RESTART_NEEDED, "restart needed: the running bus keeps the roles it loaded at start; this command does not restart it");
assert.doesNotMatch(RESTART_NEEDED, /Mos|Jason/, "product text names no seat (sage-0931)");
assert.doesNotMatch(added.out, /--restart|run `mosaic bus/, "the CLI names the restart and doesn't offer to run it");
const doc = JSON.parse(readFileSync(s.file, "utf8"));
assert.deepEqual(doc.roles["sec-1"], { definition: "security-reviewer" });
assert.ok(doc.launch.instances.includes("sec-1"));
assert.deepEqual([entry.actor, entry.state], ["jason", "committed"]);
const checked = s.validate();
assert.equal(checked.status, 0, checked.stderr);
});
test("row 165 CLI: instance set passes the vars file and --no-launch, and a vars-only change needs no restart", async (t) => {
const s = await setup(t);
const vars = writeJson(join(s.root, "vars.json"), { harness: "pi", model: "claude-sonnet-5-5" });
const changed = await s.mosaic(["instance", "set", "acme", "coder", "--vars", vars, "--no-launch", "--revision", await s.revision()]);
assert.equal(changed.code, 0, changed.err);
assert.deepEqual(s.calls.at(-1).args, { revision: s.calls.at(-1).args.revision, instance: "coder", op: "change", vars: { harness: "pi", model: "claude-sonnet-5-5" }, launch: false });
assert.match(changed.out, /^business acme: changed coder \(coder\)$/m);
assert.match(changed.out, /^no restart: the launcher reads the change at its next launch check$/m);
const doc = JSON.parse(readFileSync(s.file, "utf8"));
assert.equal(doc.launch.instances.includes("coder"), false);
assert.ok(doc.roles.coder.credentials.gitea && doc.roles.coder.tracker, "a vars change keeps the binding");
assert.equal(s.validate().status, 0);
});
test("row 165 CLI: a refusal names its code and why, exits 2 and keeps the bytes", async (t) => {
const s = await setup(t);
const rev = await s.revision();
const before = readFileSync(s.file, "utf8");
const cases = [
[["instance", "add", "acme", "reviewer-2", "--definition", "reviewer", "--revision", rev], /^mosaic: organization-credentials-out-of-scope: this command binds no credentials/],
[["instance", "set", "acme", "coder", "--definition", "security-reviewer", "--revision", rev], /^mosaic: organization-credentials-out-of-scope: /],
[["instance", "add", "acme", "coder", "--definition", "merge-gate", "--revision", rev], /^mosaic: organization-instance-exists: /],
[["instance", "set", "acme", "ghost", "--launch", "--revision", rev], /^mosaic: organization-unknown-instance: /],
[["instance", "add", "acme", "asst-2", "--definition", "assistant", "--revision", rev], /^mosaic: organization-definition-refused: this command neither adds nor changes an assistant, and moves no instance to the assistant definition;/],
[["instance", "add", "acme", "gate-1", "--definition", "merge-gate", "--revision", "b".repeat(64)], /^mosaic: revision-conflict: the business file changed/],
];
for (const [args, message] of cases) {
const r = await s.mosaic(args);
assert.equal(r.code, 2, args.join(" "));
assert.match(r.err, message);
}
assert.equal(readFileSync(s.file, "utf8"), before);
});
test("row 165 CLI: usage errors exit 4 before any bus call, and an agent session is refused", async (t) => {
const s = await setup(t);
const rev = "a".repeat(64);
for (const args of [
["instances"], ["instances", "acme", "extra"], ["instances", "acme", "--launch"],
["instance", "add", "acme", "sec-1", "--definition", "security-reviewer"],
["instance", "add", "acme", "sec-1", "--revision", rev],
["instance", "add", "acme", "sec-1", "--definition", "security-reviewer", "--no-launch", "--revision", rev],
["instance", "set", "acme", "coder", "--revision", rev],
["instance", "set", "acme", "coder", "--launch", "--no-launch", "--revision", rev],
["instance", "set", "acme", "coder", "--vars", join(s.root, "missing.json"), "--revision", rev],
["instance", "remove", "acme", "coder", "--revision", rev],
["instance", "set", "acme", "coder", "--holder", "mos", "--revision", rev],
]) {
const r = await s.mosaic(args);
assert.equal(r.code, 4, args.join(" "));
}
assert.equal(s.calls.length, 0);
const agent = await s.mosaic(["instances", "acme"], { ...s.f.env, CODEX_THREAD_ID: "fixture-agent" });
assert.equal(agent.code, 3);
assert.match(agent.err, /agent/i);
assert.equal(s.calls.length, 0);
await assert.rejects(main(["business", "validate", "acme"], io(s.f.env), {}), /mosaic business instances/);
});
test("row 165: scripts/mosaic sends business instances and instance to packages/cli, and validate still to packages/business", (t) => {
const root = tmp(t, "mosaic-cli-route-");
const env = { PATH: process.env.PATH, HOME: join(root, "home"), MOSAIC_CONFIG: join(root, "none.json") };
const routed = spawnSync(MOSAIC, ["business", "instance"], { env, encoding: "utf8" });
assert.equal(routed.status, 4);
assert.match(routed.stderr, /mosaic business instances BUSINESS/);
const business = spawnSync(MOSAIC, ["business", "validate"], { env, encoding: "utf8" });
assert.doesNotMatch(business.stderr, /mosaic business instances BUSINESS/);
});