salvage 2026-11-06: uncommitted work from src/mosaic-stack-rocko-122 (disk cleanup #824)

This commit is contained in:
mos committed 2026-11-06 10:06:26 -06:00
1 parent f529cf485c
commit eee44c11c4
43 files changed
+566 -100

No files matched your search

+28 -2
View File
@@ -263,8 +263,8 @@ is `{"ok": true, "result": {run, instance, harness, model}}` or
| its role has a contract file | `no-role-contract` |
| a Claude Code session has `CLAUDE_CODE_OAUTH_TOKEN`, `ANTHROPIC_API_KEY`, or `ANTHROPIC_AUTH_TOKEN` with `ANTHROPIC_BASE_URL` to log in with | `no-session-credential` |
| bwrap runs here | `sandbox-unavailable` |
| its model names exactly one `launch.max` family | `unknown-model-family` |
| that family has room; every running session counts, the PM's too | `capacity-full` |
| its model selects an exact entry in `launch.models` | `unsupported-harness` |
| total, provider and exact provider/model limits have room; the PM counts too | `capacity-full` |
| the broker authorizes `role.launch` for the caller | the broker's code (`launch-revoked`, `decision-required`, …) |
| the workspace has a clone of each project, or the host can make one | `checkout-failed`, with the project id |
| the bundle builds and the runner starts | `launch-failed` |
@@ -628,3 +628,29 @@ exit 3, so a host never starts until someone decides whether it DMs.
## Not in this piece
The WebUI (S5).
## Agent limits and models
`mosaic limits [--business ID] [--json]` reads the model table, each role's
selection, limits and running counts. `mosaic limits set --business ID
--file PATCH` submits JSON with the read's `revision` and any of `limits`,
`models`, `instances`. `limits` and `models` replace those entire objects;
`instances` maps role instance names to model-table keys. Both commands use
the existing human proof and broker; neither is available to a managed role
or tester. The Console Settings form uses the same write path and requires
signed-in send mode, named Host, exact Origin and same-origin Fetch Metadata.
Unset limits mean unlimited; zero blocks new launches. Limits are checked
afresh at each launch in total, per provider and per exact provider/model.
Lowering one leaves running sessions alive and counted against their recorded
provider/model, including the PM. Capacity refusals log the scope, configured
limit and running count; launches log harness, provider and external model.
`mosaic limits migrate --file ORGANIZATION --models MAPPING [--roles-dir DIR]`
needs no bus. It prints the whole converted document and never writes, including
on refusal. There is no `--write`. Mapping JSON supplies `models` (keys to
provider/model pairs), `families` (old family names to keys), and optional
`instances` or `selections` (old model strings to keys). Unknown or ambiguous
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).
+3
View File
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { createInterface } from "node:readline/promises";
import { fileURLToPath } from "node:url";
import { BINDING_NAME } from "../../discord/src/binding.mjs";
import { limitsCommand, LIMITS_USAGE } from "./limits.mjs";
import { CliError } from "./errors.mjs";
import { bootConfig, loadSystem, socketPath } from "./config.mjs";
import { humanTransport, refuseInsideAgent, testerTransport } from "./transport.mjs";
@@ -24,6 +25,7 @@ import { readSessions, stopSession } from "../../seat/src/session.mjs";
import { SeatError } from "../../seat/src/seat.mjs";
export const USAGE = `usage:
${LIMITS_USAGE}
mosaic inbox [--business <id>] [--json] [--tester]
mosaic decide <decision> <option> [--note <text>] [--yes] [--business <id>]
mosaic tasks [--business <id>] [--json] [--tester]
@@ -379,6 +381,7 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
if (argv.length === 0) return app(io, deps);
const [verb, ...rest] = argv;
if (["inbox", "decide", "tasks", "agents", "trail"].includes(verb)) return human(verb, rest, io, deps);
if (verb === "limits") return limitsCommand(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 === "stop") return stop(rest, io, deps);
+1
View File
@@ -94,6 +94,7 @@ export function bootConfig({ system, businessId, env = process.env, warn = () =>
const config = {
dataRoot: system.dataRoot,
businesses: { [b.id]: busBusiness(b, resolved) },
organization: {dir:configDir(env),rolesDir:rolesDir(env),system:vars},
launches: [],
readers: [b.id],
};
+17 -15
View File
@@ -16,8 +16,8 @@
// 5. a Claude Code session has a credential to log in with
// (no-session-credential)
// 6. bwrap runs here (sandbox-unavailable)
// 7. its model is in exactly one launch.max family (unknown-model-family)
// 8. that family has room; every running session counts, the PM's too
// 7. its model names an exact provider/model table entry
// 8. total, provider and provider/model have room, including the launcher
// (capacity-full)
// 9. the broker authorizes role.launch for the caller (its own codes:
// launch-revoked, gated, ...)
@@ -45,12 +45,12 @@ import { createServer } from "node:net";
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { configDir, loadBusiness, resolveInstance, systemVars } from "../../business/src/index.mjs";
import { limitHit } from "../../business/src/launch.mjs";
import { buildBundle, sessionModel } from "../../harness/src/bundle.mjs";
import {
ADAPTERS,
appendLaunchLog,
endReason,
family,
hasSessionCredential,
gitSocketPath,
launchSocketPath,
@@ -120,7 +120,7 @@ export function createLauncher({
log = (l) => process.stderr.write(`mosaic-bus: ${l}\n`),
}) {
const dataRoot = system.dataRoot;
const b = loadBusiness(host.business, { dir: configDir(env), rolesDir: rolesDir(env) });
let b = loadBusiness(host.business, { dir: configDir(env), rolesDir: rolesDir(env) });
const vars = systemVars(system);
// Sessions an earlier host left in sessions.json: it died without ending
@@ -157,13 +157,14 @@ export function createLauncher({
// Steps 2 to 8. Returns what the launch needs. Only `--pm` may name
// launch.by itself.
function check(instance, { pm = false } = {}) {
try { b=loadBusiness(host.business,{dir:configDir(env),rolesDir:rolesDir(env)}); } catch(e){throw new Refusal("organization-refused",e.message);}
if (!b.launch) throw new Refusal("launch-not-configured", `business ${b.id} has no launch block`);
if (!(pm ? instance === b.launch.by : b.launch.instances.includes(instance))) throw new Refusal("instance-not-listed");
if (registry.running(b.id, instance)) throw new Refusal("instance-running");
let resolved, model;
try {
resolved = resolveInstance({ system: vars, business: b, instance });
model = sessionModel(resolved);
model = sessionModel(resolved, b.launch.models);
} catch (e) {
throw new Refusal("unsupported-harness", e.message);
}
@@ -174,14 +175,13 @@ export function createLauncher({
}
const unavailable = sandboxProblem({ bwrap });
if (unavailable) throw new Refusal("sandbox-unavailable", unavailable);
const fam = family(model.model, b.launch.max);
if (!fam) throw new Refusal("unknown-model-family", `model ${model.model} is in none, or more than one, of ${Object.keys(b.launch.max).join(", ")}`);
if (registry.count(b.id, fam) >= b.launch.max[fam]) throw new Refusal("capacity-full", `${fam} sessions: ${registry.count(b.id, fam)} of ${b.launch.max[fam]}`);
return { resolved, model, fam };
const hit=limitHit(registry.sessions,b.id,b.launch.limits,model);
if(hit){const error=new Refusal("capacity-full",JSON.stringify(hit));error.limit=hit;throw error;}
return { resolved, model };
}
// Bundle, spawn, bind, register, hand over the capability.
async function start({ instance, launchedBy, resolved, model, fam }) {
async function start({ instance, launchedBy, resolved, model }) {
const credentials = await host.op({ op: "credentialStatus", business: b.id, role: instance });
// The clones come before the run, so one that can't be made leaves no
// run behind. The host's git treats each clone as hostile, and its
@@ -201,6 +201,7 @@ export function createLauncher({
if (c.outcome === "kept") record({ event: "checkout-kept", instance, project: c.project, reason: c.reason });
else if (c.outcome === "fetched") record({ event: "checkout-fetched", instance, project: c.project, reason: c.reason });
}
({resolved,model}=check(instance,{pm:instance===b.launch.by}));
const { run, runDir } = newRun(dataRoot, b.id);
const sessionDir = join(runDir, "session");
mkdirSync(sessionDir, { mode: 0o700 });
@@ -210,6 +211,7 @@ export function createLauncher({
const bundle = buildBundle({
dir: join(runDir, "bundle"),
resolved,
models: b.launch.models,
contract: readFileSync(resolved.contract, "utf8"),
arbiter: Object.values(b.arbiters).includes(instance),
tracker,
@@ -266,7 +268,7 @@ export function createLauncher({
const launch = await host.bindLaunch({ business: b.id, role: instance, run, harness: model.harness, pid: child.pid, startTime: outerStart });
bound = true;
entry = {
business: b.id, instance, run, launchedBy, harness: model.harness, model: model.model, family: fam,
business: b.id, instance, run, launchedBy, harness: model.harness, model: model.model, provider: model.provider, modelKey: model.modelKey,
pid: child.pid, startTime: outerStart, runnerPid: runner.pid, runnerStartTime: runner.startTime, runDir, startedAt: new Date().toISOString(),
};
registry.add(entry);
@@ -291,7 +293,7 @@ export function createLauncher({
children.delete(run);
}
});
record({ event: "launch", instance, run, launchedBy, harness: model.harness, model: model.model, family: fam, pid: child.pid, runnerPid: entry.runnerPid, manifest });
record({ event: "launch", instance, run, launchedBy, harness: model.harness, model: model.model, provider: model.provider, modelKey: model.modelKey, pid: child.pid, runnerPid: entry.runnerPid, manifest });
return { run, instance, harness: model.harness, model: model.model };
}
@@ -324,7 +326,7 @@ export function createLauncher({
} catch (e) {
if (!(e instanceof Refusal)) throw e;
await host.op({ op: "refuse", cap, code: e.code }).catch(() => {});
record({ event: "refused", by: who.role, instance, code: e.code, why: e.message });
record({ event: "refused", by: who.role, instance, code: e.code, why: e.message, ...(e.limit?{limit:e.limit}:{}) });
return { ok: false, error: e.code };
}
try {
@@ -339,7 +341,7 @@ export function createLauncher({
const code = e instanceof Refusal ? e.code : "launch-failed";
log(`launch of ${instance} for ${who.role} failed: ${e.message}`);
await host.op({ op: "refuse", cap, code }).catch(() => {});
record({ event: "refused", by: who.role, instance, code, why: e.message });
record({ event: "refused", by: who.role, instance, code, why: e.message, ...(e.limit?{limit:e.limit}:{}) });
return { ok: false, error: code };
}
});
@@ -353,7 +355,7 @@ export function createLauncher({
return await start({ instance: b.launch.by, launchedBy: b.human, ...check(b.launch.by, { pm: true }) });
} catch (e) {
if (!(e instanceof Refusal)) throw e;
record({ event: "refused", by: b.human, instance: b.launch.by, code: e.code, why: e.message });
record({ event: "refused", by: b.human, instance: b.launch.by, code: e.code, why: e.message, ...(e.limit?{limit:e.limit}:{}) });
throw new CliError(`PM launch refused: ${e.code}${e.message !== e.code ? ` (${e.message})` : ""}`, 3);
}
});
+21
View File
@@ -0,0 +1,21 @@
// REQ-LIMIT-1: human settings; decision145 migration is a separate print-only read.
import {readFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
import {join} from 'node:path';
import {CliError} from './errors.mjs';
import {migrateLaunch} from '../../business/src/migrate-launch.mjs';
export const LIMITS_USAGE='mosaic limits [--business ID] [--json] | set --file PATCH [--business ID] | migrate --file ORGANIZATION --models MAPPING [--roles-dir DIR]';
export function parseLimits(args){const out={positional:[],flags:new Set(),values:{}};for(let i=0;i<args.length;i++){const a=args[i];if(a==='--json')out.flags.add(a);else if(['--file','--models','--roles-dir','--business'].includes(a)){if(!args[i+1]||Object.hasOwn(out.values,a))throw new CliError(LIMITS_USAGE,4);out.values[a]=args[++i];}else if(a.startsWith('--'))throw new CliError(LIMITS_USAGE,4);else out.positional.push(a);}return out;}
export async function limitsCommand(args,io,callFor){
const p=parseLimits(args),verb=p.positional[0]??'view';if(p.positional.length>1)throw new CliError(LIMITS_USAGE,4);
try{
if(verb==='migrate'){
if(!p.values['--file']||!p.values['--models']||p.values['--business'])throw new CliError(LIMITS_USAGE,4);
const file=p.values['--file'],raw=JSON.parse(readFileSync(file,'utf8')),mapping=JSON.parse(readFileSync(p.values['--models'],'utf8'));const rolesDir=p.values['--roles-dir']??fileURLToPath(new URL('../../../roles',import.meta.url));
io.stdout.write(JSON.stringify(migrateLaunch(raw,mapping,file,{rolesDir}),null,2)+'\n');return;
}
if(!['view','set'].includes(verb)||p.values['--models']||p.values['--roles-dir']||(verb==='view'&&p.values['--file'])||(verb==='set'&&!p.values['--file']))throw new CliError(LIMITS_USAGE,4);
const call=callFor(p);const result=verb==='set'?await call('limits.set',JSON.parse(readFileSync(p.values['--file'],'utf8'))):await call('limits',{});
io.stdout.write(JSON.stringify(result,null,2)+'\n');
}catch(e){if(e instanceof CliError)throw e;throw new CliError(e.message,2);}
}
+20
View File
@@ -0,0 +1,20 @@
// REQ-LIMIT-1: pure launch-policy checks; no sandbox, Docker or session process.
import test from 'node:test';
import assert from 'node:assert/strict';
import {join} from 'node:path';
import {readFileSync,writeFileSync} from 'node:fs';
import {createLauncher} from '../src/launcher.mjs';
import {fixture,tmp} from './helpers.mjs';
import {systemFor,writeJson} from '../../business/tests/helpers.mjs';
import {launchLogFile} from '../../seat/src/session.mjs';
test('each launch rereads limits and model selections; lowered limits keep sessions and log exact hit',async t=>{
const root=tmp(t),f=fixture(root,'acme',doc=>{doc.roles.coder.vars.model='claude-sonnet-5-5';return doc;}),file=join(root,'config/businesses/acme.json'),ops=[];
const host={business:'acme',beforeClose:()=>{},op:async x=>{ops.push(x);if(x.op==='identity')return {business:'acme',role:'pm'};if(x.op==='authorizeLaunch')throw Object.assign(Error('fixture authorization stop'),{code:'fixture-policy'});return {};}};
const launcher=createLauncher({host,system:JSON.parse(readFileSync(f.config,'utf8')),env:f.env,bwrap:'/usr/bin/true',log:()=>{}});
const session={business:'acme',instance:'reviewer',run:'fixture-existing',harness:'pi',provider:'zai',model:'claude-sonnet-5-5'};launcher.registry.add(session);
const update=limits=>{f.doc.launch.limits=limits;writeJson(file,f.doc);};
for(const [limits,scope] of [[{total:0},'total'],[{providers:{zai:1}},'provider'],[{models:{zai:{'claude-sonnet-5-5':1}}},'model']]){update(limits);assert.deepEqual(await launcher.fromSession('fixture-cap','coder'),{ok:false,error:'capacity-full'});const event=JSON.parse(readFileSync(launchLogFile(f.dataRoot,'acme'),'utf8').trim().split('\n').at(-1));assert.equal(event.limit.scope,scope);assert.equal(event.limit.running,1);assert.deepEqual(launcher.registry.sessions,[session]);}
update({total:2});assert.equal((await launcher.fromSession('fixture-cap','coder')).error,'fixture-policy');
f.doc.launch.models['claude-sonnet-5-5'].provider='another-provider';update({models:{zai:{'claude-sonnet-5-5':1}}});assert.equal((await launcher.fromSession('fixture-cap','coder')).error,'fixture-policy');assert.equal(launcher.registry.sessions[0].provider,'zai');
writeFileSync(file,'invalid JSON');assert.equal((await launcher.fromSession('fixture-cap','coder')).error,'organization-refused');assert.deepEqual(launcher.registry.sessions,[session]);
});
+4 -3
View File
@@ -1,3 +1,4 @@
import { launchDoc } from "../../business/tests/helpers.mjs";
// The S6 launcher inside a real bus host: real broker child, real runners
// in the bwrap sandbox, the fake adapter from packages/harness standing in for the
// harness. The PM launches a coder through its `launch` tool; every host
@@ -31,7 +32,7 @@ const skip = sandboxProblem() ?? false;
function edit(doc) {
doc.roles.coder.vars.model = "claude-sonnet-5-5";
doc.roles.reviewer.vars = { harness: "pi", model: "claude-sonnet-5-5" };
doc.launch = { by: "pm", instances: ["coder", "reviewer", "cto"], max: { opus: 1, sonnet: 1 } };
doc.launch = launchDoc("pm",["coder","reviewer","cto"],{opus:1,sonnet:1});doc.launch.limits.models.zai["glm-5.3-flash"]=0;
return doc;
}
@@ -139,7 +140,7 @@ test("bus start --pm: the PM runs under its own PID namespace, registered, with
const [s] = readSessions(f.dataRoot);
assert.equal(s.run, pm.run);
assert.equal(s.live, true);
assert.equal(s.family, "opus");
assert.equal(s.provider, "zai");
assert.equal(s.launchedBy, "jason");
assert.notEqual(s.pid, s.runnerPid, "the runner is the bwrap process's child");
assert.equal(statSync(sessionsFile(f.dataRoot)).mode & 0o777, 0o600);
@@ -250,7 +251,7 @@ test("the PM launches a coder through its launch tool; the coder answers; refusa
["nobody", "instance-not-listed"],
["coder", "instance-running"],
["reviewer", "capacity-full"],
["cto", "unknown-model-family"],
["cto", "capacity-full"],
];
for (const [instance, code] of refusals) {
assert.deepEqual(await ask(sock, `${JSON.stringify({ cap: cto.cap, instance })}\n`), { ok: false, error: code }, instance);
+28
View File
@@ -0,0 +1,28 @@
// REQ-LIMIT-1 and decision145: human transport and print-only migration.
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync,statSync} from 'node:fs';
import {join} from 'node:path';
import {main} from '../src/cli.mjs';
import {limitsCommand} from '../src/limits.mjs';
import {fixture,io,tmp} from './helpers.mjs';
import {writeJson} from '../../business/tests/helpers.mjs';
test('migration needs no bus/config, prints whole converted document, is idempotent and never writes',async t=>{
const root=tmp(t),f=fixture(root,'acme'),file=join(root,'config/businesses/acme.json');
const old=f.doc;old.roles.pm.vars.model='claude-opus-5-5';old.roles.cto.vars.model='claude-opus-5-5';old.roles.coder.vars.model='claude-sonnet-5-5';old.roles.reviewer.vars={model:'claude-opus-5-5'};old.launch={by:'pm',instances:['coder','reviewer'],max:{opus:4,sonnet:4}};writeJson(file,old);
const mapping={models:{opus:{provider:'anthropic',model:'claude-opus-5-5'},sonnet:{provider:'anthropic',model:'claude-sonnet-5-5'}},families:{opus:'opus',sonnet:'sonnet'},instances:{pm:'opus',cto:'opus',coder:'sonnet',reviewer:'opus'}};
const map=writeJson(join(root,'mapping.json'),mapping),args=['limits','migrate','--file',file,'--models',map,'--roles-dir',f.roles],bytes=readFileSync(file,'utf8'),mtime=statSync(file).mtimeNs??statSync(file).mtimeMs;
const x=io({MOSAIC_CONFIG:'/nonexistent'});await main(args,x,{transport:()=>assert.fail('migration contacted bus')});const migrated=JSON.parse(x.out.text);
assert.equal(migrated.roles.cto.vars.model,'opus');assert.deepEqual(migrated.launch.limits,{models:{anthropic:{'claude-opus-5-5':4,'claude-sonnet-5-5':4}}});assert.equal(migrated.roles.pm.vars.harness,'pi');assert.equal(readFileSync(file,'utf8'),bytes);assert.equal(statSync(file).mtimeNs??statSync(file).mtimeMs,mtime);
for(const bad of [{...mapping,families:{opus:'missing',sonnet:'sonnet'}},{...mapping,families:{opus:'opus',sonnet:'opus'}}]){writeJson(map,bad);await assert.rejects(main(args,io(),{}));assert.equal(readFileSync(file,'utf8'),bytes);assert.equal(statSync(file).mtimeMs,mtime);}
writeJson(map,mapping);const migratedFile=writeJson(join(root,'acme.json'),migrated),before=readFileSync(migratedFile,'utf8'),mt=statSync(migratedFile).mtimeMs,y=io();await main(['limits','migrate','--file',migratedFile,'--models',map,'--roles-dir',f.roles],y,{});assert.deepEqual(JSON.parse(y.out.text),migrated);assert.equal(readFileSync(migratedFile,'utf8'),before);assert.equal(statSync(migratedFile).mtimeMs,mt);
await assert.rejects(main([...args,'--write'],io(),{}),/mosaic limits/);
});
test('limits view/set use the human bus transport and pass only the explicit patch',async t=>{
const root=tmp(t),patch={revision:'a'.repeat(64),limits:{total:9},instances:{coder:'opus'}},file=writeJson(join(root,'patch.json'),patch),calls=[];
const deps={system:{dataRoot:root},transport:business=>(verb,args)=>{calls.push({business,verb,args});return {revision:'b'.repeat(64),limits:args.limits??{}};}};
const x=io();await main(['limits','--business','acme','--json'],x,deps);await main(['limits','set','--business','acme','--file',file],io(),deps);
assert.deepEqual(calls,[{business:'acme',verb:'limits',args:{}},{business:'acme',verb:'limits.set',args:patch}]);assert.equal(JSON.parse(x.out.text).revision,'b'.repeat(64));
await assert.rejects(main(['limits','--business','acme'],io({CODEX_THREAD_ID:'fixture-agent'}),deps),/agent/i);assert.equal(calls.length,2);
});