Files
stack/packages/organization/src/definitions.mjs
T
jason.woltje 079ced93f3 feat(packs): pack, board and workflow verbs, routes and CLI words (#1873 SP4)
Design section 8. The bus answers packs, pack.preview, pack.apply,
board.set and workflow.set to the organization's human, and their
.console forms to the owner's Console cap. The broker runs the section 3
merge, the plan digest (pack-plan-stale on a mismatch) and the held
credential check. The organization writer keeps packs, board and
workflows out of the generic write and refuses definition writes to
every actor name an agent carries, project agents included.

mosaic org pack list|preview|apply, board set and workflow set|remove
go over the organization's bus as its human and refuse inside an agent
shell before any file is read. The Console serves GET /api/orgs/<id>/packs,
packs/preview, packs/apply, board and workflows/<name> (POST and
DELETE) to the root owner's session only, writes under --send only.
2026-11-12 16:51:46 -06:00

286 lines
14 KiB
JavaScript

// Roles round 2, slice T1 (#1873): an organization's own role definitions and the templates they
// copy. Design: docs/plans/2026-11-10_roles-and-rails-design.md sections 4 and 5, and the T1
// paragraph of section 13.
//
// The organization file's `definitions` key holds one entry per name:
// { rev, from?: { template, sha256 }, role: { tools, network, authority, credentials,
// messaging?, skills? }, instructions, personality? }
// An instance names one as `definition: "org:<name>"`. Every entry passes checkComposition (P1)
// whenever the file is validated, so no path writes or loads a definition that skips it. A refusal
// names the definition and the key at fault, never a value: composition.mjs quotes only registered
// names, and this module quotes only definition and template names, which match ID_PATTERN.
//
// A template is a shipped roles/<name>.json (role version 2) with its contract. Its identity is the
// name plus templateHash: sha256 over the JSON bytes and the contract bytes together, each preceded
// by its byte length and a newline, so no field goes into roles/.
//
// Pure reads only. The writer verbs live in definition-verbs.mjs, which organization.mjs's writer
// backs; this module is imported by organization-config.mjs and must not import the writer.
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { refuse } from "./errors.mjs";
import { buildRegistry, checkComposition } from "./composition.mjs";
import { validateRoleDocument } from "./role.mjs";
import { ID_PATTERN } from "./vocabulary.mjs";
import { canonicalJson, deepFreeze } from "./util.mjs";
export const ORG_PREFIX = "org:";
export const ENTRY_KEYS = Object.freeze(["rev", "from", "role", "instructions", "personality"]);
// The primitives an entry keeps under `role`; instructions and personality sit beside it.
export const ROLE_KEYS = Object.freeze(["tools", "network", "authority", "credentials", "messaging", "skills"]);
// What the diff read compares, in section 4's order.
export const PRIMITIVES = Object.freeze([...ROLE_KEYS, "instructions", "personality"]);
const FROM_KEYS = Object.freeze(["template", "sha256"]);
const HEX64 = /^[0-9a-f]{64}$/;
// The core registry. Plugin-declared primitives arrive with PL1; until then an org definition uses
// core names only.
const CORE = buildRegistry();
// Validation keeps no flagged lines: A4 computes them at the decision, against the chief's live
// role. Step 7 only flags, so a chief holding nothing refuses nothing here.
const NO_CHIEF = Object.freeze({
tools: Object.freeze([]), network: "none",
authority: Object.freeze({ withinRole: Object.freeze([]), crossRole: Object.freeze([]) }),
credentials: Object.freeze([]), messaging: null,
});
// The file-load check has no credential store: a load runs before the bus builds one from the file.
// The held-secret scan runs where definitions are written (setDefinition requires it, and the bus
// passes credentials.assertClean). A load still runs every other composition check.
const NO_STORE = () => {};
const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
&& [Object.prototype, null].includes(Object.getPrototypeOf(value));
// The definition name an instance's `definition` value names, or null for a template name.
export function orgDefinitionName(value) {
return typeof value === "string" && value.startsWith(ORG_PREFIX) ? value.slice(ORG_PREFIX.length) : null;
}
export function checkDefinitionName(name, where) {
if (typeof name !== "string" || !ID_PATTERN.test(name)) refuse(`${where} must be a definition name matching ${ID_PATTERN}`);
return name;
}
function keysOnly(object, allowed, where) {
Object.keys(object).forEach((key, i) => {
if (!allowed.includes(key)) refuse(`${where} has an unknown key (key ${i + 1}; allowed: ${allowed.join(", ")})`);
});
}
// The composition an entry describes, for checkComposition. Absent optional keys stay absent.
export function compositionOf(entry) {
const out = { ...entry.role, instructions: entry.instructions };
if (entry.personality !== undefined) out.personality = entry.personality;
return out;
}
// One entry: its own keys, then checkComposition. Returns { composition, flagged }. options.assertClean
// is the credential store's check; a write always passes it (setDefinition), a file load can't.
export function checkDefinition(name, entry, { assertClean = NO_STORE, where = "definitions" } = {}) {
const at = `${where}.${checkDefinitionName(name, `${where} key`)}`;
if (!plain(entry)) refuse(`${at} must be a JSON object`);
keysOnly(entry, ENTRY_KEYS, at);
if (!Number.isSafeInteger(entry.rev) || entry.rev < 1) refuse(`${at}.rev must be a positive integer`);
if (entry.from !== undefined) {
if (!plain(entry.from)) refuse(`${at}.from must be a JSON object`);
keysOnly(entry.from, FROM_KEYS, `${at}.from`);
if (typeof entry.from.template !== "string" || !ID_PATTERN.test(entry.from.template)) refuse(`${at}.from.template must be a template name matching ${ID_PATTERN}`);
if (typeof entry.from.sha256 !== "string" || !HEX64.test(entry.from.sha256)) refuse(`${at}.from.sha256 must be 64 lowercase hex characters`);
}
if (!plain(entry.role)) refuse(`${at}.role must be a JSON object`);
keysOnly(entry.role, ROLE_KEYS, `${at}.role`);
try {
return checkComposition(compositionOf(entry), CORE, NO_CHIEF, { assertClean });
} catch (error) {
// composition.mjs's refusals quote registered names only; keep its text, add where.
if (error?.name === "BusinessError") refuse(`${at}: ${error.message}`);
throw error;
}
}
// The resolved role an `org:` instance launches with: loadRole's shape, so the business checks,
// the resolver and the broker read it as they read a template. Instructions stand in for the
// contract file (contractPath null). A definition grants no hiring authority.
function resolved(name, entry, composition) {
return {
roleVersion: 2, name: ORG_PREFIX + name, title: name, contract: null, contractPath: null,
tools: composition.tools, network: composition.network, authority: composition.authority,
credentials: composition.credentials, messaging: composition.messaging, skills: composition.skills,
instructions: composition.instructions, personality: composition.personality,
rev: entry.rev, from: entry.from === undefined ? null : { ...entry.from },
};
}
// The whole `definitions` key. Returns a frozen map "org:<name>" -> resolved role. A bad entry
// refuses the whole file.
export function checkDefinitions(definitions, file, options = {}) {
if (definitions === undefined) return deepFreeze({});
const where = `${file} definitions`;
if (!plain(definitions)) refuse(`${where} must be a JSON object`);
const out = {};
Object.keys(definitions).forEach((name, i) => {
checkDefinitionName(name, `${where} key ${i + 1}`);
const { composition } = checkDefinition(name, definitions[name], { ...options, where });
out[ORG_PREFIX + name] = resolved(name, definitions[name], composition);
});
return deepFreeze(out);
}
// The instances that name `org:<name>`, sorted.
export function instancesNaming(document, name) {
const ref=ORG_PREFIX+name;
const users=Object.entries(document.roles??{}).filter(([,entry])=>entry.definition===ref).map(([instance])=>instance);
for(const [project,p]of Object.entries(document.projects??{}))for(const [instance,entry]of Object.entries(p.agents??{}))if(entry.definition===ref)users.push(`${project}.${instance}`);
return users.sort();
}
// SP4: every actor name an agent of the organization can carry: a root instance as `n` and
// `<definition>.n`, a project agent as `n`, `n.<project>` and `<definition>.n.<project>`. A write
// only a human makes refuses any of them.
export function agentActors(document) {
const out = [];
for (const [n, role] of Object.entries(document?.roles ?? {})) out.push(n, `${role?.definition}.${n}`);
for (const [project, p] of Object.entries(document?.projects ?? {})) {
for (const [n, entry] of Object.entries(p?.agents ?? {})) out.push(n, `${n}.${project}`, `${entry?.definition}.${n}.${project}`);
}
return out;
}
// ---- Templates ----
function frame(...parts) {
const hash = createHash("sha256");
for (const part of parts) {
hash.update(`${part.length}\n`);
hash.update(part);
}
return hash.digest("hex");
}
// One template, read once: its validated role, its contract text and its hash. Refuses a missing,
// invalid or version 1 template.
export function readTemplate(rolesDir, name) {
if (typeof name !== "string" || !ID_PATTERN.test(name)) refuse(`template name must match ${ID_PATTERN}`);
const file = join(rolesDir, `${name}.json`);
let json;
try {
json = readFileSync(file);
} catch {
refuse(`template ${name} not found`);
}
let document;
try {
document = JSON.parse(json.toString("utf8"));
} catch {
refuse(`template ${name} is not valid JSON`);
}
const role = validateRoleDocument(document, file);
if (role.roleVersion !== 2) refuse(`template ${name} is role version 1 and has no contract`);
let contract;
try { contract = readFileSync(role.contractPath); } catch { refuse(`template ${name} contract is unavailable`); }
return { name, role, contract: contract.toString("utf8"), sha256: frame(json, contract) };
}
export function templateHash(rolesDir, name) {
return readTemplate(rolesDir, name).sha256;
}
// The read: every version 2 template in rolesDir with its current hash, sorted by name. A file that
// is not a usable version 2 role (conductor-policy.json, a version 1 role) is not a template.
export function templateHashes(rolesDir) {
const out = [];
for (const entry of readdirSync(rolesDir).filter((f) => f.endsWith(".json")).sort()) {
const name = entry.slice(0, -".json".length);
if (!ID_PATTERN.test(name)) continue;
let template;
try {
template = readTemplate(rolesDir, name);
} catch (error) {
if (error?.name === "BusinessError") continue;
throw error;
}
out.push({ template: name, sha256: template.sha256 });
}
return out;
}
// The entry an import writes: the template's primitives and its contract as instructions.
export function entryFromTemplate(template) {
const { role } = template;
const out = {
tools: [...role.tools], network: role.network,
authority: { withinRole: [...role.authority.withinRole], crossRole: [...role.authority.crossRole] },
credentials: role.credentials.map((c) => (c.scopes === undefined ? { service: c.service } : { service: c.service, scopes: structuredClone(c.scopes) })),
};
if (role.messaging) out.messaging = { sendTo: [...role.messaging.sendTo], receiveFrom: [...role.messaging.receiveFrom] };
if (role.skills.length) out.skills = [...role.skills];
return { rev: 1, from: { template: template.name, sha256: template.sha256 }, role: out, instructions: template.contract };
}
// ---- The diff read ----
// A line diff of two texts: [{ op: " " | "-" | "+", line }]. Longest common subsequence over lines;
// past MAX_CELLS it reports the old text removed and the new one added, which is still exact.
const MAX_CELLS = 4_000_000;
export function lineDiff(before, after) {
const a = before.split("\n");
const b = after.split("\n");
if (a.length * b.length > MAX_CELLS) {
return [...a.map((line) => ({ op: "-", line })), ...b.map((line) => ({ op: "+", line }))];
}
const width = b.length + 1;
const table = new Uint32Array((a.length + 1) * width);
for (let i = a.length - 1; i >= 0; i--) {
for (let j = b.length - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1
: Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
}
}
const out = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] === b[j]) {
out.push({ op: " ", line: a[i] });
i++;
j++;
} else if (table[(i + 1) * width + j] >= table[i * width + j + 1]) {
out.push({ op: "-", line: a[i++] });
} else {
out.push({ op: "+", line: b[j++] });
}
}
while (i < a.length) out.push({ op: "-", line: a[i++] });
while (j < b.length) out.push({ op: "+", line: b[j++] });
return out;
}
// For a copy whose from.sha256 differs from its template's current hash: which primitives differ
// between the copy as it stands and the template as it stands, and the instructions' line diff.
// The file keeps only the hash of what was imported, so a customized copy's own edits show here
// too. Nothing is applied: apply or keep is a change decision (A4).
export function diffDefinition(document, name, rolesDir) {
const definitions = document?.definitions ?? {};
if (!Object.hasOwn(definitions, name)) refuse(`definitions declares no ${name}`);
const entry = definitions[name];
const base = { definition: name, rev: entry.rev, from: entry.from ?? null };
if (!entry.from) return { ...base, current: null, changed: false, primitives: [], instructions: [] };
let template;
try {
template = readTemplate(rolesDir, entry.from.template);
} catch (error) {
if (error?.name !== "BusinessError") throw error;
return { ...base, current: null, changed: true, templateMissing: true, primitives: [], instructions: [] };
}
if (template.sha256 === entry.from.sha256) return { ...base, current: template.sha256, changed: false, primitives: [], instructions: [] };
const now = compositionOf(entryFromTemplate(template));
const copy = compositionOf(entry);
const primitives = PRIMITIVES.filter((key) => canonicalJson(copy[key] ?? null) !== canonicalJson(now[key] ?? null));
return {
...base, current: template.sha256, changed: true, primitives,
instructions: primitives.includes("instructions") ? lineDiff(copy.instructions, now.instructions) : [],
};
}