CB0: registry incarnation minted at reserve (legacy entries get one at the first binding proposal, under the registry lock); copyId, source and definition pin, binding generation; a pure resolver where effective = role intersect approved and only a bound, matching, unshadowed record resolves. CB1: copyBindings in the organization file (ids, scope names, project ids and integers only). applyCopyBindingDecision is its only writer, behind a module-private capability every other commit is fenced against. A binding is an owner-only subtype of the hire decision: only the chief raises it, no autonomy level, resolver agent, member right, tester or reader resolves it. Digest, expiry, single consumption, revision, generation, incarnation and definition pin are rechecked before any effect; a bind writes pending, an unbind the unbound tombstone, receipts are paths only. Nothing writes bound, so nothing launches on a binding yet (CB2/CB3). The org service and the Console update path keep copyBindings server-held. Eight new refusal codes with next steps.
399 lines
26 KiB
JavaScript
399 lines
26 KiB
JavaScript
import { checkAutonomy } from './autonomy.mjs';
|
|
// The organization configuration file, still the v1 business file at
|
|
// <configDir>/businesses/<id>.json (REQ-ROLE-3, note section 2, addendum A
|
|
// sections 7 and 8; rename design r2 stage B: names only, same bytes). Human edits go through the trusted
|
|
// organization writer. A missing or invalid file refuses (lead decision 46, 6.1).
|
|
|
|
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
import { homedir } from "node:os";
|
|
import { refuse } from "./errors.mjs";
|
|
import { checkModels, checkLimits, checkAccount } from "./launch.mjs";
|
|
import { checkVars } from "./vars.mjs";
|
|
import { parseCredentialRef } from "./credentials.mjs";
|
|
import { loadRole } from "./role.mjs";
|
|
import { checkDefinitions, checkDefinitionName, orgDefinitionName, ORG_PREFIX } from "./definitions.mjs";
|
|
import { END_PROTECTED } from "./vocabulary.mjs";
|
|
import { checkPlugins, checkUsageSettings } from "../../plugins/src/kinds.mjs";
|
|
import { hasModule } from "../../plugins/src/loader.mjs";
|
|
import { readPluginLock } from "../../plugins/src/pinned.mjs";
|
|
import { checkMapping } from "../../library/src/mapping.mjs";
|
|
import { forkProblem, giteaName, parseGiteaUrl, HOST_SERVICE, CREATIVE_DEFINITIONS } from "./vocabulary.mjs";
|
|
import { checkAppearance } from "./appearance.mjs";
|
|
import { checkProjectAgents } from "./agent-levels.mjs";
|
|
import { validateCopyBindings } from "./copy-bindings.mjs";
|
|
import {
|
|
requireObject, rejectUnknownKeys, requireId, requirePositiveInt, requireString, requireDistinctList, readJsonFile, deepFreeze,
|
|
} from "./util.mjs";
|
|
|
|
const BOT_NAME = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/;
|
|
// How long a thread's session stays up with no turn before the launcher stops
|
|
// it, when launch.threadIdleSeconds is absent (REQ-THREAD-2, row 121).
|
|
export const THREAD_IDLE_SECONDS = 900;
|
|
const TOP_KEYS = ["businessVersion", "id", "human", "arbiters", "projects", "vars", "tracker", "roles", "launch", "plugins", "hosts", "retired", "replyLimits", "usage", "appearance", "definitions", "autonomy", "copyBindings"];
|
|
|
|
// The config directory: next to the system config, $MOSAIC_CONFIG or
|
|
// ~/.config/mosaic-dev/config.json, the same rule mosaic-config.mjs uses.
|
|
export function configDir(env = process.env) {
|
|
const file = env.MOSAIC_CONFIG || join(homedir(), ".config", "mosaic-dev", "config.json");
|
|
return dirname(file);
|
|
}
|
|
|
|
export function organizationFilePath(id, dir = configDir()) {
|
|
requireId(id, "business id");
|
|
return join(dir, "businesses", `${id}.json`);
|
|
}
|
|
|
|
export function checkBot(tracker, where) {
|
|
requireObject(tracker, where);
|
|
rejectUnknownKeys(tracker, ["bot", "botId"], where);
|
|
if (typeof tracker.bot !== "string" || !BOT_NAME.test(tracker.bot)) refuse(`${where}.bot must be a Vikunja bot username starting with "bot-"`);
|
|
requirePositiveInt(tracker.botId, `${where}.botId`);
|
|
return { bot: tracker.bot, botId: tracker.botId };
|
|
}
|
|
|
|
function checkCredentialMap(map, services, where, store = null) {
|
|
requireObject(map, where);
|
|
const names = Object.keys(map).sort();
|
|
const wanted = [...services].sort();
|
|
if (names.join(",") !== wanted.join(",")) {
|
|
refuse(`${where} must reference exactly the services its role definition needs (${wanted.join(", ") || "none"}; got ${names.join(", ") || "none"})`);
|
|
}
|
|
const out = {};
|
|
for (const service of names) out[service] = parseCredentialRef(map[service], service, `${where}.${service}`, { store });
|
|
return out;
|
|
}
|
|
|
|
// Row 199 (#1697, design D8): the agent's own git identity. The email is the one its Gitea user
|
|
// has, so Gitea links the commits to that user; gitea.url is the instance its pushes go to.
|
|
const EMAIL = /^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,190}\.[A-Za-z]{2,24}$/;
|
|
const NAME = /^[^\0\n\r<>]{1,100}$/;
|
|
|
|
// Row 199 (design D9c): the parse is vocabulary.mjs's, where the broker reads it; this wraps it with
|
|
// the loader's refusals. Returns {url, owner, repo}.
|
|
export function httpsUrl(value, where, { repo = false } = {}) {
|
|
const parsed = parseGiteaUrl(value, { repo });
|
|
if (parsed.problem === "form") refuse(`${where} must be a normalized https URL with no user, query or fragment`);
|
|
if (parsed.problem === "instance") refuse(`${where} must name the Gitea instance only, https://HOST[:PORT]`);
|
|
if (parsed.problem === "repository") refuse(`${where} must name a repository, https://HOST/OWNER/REPO`);
|
|
return parsed;
|
|
}
|
|
|
|
function checkIdentity(identity, where) {
|
|
requireObject(identity, where);
|
|
rejectUnknownKeys(identity, ["name", "email", "gitea"], where);
|
|
if (typeof identity.name !== "string" || !NAME.test(identity.name)) refuse(`${where}.name must be 1 to 100 characters with no <, > or line break`);
|
|
if (typeof identity.email !== "string" || !EMAIL.test(identity.email)) refuse(`${where}.email must be an email address`);
|
|
requireObject(identity.gitea, `${where}.gitea`);
|
|
rejectUnknownKeys(identity.gitea, ["url", "user"], `${where}.gitea`);
|
|
httpsUrl(identity.gitea.url, `${where}.gitea.url`);
|
|
if (!giteaName(identity.gitea.user)) refuse(`${where}.gitea.user must be a Gitea user name`);
|
|
return { name: identity.name, email: identity.email, gitea: { url: identity.gitea.url, user: identity.gitea.user } };
|
|
}
|
|
|
|
function checkTracker(tracker, file) {
|
|
const where = `${file} tracker`;
|
|
requireObject(tracker, where);
|
|
rejectUnknownKeys(tracker, ["sync", "labels"], where);
|
|
requireObject(tracker.sync, `${where}.sync`);
|
|
rejectUnknownKeys(tracker.sync, ["bot", "botId", "credentials"], `${where}.sync`);
|
|
const sync = {
|
|
...checkBot({ bot: tracker.sync.bot, botId: tracker.sync.botId }, `${where}.sync`),
|
|
credentials: checkCredentialMap(tracker.sync.credentials, ["vikunja"], `${where}.sync.credentials`),
|
|
};
|
|
let labels = {};
|
|
if (tracker.labels !== undefined) {
|
|
requireObject(tracker.labels, `${where}.labels`);
|
|
// fromEntries defines own properties, so a "__proto__" title stays data.
|
|
labels = Object.fromEntries(Object.entries(tracker.labels).map(([title, id]) => [
|
|
requireString(title, `${where}.labels title`, { max: 100 }),
|
|
requirePositiveInt(id, `${where}.labels.${title}`),
|
|
]));
|
|
}
|
|
return { sync, labels };
|
|
}
|
|
|
|
// Row 213 (C2-08, Case 2 design 4): persona vars belong only to a creative instance, and come as a
|
|
// pair, since the bundle reads the file only against its digest.
|
|
function checkPersonaVars(vars, definition, at) {
|
|
const set = ["persona.name", "persona.sha256"].filter((key) => Object.hasOwn(vars, key));
|
|
if (set.length === 0) return;
|
|
if (!CREATIVE_DEFINITIONS.includes(definition)) refuse(`${at}.vars: persona vars need a creative definition (${definition} isn't one)`);
|
|
if (set.length === 1) refuse(`${at}.vars: persona.name and persona.sha256 are set together or not at all`);
|
|
}
|
|
|
|
// Row 234 (#1740, r6 S1): hosts and host grants are bus store records made by a human-approved grant,
|
|
// so the business file can't name them. The key stays known so the refusal says where they went.
|
|
const HOSTS_MOVED = "lives in the bus store now: enroll a host with a host-enroll grant (mosaic hosts status)";
|
|
|
|
function checkRoles(roles, file, rolesDir, business, hasLibrary, orgDefinitions) {
|
|
const where = `${file} roles`;
|
|
requireObject(roles, where);
|
|
if (Object.keys(roles).length === 0) refuse(`${where} must declare at least one role instance`);
|
|
const out = {};
|
|
const definitions = {};
|
|
const bots = new Set();
|
|
const botIds = new Set();
|
|
for (const [instance, entry] of Object.entries(roles)) {
|
|
requireId(instance, `${where} instance name`);
|
|
const at = `${where}.${instance}`;
|
|
requireObject(entry, at);
|
|
rejectUnknownKeys(entry, ["definition", "holder", "vars", "tracker", "credentials", "identity", "publish", "hosts", "hireDecision"], at);
|
|
// #1873 T1: "org:<name>" names one of this file's definitions; anything else is a template.
|
|
const orgName = orgDefinitionName(entry.definition);
|
|
if (orgName === null) requireId(entry.definition, `${at}.definition`);
|
|
else if (!Object.hasOwn(orgDefinitions, ORG_PREFIX + checkDefinitionName(orgName, `${at}.definition after org:`))) {
|
|
refuse(`definition-missing: ${at}.definition names ${ORG_PREFIX}${orgName}, which definitions doesn't declare`);
|
|
}
|
|
const definition = Object.hasOwn(definitions, entry.definition) ? definitions[entry.definition]
|
|
: orgName === null ? loadRole(rolesDir, entry.definition) : orgDefinitions[entry.definition];
|
|
definitions[entry.definition] = definition;
|
|
if (definition.roleVersion !== 2) refuse(`${at}: role definition ${entry.definition} is version 1 and can't back a business role instance`);
|
|
const services = definition.credentials.map((c) => c.service);
|
|
const hired = typeof entry.hireDecision === 'string' && /^[a-f0-9-]{36}$/.test(entry.hireDecision) && orgName !== null;
|
|
if (entry.hireDecision !== undefined && !hired) refuse(`${at}.hireDecision must name an approved composition decision`);
|
|
const missing = hired ? services.filter(s => s !== HOST_SERVICE && !Object.hasOwn(entry.credentials ?? {},s)) : [];
|
|
if (entry.hosts !== undefined) refuse(`${at}.hosts ${HOSTS_MOVED}`);
|
|
// A host.<id> key reference comes from the agent's grant record at bus start (r6 X4), never from here.
|
|
// Row 285 amendment 1 (mos-1580): the chief needs its read reference only for a library.
|
|
// Other definitions keep the exact service list; checkCredentialMap itself is unchanged.
|
|
const kinds = services.filter((s) => s !== HOST_SERVICE && !(entry.definition === "chief-of-staff" && !hasLibrary && s === "gitea"));
|
|
if (entry.definition === "chief-of-staff" && hasLibrary && !Object.hasOwn(entry.credentials ?? {}, "gitea")) {
|
|
refuse(`chief-library-gitea-required: ${at}.credentials must reference gitea because this business declares a library`);
|
|
}
|
|
let tracker = null;
|
|
if (services.includes("vikunja")) {
|
|
if (entry.tracker === undefined && !missing.includes("vikunja")) refuse(`${at} needs "tracker" with its Vikunja bot, because ${entry.definition} uses vikunja`);
|
|
tracker = missing.includes("vikunja") ? null : checkBot(entry.tracker, `${at}.tracker`);
|
|
if (tracker && bots.has(tracker.bot)) refuse(`${at}.tracker.bot ${tracker.bot} is used by another instance`);
|
|
if (tracker && botIds.has(tracker.botId)) refuse(`${at}.tracker.botId ${tracker.botId} is used by another instance`);
|
|
if(tracker) bots.add(tracker.bot);
|
|
if(tracker) botIds.add(tracker.botId);
|
|
} else if (entry.tracker !== undefined) {
|
|
refuse(`${at} has "tracker" but ${entry.definition} uses no vikunja credential`);
|
|
}
|
|
out[instance] = {
|
|
definition: entry.definition,
|
|
holder: entry.holder === undefined ? null : requireId(entry.holder, `${at}.holder`),
|
|
vars: checkVars(entry.vars ?? {}, "agent", `${at}.vars`),
|
|
tracker,
|
|
credentials: checkCredentialMap(entry.credentials ?? {}, hired ? kinds.filter(s=>!missing.includes(s)) : kinds, `${at}.credentials`,
|
|
{ configDir: dirname(dirname(file)), business, agent: instance }),
|
|
};
|
|
if(hired) { out[instance].hireDecision=entry.hireDecision; out[instance].unbound=missing; }
|
|
// Row 199 (#1697, design D8, D9 step 2): identity and publish are optional, so today's files
|
|
// load unchanged. publish needs both an identity and a gitea credential; the project ids it
|
|
// names are checked against projects once those are read.
|
|
if (entry.identity !== undefined) out[instance].identity = checkIdentity(entry.identity, `${at}.identity`);
|
|
if (entry.publish !== undefined) {
|
|
// N10: one message for both, naming the grant.
|
|
if (!out[instance].identity || !services.includes("gitea")) refuse(`${at}.publish needs identity and a gitea definition`);
|
|
out[instance].publish = requireDistinctList(entry.publish, `${at}.publish`, (p) => requireId(p, `${at}.publish entry`), { nonEmpty: true });
|
|
}
|
|
checkPersonaVars(out[instance].vars, entry.definition, at);
|
|
}
|
|
return { roles: out, definitions };
|
|
}
|
|
|
|
function checkLaunch(launch, roles, definitions, file) {
|
|
const where = `${file} launch`;
|
|
requireObject(launch, where);
|
|
if (Object.hasOwn(launch,"max")) refuse(`${where}.max needs migration: mosaic limits migrate --file FILE --models FILE`);
|
|
rejectUnknownKeys(launch, ["by", "instances", "models", "limits", "threadIdleSeconds", "account", "keep", "noHire", "grantScope"], where);
|
|
requireId(launch.by, `${where}.by`);
|
|
if (!Object.hasOwn(roles, launch.by)) refuse(`${where}.by names ${launch.by}, which the business file doesn't declare`);
|
|
const launcher = definitions[roles[launch.by].definition];
|
|
if (!launcher.authority.withinRole.includes("role.launch")) {
|
|
refuse(`${where}.by names ${launch.by}, whose role ${launcher.name} doesn't hold role.launch within-role`);
|
|
}
|
|
const instances = requireDistinctList(launch.instances, `${where}.instances`, (name) => {
|
|
requireId(name, `${where}.instances entry`);
|
|
if (!Object.hasOwn(roles, name)) refuse(`${where}.instances names ${name}, which the business file doesn't declare`);
|
|
if (name === launch.by) refuse(`${where}.instances can't include the launcher itself (${name})`);
|
|
}, { nonEmpty: true });
|
|
const models=checkModels(launch.models,`${where}.models`);
|
|
const limits=checkLimits(launch.limits===undefined?{}:launch.limits,`${where}.limits`);
|
|
for(const instance of Object.keys(limits.tokens?.instances??{}))if(!Object.hasOwn(roles,instance))refuse(`${where}.limits.tokens.instances names ${instance}, which the business file doesn't declare`);
|
|
// Row 126 (#1620): a daily quota for any account but launch.account would count nothing and still
|
|
// show as counted, so it refuses the read.
|
|
const account = launch.account === undefined ? undefined : checkAccount(launch.account, `${where}.account`);
|
|
for (const name of Object.keys(limits.tokens?.daily ?? {})) {
|
|
if (name !== account?.name) refuse(`${where}.limits.tokens.daily names ${name}, which isn't ${where}.account.name`);
|
|
}
|
|
for(const [instance,role] of Object.entries(roles))if(role.vars.model!==undefined&&!Object.hasOwn(models,role.vars.model))refuse(`${where}: instance ${instance} variable model selects an unknown model`);
|
|
// No upper bound: limits have no ceiling in code (Q150).
|
|
const threadIdleSeconds = launch.threadIdleSeconds === undefined ? THREAD_IDLE_SECONDS : requirePositiveInt(launch.threadIdleSeconds, `${where}.threadIdleSeconds`);
|
|
// Row 194 (#1692, D2.4, D2.5): the human's per-agent forbid. keep names declared instances the
|
|
// chief can't fire, replace or end. noHire names definitions the chief can't hire, by the id
|
|
// pattern only, so a stale entry is harmless. Both are optional and only the human writes them.
|
|
const keep = launch.keep === undefined ? undefined : requireDistinctList(launch.keep, `${where}.keep`, (name) => {
|
|
requireId(name, `${where}.keep entry`);
|
|
if (!Object.hasOwn(roles, name)) refuse(`${where}.keep names ${name}, which the business file doesn't declare`);
|
|
if (END_PROTECTED.includes(roles[name].definition)) refuse(`${where}.keep names ${name}, whose definition ${roles[name].definition} can't be kept`);
|
|
});
|
|
const noHire = launch.noHire === undefined ? undefined
|
|
: requireDistinctList(launch.noHire, `${where}.noHire`, (name) => requireId(name, `${where}.noHire entry`));
|
|
return {
|
|
by: launch.by, instances, models, limits, threadIdleSeconds, ...(account ? { account } : {}),
|
|
...(keep ? { keep } : {}), ...(noHire ? { noHire } : {}),
|
|
// Row 298 (#1804, Q228): the chief's grant scope passes through unchecked. A bad value must not
|
|
// refuse the whole file; the broker's reader (grantScopeOf) falls back to the empty scope instead.
|
|
...(launch.grantScope !== undefined ? { grantScope: structuredClone(launch.grantScope) } : {}),
|
|
};
|
|
}
|
|
|
|
// Row 194 (#1692, V5): instance names a delete retired. None may be declared again, so a later
|
|
// create or hire can't reuse a name whose decisions outlive it.
|
|
function checkRetired(retired, roles, file) {
|
|
return requireDistinctList(retired, `${file} retired`, (name) => {
|
|
requireId(name, `${file} retired entry`);
|
|
if (Object.hasOwn(roles, name)) refuse(`${file} retired names ${name}, which roles still declares`);
|
|
});
|
|
}
|
|
|
|
// Validate a parsed business document read from `file`. `rolesDir` is where
|
|
// role definitions live. Returns a frozen business with its definitions.
|
|
// options.assertClean is the credential store's secret check for the definitions' text, when the
|
|
// caller holds one (#1873 T1); without it the check is the empty store's.
|
|
export function validateOrganizationDocument(document, file, { rolesDir, dataRoot = null, assertClean } = {}) {
|
|
requireObject(document, "business file");
|
|
rejectUnknownKeys(document, TOP_KEYS, "business file");
|
|
if (document.businessVersion !== 1) refuse(`business file "businessVersion" must be 1 (${file})`);
|
|
requireId(document.id, "business id");
|
|
const base = file.split("/").pop().replace(/\.json$/, "");
|
|
if (document.id !== base) refuse(`business "id" (${document.id}) must match its filename (${base}.json)`);
|
|
for (const key of ["human", "arbiters", "projects", "roles"]) {
|
|
if (document[key] === undefined) refuse(`business file requires "${key}" (${file})`);
|
|
}
|
|
const human = requireId(document.human, "business human");
|
|
const vars = checkVars(document.vars ?? {}, "business", `${file} vars`);
|
|
if (document.hosts !== undefined) refuse(`${file} hosts ${HOSTS_MOVED}`);
|
|
const hasLibrary = Object.values(document.projects ?? {}).some((project) => project?.kind === "library");
|
|
const orgDefinitions = checkDefinitions(document.definitions, file, assertClean ? { assertClean } : {});
|
|
const { roles, definitions } = checkRoles(document.roles, file, rolesDir, document.id, hasLibrary, orgDefinitions);
|
|
|
|
requireObject(document.arbiters, `${file} arbiters`);
|
|
rejectUnknownKeys(document.arbiters, ["delivery", "technical"], `${file} arbiters`);
|
|
const arbiters = {};
|
|
for (const kind of ["delivery", "technical"]) {
|
|
const name = document.arbiters[kind];
|
|
requireId(name, `${file} arbiters.${kind}`);
|
|
if (!Object.hasOwn(roles, name)) refuse(`${file} arbiters.${kind} names ${name}, which the business file doesn't declare`);
|
|
// Row 133 (#1627): an arbiter messages the raiser when it closes a decision, so it can't be a
|
|
// role whose definition limits who it sends to and hears from.
|
|
const definition = roles[name].definition;
|
|
if (definitions[definition].messaging) {
|
|
refuse(`${file} arbiters.${kind} names ${name}, whose role definition ${definition} declares messaging lists`);
|
|
}
|
|
const right = `decision.resolve.${kind}`;
|
|
const narrowed = [vars, roles[name].vars].some(layer =>
|
|
layer["limits.authority"] !== undefined && !layer["limits.authority"].includes(right));
|
|
if (!definitions[definition].authority.withinRole.includes(right) || narrowed) {
|
|
refuse(`${file} arbiters.${kind} names ${name}, whose role definition ${definition} lacks ${right}`);
|
|
}
|
|
arbiters[kind] = name;
|
|
}
|
|
|
|
requireObject(document.projects, `${file} projects`);
|
|
if (Object.keys(document.projects).length === 0) refuse(`${file} projects must name at least one project`);
|
|
const projects = {};
|
|
for (const [id, entry] of Object.entries(document.projects)) {
|
|
requireId(id, `${file} project id`);
|
|
requireObject(entry, `${file} projects.${id}`);
|
|
if (entry.kind === 'library') {
|
|
projects[id] = checkMapping(entry, `${file} projects.${id}`, { fail: (code, message) => refuse(`${code}: ${message}`) });
|
|
continue;
|
|
}
|
|
rejectUnknownKeys(entry, ["root", "repo", "remote", "git", "agents"], `${file} projects.${id}`);
|
|
// #1873 A1: the project's own agent entries. Checked so a bad entry refuses the whole file, but
|
|
// not copied below: nothing a bus loads sees them; only the Console's agent-levels read does.
|
|
if (Object.hasOwn(entry, "agents")) checkProjectAgents(entry.agents, { rolesDir, where: `projects.${id}.agents`, definitions:document.definitions });
|
|
if (typeof entry.root !== "string" || !isAbsolute(entry.root) || normalize(entry.root) !== entry.root || entry.root.includes("\0")) {
|
|
refuse(`${file} projects.${id}.root must be a normalized absolute path`);
|
|
}
|
|
if (Object.hasOwn(entry, "repo") && (typeof entry.repo !== "string" || !isAbsolute(entry.repo) ||
|
|
normalize(entry.repo) !== entry.repo || entry.repo.includes("\0"))) {
|
|
refuse(`${file} projects.${id}.repo must be a normalized absolute path`);
|
|
}
|
|
// Row 199 (#1697, design D9 step 2): the upstream; a granted agent's work goes to its fork.
|
|
if (Object.hasOwn(entry, "remote")) httpsUrl(entry.remote, `${file} projects.${id}.remote`, { repo: true });
|
|
if (Object.hasOwn(entry, "git")) {
|
|
requireObject(entry.git, `${file} projects.${id}.git`);
|
|
rejectUnknownKeys(entry.git, ["mode", "remote"], `${file} projects.${id}.git`);
|
|
if (!['local-only', 'remote'].includes(entry.git.mode)) refuse(`${file} projects.${id}.git.mode must be local-only or remote`);
|
|
if (entry.git.mode === 'remote') httpsUrl(entry.git.remote, `${file} projects.${id}.git.remote`, { repo: true });
|
|
else if (Object.hasOwn(entry.git, 'remote')) refuse(`${file} projects.${id}.git.remote is not allowed for local-only`);
|
|
}
|
|
projects[id] = { root: entry.root, ...(Object.hasOwn(entry, "repo") ? { repo: entry.repo } : {}),
|
|
...(Object.hasOwn(entry, "remote") ? { remote: entry.remote } : {}),
|
|
...(Object.hasOwn(entry, "git") ? { git: { ...entry.git } } : {}) };
|
|
}
|
|
for (const [instance, role] of Object.entries(roles)) {
|
|
for (const project of role.publish ?? []) {
|
|
if (!Object.hasOwn(projects, project)) refuse(`${file} roles.${instance}.publish names ${project}, which the business file doesn't declare`);
|
|
// C2-21, sage-2916: retain the fence; only creative instances and the chief may hold library reach.
|
|
if (projects[project].kind === 'library' && !CREATIVE_DEFINITIONS.includes(role.definition) && role.definition !== 'chief-of-staff')
|
|
refuse(`${file} roles.${instance}.publish names library project ${project}; library publish requires a creative definition or chief-of-staff with gitea`);
|
|
if (!projects[project].remote) refuse(`${file} roles.${instance}.publish names ${project}, which has no "remote"`);
|
|
const problem = forkProblem(projects[project].remote, role.identity);
|
|
if (problem) refuse(`${file} roles.${instance}.publish names ${project}: ${problem}`);
|
|
}
|
|
}
|
|
|
|
const tracker = Object.hasOwn(document, "tracker") ? checkTracker(document.tracker, file) : null;
|
|
for (const [instance, role] of Object.entries(roles)) {
|
|
if (tracker && role.tracker && (role.tracker.bot === tracker.sync.bot || role.tracker.botId === tracker.sync.botId)) {
|
|
refuse(`${file} tracker.sync must use its own bot, not the one roles.${instance} uses`);
|
|
}
|
|
}
|
|
// #1873 CB1: copy credential bindings. Each copy's tracker bot is unique against every named
|
|
// instance's bot, the tracker sync bot and the other copies.
|
|
validateCopyBindings(document.copyBindings, { trackers: [...Object.values(roles).map((r) => r.tracker).filter(Boolean), ...(tracker ? [tracker.sync] : [])] });
|
|
const copyBindings = document.copyBindings === undefined ? undefined : structuredClone(document.copyBindings);
|
|
const launch = document.launch === undefined ? null : checkLaunch(document.launch, roles, definitions, file);
|
|
// REQ-PLUG-1: the module names switched on per kind. The names are checked
|
|
// here; whether each module loads is the loader's check, at load time.
|
|
const plugins = document.plugins === undefined ? {}
|
|
: structuredClone(checkPlugins(document.plugins, `${file} plugins`, { fail: (_code, message) => refuse(message) }));
|
|
let installedNames = new Set();
|
|
if (dataRoot !== null && plugins["system-type"]?.some(id=>!hasModule("system-type",id))) {
|
|
try { installedNames = new Set(Object.keys(readPluginLock(dataRoot).plugins)); }
|
|
catch { installedNames = null; } // the loader reports an unreadable lock; core still loads
|
|
}
|
|
for (const id of plugins["system-type"] ?? []) {
|
|
if (!hasModule("system-type", id) && installedNames !== null && !installedNames.has(id)) refuse(`${file} plugins.system-type names unknown module ${id}`);
|
|
}
|
|
const usage = document.usage === undefined ? undefined : checkUsageSettings(document.usage);
|
|
const autonomy = checkAutonomy(document.autonomy);
|
|
if(autonomy?.authorityResolver) {
|
|
const entry=roles[autonomy.authorityResolver],right='decision.resolve.authority';
|
|
if(!entry || !definitions[entry.definition].authority.withinRole.includes(right) ||
|
|
[vars,entry.vars].some(layer=>layer?.['limits.authority']!==undefined && !layer['limits.authority'].includes(right))) {
|
|
const e=new Error('invalid-autonomy');e.code='invalid-autonomy';throw e;
|
|
}
|
|
}
|
|
const appearance = checkAppearance(document.appearance, `${file} appearance`);
|
|
const retired = document.retired === undefined ? undefined : checkRetired(document.retired, roles, file);
|
|
|
|
return deepFreeze({
|
|
businessVersion: 1, id: document.id, file, human, arbiters, projects, vars, tracker, roles, launch, plugins, definitions,
|
|
...(autonomy === undefined ? {} : { autonomy }), ...(retired ? { retired } : {}), ...(usage === undefined ? {} : { usage }), ...(appearance === undefined ? {} : { appearance }),
|
|
...(copyBindings === undefined ? {} : { copyBindings }),
|
|
});
|
|
}
|
|
|
|
// Load businesses/<id>.json from the config directory. The file holds
|
|
// authority, so it must belong to this user and not be writable by group
|
|
// or other.
|
|
export function loadOrganization(id, { dir = configDir(), rolesDir, dataRoot = null }) {
|
|
if (!rolesDir) throw new Error("loadBusiness needs rolesDir");
|
|
const file = organizationFilePath(id, dir);
|
|
const document = readJsonFile(file, `business file ${id}.json`, (stat) => {
|
|
if (stat.uid !== process.getuid()) refuse(`business file must belong to uid ${process.getuid()}: ${file}`);
|
|
if ((stat.mode & 0o022) !== 0) refuse(`business file must not be writable by group or other (mode ${(stat.mode & 0o777).toString(8)}): ${file}`);
|
|
});
|
|
return validateOrganizationDocument(document, file, { rolesDir, dataRoot });
|
|
}
|
|
|
|
// The old names (rename design r2, module map): the same functions, not copies.
|
|
export { organizationFilePath as businessFilePath, validateOrganizationDocument as validateBusinessDocument, loadOrganization as loadBusiness };
|