Compare commits

...
15 changed files with 260 additions and 37 deletions

No files matched your search

+49
View File
@@ -319,3 +319,52 @@ CREATE TRIGGER message_threads_no_replace BEFORE INSERT ON message_threads WHEN
CREATE TRIGGER thread_opens_no_update BEFORE UPDATE ON thread_opens BEGIN SELECT RAISE(ABORT, 'thread_opens is append-only'); END;
CREATE TRIGGER thread_opens_no_delete BEFORE DELETE ON thread_opens BEGIN SELECT RAISE(ABORT, 'thread_opens is append-only'); END;
CREATE TRIGGER thread_opens_no_replace BEFORE INSERT ON thread_opens WHEN EXISTS (SELECT 1 FROM thread_opens WHERE seq = NEW.seq) BEGIN SELECT RAISE(ABORT, 'thread_opens is append-only'); END;
-- Row 138 (#1632): immutable proposals and human confirmations, with exact decision citations.
CREATE TABLE specs (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
business TEXT NOT NULL,
spec_id TEXT NOT NULL,
need TEXT NOT NULL,
version INTEGER NOT NULL CHECK (version > 0),
text TEXT NOT NULL CHECK (length(text) BETWEEN 1 AND 32768),
proposed_by_role TEXT NOT NULL,
proposed_by_run TEXT NOT NULL,
UNIQUE (business, spec_id, version)
) STRICT;
CREATE TABLE spec_confirmations (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
business TEXT NOT NULL,
spec_id TEXT NOT NULL,
spec_version INTEGER NOT NULL,
confirmed_by TEXT NOT NULL,
UNIQUE (business, spec_id, spec_version),
FOREIGN KEY (business, spec_id, spec_version) REFERENCES specs(business, spec_id, version)
) STRICT;
ALTER TABLE decisions ADD COLUMN spec_id TEXT;
ALTER TABLE decisions ADD COLUMN spec_version INTEGER;
CREATE TRIGGER specs_identity BEFORE INSERT ON specs
WHEN EXISTS (SELECT 1 FROM specs s WHERE s.business = NEW.business
AND ((s.spec_id = NEW.spec_id AND s.need <> NEW.need) OR (s.need = NEW.need AND s.spec_id <> NEW.spec_id)))
BEGIN SELECT RAISE(ABORT, 'spec need and id are immutable'); END;
CREATE TRIGGER specs_version BEFORE INSERT ON specs
WHEN NEW.version <> COALESCE((SELECT max(version) FROM specs WHERE business = NEW.business AND spec_id = NEW.spec_id), 0) + 1
BEGIN SELECT RAISE(ABORT, 'spec versions advance by one'); END;
CREATE TRIGGER spec_confirmations_forward BEFORE INSERT ON spec_confirmations
WHEN NEW.spec_version <= COALESCE((SELECT max(spec_version) FROM spec_confirmations
WHERE business = NEW.business AND spec_id = NEW.spec_id), 0)
BEGIN SELECT RAISE(ABORT, 'spec confirmation must advance'); END;
CREATE TRIGGER decisions_spec BEFORE INSERT ON decisions
WHEN (NEW.spec_id IS NULL) <> (NEW.spec_version IS NULL)
OR (NEW.spec_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM spec_confirmations c
WHERE c.business = NEW.business AND c.spec_id = NEW.spec_id AND c.spec_version = NEW.spec_version
AND c.spec_version = (SELECT max(spec_version) FROM spec_confirmations
WHERE business = NEW.business AND spec_id = NEW.spec_id)))
BEGIN SELECT RAISE(ABORT, 'decision needs current confirmed spec'); END;
CREATE TRIGGER specs_no_update BEFORE UPDATE ON specs BEGIN SELECT RAISE(ABORT, 'specs is append-only'); END;
CREATE TRIGGER specs_no_delete BEFORE DELETE ON specs BEGIN SELECT RAISE(ABORT, 'specs is append-only'); END;
CREATE TRIGGER specs_no_replace BEFORE INSERT ON specs WHEN EXISTS (SELECT 1 FROM specs WHERE seq = NEW.seq OR (business = NEW.business AND spec_id = NEW.spec_id AND version = NEW.version)) BEGIN SELECT RAISE(ABORT, 'specs is append-only'); END;
CREATE TRIGGER spec_confirmations_no_update BEFORE UPDATE ON spec_confirmations BEGIN SELECT RAISE(ABORT, 'spec_confirmations is append-only'); END;
CREATE TRIGGER spec_confirmations_no_delete BEFORE DELETE ON spec_confirmations BEGIN SELECT RAISE(ABORT, 'spec_confirmations is append-only'); END;
CREATE TRIGGER spec_confirmations_no_replace BEFORE INSERT ON spec_confirmations WHEN EXISTS (SELECT 1 FROM spec_confirmations WHERE seq = NEW.seq OR (business = NEW.business AND spec_id = NEW.spec_id AND spec_version = NEW.spec_version)) BEGIN SELECT RAISE(ABORT, 'spec_confirmations is append-only'); END;
+83 -1
View File
@@ -22,6 +22,7 @@ export const ACTIONS = Object.freeze([
'role.revoke',
'role.end',
'organization.change',
'spec.propose',
'credential.mint',
'spend',
'deploy',
@@ -475,6 +476,24 @@ export class Broker {
#sender(s) {
return s.human ? 'human' : s.tester ? 'tester' : s.role;
}
// Row 138: exact proposal versions are immutable; confirmation is separate human evidence.
#spec(s, specId, version = null) {
const exists = this.#store.get('SELECT 1 FROM specs WHERE business=? AND spec_id=?', s.business, specId);
if (!exists) fail('spec-not-found');
const row = version === null
? this.#store.get(
`SELECT p.*, c.at AS confirmed_at, c.confirmed_by FROM specs p
JOIN spec_confirmations c ON c.business=p.business AND c.spec_id=p.spec_id AND c.spec_version=p.version
WHERE p.business=? AND p.spec_id=? ORDER BY p.version DESC LIMIT 1`, s.business, specId,
)
: this.#store.get(
`SELECT p.*, c.at AS confirmed_at, c.confirmed_by FROM specs p
LEFT JOIN spec_confirmations c ON c.business=p.business AND c.spec_id=p.spec_id AND c.spec_version=p.version
WHERE p.business=? AND p.spec_id=? AND p.version=?`, s.business, specId, version,
);
if (!row) fail(version === null ? 'spec-unconfirmed' : 'spec-version-not-found');
return row;
}
#decision(s, id) {
const d = this.#store.get('SELECT * FROM decisions WHERE id=? AND business=?', id, s.business);
if (!d) fail('decision-not-found');
@@ -991,6 +1010,58 @@ export class Broker {
this.#claimEnd(s, h, 'revoke', a.decision ?? null, a.reason ?? null);
return { revoked: true };
}
case 'spec': {
keys(a, ['spec_id', 'version'], ['spec_id']);
identifier(a.spec_id);
if (a.version !== undefined) {
this.#human(s);
if (!Number.isSafeInteger(a.version) || a.version < 1) fail('invalid-request');
} else if (s.human) this.#human(s);
else this.#agent(s);
return this.#spec(s, a.spec_id, a.version ?? null);
}
case 'spec.propose': {
keys(a, ['spec_id', 'need', 'text'], ['spec_id', 'need', 'text']);
this.#agent(s);
if (b.roles[s.role]?.definition !== 'assistant') fail('assistant-required');
if (this.#classification(s, 'spec.propose') !== 'within-role') fail('spec-proposal-refused');
identifier(a.spec_id);
string(a.need, 1024);
string(a.text, 32768);
if (this.#store.get(
`SELECT 1 FROM specs WHERE business=? AND
((spec_id=? AND need<>?) OR (need=? AND spec_id<>?))`,
s.business, a.spec_id, a.need, a.need, a.spec_id,
)) fail('spec-need-conflict');
const version = this.#store.get(
'SELECT COALESCE(max(version),0)+1 AS version FROM specs WHERE business=? AND spec_id=?',
s.business, a.spec_id,
).version;
this.#consumeAuthority(s, 'spec.propose', {}, { operation: 'spec.propose', spec_id: a.spec_id, version });
this.#store.run(
`INSERT INTO specs(at,business,spec_id,need,version,text,proposed_by_role,proposed_by_run)
VALUES(?,?,?,?,?,?,?,?)`, this.#now(), s.business, a.spec_id, a.need, version, a.text, s.role, s.run,
);
return this.#spec(s, a.spec_id, version);
}
case 'spec.confirm': {
keys(a, ['spec_id', 'version'], ['spec_id', 'version']);
this.#human(s);
identifier(a.spec_id);
if (!Number.isSafeInteger(a.version) || a.version < 1) fail('invalid-request');
this.#spec(s, a.spec_id, a.version);
const current = this.#store.get(
'SELECT max(spec_version) AS version FROM spec_confirmations WHERE business=? AND spec_id=?',
s.business, a.spec_id,
).version;
if (current !== null && a.version <= current) fail('spec-confirmation-stale');
this.#store.run(
'INSERT INTO spec_confirmations(at,business,spec_id,spec_version,confirmed_by) VALUES(?,?,?,?,?)',
this.#now(), s.business, a.spec_id, a.version, s.human,
);
this.#event(s, 'action.allowed', { operation: 'spec.confirm', spec_id: a.spec_id, version: a.version });
return this.#spec(s, a.spec_id);
}
case 'decision.raise': {
keys(
a,
@@ -1008,11 +1079,20 @@ export class Broker {
'supersedes',
'choice',
'approvalChoice',
'spec_id',
'spec_version',
],
['action', 'question', 'options', 'recommendation', 'blocking'],
);
this.#agent(s);
const cls = this.#classification(s, a.action);
if ((a.spec_id !== undefined) !== (a.spec_version !== undefined)) fail('invalid-request');
if (a.spec_id !== undefined) {
identifier(a.spec_id);
if (!Number.isSafeInteger(a.spec_version) || a.spec_version < 1) fail('invalid-request');
const spec = this.#spec(s, a.spec_id);
if (spec.version !== a.spec_version) fail('spec-version-stale');
}
string(a.question);
if (typeof a.blocking !== 'boolean') fail('invalid-request');
if (a.blocking && !a.task_ref) fail('task-required');
@@ -1052,7 +1132,7 @@ export class Broker {
}
const did = randomUUID();
this.#store.run(
'INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,task_ref,requirement_ref,blocking,supersedes) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
'INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,task_ref,requirement_ref,blocking,supersedes,spec_id,spec_version) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
did,
this.#now(),
s.business,
@@ -1069,6 +1149,8 @@ export class Broker {
a.requirement_ref ?? null,
Number(a.blocking),
a.supersedes ?? null,
a.spec_id ?? null,
a.spec_version ?? null,
);
this.#event(
s,
+8 -2
View File
@@ -13,8 +13,8 @@ import { join, isAbsolute } from 'node:path';
import { createHash } from 'node:crypto';
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
export const SCHEMA_SHA256 = '21e6c091f14f818396f4d7836f381cc1389d45b2680ecaa1a00646b652c45050';
export const SCHEMA_VERSION = '3e';
export const SCHEMA_SHA256 = '348304fd160dba7227531b7ce22fbb44afd0fe68f1985476ba74b29940951c87';
export const SCHEMA_VERSION = '3f';
// Ordered, named offline steps. New schema changes append a step and keep prior DDL pinned.
const legacyDDL = readFileSync(new URL('./migrations/3b.sql', import.meta.url), 'utf8');
const LEGACY_SHA256 = '179ffe356d4ff19a49b5ebad39b6c6bfd7771deb8e1b7c55b5e746f039d69e65';
@@ -38,6 +38,10 @@ const migrations = [{
report: (store) => store.all(
"SELECT business, to_role, count(*) AS n FROM messages m WHERE NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op IN ('delivered','read')) GROUP BY business, to_role ORDER BY business, to_role",
).map((r) => `kept ${r.n} undelivered message(s) for ${r.business}/${r.to_role} without a thread; if that role is a thread instance, its thread runs never receive them, so the human re-sends them with thread.send`),
}, {
from: '3e',
to: '3f',
sql: readFileSync(new URL('./migrations/3e-3f.sql', import.meta.url), 'utf8'),
}];
const timedTables = [
'events',
@@ -51,6 +55,8 @@ const timedTables = [
'threads',
'thread_claims',
'thread_opens',
'specs',
'spec_confirmations',
];
const hex = (value) => createHash('sha256').update(value).digest('hex');
if (hex(ddl) !== SCHEMA_SHA256) throw Error('schema-source-mismatch');
+3 -3
View File
@@ -6,7 +6,7 @@ import { join } from 'node:path';
import { createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { Store, schemaDigest } from '../src/store.mjs';
import { Store, schemaDigest, SCHEMA_VERSION } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
import { startBroker } from '../src/runtime.mjs';
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../business/tests/helpers.mjs';
@@ -367,7 +367,7 @@ async function database3c(t) {
let source = readFileSync(here('../src/store.mjs'), 'utf8');
const pinned = source
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3c).digest('hex')}';`)
.replace("export const SCHEMA_VERSION = '3e';", "export const SCHEMA_VERSION = '3c';")
.replace(/export const SCHEMA_VERSION = '[^']+';/, "export const SCHEMA_VERSION = '3c';")
.replace(/\}, \{\n {2}from: '3c',[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
assert.notEqual(pinned, source);
assert.ok(!pinned.includes('3c-3d'), 'the 3c engine has no 3c→3d step');
@@ -391,7 +391,7 @@ test('REQ-ROLE-2, REQ-COS-1: the 3c→3d migration lets the chief of staff end a
assert.throws(() => new Store(root), /schema-mismatch/);
const store = new Store(root, { migrateSchema: true });
t.after(() => store.close());
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3e');
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, SCHEMA_VERSION);
assert.equal(store.get("SELECT body FROM events WHERE id='preserved'").body, '{"fixture":true}');
assert.equal(store.get("SELECT holder_run FROM role_claims WHERE role='coder'").holder_run, 'coder-run');
const b = new Broker({ store, businesses: demo(), organization: null });
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { createHash } from 'node:crypto';
import { Store, schemaDigest } from '../src/store.mjs';
import { Store, schemaDigest, SCHEMA_VERSION } from '../src/store.mjs';
function legacy(t) {
const root = mkdtempSync(join(tmpdir(), 'comment-migration-'));
@@ -33,7 +33,7 @@ test('explicit 3b copy migration preserves evidence and opens as 3e; normal star
const original = readFileSync(source);
assert.throws(() => new Store(root), /schema-mismatch/);
const store = new Store(root, { migrateSchema: true });
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3e');
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, SCHEMA_VERSION);
assert.equal(store.get("SELECT body FROM events WHERE id='preserved'").body, '{"fixture":true}');
assert.equal(store.get('SELECT count(*) n FROM task_comment_cursors').n, 0);
const epoch = store.get("SELECT value FROM meta WHERE key='comment_cursor_epoch'").value;
@@ -62,7 +62,7 @@ test('migration refuses active writers and drifted legacy schemas, with no parti
assert.throws(() => new Store(other.root, { migrateSchema: true }), /writer-locked/);
});
test('named migration registry chains 3b through 3e to a fixture-only future version in order', async t => {
test('named migration registry chains 3b through 3f to a fixture-only future version in order', async t => {
const { root } = legacy(t);
const { writeFileSync } = await import('node:fs');
const { pathToFileURL } = await import('node:url');
@@ -75,15 +75,15 @@ test('named migration registry chains 3b through 3e to a fixture-only future ver
const sha = createHash('sha256').update(futureDDL).digest('hex');
let source = readFileSync(new URL('../src/store.mjs', import.meta.url), 'utf8');
source = source.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${sha}';`)
.replace("export const SCHEMA_VERSION = '3e';", "export const SCHEMA_VERSION = '3f';")
.replace('}];\nconst timedTables', `}, { from: '3e', to: '3f', sql: ${JSON.stringify(futureSQL)} }];\nconst timedTables`);
.replace("export const SCHEMA_VERSION = '3f';", "export const SCHEMA_VERSION = '3g';")
.replace('}];\nconst timedTables', `}, { from: '3f', to: '3g', sql: ${JSON.stringify(futureSQL)} }];\nconst timedTables`);
writeFileSync(join(moduleRoot, 'src/store.mjs'), source);
writeFileSync(join(moduleRoot, 'schema.sql'), futureDDL);
for (const name of ['3b.sql', '3b-3c.sql', '3c-3d.sql', '3d-3e.sql'])
for (const name of ['3b.sql', '3b-3c.sql', '3c-3d.sql', '3d-3e.sql', '3e-3f.sql'])
copyFileSync(new URL('../src/migrations/' + name, import.meta.url), join(moduleRoot, 'src/migrations', name));
const { Store: FutureStore } = await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')));
const future = new FutureStore(root, { migrateSchema: true });
assert.equal(future.get("SELECT value FROM meta WHERE key='schema_version'").value, '3f');
assert.equal(future.get("SELECT value FROM meta WHERE key='schema_version'").value, '3g');
assert.equal(future.get("SELECT name FROM sqlite_master WHERE name='future_fixture'").name, 'future_fixture');
assert.equal(future.get("SELECT count(*) n FROM task_comment_cursors").n, 0);
assert.equal(future.get("SELECT id FROM events").id, 'preserved');
@@ -109,7 +109,7 @@ test('offline command migrates only the supplied fixture root and reports usage
const command = new URL('../src/migrate-schema.mjs', import.meta.url).pathname;
const migrated = spawnSync(process.execPath, [command, root], { encoding: 'utf8' });
assert.equal(migrated.status, 0, migrated.stderr);
assert.match(migrated.stdout, /bus schema 3e ready/);
assert.match(migrated.stdout, new RegExp(`bus schema ${SCHEMA_VERSION} ready`));
new Store(root).close();
const usage = spawnSync(process.execPath, [command], { encoding: 'utf8' });
assert.equal(usage.status, 2);
+2 -2
View File
@@ -517,7 +517,7 @@ test('v3b prototype refusals, views and append-only mutations', (t) => {
const count = (type) => db.prepare('SELECT count(*) n FROM sqlite_master WHERE type = ?').get(type).n;
for (const label of refused) assert.ok(tested.has(label), label);
// Row 121 (#1615) adds 5 tables and 24 triggers for projects and threads; threads.test.mjs tests them.
assert.equal(count('table') - 1, 14);
assert.equal(count('trigger'), 63);
assert.equal(count('table') - 1, 16);
assert.equal(count('trigger'), 73);
assert.equal(count('view'), 5);
});
+4 -4
View File
@@ -7,7 +7,7 @@ import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { DatabaseSync } from 'node:sqlite';
import { pathToFileURL } from 'node:url';
import { Store, schemaDigest } from '../src/store.mjs';
import { Store, schemaDigest, SCHEMA_VERSION } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
const here = (path) => new URL(path, import.meta.url);
@@ -49,7 +49,7 @@ async function database3d(t) {
const source = readFileSync(here('../src/store.mjs'), 'utf8');
const pinned = source
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3d).digest('hex')}';`)
.replace("export const SCHEMA_VERSION = '3e';", "export const SCHEMA_VERSION = '3d';")
.replace(/export const SCHEMA_VERSION = '[^']+';/, "export const SCHEMA_VERSION = '3d';")
.replace(/\}, \{\n {2}from: '3d',[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
assert.ok(!pinned.includes('3d-3e'), 'the 3d engine has no 3d→3e step');
writeFileSync(join(moduleRoot, 'src/store.mjs'), pinned);
@@ -95,7 +95,7 @@ test('REQ-THREAD-1 REQ-ORG-2: the 3d→3e migration adds the thread tables and l
assert.throws(() => new Store(root), /schema-mismatch/);
const store = new Store(root, { migrateSchema: true });
t.after(() => store.close());
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3e');
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, SCHEMA_VERSION);
for (const table of ['projects', 'threads', 'thread_claims', 'message_threads', 'thread_opens'])
assert.equal(store.get(`SELECT count(*) n FROM ${table}`).n, 0, table);
// Parked: the undelivered ones are counted per business and role, and none is changed or given a thread.
@@ -155,5 +155,5 @@ test('REQ-THREAD-1: the offline command prints the kept-message counts before th
const command = new URL('../src/migrate-schema.mjs', import.meta.url).pathname;
const migrated = spawnSync(process.execPath, [command, root], { encoding: 'utf8' });
assert.equal(migrated.status, 0, migrated.stderr);
assert.equal(migrated.stdout, [...REPORT, 'bus schema 3e ready', ''].join('\n'));
assert.equal(migrated.stdout, [...REPORT, `bus schema ${SCHEMA_VERSION} ready`, ''].join('\n'));
});
+1
View File
@@ -31,6 +31,7 @@ export const ACTIONS = Object.freeze([
// so the grant lives in a role file; role.revoke itself stays gated for every role.
"role.end",
"organization.change",
"spec.propose",
"credential.mint",
"spend",
"deploy",
+5 -5
View File
@@ -12,7 +12,7 @@ import { businessDoc, REPO_ROLES, systemFor, tmp, writeJson } from "./helpers.mj
const APPROVED = Object.freeze({
tools: ["read", "grep", "find", "ls"],
network: "api-only",
authority: Object.freeze({ withinRole: Object.freeze(["message.send"]), crossRole: Object.freeze([]) }),
authority: Object.freeze({ withinRole: Object.freeze(["message.send", "spec.propose"]), crossRole: Object.freeze([]) }),
credentials: Object.freeze([]),
// REQ-ASSIST-2: the user and the chief of staff, both ways. The broker enforces these lists (row 120).
messaging: Object.freeze({
@@ -67,15 +67,15 @@ test("the shipped file is exactly the approved list", () => {
assert.deepEqual(rest, { roleVersion: 2, name: "assistant", contract: "assistant.md", ...APPROVED });
});
test("the assistant's authority is message.send within role and nothing else", () => {
test("the assistant holds only message.send and spec.propose within role", () => {
const role = loadRole(REPO_ROLES, "assistant");
assert.deepEqual(role.authority, { withinRole: ["message.send"], crossRole: [] });
assert.deepEqual(role.authority, { withinRole: ["message.send", "spec.propose"], crossRole: [] });
assert.deepEqual(role.credentials, []);
const record = resolved(loadFixture());
assert.deepEqual(record.limits.authority, { withinRole: ["message.send"], crossRole: [] });
assert.deepEqual(record.limits.authority, { withinRole: ["message.send", "spec.propose"], crossRole: [] });
assert.deepEqual(record.credentials, {});
for (const action of ACTIONS) {
assert.equal(classify(record, action), action === "message.send" ? "within" : "gated", action);
assert.equal(classify(record, action), ["message.send", "spec.propose"].includes(action) ? "within" : "gated", action);
}
for (const action of ["task.create", "task.assign", "role.launch"]) assert.equal(classify(record, action), "gated", action);
});
+36
View File
@@ -26,6 +26,8 @@ import { SeatError } from "../../seat/src/seat.mjs";
export const USAGE = `usage:
${LIMITS_USAGE}
mosaic spec <id> [--json] [--business <id>]
mosaic spec confirm <id> <version> [--yes] [--business <id>]
mosaic inbox [--business <id>] [--json] [--tester]
mosaic decide <decision> <option> [--note <text>] [--yes] [--business <id>]
mosaic tasks [--business <id>] [--json] [--tester]
@@ -169,6 +171,39 @@ function callFor(parsed, io, deps) {
return deps.transport ? deps.transport(business) : humanTransport({ socket: socketPath(system.dataRoot), business, env: io.env });
}
// Human spec confirmation reviews one immutable version through the same outside-run transport.
async function specCommand(rest, io, deps) {
const parsed = parse(rest, { flags: ['--json', '--yes'], values: ['--business'] });
const confirmVersion = parsed.positional[0] === 'confirm';
const [spec_id, rawVersion] = confirmVersion ? parsed.positional.slice(1) : parsed.positional;
if (confirmVersion) {
if (parsed.positional.length !== 3 || parsed.flags.has('--json') || !/^[1-9][0-9]*$/.test(rawVersion))
throw usage('spec confirm takes an id and a positive version');
} else if (parsed.positional.length !== 1 || parsed.flags.has('--yes')) {
throw usage('spec takes one id');
}
const version = Number(rawVersion);
if (confirmVersion && !Number.isSafeInteger(version)) throw usage('invalid spec version');
if (confirmVersion && !parsed.flags.has('--yes') && !io.stdin.isTTY)
throw usage('stdin is not a terminal; pass --yes to confirm this version');
const call = callFor(parsed, io, deps);
const proposal = await call('spec', { spec_id, ...(confirmVersion ? { version } : {}) });
// JSON escapes terminal controls and preserves every character of the proposed text.
io.stdout.write(JSON.stringify(proposal, null, 2) + '\n');
if (!confirmVersion) return proposal;
if (!parsed.flags.has('--yes') && !(await confirm(io, `confirm spec ${spec_id} version ${version}? [y/N] `)))
throw new CliError('not confirmed', 1);
try {
const result = await call('spec.confirm', { spec_id, version });
io.stdout.write(`confirmed ${spec_id} version ${version}\n`);
return result;
} catch (e) {
if (e.code === 'outcome-unknown')
throw new CliError('outcome unknown: re-read mosaic spec before attempting another confirmation', 1);
throw e;
}
}
async function human(verb, rest, io, deps) {
const spec = verb === "decide" ? { flags: ["--yes"], values: ["--business", "--note"] } : { flags: ["--json", "--tester"], values: ["--business"] };
const parsed = parse(rest, spec);
@@ -381,6 +416,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 === "spec") return specCommand(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);
+12
View File
@@ -151,6 +151,16 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
instances: { type: "object", description: "Role instance to model key, for the instances that change", additionalProperties: { type: "string" } },
}, ["revision"]));
}
if (held.has("spec.propose")) {
add("propose_spec", "spec.propose", "spec.propose", "Propose a north-star version. It takes effect only after the human confirms it through the outside-run CLI.", obj({
spec_id: str("Stable spec id for this need"),
need: str("The need this spec addresses"),
text: str("Complete proposed north-star text", { maxLength: 32768 }),
}, ["spec_id", "need", "text"]));
}
add("read_spec", "spec", null, "Read the current human-confirmed north-star spec for this business.", obj({
spec_id: str("Spec id"),
}, ["spec_id"]));
add("raise_decision", "decision.raise", null, "Ask for a decision before a gated or cross-role action, or when you need a choice made. The answer arrives as a message.", obj({
action: str("The action the decision is about", { enum: [...ACTIONS] }),
question: str("The question, with enough context to answer it and the reason for your recommendation"),
@@ -161,6 +171,8 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
approvalChoice: str("The option key that approves the action. It defaults to yes, so pass it whenever no option key is yes"),
task_ref: TASK_REF,
requirement_ref: str("Requirement id"),
spec_id: str("Current confirmed spec covering this decision; pair with spec_version"),
spec_version: { type: "integer", minimum: 1, description: "Exact current confirmed spec version" },
}, ["action", "question", "options", "recommendation", "blocking"]));
if (arbiter) {
add("resolve_decision", "decision.resolve", null, "Resolve a decision routed to you.", obj({
+34 -9
View File
@@ -13,7 +13,7 @@ test("the PM gets its task verbs and the reads, and no launch", (t) => {
"send_message",
"task_create", "task_assign", "task_reassign", "task_schedule", "task_priority_change", "task_scope_change",
"task_update_assigned", "task_close",
"raise_decision", "resolve_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task", "list_requirements",
"read_spec", "raise_decision", "resolve_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task", "list_requirements",
]);
// Row 119 (#1613): only the chief of staff launches (REQ-COS-1).
assert.equal(pm.launch, null);
@@ -33,7 +33,7 @@ test("the PM gets its task verbs and the reads, and no launch", (t) => {
test("the chief of staff gets launch, send_message, end_run and change_organization, and no task verbs", (t) => {
const chief = resolvedFor(t, "chief");
const tools = typedTools({ resolved: chief, tracker: true });
assert.deepEqual(names(tools), ["send_message", "launch", "end_run", "change_organization", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
assert.deepEqual(names(tools), ["send_message", "launch", "end_run", "change_organization", "read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
const launch = tools.find((x) => x.name === "launch");
assert.equal(launch.verb, "launch");
assert.equal(launch.action, "role.launch");
@@ -78,11 +78,11 @@ test("a role without role.end or organization.change gets neither tool, and each
assert.deepEqual(names(typedTools({ resolved: only("organization.change") })).filter((n) => n === "end_run" || n === "change_organization"), ["change_organization"]);
});
// Row 119 (#1613): the assistant holds message.send alone.
// Row 138: the assistant also holds spec.propose; other authority stays gated.
test("the assistant gets send_message and the reads, no launch", (t) => {
const assistant = resolvedFor(t, "assistant", (d) => (d.roles.assistant = { definition: "assistant", holder: "mos" }));
const tools = typedTools({ resolved: assistant, tracker: true });
assert.deepEqual(names(tools), ["send_message", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
assert.deepEqual(names(tools), ["send_message", "propose_spec", "read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
assert.equal(assistant.launch, null);
assert.deepEqual(untypedActions(assistant, tools), []);
});
@@ -116,7 +116,7 @@ test("list_requirements reads the requirement ids, for a task.create holder with
test("a coder gets no launch, no resolve_decision, and no task tools without a tracker", (t) => {
const coder = resolvedFor(t, "coder");
const tools = typedTools({ resolved: coder });
assert.deepEqual(names(tools), ["send_message", "request_review", "raise_decision", "list_agents", "inbox", "trail"]);
assert.deepEqual(names(tools), ["send_message", "request_review", "read_spec", "raise_decision", "list_agents", "inbox", "trail"]);
// Held actions without a tool are listed, so the manifest shows them. With
// no clone to push from, push_working is one of them.
assert.deepEqual(untypedActions(coder, tools), ["task.update.assigned", "git.push.working", "task.scope.change"]);
@@ -126,7 +126,7 @@ test("a coder with a tracker gets its own task tools and no task_reassign", (t)
const coder = resolvedFor(t, "coder");
assert.deepEqual(names(typedTools({ resolved: coder, tracker: true })), [
"send_message", "task_scope_change", "task_update_assigned", "request_review",
"raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task",
"read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task",
]);
});
@@ -139,7 +139,7 @@ test("launch only when the business's launch block names the instance as launche
test("an action outside the instance's authority has no tool", (t) => {
const coder = resolvedFor(t, "coder", (d) => (d.roles.coder.vars["limits.authority"] = ["review.request"]));
assert.deepEqual(names(typedTools({ resolved: coder, tracker: true, projects: ["stack"] })), ["request_review", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
assert.deepEqual(names(typedTools({ resolved: coder, tracker: true, projects: ["stack"] })), ["request_review", "read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
});
// Row 93 (#1587): the review loop's tools, by authority, and the git ones only with a clone.
@@ -148,7 +148,7 @@ test("the review loop: push_working and request_review for the coder, fetch_revi
const tools = typedTools({ resolved: coder, tracker: true, projects: ["stack", "site"] });
assert.deepEqual(names(tools), [
"send_message", "task_scope_change", "task_update_assigned", "push_working", "request_review",
"raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task",
"read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task",
]);
assert.deepEqual(untypedActions(coder, tools), []);
const push = tools.find((x) => x.name === "push_working");
@@ -165,7 +165,7 @@ test("the review loop: push_working and request_review for the coder, fetch_revi
const reviewer = resolvedFor(t, "reviewer");
const rtools = typedTools({ resolved: reviewer, tracker: true, projects: ["stack"] });
assert.deepEqual(names(rtools), ["send_message", "task_update_assigned", "fetch_review", "review_verdict", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
assert.deepEqual(names(rtools), ["send_message", "task_update_assigned", "fetch_review", "review_verdict", "read_spec", "raise_decision", "list_agents", "inbox", "trail", "list_tasks", "get_task"]);
const fetch = rtools.find((x) => x.name === "fetch_review");
assert.deepEqual([fetch.verb, fetch.action], ["working.fetch", null]);
assert.deepEqual(fetch.parameters.required, ["task_ref", "request"]);
@@ -245,3 +245,28 @@ test("replyText: compact JSON up to the cap, an error naming the size and the ca
// 40000 units fit, though they are 79998 bytes: the cap isn't a byte count.
assert.equal(replyText("\u{1F600}".repeat(REPLY_CAP / 2 - 1)).length, REPLY_CAP);
});
test('spec proposal is grant-bound, spec read is universal and raises accept exact spec citations', t => {
const assistant = resolvedFor(t, 'assistant', d => { d.roles.assistant = { definition: "assistant", holder: "mos" }; });
const tools = typedTools({ resolved: assistant });
const proposal = tools.find(tool => tool.name === 'propose_spec');
assert.ok(proposal);
assert.equal(proposal.verb, 'spec.propose');
assert.equal(proposal.action, 'spec.propose');
assert.deepEqual(proposal.parameters.required, ['spec_id', 'need', 'text']);
const noGrant = { ...assistant, limits: { ...assistant.limits, authority: { withinRole: ['message.send'], crossRole: [] } } };
assert.ok(!typedTools({ resolved: noGrant }).some(tool => tool.name === 'propose_spec'));
for (const instance of ['assistant', 'pm', 'cto', 'coder', 'reviewer', 'chief']) {
const resolved = resolvedFor(t, instance, d => { d.roles.assistant = { definition: "assistant", holder: "mos" }; });
const list = typedTools({ resolved });
assert.equal(list.find(tool => tool.name === 'read_spec').verb, 'spec');
const raise = list.find(tool => tool.name === 'raise_decision').parameters;
assert.equal(raise.properties.spec_id.type, 'string');
assert.equal(raise.properties.spec_version.type, 'integer');
assert.equal(raise.properties.spec_version.minimum, 1);
assert.equal(raise.additionalProperties, false);
assert.ok(!raise.required.includes('spec_id'));
if (instance !== 'assistant') assert.ok(!list.some(tool => tool.name === 'propose_spec'));
}
assert.deepEqual(untypedActions(assistant, tools), []);
});
+1 -1
View File
@@ -6,7 +6,7 @@
"tools": ["read", "grep", "find", "ls"],
"network": "api-only",
"authority": {
"withinRole": ["message.send"],
"withinRole": ["message.send", "spec.propose"],
"crossRole": []
},
"credentials": [],
+13 -1
View File
@@ -21,7 +21,8 @@ sessions.
## Authority
Your role file lists what you do on your own: sending messages. Anything
Your role file lists what you do on your own: sending messages and proposing
north-star spec versions with `propose_spec`. Anything
the list doesn't name is gated. That includes creating or assigning
tasks, directing another role, launching a role session, pushing to a
repository, sending messages outside the business, minting credentials,
@@ -43,3 +44,14 @@ stop, say so to the user. Don't stop it yourself.
a token or a credential.
- Send messages through the bus, addressed to a role, not a person.
- Report a blocker as soon as you find it, with what you tried.
## North-star specs
Keep a north-star spec for each need with the human. Use `propose_spec` to propose
text with a stable spec_id and need. A proposal grants no permission and takes
no effect until the human confirms its exact version from an outside-run CLI
session (`mosaic spec confirm`). You cannot confirm, approve in their name or
change an earlier proposal. Use `read_spec` for the current confirmed version.
When raising a decision covered by a spec, cite its spec_id and current version.
A later confirmed version does not reopen decisions settled under an older one.
Hard waits still require the human; proposing a spec never changes authority.
+1 -1
View File
@@ -30,6 +30,6 @@ if [ "${1:-}" = business ]; then
exec node "$REPO/packages/business/src/cli.mjs" "$@"
fi
case "${1:-}" in
limits|inbox|decide|tasks|agents|trail|talk|stop|launches|bus) exec node "$REPO/packages/cli/src/cli.mjs" "$@" ;;
spec|limits|inbox|decide|tasks|agents|trail|talk|stop|launches|bus) exec node "$REPO/packages/cli/src/cli.mjs" "$@" ;;
esac
exec node "$REPO/packages/seat/src/cli.mjs" "$@"