// #1873 CB1: a copy credential binding through the broker. Only the chief raises one; only the // organization owner resolves it; no autonomy level, member right, resolver agent, tester or reader // moves it. The written record stays pending, so nothing launches on it in CB1. import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Broker } from '../src/broker.mjs'; import { Store } from '../src/store.mjs'; import { REFUSALS } from '../src/refusals.mjs'; import { hireDecisions } from '../../organization/src/hire-decisions.mjs'; import { organizationWriter } from '../../organization/src/organization.mjs'; import { loadBusiness } from '../../organization/src/organization-config.mjs'; import { checkRootAgents } from '../../organization/src/agent-levels.mjs'; import { materializeCopies } from '../../organization/src/agent-copies.mjs'; import { activateOrg, reserveOrg } from '../../organization/src/org-registry.mjs'; import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs'; const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' }; const GITEA = { gitea: { scopes: ['read:repository'], projects: ['stack'] } }; const SECRET = 'sk-test-NOT-A-SECRET-1234'; async function fixture(t, edit = d => d) { const root = mkdtempSync(join(tmpdir(), 'cb1-bus-')), rolesDir = rolesCopy(root); const base = { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] }, vars: { 'bus.tester': true } }; base.projects.stack.agents = { checker: { definition: 'reviewer' } }; const doc = edit(base); const file = writeJson(join(root, 'businesses/demo.json'), doc); const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 }); const ctx = { configDir: root, dataRoot: storeRoot, instance: 'test' }; await reserveOrg(ctx, 'demo'); await activateOrg(ctx, 'demo'); const snapshot = materializeCopies({ orgId: 'demo', doc, root: { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: { rev: { definition: 'reviewer' } } }, { rolesDir }) }, rolesDir }); const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot); const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: v => { if (JSON.stringify(v).includes(SECRET)) throw Object.assign(new Error('x'), { code: 'definition-holds-credential' }); }, copies: id => snapshot.org === id ? snapshot : null }); const loaded = () => { const d = loadBusiness('demo', { dir: root, rolesDir }); return { ...d, roles: Object.fromEntries(Object.entries(d.roles).map(([n, e]) => [n, { ...d.definitions[e.definition], ...e }])) }; }; let writes = 0; const b = new Broker({ store, businesses: { demo: loaded() }, hires: { ...service, apply: async (...args) => { writes++; const r = await service.apply(...args); b.reloadBusiness('demo', loaded()); return r; } } }); const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT }); const member = (rights, extra = {}) => b.bindHireConsole({ business: 'demo', actor: 'member', subject: { ...SUBJECT, sub: 'member' }, rights, ...extra }); const caps = { chief: b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' }), coder: b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi' }) }; b.request(caps.chief, { verb: 'role.claim' }); b.request(caps.coder, { verb: 'role.claim' }); const call = (cap, verb, args = {}) => Promise.resolve().then(() => b.request(cap, { verb, args })); const bind = (extra = {}) => ({ op: 'change', level: 'root', name: 'rev', reason: 'Bind the reviewer copy', binding: { services: GITEA }, ...extra }); const raise = extra => call(caps.chief, 'hire.raise', bind(extra)); t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); }); const bindings = () => JSON.parse(readFileSync(file, 'utf8')).copyBindings ?? {}; return { root, rolesDir, file, b, store, writer, service, owner, member, caps, call, bind, raise, bindings, writes: () => writes, loaded }; } test('CB1 bus: only the chief raises a binding; the decision names the copy and holds no token or path', async t => { const f = await fixture(t); await assert.rejects(f.call(f.caps.coder, 'hire.raise', f.bind()), { code: 'role-not-chief' }); assert.equal(f.store.get('SELECT count(*) n FROM decisions').n, 0); const d = await f.raise(); assert.equal(d.route_to, 'human'); assert.equal(d.question, 'bind credentials for copy rev?'); assert.equal(d.hire.binding.instance, 'rev'); const text = JSON.stringify(d); for (const bad of [SECRET, f.root, 'token']) assert.ok(!text.includes(bad), bad); assert.equal(f.writes(), 0); assert.deepEqual(f.bindings(), {}); }); test('CB1 bus: no autonomy level routes a binding away from the owner', async t => { for (const authority of ['near the loop', 'out of the loop']) { const f = await fixture(t, doc => { doc.definitions = { resolver: { rev: 1, role: { tools: ['read'], network: 'none', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.authority'], crossRole: [] }, credentials: [] }, instructions: 'Resolve independent decisions.' } }; doc.roles.cto = { definition: 'org:resolver' }; doc.plugins['limit-check'] = ['token-limit']; doc.launch.limits = { tokens: { providers: { zai: { limit: 100000, since: '2026-01-01T00:00:00.000Z' } } } }; doc.autonomy = { authority, authorityResolver: 'cto', notices: true }; return doc; }); const live = f.loaded(); live.roles.cto.authority = { withinRole: ['decision.resolve.authority'], crossRole: [] }; f.b.reloadBusiness('demo', live); const resolver = f.b.bindLaunch({ business: 'demo', role: 'cto', run: 'cto-run', harness: 'pi' }); f.b.request(resolver, { verb: 'role.claim' }); const d = await f.raise(); assert.equal(d.route_to, 'human', authority); // The authority resolver cannot take it, nor can the chief through the agent verb. await assert.rejects(f.call(resolver, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'hire-resolution-required' }, authority); await assert.rejects(f.call(f.caps.chief, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'hire-resolution-required' }, authority); assert.equal(f.writes(), 0, authority); assert.deepEqual(f.bindings(), {}, authority); // A project-level unbind is not root; it lists the lines it removes and still goes to the owner. if (authority === 'near the loop') { await f.call(f.owner, 'hire.start.console', { op: 'change', level: 'project', project: 'stack', name: 'checker', reason: 'Bind', binding: { services: GITEA } }); const u = await f.raise({ level: 'project', project: 'stack', name: 'checker', binding: { services: null } }); assert.equal(u.hire.level, 'project'); assert.equal(u.route_to, 'human'); await assert.rejects(f.call(resolver, 'decision.resolve', { id: u.id, choice: 'yes' }), { code: 'hire-resolution-required' }); assert.equal(f.bindings()['checker.stack'].state, 'pending'); } } }); test('CB1 bus: members with org.hire or decide, the tester and a reader cannot resolve; the owner can, once', async t => { const f = await fixture(t); const d = await f.raise(); const digest = d.hire.digest; await assert.rejects(f.call(f.member(['org.hire']), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' }); await assert.rejects(f.call(f.member(['org.hire', 'decide'], { instanceOwner: true }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' }); await assert.rejects(f.call(f.member(['decide']), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'right-required' }); await assert.rejects(f.call(f.b.bindTester({ business: 'demo' }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' }); await assert.rejects(f.call(f.b.bindReader({ business: 'demo' }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' }); await assert.rejects(f.call(f.owner, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'human-required' }); assert.equal(f.writes(), 0); assert.deepEqual(f.bindings(), {}); await assert.rejects(f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest: '0'.repeat(64) }), { code: 'decision-stale' }); await f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest }); assert.equal(f.writes(), 1); const rec = f.bindings().rev; assert.equal(rec.state, 'pending'); assert.equal(rec.decision, d.id); await assert.rejects(f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'decision-closed' }); assert.equal(f.writes(), 1); }); test('CB1 bus: a one-step Console binding is owner-only; a member is refused before any decision is saved', async t => { const f = await fixture(t); await assert.rejects(f.call(f.member(['org.hire'], { instanceOwner: true }), 'hire.start.console', f.bind()), { code: 'human-required' }); assert.equal(f.store.get('SELECT count(*) n FROM decisions').n, 0); await f.call(f.owner, 'hire.start.console', f.bind()); assert.equal(f.bindings().rev.state, 'pending'); // Unbind is owner-only too. await assert.rejects(f.call(f.member(['org.hire']), 'hire.start.console', f.bind({ binding: { services: null } })), { code: 'human-required' }); await f.call(f.owner, 'hire.start.console', f.bind({ binding: { services: null } })); assert.equal(f.bindings().rev.state, 'unbound'); }); test('CB1 bus: every new refusal has a table entry with a next step', () => { for (const code of ['organization-bindings-protected', 'credential-binding-changed', 'credential-role-changed', 'credential-definition-unpinned', 'credential-scope-exceeded', 'credential-unbound', 'copy-unavailable', 'copy-refused']) { assert.ok(Object.hasOwn(REFUSALS, code), code); assert.ok(REFUSALS[code].nextStep?.length > 20, code); assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[code].nextStep), code); } });