Files
stack/packages/model-proxy/tests/admin-control.test.mjs

570 lines
40 KiB
JavaScript

// #1873 the setup controller the Console page and `mosaic proxy` share: next steps from state,
// a fetch receipt with every pinned hash, init through the bus call, and the fence clear that
// needs a restart this controller confirmed.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createHash } from 'node:crypto';
import { createProxyAdmin, installedHarnesses, harnessesNamed, rootHarnessesNamed } from '../src/admin-control.mjs';
import { pluginHash } from '../../plugins/src/pinned.mjs';
import { installPlugin } from '../../plugins/src/install.mjs';
import { KINDS } from '../../plugins/src/kinds.mjs';
import { initFiles, receiptFile } from '../src/admin.mjs';
import { PIN } from '../src/common.mjs';
const code = name => error => error.code === name;
const SENTINEL = 'pa-sentinel-management-key-0123456789';
const stopped = async () => ({ stopped: true, running: [] });
function fixture(t, { unitState = { installed: false, active: 'inactive', healthy: false }, restart = null, fetch = null, pin = PIN, statusHook = null, extra = {} } = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'pc-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const ops = [];
const unit = {
unit: 'mosaic-proxy-zz.service',
status: async () => { await statusHook?.(); return { unit: 'mosaic-proxy-zz.service', ...unitState }; },
render: async () => `ExecStart=/usr/bin/node ${process.env.HOME ?? '/nohome'}/repo/run.mjs\n`,
install: async () => { ops.push('install'); return { ...unitState, installed: true }; },
start: async () => { ops.push('start'); return { ...unitState, active: 'active', pid: 11, healthy: true }; },
stop: async () => { ops.push('stop'); return { ...unitState, active: 'inactive', pid: null }; },
restart: async () => { ops.push('restart'); return restart ?? { state: unitState, evidence: { unit: 'mosaic-proxy-zz.service', confirmed: true, before: { pid: 10, since: 1, active: 'active' }, after: { pid: 11, since: 2, active: 'active', listening: true }, observedAt: new Date(0).toISOString() } }; },
};
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: fetch ?? (async () => ({})), now: () => new Date(0), orgs: async () => [{ id: 'acme', catalogue: 'ready' }], pin, ...extra });
return { root, configDir, dataRoot, admin, ops, files: initFiles(configDir, dataRoot) };
}
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
test('a fresh instance says fetch first; status names files by label and offers no own proxy', async t => {
const { root, admin } = fixture(t);
const status = await admin.status();
assert.deepEqual(status.next, ['fetch']);
assert.equal(status.release.version, PIN.version);
assert.equal(status.release.fetched, false);
assert.deepEqual(status.init.files.map(f => f.label), ['proxy.json', 'the management key file', 'the proxy state directory', 'the init lock']);
assert.deepEqual(status.ownProxy, { available: false, state: 'not built', reason: 'This instance has one shared proxy. A separate proxy per organization is not built yet.' });
assert.deepEqual(status.organizations, [{ id: 'acme', catalogue: 'ready' }]);
assert.equal(JSON.stringify(status).includes(root), false);
});
test('fetch runs in the background, reports each step and writes a receipt with every pinned hash', async t => {
const steps = [];
let release;
const gate = new Promise(r => { release = r; });
const { dataRoot, admin } = fixture(t, { fetch: async ({ pin, progress }) => { assert.equal(pin, PIN); progress('verify-archive'); steps.push('called'); await gate; } });
assert.deepEqual(admin.fetchStart(), { state: 'running' });
await new Promise(r => setImmediate(r));
assert.throws(() => admin.fetchStart(), code('proxy-admin-busy'));
await assert.rejects(admin.unitAction('start'), code('proxy-admin-busy'));
const running = await admin.status();
assert.equal(running.fetch.state, 'running'); assert.equal(running.fetch.step, 'verify-archive'); assert.equal(running.busy, 'fetch');
release();
await new Promise(r => setTimeout(r, 10));
const done = await admin.status();
assert.equal(done.fetch.state, 'done');
assert.deepEqual(done.fetch.receipt, { time: new Date(0).toISOString(), op: 'fetch', version: PIN.version, panelVersion: PIN.panel.version, archiveSha256: PIN.archive.sha256, panelSha256: PIN.panel.sha256, binarySha256: PIN.binary.sha256, verified: true });
assert.deepEqual(receipts(dataRoot), [done.fetch.receipt]);
});
test('a fetch that ends while status is being read is never reported done with the release still not fetched', async t => {
// E2E finding: status read the release before its awaits and the job after them, so the page
// saw "done" next to "Not fetched", stopped polling and kept offering Fetch.
const sha = text => createHash('sha256').update(text).digest('hex');
const pin = { ...PIN, archive: { ...PIN.archive, sha256: sha('a') }, binary: { sha256: sha('b') }, panel: { ...PIN.panel, sha256: sha('p') } };
let release, during = null;
const gate = new Promise(r => { release = r; });
const f = fixture(t, { pin, statusHook: async () => { const d = during; during = null; await d?.(); }, fetch: async ({ dataRoot }) => {
await gate;
const dir = join(dataRoot, 'opt', 'cliproxyapi', PIN.version);
fs.mkdirSync(join(dir, 'static'), { recursive: true });
fs.writeFileSync(join(dir, 'cli-proxy-api'), 'b'); fs.writeFileSync(join(dir, 'static', 'management.html'), 'p');
} });
f.admin.fetchStart();
await new Promise(r => setImmediate(r));
during = async () => { release(); await new Promise(r => setTimeout(r, 10)); };
const racing = await f.admin.status();
assert.equal(during, null, 'the fetch ended inside this status read');
assert.equal(racing.fetch.state === 'done' && !racing.release.fetched, false, `fetch ${racing.fetch.state} with release fetched=${racing.release.fetched}`);
const after = await f.admin.status();
assert.equal(after.fetch.state, 'done'); assert.equal(after.release.verified, true); assert.equal(after.next[0], 'init');
});
test('a refused fetch keeps its code and writes no receipt', async t => {
const { dataRoot, admin } = fixture(t, { fetch: async () => { throw Object.assign(Error('/home/x upstream body'), { code: 'proxy-fetch-hash' }); } });
admin.fetchStart();
await new Promise(r => setTimeout(r, 10));
const status = await admin.status();
assert.equal(status.fetch.state, 'failed'); assert.equal(status.fetch.error, 'proxy-fetch-hash');
assert.equal(JSON.stringify(status).includes('upstream body'), false);
assert.deepEqual(receipts(dataRoot), []);
});
test('init sends the arguments to proxy.init and its receipt carries settings only', async t => {
const { dataRoot, admin } = fixture(t);
const calls = [];
const result = await admin.init(async (verb, args) => { calls.push([verb, args]); return { port: 18432, binary: '/fixture', rotateGraceMinutes: 5, firstOutputSeconds: 90 }; }, { generate: true, port: 18432 });
assert.deepEqual(calls, [['proxy.init', { generate: true, port: 18432 }]]);
assert.deepEqual(result.settings, { port: 18432, rotateGraceMinutes: 5, firstOutputSeconds: 90 });
assert.deepEqual(receipts(dataRoot), [{ time: new Date(0).toISOString(), op: 'init', generated: true, port: 18432, rotateGraceMinutes: 5, firstOutputSeconds: 90 }]);
await admin.init(async () => ({ port: 18433, binary: '/fixture' }), { key: SENTINEL });
assert.equal(fs.readFileSync(receiptFile(dataRoot), 'utf8').includes(SENTINEL), false);
assert.equal(JSON.stringify(receipts(dataRoot)).includes('/fixture'), false);
});
test('fence clear refuses without a restart, and after an unconfirmed one, before calling the bus', async t => {
const { admin, ops } = fixture(t, { restart: { state: {}, evidence: { unit: 'mosaic-proxy-zz.service', confirmed: false, before: { pid: 10 }, after: { pid: 10, listening: true }, observedAt: new Date(0).toISOString() } } });
const calls = [];
const call = async (verb, args) => { calls.push([verb, args]); return { cleared: true }; };
await assert.rejects(admin.fenceClear(call), code('proxy-restart-required'));
const restart = await admin.unitAction('restart');
assert.equal(restart.evidence.confirmed, false);
assert.equal(restart.receipt.confirmed, false);
await assert.rejects(admin.fenceClear(call), code('proxy-restart-required'));
assert.deepEqual(calls, []);
assert.deepEqual(ops, ['restart']);
});
test('fence clear after a confirmed restart sends that evidence once; another unit action ends it', async t => {
const { dataRoot, admin } = fixture(t, { unitState: { installed: true, active: 'active', healthy: true, pid: 11 } });
const calls = [];
const call = async (verb, args) => { calls.push([verb, args]); return { cleared: true, evidence: { after: { pid: 11 } } }; };
const restart = await admin.unitAction('restart');
assert.equal(restart.evidence.confirmed, true);
assert.deepEqual((await admin.status()).restart, { confirmed: true, observedAt: new Date(0).toISOString(), pid: 11 });
const cleared = await admin.fenceClear(call);
assert.deepEqual(calls, [['proxy.fence.clear', { evidence: restart.evidence }]]);
assert.equal(cleared.cleared, true);
assert.deepEqual(cleared.receipt.evidence, { after: { pid: 11 } });
await assert.rejects(admin.fenceClear(call), code('proxy-restart-required'), 'one restart, one clear');
await admin.unitAction('restart');
await admin.unitAction('stop');
await assert.rejects(admin.fenceClear(call), code('proxy-restart-required'), 'a stop ends the confirmed restart');
assert.deepEqual(receipts(dataRoot).map(r => r.op), ['unit.restart', 'fence.clear', 'unit.restart', 'unit.stop']);
});
test('a fence clear the bus did not answer keeps the confirmed restart for a retry', async t => {
const { admin } = fixture(t, { unitState: { installed: true, active: 'active', healthy: true, pid: 11 } });
let fail = true;
const call = async () => { if (fail) { fail = false; throw Object.assign(new Error('bus down'), { code: 'bus-unavailable' }); } return { cleared: true }; };
await admin.unitAction('restart');
await assert.rejects(admin.fenceClear(call), /bus down/);
assert.equal((await admin.status()).restart?.confirmed, true, 'the restart is still confirmed');
assert.equal((await admin.fenceClear(call)).cleared, true);
assert.equal((await admin.status()).restart, null);
});
test('next step walks fetch, init lock, repair, init, unit install, start, restart, fence and accounts', async t => {
const sha = text => createHash('sha256').update(text).digest('hex');
const pin = { ...PIN, archive: { ...PIN.archive, sha256: sha('a') }, binary: { sha256: sha('b') }, panel: { ...PIN.panel, sha256: sha('p') } };
const state = { installed: false, active: 'inactive', healthy: false, pid: null };
const f = fixture(t, { unitState: state, pin });
const next = async () => (await f.admin.status()).next[0];
assert.equal(await next(), 'fetch');
const binDir = join(f.dataRoot, 'opt', 'cliproxyapi', PIN.version);
fs.mkdirSync(join(binDir, 'static'), { recursive: true });
fs.writeFileSync(join(binDir, 'cli-proxy-api'), 'b'); fs.writeFileSync(join(binDir, 'static', 'management.html'), 'wrong');
assert.equal(await next(), 'fetch', 'a hash mismatch is not a fetched release');
fs.rmSync(join(binDir, 'static', 'management.html')); fs.writeFileSync(join(binDir, 'static', 'management.html'), 'p');
fs.mkdirSync(join(f.configDir, 'secrets'), { mode: 0o700 });
fs.writeFileSync(f.files.key, 'fixture', { mode: 0o600 });
fs.writeFileSync(f.files.lock, '', { mode: 0o600 });
assert.equal(await next(), 'init-lock-wait', 'a key file blocks the lock clear');
fs.rmSync(f.files.key);
assert.equal(await next(), 'init-lock-clear');
fs.rmSync(f.files.lock);
fs.writeFileSync(f.files.key, 'fixture', { mode: 0o600 });
assert.equal(await next(), 'init-repair');
fs.rmSync(f.files.key);
assert.equal(await next(), 'init');
fs.writeFileSync(f.files.key, 'fixture', { mode: 0o600 });
fs.mkdirSync(f.files.proxyDir, { mode: 0o700 });
fs.writeFileSync(f.files.settings, JSON.stringify({ binary: join(binDir, 'cli-proxy-api'), port: 18432 }), { mode: 0o600 });
const initialized = await f.admin.status();
assert.equal(initialized.init.initialized, true);
assert.deepEqual(initialized.init.settings, { port: 18432, rotateGraceMinutes: null, firstOutputSeconds: null });
assert.equal(initialized.next[0], 'unit-install');
state.installed = true;
assert.equal(await next(), 'unit-start');
state.active = 'active';
assert.equal(await next(), 'unit-restart', 'active but not answering');
state.healthy = true;
assert.equal(await next(), 'accounts');
fs.writeFileSync(join(f.files.proxyDir, 'mosaic-keys.uncertain'), JSON.stringify({ org: 'acme', op: 'write', time: new Date(0).toISOString(), pid: 1 }), { mode: 0o600 });
const fenced = await f.admin.status();
assert.deepEqual(fenced.fence, { set: true, org: 'acme', op: 'write', time: new Date(0).toISOString(), invalid: false });
assert.equal(fenced.next[0], 'unit-restart', 'a fence needs a restart first');
await f.admin.unitAction('restart');
assert.equal(await next(), 'fence-clear');
});
test('the init lock clears through the controller only on the README conditions', async t => {
const { dataRoot, admin, files } = fixture(t);
await assert.rejects(admin.initLockClear(), code('proxy-init-lock-absent'));
fs.writeFileSync(files.lock, '', { mode: 0o600 });
fs.mkdirSync(files.proxyDir, { mode: 0o700 });
await assert.rejects(admin.initLockClear(), code('proxy-init-lock-held'));
assert.deepEqual((await admin.status()).initLock, { present: true, clearable: false, blockers: ['the proxy state directory exists'] });
fs.rmdirSync(files.proxyDir);
const result = await admin.initLockClear();
assert.equal(result.receipt.op, 'init-lock.clear');
assert.equal(fs.existsSync(files.lock), false);
assert.deepEqual(receipts(dataRoot).map(r => r.op), ['init-lock.clear']);
});
test('render replaces the home directory with ~', async t => {
const { admin } = fixture(t);
const { unit, text } = await admin.render();
assert.equal(unit, 'mosaic-proxy-zz.service');
if (process.env.HOME && process.env.HOME !== '/') assert.equal(text.includes(process.env.HOME), false);
});
test('status carries the last receipts from proxy-admin.jsonl, so the page shows them after a reload', async t => {
const { dataRoot, admin } = fixture(t, { unitState: { installed: true, active: 'active', healthy: true, pid: 11 } });
assert.deepEqual((await admin.status()).receipts, []);
for (let i = 0; i < 12; i++) await admin.unitAction('stop');
fs.appendFileSync(receiptFile(dataRoot), '{"op":"torn');
const { receipts } = await admin.status();
assert.equal(receipts.length, 10);
assert.ok(receipts.every(r => r.op === 'unit.stop'));
});
// #1873 settings-backend A1: the controller's three reads and the account-change record.
function a1Fixture(t, { unitState = { installed: true, active: 'active', healthy: true }, log = undefined, statusError = false, env = {} } = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'pc-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const calls = [];
const unit = {
unit: 'mosaic-proxy-zz.service',
status: async () => { if (statusError) throw Object.assign(new Error('systemctl gone'), { code: 'proxy-unit-failed' }); return { unit: 'mosaic-proxy-zz.service', ...unitState }; },
...(log === undefined ? { log: async (lines, options) => { calls.push({ lines, options }); return { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 }; } } : log === null ? {} : { log }),
};
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, now: () => new Date(0), env });
return { admin, calls, configDir, dataRoot };
}
test('log reads the unit journal with the env secrets; a missing unit or log reader is not-configured, an unreadable state outcome-unknown', async t => {
const { admin, calls } = a1Fixture(t, { env: { MOSAIC_PROXY_KEY: 'plainwordsonly', PATH: '/usr/bin' } });
assert.deepEqual(await admin.log(), { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 });
assert.deepEqual(calls, [{ lines: 50, options: { secrets: ['plainwordsonly'] } }]);
await admin.log({ lines: 7 });
assert.equal(calls[1].lines, 7);
await assert.rejects(a1Fixture(t, { unitState: { installed: false, active: 'inactive', healthy: false } }).admin.log(), code('not-configured'));
await assert.rejects(a1Fixture(t, { log: null }).admin.log(), code('not-configured'));
await assert.rejects(a1Fixture(t, { statusError: true }).admin.log(), code('outcome-unknown'));
const failing = a1Fixture(t, { log: async () => { throw Object.assign(new Error('journal'), { code: 'outcome-unknown' }); } });
await assert.rejects(failing.admin.log(), code('outcome-unknown'));
});
test('serviceKey and history read the configured directories', async t => {
const { admin, configDir, dataRoot } = a1Fixture(t);
assert.equal(admin.serviceKey().problem, 'missing');
fs.writeFileSync(join(configDir, 'proxy.json'), '{}', { mode: 0o600 });
assert.equal(admin.serviceKey().problem, null);
assert.match(admin.serviceKey().madeAt, /^\d{4}-\d\d-\d\dT/);
assert.deepEqual(admin.history(), { entries: [], next: null });
admin.recordAccount({ verb: 'proxy.login.status', result: { status: 'ok' } });
assert.deepEqual(admin.history({ limit: 5 }), { entries: [{ time: new Date(0).toISOString(), op: 'account.proxy.login.complete' }], next: null });
assert.equal(receipts(dataRoot).length, 1);
});
test('history withholds an env secret a receipt holds', async t => {
const { admin, dataRoot } = a1Fixture(t, { env: { PROXY_TOKEN: 'plainwordsonly' } });
fs.mkdirSync(join(dataRoot, 'state'), { recursive: true, mode: 0o700 });
fs.writeFileSync(receiptFile(dataRoot), JSON.stringify({ op: 'x', note: 'plain words only' }) + '\n', { mode: 0o600 });
assert.deepEqual(admin.history().entries, [{ op: 'x', note: '[redacted]' }]);
});
test('recordAccount records account changes by label only, never a key, login state, callback or model name', async t => {
const { admin, dataRoot } = a1Fixture(t);
const KEY = 'sk-proj-Ab3dE5fG7hJ9kL1mN3pQ5rS7tU9vW1xY';
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: KEY }, result: { added: true }, user: 'jason', org: 'acme' }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: KEY, key: KEY } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'ok' } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'wait' } }), null);
assert.equal(admin.recordAccount({ verb: 'proxy.priority.set', args: { accountId: '0123456789ab', priority: 2 } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.group.models.set', args: { accountId: 'not-hex', models: ['secret-model-name', 'b'] }, org: '../x' }), true);
for (const verb of ['proxy.login.start', 'proxy.login.submit', 'proxy.login.cancel', 'plugins.set', 'proxy.accounts', undefined]) {
assert.equal(admin.recordAccount({ verb, args: { redirect_url: 'https://cb.example/?code=abc', provider: 'x' } }), null, String(verb));
}
const all = receipts(dataRoot);
const at = new Date(0).toISOString();
assert.deepEqual(all, [
{ time: at, op: 'account.proxy.apikey.add', provider: 'openai', org: 'acme', user: 'jason' },
{ time: at, op: 'account.proxy.apikey.add', provider: null },
{ time: at, op: 'account.proxy.login.complete' },
{ time: at, op: 'account.proxy.priority.set', accountId: '0123456789ab', priority: 2 },
{ time: at, op: 'account.proxy.group.models.set', accountId: null, models: 2 },
]);
const text = fs.readFileSync(receiptFile(dataRoot), 'utf8');
for (const bit of ['Ab3dE5', 'state-secret', 'secret-model', 'cb.example', 'code=abc']) assert.equal(text.includes(bit), false, bit);
});
test('recordAccount answers false, and throws nothing, when the history cannot be written', async t => {
const { admin, dataRoot } = a1Fixture(t);
fs.mkdirSync(join(dataRoot, 'state'), { mode: 0o700 });
fs.mkdirSync(receiptFile(dataRoot));
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: 'k' } }), false);
});
// #1873 settings-backend A2 (items 5 and 8): fake organizations behind the riders. The harness names
// are made up; every answer carries a planted key, which no result, receipt or history entry may hold.
const REV = 'a'.repeat(64), REV2 = 'b'.repeat(64);
const PLANT = `mso-zz-acme-key-${'Q'.repeat(43)}`;
const KEY_TEXT = /ms[kotp][-_][A-Za-z0-9_-]{6,}/;
const busError = name => Object.assign(new Error(`refused ${PLANT}`), { code: name, reason: PLANT });
function fakeOrg(id, { on = ['alpha', 'beta'], revision = REV, fileRevision = null, instances = {}, routesError = null, routesRevision = null, document = null, fileError = false, down = false, setError = null, keys = [], keysError = null, fixture = false, cliproxy = true, plugins = undefined } = {}) {
const calls = [];
const rider = {
id, fixture, cliproxy, changes: '',
file: () => { if (fileError) throw new Error(PLANT); return { document: document ?? { roles: {}, plugins: { harness: on }, secretNote: PLANT }, revision: fileRevision ?? revision }; },
call: async (verb, args) => {
calls.push(args === undefined ? [verb] : [verb, args]);
if (down) throw busError('outcome-unknown');
if (verb === 'plugins') return { business: id, revision, plugins: plugins !== undefined ? plugins : { harness: on, 'model-provider': ['cliproxy'] }, available: { harness: on }, note: PLANT };
if (verb === 'routes') { if (routesError) throw busError(routesError); return { business: id, revision: routesRevision ?? revision, harnesses: on, models: ['m1'], providerModels: {}, levels: {}, instances, note: PLANT }; }
if (verb === 'plugins.set') { if (setError) throw busError(setError); return { business: id, revision: REV2, plugins: args.plugins }; }
if (verb === 'proxy.keys') { if (keysError) throw busError(keysError); return { keys }; }
throw busError('invalid-request');
},
};
return { rider, calls };
}
const NO_ROOT = { state: 'absent', agents: {}, assistant: null };
const programsFixture = (t, orgs, extra = {}) => fixture(t, { extra: { riders: async () => orgs.map(o => o.rider), harnesses: () => ['alpha', 'beta', 'gamma'], rootAgents: () => NO_ROOT, ...extra } });
const rootAgent = (vars, { definition = 'coder', excludeOrgs = [] } = {}) => ({ definition, title: 'Coder', vars, excludeOrgs });
const route = harness => ({ harness, model: 'm1', thinking: null, fallback: null });
test('A2 item 5: the installed list comes from the harness plugin tree, and status lists it with no organization', async t => {
const tree = new URL('../../plugins/harness/', import.meta.url);
const fromTree = fs.readdirSync(tree).filter(name => { try { return fs.lstatSync(new URL(`${name}/index.mjs`, tree)).isFile(); } catch { return false; } }).sort();
assert.ok(fromTree.length >= 1);
assert.deepEqual(installedHarnesses(), fromTree);
const { admin } = fixture(t);
assert.deepEqual((await admin.status()).programs, { installed: fromTree, organizations: [] });
});
test('A2 item 5: status names the programs each organization has on; one bus down is null and leaves the others', async t => {
const acme = fakeOrg('acme', { on: ['alpha'] }), bolt = fakeOrg('bolt', { down: true }), crux = fakeOrg('crux', { plugins: { harness: 'alpha' } });
const { admin } = programsFixture(t, [acme, bolt, crux]);
const status = await admin.status();
assert.deepEqual(status.programs, { installed: ['alpha', 'beta', 'gamma'], organizations: [{ id: 'acme', on: ['alpha'] }, { id: 'bolt', on: null }, { id: 'crux', on: null }] });
assert.doesNotMatch(JSON.stringify(status), KEY_TEXT);
});
test('A2 item 5: off skips a program any route still uses, whatever its model, and writes nothing there', async t => {
// A role route, a fallback route, a project agent only the file shows, and a route whose model has
// no known account kind: each keeps alpha on (the harness rule).
const role = fakeOrg('role', { instances: { chief: route('alpha') } });
const fallback = fakeOrg('fallback', { instances: { chief: { ...route('beta'), fallback: { harness: 'alpha', model: 'm1', thinking: null } } } });
const project = fakeOrg('project', { routesError: 'launch-not-configured', document: { roles: {}, plugins: { harness: ['alpha', 'beta'] }, projects: { site: { agents: { dev: { definition: 'coder', vars: { harness: 'alpha' } } } } } } });
const unknownKind = fakeOrg('unknown-kind', { instances: { chief: { harness: 'alpha', model: 'mystery-account-model', thinking: null, fallback: null } } });
const { admin } = programsFixture(t, [role, fallback, project, unknownKind]);
const out = await admin.programsOff({ name: 'alpha' });
assert.deepEqual(out.results.map(r => [r.id, r.outcome]), [['role', 'in-use'], ['fallback', 'in-use'], ['project', 'in-use'], ['unknown-kind', 'in-use']]);
for (const o of [role, fallback, project, unknownKind]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
});
test('A2 item 5: off turns the program off where nothing uses it, skips the last program, already off and unreadable, and reports bus down', async t => {
const free = fakeOrg('free', { instances: { chief: route('beta') } });
const last = fakeOrg('last', { on: ['alpha'] });
const already = fakeOrg('already', { on: ['beta'] });
const down = fakeOrg('down', { down: true });
const unreadable = fakeOrg('unreadable', { fileError: true });
const noFile = fakeOrg('no-file'); delete noFile.rider.file;
const badRoutes = fakeOrg('bad-routes', { routesError: 'organization-invalid' });
const { admin } = programsFixture(t, [free, last, already, down, unreadable, noFile, badRoutes]);
const out = await admin.programsOff({ name: 'alpha', user: 'owner' });
assert.equal(out.name, 'alpha');
assert.deepEqual(out.results, [
{ id: 'free', outcome: 'off' }, { id: 'last', outcome: 'last-program' }, { id: 'already', outcome: 'already-off' },
{ id: 'down', outcome: 'bus-down' }, { id: 'unreadable', outcome: 'unreadable' }, { id: 'no-file', outcome: 'unreadable' }, { id: 'bad-routes', outcome: 'unreadable' },
]);
assert.deepEqual(free.calls.find(([verb]) => verb === 'plugins.set'), ['plugins.set', { revision: REV, plugins: { harness: ['beta'] } }]);
for (const o of [last, already, down, unreadable, noFile, badRoutes]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
});
test('A2 item 5: a plugins.set refusal is reported per organization, and a revision change is reported once, never retried', async t => {
const refused = fakeOrg('refused', { setError: 'unknown-plugin' });
const raced = fakeOrg('raced', { setError: 'revision-conflict' });
const moved = fakeOrg('moved', { fileRevision: REV2 });
const ok = fakeOrg('ok');
const { admin } = programsFixture(t, [refused, raced, moved, ok]);
const out = await admin.programsOff({ name: 'alpha' });
assert.deepEqual(out.results.map(r => r.outcome), ['failed:unknown-plugin', 'failed:revision-conflict', 'failed:revision-conflict', 'off']);
assert.equal(raced.calls.filter(([verb]) => verb === 'plugins.set').length, 1);
assert.equal(moved.calls.some(([verb]) => verb === 'plugins.set'), false);
});
test('A2 item 5: off writes one receipt by name and outcome ids, and no answer, receipt or history entry holds a key', async t => {
const a = fakeOrg('acme'), b = fakeOrg('bolt', { setError: 'invalid-plugins' });
const { admin, dataRoot } = programsFixture(t, [a, b]);
const out = await admin.programsOff({ name: 'beta', user: 'owner' });
const record = { time: new Date(0).toISOString(), op: 'programs.off', name: 'beta', results: [{ id: 'acme', outcome: 'off' }, { id: 'bolt', outcome: 'failed:invalid-plugins' }], user: 'owner' };
assert.deepEqual(out.receipt, record);
assert.deepEqual(receipts(dataRoot), [record]);
const history = admin.history({});
assert.deepEqual(history.entries, [record]);
for (const value of [out, receipts(dataRoot), history]) assert.doesNotMatch(JSON.stringify(value), KEY_TEXT);
});
test('A2 item 5: an unknown name is invalid-request and calls no bus; two off calls at once give proxy-admin-busy for one', async t => {
let release;
const gate = new Promise(r => { release = r; });
const slow = fakeOrg('slow');
const original = slow.rider.call;
// Blocks only from the busy part on, so a name check that lets a bad name through goes red, not hangs.
let blocking = false;
slow.rider.call = async (verb, args) => { if (verb === 'plugins' && blocking) await gate; return original(verb, args); };
const { admin, dataRoot } = programsFixture(t, [slow]);
await assert.rejects(admin.programsOff({ name: 'delta' }), code('invalid-request'));
await assert.rejects(admin.programsOff({ name: 42 }), code('invalid-request'));
assert.deepEqual(slow.calls, []);
assert.deepEqual(receipts(dataRoot), []);
blocking = true;
const first = admin.programsOff({ name: 'alpha' });
await new Promise(r => setImmediate(r));
// Bounded: without the lock the second call would wait on the same gate, so it answers 'waited'.
const second = admin.programsOff({ name: 'beta' }).then(() => 'answered', e => e?.code);
assert.equal(await Promise.race([second, new Promise(r => setTimeout(() => r('waited'), 1000))]), 'proxy-admin-busy');
release();
await second;
assert.deepEqual((await first).results, [{ id: 'slow', outcome: 'off' }]);
assert.equal(receipts(dataRoot).length, 1);
});
test('A2 item 5: an installed list that cannot be read refuses off as invalid-request', async t => {
const a = fakeOrg('acme');
const { admin } = programsFixture(t, [a], { harnesses: () => { throw new Error('unreadable tree'); } });
await assert.rejects(admin.programsOff({ name: 'alpha' }), code('invalid-request'));
assert.deepEqual(a.calls, []);
assert.equal((await admin.status()).programs.installed, null);
});
test('A2 item 5 (review P1-1): a root agent the organization takes keeps its program on; an excluded organization and the root assistant do not count', async t => {
// Only the root agent file names alpha: nothing in either organization's file or routes does.
const root = { state: 'ok', assistant: 'helper', agents: {
writer: rootAgent({ harness: 'gamma', 'fallback.harness': 'alpha' }, { excludeOrgs: ['spare'] }),
helper: rootAgent({ harness: 'beta' }, { definition: 'assistant' }),
} };
const takes = fakeOrg('takes', { on: ['alpha', 'beta', 'gamma'] });
const spare = fakeOrg('spare', { on: ['alpha', 'beta', 'gamma'] });
const { admin } = programsFixture(t, [takes, spare], { rootAgents: () => root });
const out = await admin.programsOff({ name: 'alpha' });
assert.deepEqual(out.results, [{ id: 'takes', outcome: 'in-use' }, { id: 'spare', outcome: 'off' }]);
assert.equal(takes.calls.some(([verb]) => verb === 'plugins.set'), false);
// The root assistant is not copied into an organization, so its harness does not keep beta on.
const again = await admin.programsOff({ name: 'beta' });
assert.deepEqual(again.results.map(r => r.outcome), ['off', 'off']);
// The root file is read once per call, not once per organization.
let reads = 0;
const counted = programsFixture(t, [fakeOrg('a'), fakeOrg('b')], { rootAgents: () => { reads++; return NO_ROOT; } });
await counted.admin.programsOff({ name: 'alpha' });
assert.equal(reads, 1);
});
test('A2 item 5 (review P1-1): a root agent file that cannot be read, or no reader, writes nothing where the program is on', async t => {
const on = fakeOrg('on'), already = fakeOrg('already', { on: ['beta'] });
const { admin } = programsFixture(t, [on, already], { rootAgents: () => { throw Object.assign(new Error(`root agent file refused ${PLANT}`), { name: 'BusinessError' }); } });
const out = await admin.programsOff({ name: 'alpha' });
assert.deepEqual(out.results, [{ id: 'on', outcome: 'unreadable' }, { id: 'already', outcome: 'already-off' }]);
assert.doesNotMatch(JSON.stringify(out), KEY_TEXT);
const bare = fakeOrg('bare');
const none = fixture(t, { extra: { riders: async () => [bare.rider], harnesses: () => ['alpha', 'beta'] } });
assert.deepEqual((await none.admin.programsOff({ name: 'alpha' })).results, [{ id: 'bare', outcome: 'unreadable' }]);
for (const o of [on, already, bare]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
// A root answer of the wrong shape is unreadable too.
assert.equal(rootHarnessesNamed({ agents: { w: { vars: { harness: 'alpha' } } } }, 'acme'), null);
assert.equal(rootHarnessesNamed(null, 'acme'), null);
assert.deepEqual([...rootHarnessesNamed(NO_ROOT, 'acme')], []);
});
test('A2 item 5 (review P3-1): a revision that is not 64 hex, routes from another revision, and routes with no instances write nothing; later organizations still go', async t => {
const badRev = fakeOrg('bad-rev', { revision: 'not-a-revision' });
const routesMoved = fakeOrg('routes-moved', { routesRevision: REV2 });
const noInstances = fakeOrg('no-instances', { instances: null });
const after = fakeOrg('after');
const { admin, dataRoot } = programsFixture(t, [badRev, routesMoved, noInstances, after]);
const out = await admin.programsOff({ name: 'alpha' });
assert.deepEqual(out.results, [{ id: 'bad-rev', outcome: 'unreadable' }, { id: 'routes-moved', outcome: 'failed:revision-conflict' }, { id: 'no-instances', outcome: 'unreadable' }, { id: 'after', outcome: 'off' }]);
for (const o of [badRev, routesMoved, noInstances]) assert.equal(o.calls.some(([verb]) => verb === 'plugins.set'), false);
assert.equal(receipts(dataRoot).length, 1);
});
test('A2 item 5 (review P3-1): a harness program the instance plugin lock pins is listed as installed', t => {
const root = fs.mkdtempSync(join(tmpdir(), 'pl-'));
// The install leaves read-only directories; open them up before removing the tree.
const thaw = p => { const st = fs.lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { fs.chmodSync(p, 0o700); for (const n of fs.readdirSync(p)) thaw(join(p, n)); } };
t.after(() => { thaw(root); fs.rmSync(root, { recursive: true, force: true }); });
const src = join(root, 'src'), dataRoot = join(root, 'data');
fs.mkdirSync(join(src, 'harness'), { recursive: true }); fs.mkdirSync(dataRoot);
fs.writeFileSync(join(src, 'harness', 'index.mjs'), KINDS.harness.exports.map(name => `export function ${name}(){return ${name === 'levels' ? "['high']" : name === 'countsAccount' ? 'true' : 'null'};}`).join('\n') + '\nexport const interfaceVersion=1;');
const manifest = { name: 'zetaplug', version: '1.0.0', kinds: ['harness'], interfaceVersions: { harness: 1 }, sha256: '0'.repeat(64), source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
fs.writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
manifest.sha256 = pluginHash(src);
fs.writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
assert.equal(installedHarnesses(dataRoot).includes('zetaplug'), false);
installPlugin({ dataRoot, source: src, expectedHash: manifest.sha256 });
const listed = installedHarnesses(dataRoot);
assert.ok(listed.includes('zetaplug'));
assert.deepEqual(listed.filter(n => n !== 'zetaplug'), installedHarnesses());
});
test('A2 item 5 (review P3-3): an organization whose harness list holds anything but plugin names reads on: null', async t => {
const odd = fakeOrg('odd', { plugins: { harness: ['alpha', `bad ${PLANT}`] } });
const fine = fakeOrg('fine', { on: ['alpha'] });
const { admin } = programsFixture(t, [odd, fine]);
const status = await admin.status();
assert.deepEqual(status.programs.organizations, [{ id: 'odd', on: null }, { id: 'fine', on: ['alpha'] }]);
assert.doesNotMatch(JSON.stringify(status), KEY_TEXT);
});
test('A2: harnessesNamed reads every harness and fallback.harness string outside the plugins list', () => {
assert.deepEqual([...harnessesNamed({ plugins: { harness: ['alpha'] }, roles: { a: { vars: { harness: 'beta', 'fallback.harness': 'gamma' } } }, projects: { p: { agents: { x: { vars: { harness: 'delta' } } } } } })].sort(), ['beta', 'delta', 'gamma']);
assert.equal(harnessesNamed(null), null);
assert.equal(harnessesNamed([]), null);
});
const key = (keyId, management, state, agent = 'dev') => ({ keyId, management, agent, issuedAt: '2026-11-01T10:00:00.000Z', state });
test('A2 item 8: access gives each organization a health and key ids, never a key, and never reads the usage queue', async t => {
const ok = fakeOrg('ok', { keys: [key('0123456789ab', 'stack-managed', 'active'), key('ba9876543210', 'not stack-managed', null, null), key('aaaaaaaaaaaa', 'sentinel', null, null)] });
const attention = fakeOrg('attention', { keys: [key('0123456789ab', 'stack-managed', 'active'), key('bbbbbbbbbbbb', 'stack-managed', 'revoked')] });
const missing = fakeOrg('missing', { keys: [key('cccccccccccc', 'not stack-managed', null, null)] });
const fixtureOrg = fakeOrg('fixture', { fixture: true });
const ownModels = fakeOrg('own', { cliproxy: false });
const down = fakeOrg('down', { down: true });
const noClient = fakeOrg('no-client', { keysError: 'not-configured' });
const uncertain = fakeOrg('uncertain', { keysError: 'proxy-uncertain' });
const proxyDown = fakeOrg('proxy-down', { keysError: 'proxy-down' });
const badShape = fakeOrg('bad-shape', { keys: 'none' });
const planted = fakeOrg('planted', { keys: [key('dddddddddddd', 'stack-managed', PLANT, PLANT), { ...key('eeeeeeeeeeee', 'stack-managed', 'active'), value: PLANT, issuedAt: PLANT }] });
const plantedId = fakeOrg('planted-id', { keys: [key(PLANT, 'stack-managed', 'active')] });
const unread = fakeOrg('unread'); unread.rider.fixture = undefined;
const all = [ok, attention, missing, fixtureOrg, ownModels, down, noClient, uncertain, proxyDown, badShape, planted, plantedId, unread];
const { admin } = programsFixture(t, all);
const out = await admin.access();
assert.deepEqual(out.organizations, [
{ id: 'ok', health: 'ok', keys: [{ keyId: '0123456789ab', agent: 'dev', state: 'active', issuedAt: '2026-11-01T10:00:00.000Z' }], other: 1, sentinel: 1 },
{ id: 'attention', health: 'attention', keys: [{ keyId: '0123456789ab', agent: 'dev', state: 'active', issuedAt: '2026-11-01T10:00:00.000Z' }, { keyId: 'bbbbbbbbbbbb', agent: 'dev', state: 'revoked', issuedAt: '2026-11-01T10:00:00.000Z' }], other: 0, sentinel: 0 },
{ id: 'missing', health: 'missing', keys: [], other: 1, sentinel: 0 },
{ id: 'fixture', health: 'not-riding', keys: [] },
{ id: 'own', health: 'not-riding', keys: [] },
{ id: 'down', health: 'unreadable', reason: 'bus-down', keys: [] },
{ id: 'no-client', health: 'unreadable', reason: 'no-proxy-client', keys: [] },
{ id: 'uncertain', health: 'attention', reason: 'proxy-uncertain', keys: [] },
{ id: 'proxy-down', health: 'unreadable', reason: 'unreadable', keys: [] },
{ id: 'bad-shape', health: 'unreadable', reason: 'unreadable', keys: [] },
{ id: 'planted', health: 'attention', keys: [{ keyId: 'dddddddddddd', agent: null, state: null, issuedAt: '2026-11-01T10:00:00.000Z' }, { keyId: 'eeeeeeeeeeee', agent: 'dev', state: 'active', issuedAt: null }], other: 0, sentinel: 0 },
{ id: 'planted-id', health: 'unreadable', reason: 'unreadable', keys: [] },
{ id: 'unread', health: 'unreadable', reason: 'unreadable', keys: [] },
]);
assert.doesNotMatch(JSON.stringify(out), KEY_TEXT);
assert.notEqual(out.organizations.find(o => o.id === 'uncertain').health, 'ok');
// proxy.keys is the only verb access sends; the usage queue is never read.
for (const o of all) for (const [verb] of o.calls) assert.equal(verb, 'proxy.keys');
});