Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6ab8bc1fd | ||
|
|
0251acdad9 | ||
|
|
13560660ae | ||
|
|
08e50e513f | ||
|
|
a9d72b3cd1 | ||
|
|
4b35e3c1d2 | ||
|
|
56aeefb370 | ||
|
|
fdbc34413b | ||
|
|
c5bf71ab08 | ||
|
|
dbb69c8a41 | ||
|
|
34dd331016 | ||
|
|
808b2b7cbf | ||
|
|
5ffe38e3b2 |
No files matched your search
@@ -1240,16 +1240,22 @@ Added in version 1.3 (Q155).
|
||||
changes it, not in one rewrite (Q155). Until it converts, Technical
|
||||
considerations lists where it is hard-coded.
|
||||
|
||||
### System types
|
||||
### Starter packs
|
||||
|
||||
Added in version 1.20.
|
||||
|
||||
- **REQ-SYS-1.** System types are a plug-in kind. Its modules include
|
||||
coding, creative writing, marketing, Mosaic Montage (the OpenMontage
|
||||
fork) and business management. An organization enables a list of them.
|
||||
- **REQ-SYS-2.** A project may use any system type its organization
|
||||
enables, and none is required. An agent working in a project gets the
|
||||
toolsets of the system types that project uses.
|
||||
- **REQ-SYS-1.** Starter packs are a plug-in kind. Mosaic Stack ships five:
|
||||
coding, creative writing, marketing, Mosaic Montage and business
|
||||
management. A pack is a starting configuration of role definitions,
|
||||
proposed hires, a board style and workflow templates. An organization or
|
||||
project copies a pack in once and then owns and changes what it copied. A
|
||||
user can save an organization or project as their own template and apply it
|
||||
the same way.
|
||||
- **REQ-SYS-2.** Applying a pack grants nothing by itself. Every agent it
|
||||
proposes is hired through the hire decision (REQ-AGENT-3), bounded by the
|
||||
chief's own role, with any line above it approved by the owner. A pack never
|
||||
sets credentials, rights, the autonomy setting or plug-in choices. Removing
|
||||
a pack removes nothing it copied.
|
||||
|
||||
### Meta-harness
|
||||
|
||||
|
||||
@@ -639,22 +639,6 @@ CREATE TRIGGER request_snapshot_events_no_replace BEFORE INSERT ON request_snaps
|
||||
CREATE TRIGGER request_project_events_no_update BEFORE UPDATE ON request_project_events BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
CREATE TRIGGER request_project_events_no_delete BEFORE DELETE ON request_project_events BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
CREATE TRIGGER request_project_events_no_replace BEFORE INSERT ON request_project_events WHEN EXISTS (SELECT 1 FROM request_project_events WHERE seq=NEW.seq OR (business=NEW.business AND project=NEW.project AND revision=NEW.revision)) BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
-- Per-project selections are a human-authored append-only settings trail.
|
||||
CREATE TABLE project_system_types (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
business TEXT NOT NULL,
|
||||
project TEXT NOT NULL REFERENCES projects(id),
|
||||
types TEXT NOT NULL,
|
||||
by TEXT NOT NULL
|
||||
) STRICT;
|
||||
CREATE INDEX project_system_types_project ON project_system_types (business, project, seq);
|
||||
CREATE TRIGGER project_system_types_no_update BEFORE UPDATE ON project_system_types BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_no_delete BEFORE DELETE ON project_system_types BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_no_replace BEFORE INSERT ON project_system_types WHEN EXISTS (SELECT 1 FROM project_system_types WHERE seq = NEW.seq) BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_business BEFORE INSERT ON project_system_types
|
||||
WHEN (SELECT business FROM projects WHERE id = NEW.project) IS NOT NEW.business
|
||||
BEGIN SELECT RAISE(ABORT, 'a system types row belongs to its project business'); END;
|
||||
-- U4a (#1873): the task store built into each organization, the default task-tracker module
|
||||
-- (REQ-TASK-1). Each row is the whole task after one write, so a task's state is its latest row
|
||||
-- and the rows are its history: who wrote it (a role and run, or the person), when, under which
|
||||
|
||||
+138
-52
@@ -178,13 +178,15 @@ export const USER_VERBS = Object.freeze(['project.list', 'thread.create', 'threa
|
||||
'thread.share', 'thread.unshare', 'thread.shares']);
|
||||
// Row 252 (#1753, design sections 2-3): the only verbs a Console owner cap reaches. Every other verb
|
||||
// refuses it human-required before its own checks, and these refuse every other cap.
|
||||
export const CONSOLE_VERBS = Object.freeze(['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
// Task 3 (#1839): and the owner's intake controls. The reads and writes are the same lifecycle methods the PM's
|
||||
// unsuffixed verbs reach, with the owner's verified (provider, iss, sub) as the only caller; the PM-only
|
||||
// request.question and the PM's own reads keep their unsuffixed names and refuse a console cap.
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// #1873 SP4: the owner's starter packs, board and workflows.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console']);
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
// #1873 SP8: and saving a template, with the list of the owner's own.
|
||||
'template.save.console', 'template.list.console']);
|
||||
// What an owner's console cap may ask of the request lifecycle (a read, the intake controls, and Task 4's mode and draft).
|
||||
const INTAKE_CONSOLE = Object.freeze(['artifactConsole', 'get', 'answer', 'attach', 'cancel', 'mode', 'draft']);
|
||||
const REQUEST_VERBS = Object.freeze({ 'request.open': 'open', 'request.get': 'get', 'request.projects': 'projects', 'request.propose': 'propose',
|
||||
@@ -221,6 +223,17 @@ const PACK_KEYS = Object.freeze({
|
||||
'workflow.set': [['revision', 'name', 'workflow', 'project'], ['revision', 'name', 'workflow']],
|
||||
});
|
||||
export const PACK_BUS_KEYS = Object.freeze(Object.fromEntries(Object.entries(PACK_KEYS).flatMap(([verb, k]) => [[verb, k], [`${verb}.console`, k]])));
|
||||
// #1873 SP8: saving a template and listing the caller's own, the owner's alone. The CLI calls the
|
||||
// unsuffixed name as the owner's human cap, the Console the .console one; no agent, member or tester
|
||||
// reaches either. template.save previews with preview: true and writes with the preview's digest.
|
||||
const TEMPLATE_KEYS = Object.freeze({
|
||||
'template.save': [['name', 'project', 'preview', 'digest'], ['name']],
|
||||
'template.list': [[], []],
|
||||
});
|
||||
export const TEMPLATE_BUS_KEYS = Object.freeze(Object.fromEntries(Object.entries(TEMPLATE_KEYS).flatMap(([verb, k]) => [[verb, k], [`${verb}.console`, k]])));
|
||||
// The codes a template refusal keeps, each with its reason: a field path or a checked name, never a
|
||||
// value from the organization file and never a host path.
|
||||
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
|
||||
// Row 175: the organization verbs a tester may call. Its writes run every check the human's do
|
||||
// and log actor `tester`; row 176 adds routes reads; limits.set, organization.set and organization.revision refuse it.
|
||||
export const TESTER_ORGANIZATION_VERBS = Object.freeze(['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
|
||||
@@ -280,6 +293,11 @@ const fail = (code) => {
|
||||
throw new BusError(code);
|
||||
};
|
||||
const object = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
// #1873 CB5: a copy binding proposal leaves the bus only as its copy and its change. The copy id,
|
||||
// incarnation, definition pin, services, grant ids and slots stay in the raise event, which the
|
||||
// resolve reads; the inbox preview and the trail read carry this summary (design lines 162-163).
|
||||
const bindingSummary = (v) => (object(v?.binding)
|
||||
? { ...v, binding: { instance: v.binding.instance, change: v.binding.after === null ? 'unbind' : 'bind' } } : v);
|
||||
// Lifecycle Task 5a: keep these pure helpers here because broker.mjs is also loaded by the
|
||||
// sandbox client. A new host-only import would widen its mounted source closure.
|
||||
const createJson = value => {
|
||||
@@ -2539,7 +2557,7 @@ export class Broker {
|
||||
options.some(o => !object(o) || !id(o.key) || !text(o.text, 1024)) ||
|
||||
new Set(options.map(o => o.key)).size !== options.length) return null;
|
||||
const digest = sha256(JSON.stringify([{ ...d, options }, raise]));
|
||||
if (['role.hire','role.fire','role.change'].includes(d.action)) return raise.hire ? {kind:'hire',options,...raise.hire} : null;
|
||||
if (['role.hire','role.fire','role.change'].includes(d.action)) return raise.hire ? {kind:'hire',options,...bindingSummary(raise.hire)} : null;
|
||||
if (d.action !== 'credential.mint') return 'grant' in raise ? null : { kind: 'decision', options, digest };
|
||||
if (!object(raise.grant) || typeof raise.grant.method !== 'string' || options.length !== 2) return null;
|
||||
const approve = options.find((o) => o.key === raise.approvalChoice);
|
||||
@@ -6159,28 +6177,6 @@ export class Broker {
|
||||
return result;
|
||||
}).catch(e => { throw this.#refused(s, e instanceof BusError ? e : new BusError(e.code ?? 'request-failed'), request); });
|
||||
}
|
||||
if (request.verb === 'system-types.console') {
|
||||
if (!s.console || s.human !== this.#business(s.business).human) fail('human-required');
|
||||
keys(args, ['project']);
|
||||
if (!this.#organization) fail('not-configured');
|
||||
const enabled = this.#organization(s.business, 'system-types.current', {}, s.human);
|
||||
if (!Array.isArray(enabled)) fail('not-configured');
|
||||
let project = null;
|
||||
if (args.project !== undefined) {
|
||||
const id = identifier(args.project);
|
||||
if (!this.#store.get('SELECT 1 FROM projects WHERE id=? AND business=?', id, s.business)) fail('project-not-found');
|
||||
const row = this.#store.get('SELECT types FROM project_system_types WHERE business=? AND project=? ORDER BY seq DESC LIMIT 1', s.business, id);
|
||||
const selected = row ? JSON.parse(row.types) : [];
|
||||
project = { project: id, selected, active: selected.filter(x => enabled.includes(x)), inactive: selected.filter(x => !enabled.includes(x)) };
|
||||
}
|
||||
return Promise.resolve(this.#organization(s.business, 'system-types.installed', {}, s.human))
|
||||
.then(installed => {
|
||||
if (!Array.isArray(installed)) fail('not-configured');
|
||||
const result = { installed, enabled, project };
|
||||
this.#secretCheck(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
if (request.verb === 'project.remote.get.console' || request.verb === 'project.remote.set.console') {
|
||||
if (!s.console || s.human !== this.#business(s.business).human) fail('human-required');
|
||||
if (!this.#organization) fail('not-configured');
|
||||
@@ -6287,6 +6283,9 @@ export class Broker {
|
||||
if (request.verb === 'hire.raise' || request.verb === 'hire.start.console' ||
|
||||
(request.verb === 'decision.raise' && ['role.hire','role.fire','role.change'].includes(args.action))) {
|
||||
const input=request.verb==='decision.raise' ? (()=>{ keys(args,['action','hire'],['action','hire']); if(args.action!==`role.${args.hire?.op}`)fail('invalid-request'); return args.hire; })() : args;
|
||||
// #1873 SP5: a raise from a pack's recorded proposal; the pin, not the caller, names the role.
|
||||
if(request.verb==='hire.raise' && object(args) && Object.hasOwn(args,'proposal'))
|
||||
return Promise.resolve().then(()=>this.#raiseHire(s,this.#proposalHire(s,args),false)).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
|
||||
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
|
||||
}
|
||||
if(request.verb==='decision.preview.console' && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action))return this.#hireConsole(s,'hire.preview.console',args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
|
||||
@@ -6301,20 +6300,61 @@ export class Broker {
|
||||
if (Object.hasOwn(PACK_BUS_KEYS, request.verb)) {
|
||||
if (s.tester) fail('tester-refused');
|
||||
const owner = this.#business(s.business).human;
|
||||
if (request.verb.endsWith('.console')) { if (!s.console || s.human !== owner) fail('human-required'); }
|
||||
else { this.#human(s); if (s.human !== owner) fail('human-required'); }
|
||||
keys(args, ...PACK_BUS_KEYS[request.verb]);
|
||||
// #1873 SP5: the unsuffixed verbs also serve an agent whose role file lists
|
||||
// organization.change, the test organization.set uses; any other role gets decision-required.
|
||||
// The packs read checks the grant and never spends it, as organization.revision; an agent
|
||||
// without it gets human-required. A write checks before the writer, again inside it, and
|
||||
// spends the grant once the writer has committed. A write the runtime skips (a repeat apply that
|
||||
// adds nothing) never reaches beforeWrite and spends nothing. The actor is the definition and instance.
|
||||
const agent = !request.verb.endsWith('.console') && !s.human && !s.console;
|
||||
let actor = s.human, authorityError = null, wrote = false;
|
||||
if (agent) {
|
||||
keys(args, ...PACK_BUS_KEYS[request.verb]);
|
||||
if (request.verb === 'packs') {
|
||||
this.#processingWork(); this.#agent(s);
|
||||
if (this.#classification(s, 'organization.change') !== 'within-role') fail('human-required');
|
||||
} else this.#checkAuthority(s, 'organization.change');
|
||||
actor = this.#business(s.business).roles[s.role].definition + '.' + s.role;
|
||||
}
|
||||
else {
|
||||
if (request.verb.endsWith('.console')) { if (!s.console || s.human !== owner) fail('human-required'); }
|
||||
else { this.#human(s); if (s.human !== owner) fail('human-required'); }
|
||||
keys(args, ...PACK_BUS_KEYS[request.verb]);
|
||||
}
|
||||
if (!this.#organization) fail('not-configured');
|
||||
const verb = request.verb.replace(/\.console$/, '');
|
||||
const spends = agent && verb !== 'packs' && verb !== 'pack.preview';
|
||||
const agentContext = agent ? { agent: true, beforeWrite: () => { try { this.#checkAuthority(s, 'organization.change'); } catch (e) { authorityError = e; throw e; } wrote = true; } } : {};
|
||||
const packFail = e => { if (authorityError && e === authorityError) throw e; this.#packFail(e); };
|
||||
const openHires = verb === 'pack.preview' || verb === 'pack.apply'
|
||||
? this.#store.all(`SELECT d.id FROM decisions d WHERE d.business=? AND d.action='role.hire' AND NOT EXISTS(SELECT 1 FROM decision_events x WHERE x.decision=d.id AND x.op IN ${CLOSED}) ORDER BY d.at, d.id`, s.business)
|
||||
.map(({ id }) => this.#raised(s.business, id)?.hire).filter(object).map(h => ({ name: h.name, project: h.project ?? null }))
|
||||
: [];
|
||||
let result;
|
||||
try { result = this.#organization(s.business, verb, structuredClone(args), s.human, { openHires }); }
|
||||
catch (e) { this.#packFail(e); }
|
||||
try { result = this.#organization(s.business, verb, structuredClone(args), actor, { openHires, ...agentContext }); }
|
||||
catch (e) { packFail(e); }
|
||||
const done = (value) => {
|
||||
if (spends && wrote) this.#store.transaction(() => this.#consumeAuthority(s, 'organization.change'));
|
||||
this.#secretCheck(value); return value;
|
||||
};
|
||||
return result?.then ? result.then(done, packFail) : done(result);
|
||||
}
|
||||
// #1873 SP8: saving a template. Only the organization's owner: the human cap from the CLI or the
|
||||
// owner's console cap. An agent, a member's cap and the tester are refused before any argument
|
||||
// check. The account the template is saved under is the caller's own s.human.
|
||||
if (Object.hasOwn(TEMPLATE_BUS_KEYS, request.verb)) {
|
||||
if (s.tester) fail('tester-refused');
|
||||
const owner = this.#business(s.business).human;
|
||||
if (request.verb.endsWith('.console')) { if (!s.console || s.human !== owner) fail('human-required'); }
|
||||
else { this.#human(s); if (s.human !== owner) fail('human-required'); }
|
||||
keys(args, ...TEMPLATE_BUS_KEYS[request.verb]);
|
||||
if (!this.#organization) fail('not-configured');
|
||||
const verb = request.verb.replace(/\.console$/, '');
|
||||
let result;
|
||||
try { result = this.#organization(s.business, verb, structuredClone(args), s.human, {}); }
|
||||
catch (e) { this.#templateFail(e); }
|
||||
const done = (value) => { this.#secretCheck(value); return value; };
|
||||
return result?.then ? result.then(done, e => this.#packFail(e)) : done(result);
|
||||
return result?.then ? result.then(done, (e) => this.#templateFail(e)) : done(result);
|
||||
}
|
||||
if (["limits", "limits.set", "organization.set", "organization.revision", "plugins", "plugins.set", "instances", "instances.set", "routes", "routes.set", "veto.set", "library.limits.set"].includes(request.verb) || Object.hasOwn(DEFINITION_BUS_KEYS, request.verb)) {
|
||||
// Row 123 (#1617, REQ-COS-1, REQ-LIMIT-1): organization.set is limits.set for a role whose
|
||||
@@ -6332,7 +6372,7 @@ export class Broker {
|
||||
if (["limits", "plugins", "instances", "routes", "organization.revision"].includes(request.verb)) keys(args, []);
|
||||
else if (request.verb === "plugins.set") {
|
||||
keys(args, ["revision", "plugins", "usage"], ["revision", "plugins"]);
|
||||
if (s.tester && object(args.plugins) && (Object.hasOwn(args.plugins, 'model-provider') || Object.hasOwn(args.plugins, 'system-type'))) fail('human-required');
|
||||
if (s.tester && object(args.plugins) && Object.hasOwn(args.plugins, 'model-provider')) fail('human-required');
|
||||
}
|
||||
// Row 165 (#1662): instances.set is human-only and outside ORGANIZATION_KEYS, so
|
||||
// organization.set and the chief of staff's tool never reach it (sage-0918).
|
||||
@@ -6423,6 +6463,10 @@ export class Broker {
|
||||
if (request.verb === "instances" && result?.instances && typeof result.instances === "object" && this.#business(s.business).copies)
|
||||
result.copies = Object.fromEntries(Object.entries(this.#business(s.business).copies).map(([name, c]) => [name, {
|
||||
...structuredClone(c), running: c.state === 'instance' ? this.#running(s.business, name) : [],
|
||||
// #1873 CB5: a copy that needs a binding (bound at boot, or missing a bindable service)
|
||||
// carries its binding status and next step, fixed text from the launch gate's own checks.
|
||||
// Never to a tester, and never a binding record.
|
||||
...(!s.tester && this.#copyLaunch?.status ? ((binding) => (binding ? { binding } : {}))(this.#copyLaunch.status(s.business, name, c)) : {}),
|
||||
}]));
|
||||
return result;
|
||||
}
|
||||
@@ -6664,6 +6708,54 @@ export class Broker {
|
||||
if(s.human!==this.#business(s.business).human)fail('human-required');
|
||||
return {actor:s.human,agent:false,rights:['org.hire'],owner:true,instanceOwner:true,subject:s.console};
|
||||
}
|
||||
// #1873 SP5 (design section 3, "The chief applying a pack"): hire.raise {proposal: {pack, project?,
|
||||
// hire}, route, reason?}. Only the chief gets this far. The proposal is the latest packs entry of
|
||||
// that pack id and project, in the organization as loaded, whose proposedHires names the hire. Its
|
||||
// pin fills op, name, level and role; a caller's own role, name, level, op, credentials,
|
||||
// personality or binding refuses. A template pin and a definition pin go to prepare as recorded,
|
||||
// which refuses decision-stale and definition-rev-conflict. An inline pin is checked here: the
|
||||
// stored entry must still hash to the pin (starter-pack-proposal-stale), and its from template
|
||||
// must not be in launch.noHire (definition-not-hireable), since prepare's own noHire check
|
||||
// reads only a template or definition ref. The returned input carries no proposal key, so
|
||||
// prepare's request keys are unchanged. reason defaults to the one the pack recorded. The chief
|
||||
// check and the role.hire check run before the packs list is read, so neither a non-chief nor a
|
||||
// chief without role.hire learns whether a proposal exists.
|
||||
#proposalHire(s, args) {
|
||||
this.#agent(s);
|
||||
const b = this.#business(s.business);
|
||||
if (s.role !== b.launch?.by) fail('role-not-chief');
|
||||
if (this.#classification(s, 'role.hire') !== 'within-role') fail('not-authorized');
|
||||
keys(args, ['proposal', 'route', 'reason'], ['proposal', 'route']);
|
||||
const proposal = args.proposal;
|
||||
keys(proposal, ['pack', 'project', 'hire'], ['pack', 'hire']);
|
||||
for (const value of [proposal.pack, proposal.hire, ...(Object.hasOwn(proposal, 'project') ? [proposal.project] : [])])
|
||||
if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(value)) fail('invalid-request');
|
||||
const project = proposal.project ?? null;
|
||||
const entry = (Array.isArray(b.packs) ? b.packs : [])
|
||||
.filter(e => e?.id === proposal.pack && (e.project ?? null) === project && Array.isArray(e.proposedHires) && e.proposedHires.some(h => h?.name === proposal.hire))
|
||||
.at(-1);
|
||||
if (!entry) fail('invalid-request');
|
||||
const hire = entry.proposedHires.find(h => h.name === proposal.hire);
|
||||
const pin = hire.pin;
|
||||
if (!object(pin)) fail('invalid-request');
|
||||
let role;
|
||||
if (Object.hasOwn(pin, 'inline')) {
|
||||
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
|
||||
// The broker's sandbox import closure is fixed, so the digest and the composition are local
|
||||
// copies: canonical is organization util.mjs canonicalJson, built as a string so integer-like
|
||||
// keys keep the sorted order (an object would put them first), and the composition is
|
||||
// definitions.mjs compositionOf.
|
||||
const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : object(v)
|
||||
? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v);
|
||||
if (sha256(canonical(hire.entry)) !== pin.sha256) fail('starter-pack-proposal-stale');
|
||||
const from = hire.entry.from?.template;
|
||||
if (from !== undefined && (b.launch?.noHire ?? []).includes(from)) fail('definition-not-hireable');
|
||||
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
|
||||
role = { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
|
||||
} else role = structuredClone(pin);
|
||||
const reason = Object.hasOwn(args, 'reason') ? args.reason : hire.reason;
|
||||
return { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason };
|
||||
}
|
||||
async #raiseHire(s, input, immediate) {
|
||||
const b=this.#business(s.business);
|
||||
// Change is a replacement composition and uses the existing role.hire grant.
|
||||
@@ -6705,7 +6797,7 @@ export class Broker {
|
||||
this.#event(s,'action.allowed',{operation:'decision.raise',decision:did,action,approvalChoice:'yes',target:p.name,hire:p,autonomyLevel:level},did);
|
||||
});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest});
|
||||
return {...this.#decisionView(this.#decision(s,did)),hire:p};
|
||||
return {...this.#decisionView(this.#decision(s,did)),hire:bindingSummary(p)};
|
||||
}
|
||||
// The harness fact comes from the host's loaded modules; no host, no account coverage.
|
||||
#budgetCovered(b) { return authorityBudgetCovered(b,{countsAccount:this.#autonomyHost?.countsAccount}); }
|
||||
@@ -6929,6 +7021,18 @@ export class Broker {
|
||||
if (e?.name === 'BusinessError') fail('invalid-request');
|
||||
throw new BusError('outcome-unknown');
|
||||
}
|
||||
// #1873 SP8: a template refusal keeps its code and its reason (a path, never the text); anything
|
||||
// else is read as a pack refusal.
|
||||
#templateFail(e) {
|
||||
if (e?.name === 'TemplateError' && TEMPLATE_CODES.includes(e.code)) {
|
||||
// A reason names a field path or a definition name; one that would quote a held value is dropped.
|
||||
// The check reads the whole reason before the cut, so a held value cut short is still found.
|
||||
let reason = typeof e.reason === 'string' ? e.reason : undefined;
|
||||
if (reason !== undefined) try { this.#secretCheck(reason); reason = reason.slice(0, 300); } catch { reason = undefined; }
|
||||
throw new BusError(e.code, reason);
|
||||
}
|
||||
this.#packFail(e);
|
||||
}
|
||||
// The bus code for an organization writer's refusal. Anything the writer didn't refuse by name is
|
||||
// outcome-unknown: the write may have committed.
|
||||
#organizationFail(e, verb) {
|
||||
@@ -8589,25 +8693,6 @@ export class Broker {
|
||||
.filter((p) => !s.user || this.#granted(s, 'project.list', p.id, null))
|
||||
.map((p) => (p.state === 'archive' ? { id: p.id, at: p.at, name: p.name, repo: p.repo, archived: true } : { id: p.id, at: p.at, name: p.name, repo: p.repo }));
|
||||
}
|
||||
case 'project.system-types':
|
||||
case 'project.system-types.set': {
|
||||
this.#human(s);
|
||||
const write = verb === 'project.system-types.set';
|
||||
keys(a, write ? ['project', 'systemTypes'] : ['project'], write ? ['project', 'systemTypes'] : ['project']);
|
||||
const project = identifier(a.project);
|
||||
if (!this.#store.get('SELECT 1 FROM projects WHERE id=? AND business=?', project, s.business)) fail('project-not-found');
|
||||
// When configured, read the trusted file each time; a stale bus snapshot must not reactivate a disabled type.
|
||||
const enabled = this.#organization ? this.#organization(s.business, 'system-types.current', {}, s.human) : (b.plugins?.['system-type'] ?? []);
|
||||
if (!Array.isArray(enabled)) fail('not-configured');
|
||||
if (write) {
|
||||
if (!Array.isArray(a.systemTypes) || a.systemTypes.some(x => typeof x !== 'string') || new Set(a.systemTypes).size !== a.systemTypes.length) fail('invalid-request');
|
||||
if (a.systemTypes.some(x => !enabled.includes(x))) fail('system-type-not-enabled');
|
||||
this.#store.run('INSERT INTO project_system_types(at,business,project,types,by) VALUES(?,?,?,?,?)', this.#now(), s.business, project, JSON.stringify(a.systemTypes), this.#owner(s));
|
||||
}
|
||||
const row = this.#store.get('SELECT types FROM project_system_types WHERE business=? AND project=? ORDER BY seq DESC LIMIT 1', s.business, project);
|
||||
const selected = row ? JSON.parse(row.types) : [];
|
||||
return { project, selected, active: selected.filter(x => enabled.includes(x)), inactive: selected.filter(x => !enabled.includes(x)) };
|
||||
}
|
||||
// #797 MVP3 (owner report 2026-11-06): the owner's reversible retirement of a project. The
|
||||
// human gate is project.create's minus the tester carve-out: tester, user and agent sessions
|
||||
// are refused here. Each verb appends one project_archives row (the audit trail) and deletes
|
||||
@@ -9404,6 +9489,7 @@ export class Broker {
|
||||
try {
|
||||
r[k] = JSON.parse(r[k]);
|
||||
} catch {}
|
||||
if (table === 'events' && object(r.body?.hire)) r.body = { ...r.body, hire: bindingSummary(r.body.hire) };
|
||||
rows.set(table + ':' + row.seq, r);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -37,6 +37,7 @@ import { boundRepositories, tokenLevels, verifyGiteaToken } from './copy-grant.m
|
||||
import { readOrgEntrySync } from '../../organization/src/org-registry.mjs';
|
||||
import { allGranted, CAUSE_CODES, copyBotLogin, definitionPin, resolveCopyBinding } from '../../organization/src/copy-bindings.mjs';
|
||||
import { COPY_BINDABLE, materializeCopies } from '../../organization/src/agent-copies.mjs';
|
||||
import { copyBindingStatus } from '../../organization/src/copy-binding-status.mjs';
|
||||
import { checkDefinitions, readTemplate } from '../../organization/src/definitions.mjs';
|
||||
import { loadRole } from '../../organization/src/role.mjs';
|
||||
import { resolveAgentLevels } from '../../organization/src/agent-levels.mjs';
|
||||
@@ -376,6 +377,34 @@ export function copyLaunchGate({ credentials, writer, configDir, rolesDir, snaps
|
||||
if (current(business, instance).authority !== digest) deny('copy-authority-changed');
|
||||
sameRevision(business, revision);
|
||||
},
|
||||
// CB5: the copy's binding status for its owner's views, as copy-binding-status.mjs's fixed
|
||||
// { status, next }. The same checks a launch runs, without the loss report (the sweep makes it)
|
||||
// and without returning anything the check read. An approved binding not yet issued, or one a
|
||||
// refused issue left pending, needs the owner's issue before anything else. `entry` is the copy's
|
||||
// boot entry: only one bound at boot, or unbound for want of a service, has a status. One that
|
||||
// lacks a service a copy cannot bind is refused at boot whatever it binds (above), so it reads
|
||||
// copy-service-unbindable and never asks for a gitea binding, unless a revoke of a binding it
|
||||
// was issued anyway is running or failed: that state is the owner's next step.
|
||||
status(business, instance, entry) {
|
||||
const unbound = entry?.state === 'unbound' && Array.isArray(entry.missing) && entry.missing.length > 0;
|
||||
if (!Array.isArray(entry?.bound) && !unbound) return null;
|
||||
const revoking = business === org && (Boolean(fences.get(instance)) || closed.has(instance));
|
||||
if (unbound && !revoking && entry.missing.some((s) => !COPY_BINDABLE.includes(s))) return copyBindingStatus('copy-service-unbindable');
|
||||
let code = 'ready';
|
||||
try {
|
||||
check(business, instance);
|
||||
} catch (e) {
|
||||
code = typeof e?.code === 'string' ? e.code : 'credential-unavailable';
|
||||
}
|
||||
if (['credential-unbound', 'credential-revoked', 'restart-required'].includes(code)) {
|
||||
let record = null;
|
||||
try {
|
||||
record = read(business).copyBindings?.[instance];
|
||||
} catch {}
|
||||
if (object(record) && record.state === 'pending') code = 'issue-required';
|
||||
}
|
||||
return copyBindingStatus(code);
|
||||
},
|
||||
revoking: (business, instance) => business === org && (Boolean(fences.get(instance)) || closed.has(instance)),
|
||||
// CB4: shut the copy before its revoke publishes anything. It admits nothing and every check
|
||||
// answers `code` until open(); the boot's proof of it is forgotten, so nothing reopens it but a
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- #1873 SP9: the system-type kind is removed outright (Jason, 2026-11-12: "The only deployed
|
||||
-- system is the dev environment on dragon-lin. It can be wiped and reconfigured. No reason to hold
|
||||
-- on to legacy for this change."). This step drops what 3t-3u created: the four guards, the index
|
||||
-- and the table, with its rows. It is the one deletion of append-only rows in that go, and the
|
||||
-- ruling is its authority. SQLite removes the table's sqlite_sequence row with the table.
|
||||
DROP TRIGGER project_system_types_no_update;
|
||||
DROP TRIGGER project_system_types_no_delete;
|
||||
DROP TRIGGER project_system_types_no_replace;
|
||||
DROP TRIGGER project_system_types_business;
|
||||
DROP INDEX project_system_types_project;
|
||||
DROP TABLE project_system_types;
|
||||
@@ -183,7 +183,7 @@ group(
|
||||
"Read my_rails and use the applicable decision path; ask the owner to inspect grants if no supported path exists."
|
||||
);
|
||||
group(
|
||||
"not-configured project-already-archived project-archived project-exists project-not-archived project-not-configured project-not-found project-record-invalid project-remote-configured project-remote-invalid project-remote-library project-remote-protected project-remote-unknown project-spec-human-only system-type-not-enabled tracker-not-store usage-not-configured",
|
||||
"not-configured project-already-archived project-archived project-exists project-not-archived project-not-configured project-not-found project-record-invalid project-remote-configured project-remote-invalid project-remote-library project-remote-protected project-remote-unknown project-spec-human-only tracker-not-store usage-not-configured",
|
||||
"R3/role scope: configured project and service state",
|
||||
"Read the supported project/service status and ask its owner to repair missing configuration or state before retrying."
|
||||
);
|
||||
@@ -211,6 +211,20 @@ group(
|
||||
"R8: apply writes only the plan its digest names",
|
||||
"The organization file or the pack changed since the preview. Preview again and apply the new digest."
|
||||
);
|
||||
// #1873 SP5: a hire raised from a pack proposal is the role the proposal pinned. An inline pin is the
|
||||
// canonical hash of the entry stored beside it; a stored entry that no longer hashes to it refuses.
|
||||
group(
|
||||
"starter-pack-proposal-stale",
|
||||
"R8: a hire raised from a pack proposal matches its recorded pin",
|
||||
"The role entry stored with this proposal no longer matches the hash it was recorded with. Preview and apply the pack again for a fresh proposal, then raise the hire from that one."
|
||||
);
|
||||
// #1873 SP8: a saved template carries no credential the bus holds. Save checks every kept string and
|
||||
// key against the credential store; a hit names the field, never the text.
|
||||
group(
|
||||
"template-secret-suspected",
|
||||
"R1/R10: a saved template carries no credential value the bus holds",
|
||||
"A field the template would keep holds a credential value. Remove it from the named definition, board or workflow text, then preview and save again."
|
||||
);
|
||||
group(
|
||||
"not-resolver",
|
||||
"Role resolve right and decision route",
|
||||
|
||||
@@ -27,7 +27,6 @@ import { readSessions, sessionsFile, stopSession } from '../../seat/src/session.
|
||||
import { compactionCount, storeDir } from '../../seat/src/compactions.mjs';
|
||||
import { publishRemote, workingRepo, WorkingError } from '../../seat/src/working.mjs';
|
||||
import { createLoader, hasModule } from '../../plugins/src/loader.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
import { pluginSettings } from '../../organization/src/plugin-settings.mjs';
|
||||
import { loadManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { ProxyPage } from './proxy-page.mjs';
|
||||
@@ -42,6 +41,7 @@ import { organizationWriter, OrganizationError, setReplyLimits } from '../../org
|
||||
import { definitionVerbs, DEFINITION_BUS_VERBS } from '../../organization/src/definition-verbs.mjs';
|
||||
import { ORG_PREFIX, orgDefinitionName, compositionOf, readTemplate, entryFromTemplate, lineDiff, PRIMITIVES } from '../../organization/src/definitions.mjs';
|
||||
import { installedStarterPacks, readSavedTemplate } from '../../plugins/src/starter-pack.mjs';
|
||||
import { TemplateError, templateList, templatePreview, templateSave } from '../../organization/src/template-save.mjs';
|
||||
import { checkComposition } from '../../organization/src/composition.mjs';
|
||||
import { validateBusinessDocument } from '../../organization/src/organization-config.mjs';
|
||||
import { DEFINITION_HOLDS_CREDENTIAL, heldPath, scanDefinitions } from './definition-scan.mjs';
|
||||
@@ -351,7 +351,18 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
// A saved template may reuse a shipped id, so the origin is part of the key.
|
||||
const sameApply = (e, id, origin, project) => e.id === id && e.origin === origin && (e.project ?? null) === project;
|
||||
const tombstones = (doc, id, origin, project) => new Set((doc.packs ?? []).filter(e => sameApply(e, id, origin, project)).flatMap(e => e.added ?? []));
|
||||
// #1873 SP5 (design section 3, "The chief applying a pack"): context.agent is an
|
||||
// organization.change holder's call. It names no saved template and no definitions rename
|
||||
// (human-required), and its plan writes no definition: a definition a human apply would add is
|
||||
// marked not-written, and its hire proposal pins the template or the inline entry, which the chief
|
||||
// raises as a hire decision. A workflow step naming a pack definition the organization does not
|
||||
// hold and that is not a V2 template is left out and listed; a workflow left with no step is
|
||||
// marked left-out and not written. applyPack refuses an agent's definitions or saved origin
|
||||
// whatever this builds.
|
||||
async function build(id, args, actor, context) {
|
||||
const agent = context?.agent === true;
|
||||
if (agent && typeof args.pack === 'string' && args.pack.startsWith(SAVED_PREFIX)) throw new BusError('human-required');
|
||||
if (agent && Array.isArray(args.as) && args.as.some(v => typeof v === 'string' && v.startsWith('definitions.'))) throw new BusError('human-required');
|
||||
const { document: doc, revision } = writer.read(id);
|
||||
const found = await loadPack(args.pack, actor);
|
||||
const pack = found.pack;
|
||||
@@ -379,6 +390,16 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
const chief = chiefOf(doc, `${id}.json`);
|
||||
const registry = registryFor(doc);
|
||||
const noHire = doc.launch?.noHire ?? [];
|
||||
const templates = new Map();
|
||||
const isTemplate = name => {
|
||||
if (!templates.has(name)) {
|
||||
try { readTemplate(rolesDir, name); templates.set(name, true); } catch (error) {
|
||||
if (error?.name !== 'BusinessError') throw error;
|
||||
templates.set(name, false);
|
||||
}
|
||||
}
|
||||
return templates.get(name);
|
||||
};
|
||||
const items = [];
|
||||
const plan = {};
|
||||
// Definitions are organization-wide in either scope: a project's agents name org definitions.
|
||||
@@ -400,6 +421,7 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
const primitives = PRIMITIVES.filter(k => canonicalJson(before[k] ?? null) !== canonicalJson(after[k] ?? null));
|
||||
item.diff = { primitives, instructions: primitives.includes('instructions') ? lineDiff(before.instructions, after.instructions) : [] };
|
||||
}
|
||||
if (agent && mark === 'add') item.mark = mark = 'not-written';
|
||||
if (mark === 'add') definitions[target] = entry;
|
||||
checked[name].added = mark === 'add';
|
||||
items.push(item);
|
||||
@@ -423,11 +445,24 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
const workflow = { description: value.description, steps: value.steps.map(s => ({ title: s.title, state: s.state, roles: s.roles.map(role) })) };
|
||||
if (workflow.steps.some(s => new Set(s.roles).size !== s.roles.length)) bad();
|
||||
const path = `${prefix}workflows.${target}`;
|
||||
const leftOut = [];
|
||||
if (agent) {
|
||||
// A step keeps a pack role the organization already defines, or one the pack itself pins to the
|
||||
// template of that name. An inline definition that only shares a template's name is left out.
|
||||
const unwritable = r => r !== 'human' && Object.hasOwn(pack.definitions, r) && !Object.hasOwn(doc.definitions ?? {}, role(r))
|
||||
&& !(checked[r].ref?.template === role(r) && isTemplate(role(r)));
|
||||
workflow.steps = workflow.steps.filter((s, i) => {
|
||||
const missing = value.steps[i].roles.filter(unwritable).map(role);
|
||||
if (missing.length) leftOut.push({ step: i + 1, title: s.title, roles: missing });
|
||||
return missing.length === 0;
|
||||
});
|
||||
}
|
||||
const current = scope.workflows?.[target];
|
||||
let mark;
|
||||
if (current === undefined) mark = gone.has(path) ? 'removed' : 'add';
|
||||
if (agent && workflow.steps.length === 0) mark = 'left-out';
|
||||
else if (current === undefined) mark = gone.has(path) ? 'removed' : 'add';
|
||||
else mark = canonicalJson(current) === canonicalJson(workflow) ? 'same' : 'kept';
|
||||
items.push({ item: 'workflow', name, target, path, mark });
|
||||
items.push({ item: 'workflow', name, target, path, mark, ...(leftOut.length ? { leftOut } : {}) });
|
||||
if (mark === 'add') workflows[target] = workflow;
|
||||
}
|
||||
if (Object.keys(workflows).length) plan[`${prefix}workflows`] = workflows;
|
||||
@@ -453,7 +488,10 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
items, hires, skills: { notEnabled }, chief: chief !== null, plan, digest,
|
||||
};
|
||||
}
|
||||
const write = (id, plan, revision, actor, detail) => {
|
||||
// context.beforeWrite (SP5) is the broker's recheck of an agent's organization.change grant,
|
||||
// run once more before the writer commits.
|
||||
const write = (id, plan, revision, actor, detail, context) => {
|
||||
context?.beforeWrite?.();
|
||||
const out = writer.applyPack(id, plan, { revision, actor, assertClean, detail });
|
||||
return { revision: out.revision, added: out.added };
|
||||
};
|
||||
@@ -479,15 +517,15 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
if (Object.keys(plan).every(k => k === 'packs') && last && last.sha256 === plan.packs.sha256
|
||||
&& canonicalJson(last.proposedHires ?? []) === canonicalJson(plan.packs.proposedHires))
|
||||
return { revision: preview.revision, added: [], pack: preview.pack.id };
|
||||
return { ...write(id, plan, preview.revision, actor, {}), pack: preview.pack.id };
|
||||
return { ...write(id, plan, preview.revision, actor, {}, context), pack: preview.pack.id };
|
||||
},
|
||||
'board.set': (id, args, actor) => {
|
||||
'board.set': (id, args, actor, context) => {
|
||||
if (args.board !== null && !isObject(args.board)) bad();
|
||||
return write(id, { [scoped(args, 'board')]: args.board }, revisionOf(args), actor, {});
|
||||
return write(id, { [scoped(args, 'board')]: args.board }, revisionOf(args), actor, {}, context);
|
||||
},
|
||||
'workflow.set': (id, args, actor) => {
|
||||
'workflow.set': (id, args, actor, context) => {
|
||||
if (typeof args.name !== 'string' || (args.workflow !== null && !isObject(args.workflow))) bad();
|
||||
return write(id, { [scoped(args, 'workflows')]: { [args.name]: args.workflow } }, revisionOf(args), actor, {});
|
||||
return write(id, { [scoped(args, 'workflows')]: { [args.name]: args.workflow } }, revisionOf(args), actor, {}, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1140,6 +1178,7 @@ export async function startBroker({
|
||||
}
|
||||
// #1873 SP4: the human's pack, board and workflow ops. The broker passes only the business's human;
|
||||
// the reads return here, and each write reloads the organization and refreshes its limit checks.
|
||||
// SP5: or an organization.change holder's actor, with context.agent and context.beforeWrite.
|
||||
if (Object.hasOwn(PACK_OPS, verb)) {
|
||||
const ops = packOps({ writer: organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir}), rolesDir: organization.rolesDir, dataRoot: instanceRoot ?? dataRoot,
|
||||
system: organization.system, registryFor: doc => organizationPlugins(instanceRoot ?? dataRoot, doc.plugins).registry, assertClean: value => credentials.assertClean(value), configDir: organization.dir });
|
||||
@@ -1148,8 +1187,18 @@ export async function startBroker({
|
||||
const committed = value => { reload(id); limits.refresh(id).catch(e=>limitLog({event:'limit-refresh-failed',business:id,message:e.message})); return value; };
|
||||
return out?.then ? out.then(committed) : committed(out);
|
||||
}
|
||||
if (verb === 'system-types.installed') return installedSystemTypes({dataRoot:instanceRoot ?? dataRoot});
|
||||
if (verb === 'system-types.current') return settings.current(id).plugins?.['system-type'] ?? [];
|
||||
// #1873 SP8: saving a template and listing the owner's own. The broker passes only the owner's
|
||||
// human; both read the organization file and neither writes it, so nothing reloads.
|
||||
if (verb === 'template.save' || verb === 'template.list') {
|
||||
const base = { rolesDir: organization.rolesDir, configDir: organization.dir, account: actor };
|
||||
if (verb === 'template.list') return templateList(base);
|
||||
const { name, project, preview, digest } = args;
|
||||
const document = organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir}).read(id).document;
|
||||
const assertClean = value => credentials.assertClean(value);
|
||||
if (preview === true && digest === undefined) return templatePreview({ document, name, project, rolesDir: organization.rolesDir, assertClean });
|
||||
if (preview === undefined && typeof digest === 'string') return templateSave({ ...base, document, name, project, digest, assertClean });
|
||||
throw new TemplateError('invalid-request', 'template.save takes preview: true or the preview digest');
|
||||
}
|
||||
if(verb==='limits')return withTokens(id,settings.read(id));
|
||||
if(verb==='plugins')return {...plugins.read(id), available:{harness:levels.names ?? []}};
|
||||
// Row 256 (#1761): the actor is the reader, so endProtected is the delete check for that reader.
|
||||
|
||||
@@ -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 = 'e5868996851ee60a3c6d2798a17b9da446ba666c859d84d1b575ca5104ae61f8';
|
||||
export const SCHEMA_VERSION = '3v';
|
||||
export const SCHEMA_SHA256 = '1c305d842619360c14c8388cd43cb9de81afbe46ff0662fd5de9851be9ff3ea0';
|
||||
export const SCHEMA_VERSION = '3w';
|
||||
// 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';
|
||||
@@ -120,6 +120,11 @@ const migrations = [{
|
||||
// Only a new append-only table, its index and its guards; no existing row changes.
|
||||
from: '3u', to: '3v',
|
||||
sql: readFileSync(new URL('./migrations/3u-3v.sql', import.meta.url), 'utf8'),
|
||||
}, {
|
||||
// SP9 (#1873, Jason's ruling 2026-11-12): drops the table 3t-3u created, its index and its four
|
||||
// guards, with its rows.
|
||||
from: '3v', to: '3w',
|
||||
sql: readFileSync(new URL('./migrations/3v-3w.sql', import.meta.url), 'utf8'),
|
||||
}];
|
||||
const timedTables = [
|
||||
'events',
|
||||
@@ -146,7 +151,6 @@ const timedTables = [
|
||||
'request_snapshot_events',
|
||||
'request_project_events',
|
||||
'project_archives',
|
||||
'project_system_types',
|
||||
'store_tasks',
|
||||
];
|
||||
const hex = (value) => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
@@ -19,7 +19,7 @@ const here = (p) => new URL(p, import.meta.url);
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function source3h(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'account-migrate-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
@@ -96,6 +96,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
|
||||
@@ -103,7 +104,7 @@ test('REQ-LIMIT-4 3h copy migrates to 3i: every row keeps its seq, the sequence
|
||||
const { root, path } = source3h(t), before = snapshot(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
// Every table's rows as they were, usage_records with its seq values and sqlite_sequence with 50.
|
||||
assert.deepEqual(migrated3l(snapshot(path, before.columns).rows), before.rows);
|
||||
assert.deepEqual(before.rows.usage_records.map(r => r.seq), [1, 2, 3]);
|
||||
@@ -153,7 +154,7 @@ test('REQ-LIMIT-4 a 3h→3i step that fails partway leaves the store at 3h with
|
||||
assert.deepEqual(snapshot(path, before.columns).rows, before.rows);
|
||||
// Still a whole 3h store: the real step migrates it.
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(snapshot(path, before.columns).rows), before.rows);
|
||||
});
|
||||
|
||||
@@ -165,14 +166,14 @@ test('REQ-LIMIT-4 the 3h engine refuses a migrated store, migrating or not, and
|
||||
schema: ddl3h,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3h).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3h';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3h';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 126 \(#1620\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3h/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3h';") && !pinned.includes('3h-3i'), 'the 3h engine has no 3h→3i step');
|
||||
assert.throws(() => new Store3h(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3h(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(snapshot(path, after.columns).rows, after.rows);
|
||||
});
|
||||
@@ -615,7 +615,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 = '3v';", "export const SCHEMA_VERSION = '3c';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "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');
|
||||
@@ -639,7 +639,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, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
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 });
|
||||
|
||||
@@ -33,7 +33,7 @@ test('explicit 3b copy migration preserves evidence and opens as 3g; 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, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
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;
|
||||
@@ -75,15 +75,15 @@ test('named migration registry chains 3b through 3g 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 = '3v';", "export const SCHEMA_VERSION = '3w';")
|
||||
.replace('}];\nconst timedTables', `}, { from: '3v', to: '3w', sql: ${JSON.stringify(futureSQL)} }];\nconst timedTables`);
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3x';")
|
||||
.replace('}];\nconst timedTables', `}, { from: '3w', to: '3x', 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', '3e-3f.sql', '3f-3g.sql', '3g-3h.sql', '3h-3i.sql', '3i-3j.sql', '3j-3k.sql', '3k-3l.sql', '3l-3m.sql', '3m-3n.sql', '3n-3o.sql', '3o-3p.sql', '3p-3q.sql', '3q-3r.sql', '3r-3s.sql', '3s-3t.sql', '3t-3u.sql', '3u-3v.sql'])
|
||||
for (const name of ['3b.sql', '3b-3c.sql', '3c-3d.sql', '3d-3e.sql', '3e-3f.sql', '3f-3g.sql', '3g-3h.sql', '3h-3i.sql', '3i-3j.sql', '3j-3k.sql', '3k-3l.sql', '3l-3m.sql', '3m-3n.sql', '3n-3o.sql', '3o-3p.sql', '3p-3q.sql', '3q-3r.sql', '3r-3s.sql', '3s-3t.sql', '3t-3u.sql', '3u-3v.sql', '3v-3w.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, '3w');
|
||||
assert.equal(future.get("SELECT value FROM meta WHERE key='schema_version'").value, '3x');
|
||||
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 3v ready/);
|
||||
assert.match(migrated.stdout, /bus schema 3w ready/);
|
||||
new Store(root).close();
|
||||
const usage = spawnSync(process.execPath, [command], { encoding: 'utf8' });
|
||||
assert.equal(usage.status, 2);
|
||||
|
||||
@@ -89,10 +89,12 @@ function setup(t) {
|
||||
// #797 / #1839 adds the owner-only artifact read to the existing decision and request controls;
|
||||
// no unsuffixed verb is ever a console verb.
|
||||
test('N4: owner Console verbs have an explicit immutable whitelist and exclude decision.resolve', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console']);
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
// Starter packs SP8 (#1873): the owner saves and lists templates.
|
||||
'template.save.console', 'template.list.console']);
|
||||
assert.ok(CONSOLE_VERBS.every(verb => verb.endsWith('.console')));
|
||||
assert.equal(CONSOLE_VERBS.includes('decision.resolve'), false);
|
||||
assert.ok(Object.isFrozen(CONSOLE_VERBS));
|
||||
|
||||
@@ -133,3 +133,52 @@ test('CB1 bus: every new refusal has a table entry with a next step', () => {
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[code].nextStep), code);
|
||||
}
|
||||
});
|
||||
|
||||
// #1873 CB5 (security review P2-1, P3-1): the binding record the raise holds (copy id, incarnation,
|
||||
// definition pin, services, grant ids) leaves the bus only through the owner's preview verb. The
|
||||
// raise answer, the inbox preview and the trail give every other session the copy and the change.
|
||||
test('CB5 bus: the raise answer, the inbox preview and the trail carry a binding as its copy and change only', async t => {
|
||||
const f = await fixture(t);
|
||||
const d = await f.raise();
|
||||
const raised = f.store.all('SELECT body FROM events').map((e) => JSON.parse(e.body)).find((b) => b.operation === 'decision.raise' && b.decision === d.id);
|
||||
const held = raised.hire.binding;
|
||||
assert.equal(typeof held.copyId, 'string');
|
||||
const secrets = [held.copyId, held.orgIncarnation, held.definition?.sha256].filter((v) => typeof v === 'string' && v.length >= 8);
|
||||
assert.equal(secrets.length, 3);
|
||||
const summary = { instance: 'rev', change: 'bind' };
|
||||
assert.deepEqual(d.hire.binding, summary);
|
||||
const sessions = { owner: f.b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }), tester: f.b.bindTester({ business: 'demo' }), reader: f.b.bindReader({ business: 'demo' }), chief: f.caps.chief, coder: f.caps.coder };
|
||||
const seen = [JSON.stringify(d)];
|
||||
for (const name of ['owner', 'tester', 'reader']) {
|
||||
const rows = await f.call(sessions[name], 'inbox');
|
||||
const row = rows.find((r) => r.id === d.id);
|
||||
assert.deepEqual(row?.console?.binding, summary, `${name} inbox`);
|
||||
seen.push(JSON.stringify(rows));
|
||||
}
|
||||
for (const name of Object.keys(sessions)) {
|
||||
const trail = await f.call(sessions[name], 'trail', { subject: d.id });
|
||||
const ev = trail.find((r) => r.table === 'events' && r.body?.operation === 'decision.raise');
|
||||
assert.deepEqual(ev?.body?.hire?.binding, summary, `${name} trail`);
|
||||
seen.push(JSON.stringify(trail));
|
||||
}
|
||||
for (const text of seen) for (const v of secrets) assert.equal(text.includes(v), false);
|
||||
// The owner's preview still has the record, and the resolve (which reads the raise) still writes it.
|
||||
const preview = await f.call(f.owner, 'hire.preview.console', { id: d.id });
|
||||
assert.equal(preview.binding.copyId, held.copyId);
|
||||
await f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest: d.hire.digest });
|
||||
assert.equal(f.bindings().rev.state, 'pending');
|
||||
const after = JSON.stringify(await f.call(sessions.tester, 'trail', { subject: d.id }));
|
||||
for (const v of secrets) assert.equal(after.includes(v), false);
|
||||
// An unbind of that binding reads as an unbind in the raise answer, the inbox and the trail.
|
||||
const u = await f.raise({ binding: { services: null } });
|
||||
const unbind = { instance: 'rev', change: 'unbind' };
|
||||
assert.deepEqual(u.hire.binding, unbind);
|
||||
for (const name of ['owner', 'tester', 'reader']) {
|
||||
const row = (await f.call(sessions[name], 'inbox')).find((r) => r.id === u.id);
|
||||
assert.deepEqual(row?.console?.binding, unbind, `${name} inbox unbind`);
|
||||
}
|
||||
for (const name of Object.keys(sessions)) {
|
||||
const ev = (await f.call(sessions[name], 'trail', { subject: u.id })).find((r) => r.table === 'events' && r.body?.operation === 'decision.raise');
|
||||
assert.deepEqual(ev?.body?.hire?.binding, unbind, `${name} trail unbind`);
|
||||
}
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import { loadWithCopies, materializeCopies, promoteCopies } from '../../organiza
|
||||
import { activateOrg, listOrgs, readOrgEntrySync, reserveOrg } from '../../organization/src/org-registry.mjs';
|
||||
import * as orgService from '../../organization/src/org-service.mjs';
|
||||
import { copyBotLogin } from '../../organization/src/copy-bindings.mjs';
|
||||
import { COPY_BINDING_STATUS } from '../../organization/src/copy-binding-status.mjs';
|
||||
import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' };
|
||||
@@ -62,7 +63,7 @@ async function world(t) {
|
||||
// they stand, as a restart of the bus process would; boot() runs the gate's boot proof and promotes.
|
||||
// stopRuns acknowledges each run the broker told the launcher to kill, as the launcher's exit does,
|
||||
// unless `ack` is false. The revoke's remote step goes to the organization's admin slot.
|
||||
async function org(t, w, { id = 'demo', name = 'rev', services = READ, perm = 'read', definition = 'research', admin = true, adminRotateBy = ahead(60), stopMs = 2000, project = null, gitOnly = false } = {}) {
|
||||
async function org(t, w, { id = 'demo', name = 'rev', services = READ, perm = 'read', definition = 'research', admin = true, adminRotateBy = ahead(60), stopMs = 2000, project = null, gitOnly = false, definitions = null } = {}) {
|
||||
const { root, rolesDir, api } = w;
|
||||
const owner = id === 'demo' ? 'owner' : id;
|
||||
const doc = { ...businessDoc(root, id), plugins: { harness: ['pi'] }, vars: { 'bus.tester': true } };
|
||||
@@ -72,6 +73,7 @@ async function org(t, w, { id = 'demo', name = 'rev', services = READ, perm = 'r
|
||||
// The project root the organization service derives (archive and delete check it).
|
||||
doc.projects.stack.root = join(w.data, 'org-runtime', id, 'projects', 'stack');
|
||||
if (project) doc.projects.stack.agents = project;
|
||||
if (definitions) doc.definitions = definitions;
|
||||
const file = writeJson(join(root, `businesses/${id}.json`), doc);
|
||||
chmodSync(join(root, 'businesses'), 0o700);
|
||||
const ctx = { configDir: root, dataRoot: w.data, instance: 'test', principal: LOCAL };
|
||||
@@ -746,3 +748,95 @@ test('CB4 a second organization launches and calls throughout the first one\'s r
|
||||
assert.ok(existsSync(acme.slot));
|
||||
assert.deepEqual(demo.bot.tokens, []);
|
||||
});
|
||||
|
||||
// #1873 CB5 (CB4 review P3-1): the gate finds a shadowing name only in the organization it serves,
|
||||
// and the runtime gives a gate only to a boot that made a copy (cli config.mjs bootConfig passes no
|
||||
// snapshot otherwise). A named instance the owner wrote over the only copy while the bus was down
|
||||
// leaves the next start with no copy and no gate; only the revoker's own sweep then finds the former
|
||||
// copy's record and ends its binding.
|
||||
test('CB5 shadowing in an organization no gate serves: only the revoker\'s own sweep finds the former copy, and it revokes the binding', async (t) => {
|
||||
const w = await world(t);
|
||||
const f = await org(t, w);
|
||||
await f.bind();
|
||||
assert.equal(f.rec().state, 'bound');
|
||||
assert.ok(existsSync(f.slot));
|
||||
f.edit((d) => { d.roles[f.name] = { definition: 'research', credentials: { gitea: d.roles.coder.credentials.gitea } }; });
|
||||
f.start();
|
||||
// The start makes no copy of the name, so the runtime would build no gate for this organization.
|
||||
assert.deepEqual(Object.keys(f.snapshot.copies ?? {}), []);
|
||||
const revoker = copyRevoker({ writer: f.writer, gate: () => null, credentials: f.credentials, hooks: {}, stopRuns: (...a) => f.stopRuns(...a),
|
||||
remote: giteaCopyRemote({ grant: f.grant, read: (x) => f.writer.read(x).document, incarnation: (x) => readOrgEntrySync(f.root, x)?.incarnation ?? null }),
|
||||
definitions: () => ({}) });
|
||||
assert.equal(revoker.pending(f.id, f.name), true);
|
||||
revoker.sweep(f.id);
|
||||
await until(() => tombstoned(f), 'shadowed tombstone');
|
||||
assert.equal(f.rec().revoke.cause, 'shadowed');
|
||||
assert.deepEqual(f.rec().revoke.remote, { gitea: 'revoked' });
|
||||
assert.ok(!existsSync(f.slot));
|
||||
assert.deepEqual(f.bot.tokens, []);
|
||||
assert.equal(revoker.pending(f.id, f.name), false);
|
||||
// A second pass finds a finished tombstone and starts nothing.
|
||||
const deletes = w.api.calls().filter((c) => c.startsWith('DELETE')).length;
|
||||
revoker.sweep(f.id);
|
||||
await sleep(50);
|
||||
assert.equal(revoker.has(f.id, f.name), false);
|
||||
assert.equal(w.api.calls().filter((c) => c.startsWith('DELETE')).length, deletes);
|
||||
});
|
||||
|
||||
// #1873 CB5 (CB4 review P3-3): an organization's own definition that needs gitea alone is not a
|
||||
// thread definition, so its copy runs on the ordinary path: a role claim, no thread. A revoke ends
|
||||
// that claim, kills the run, drains its call in flight and leaves its session dead.
|
||||
const GITTER = { rev: 1, role: { tools: ['read'], network: 'api-only', authority: { withinRole: ['message.send'], crossRole: [] },
|
||||
credentials: [{ service: 'gitea', scopes: ['read:repository', 'read:user'] }] }, instructions: 'Read the stack repository.' };
|
||||
test('CB5 a revoke of a copy on the ordinary run path ends its role claim, kills the run, drains its call and kills its session', async (t) => {
|
||||
const w = await world(t);
|
||||
const f = await org(t, w, { name: 'rev.stack', project: { rev: { definition: 'org:gitter' } }, definitions: { gitter: GITTER } });
|
||||
f.rootAgents = {};
|
||||
f.start();
|
||||
await f.bind({ level: 'project', project: 'stack', name: 'rev' });
|
||||
assert.equal(f.rec().state, 'bound');
|
||||
f.start();
|
||||
await f.boot();
|
||||
assert.deepEqual(Object.keys(f.gate.bound()), ['rev.stack']);
|
||||
// An ordinary run: a thread is refused, none is required.
|
||||
const revision = f.writer.read(f.id).revision;
|
||||
const { authority } = await f.gate.prepare(f.id, f.name, revision);
|
||||
assert.throws(() => f.b.bindLaunch({ business: f.id, role: f.name, run: 'run-t', harness: 'pi', thread: 'x', copyAuthority: authority, revision }), refuses('thread-not-allowed'));
|
||||
const cap = f.b.bindLaunch({ business: f.id, role: f.name, run: 'run-1', harness: 'pi', copyAuthority: authority, revision });
|
||||
await f.call(cap, 'role.claim');
|
||||
const claim = () => f.store.get('SELECT op, holder_run, reason, by FROM role_claims WHERE business=? AND role=? ORDER BY seq DESC LIMIT 1', f.id, f.name);
|
||||
assert.deepEqual({ ...claim() }, { op: 'claim', holder_run: 'run-1', reason: null, by: 'run-1' });
|
||||
assert.equal((await f.use(cap)).status, 200);
|
||||
const held = f.hold((e) => e.path === f.GET.path);
|
||||
const inflight = f.use(cap).then((x) => ({ ok: x }), (e) => ({ err: e }));
|
||||
await held.arrived;
|
||||
assert.equal(f.gate.inflight(f.id, f.name), 1);
|
||||
const out = await f.call(f.human, 'credentials.revoke', { agent: f.name, service: 'gitea', reason: 'Owner revoke' });
|
||||
assert.equal(out.state, 'unbound');
|
||||
assert.equal(f.gate.inflight(f.id, f.name), 0, 'drained before the revoke answered');
|
||||
held.release();
|
||||
const settled = await inflight;
|
||||
assert.ok(settled.err || settled.ok?.status === 0, 'the in-flight call was aborted');
|
||||
// The claim ended for the revoke, by the bus, and the run got its kill end.
|
||||
assert.deepEqual({ ...claim() }, { op: 'revoke', holder_run: 'run-1', reason: 'copy-revoked', by: 'bus' });
|
||||
assert.deepEqual(f.killed(), ['run-1']);
|
||||
assert.throws(() => f.b.copySession(cap), (e) => e instanceof BusError);
|
||||
await assert.rejects(f.call(cap, 'role.claim'), (e) => e instanceof BusError);
|
||||
await assertRevoked(f, null, { cause: 'revoke', code: 'credential-revoked' });
|
||||
});
|
||||
|
||||
// #1873 CB5 re-check: a copy whose role needs a service a copy cannot bind reads
|
||||
// copy-service-unbindable, but a revoke of a binding it was issued anyway outranks that.
|
||||
test('CB5 status: copy-service-unbindable never hides a revoke that is running or failed', async (t) => {
|
||||
const w = await world(t);
|
||||
const f = await org(t, w);
|
||||
const unbindable = { state: 'unbound', missing: ['gitea', 'vikunja'] };
|
||||
assert.equal(f.gate.status('demo', f.name, unbindable).status, 'copy-service-unbindable');
|
||||
let release;
|
||||
const held = f.gate.fence('demo', f.name, () => new Promise((r) => { release = r; }));
|
||||
assert.deepEqual(f.gate.status('demo', f.name, unbindable), { status: 'credential-revoking', next: COPY_BINDING_STATUS['credential-revoking'] });
|
||||
release();
|
||||
await held;
|
||||
f.gate.close('demo', f.name, 'credential-revoke-failed');
|
||||
assert.deepEqual(f.gate.status('demo', f.name, unbindable), { status: 'credential-revoke-failed', next: COPY_BINDING_STATUS['credential-revoke-failed'] });
|
||||
});
|
||||
@@ -36,11 +36,11 @@ function source3j(t) {
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function rows(path) {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','project_system_types','store_tasks')").all()
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','store_tasks')").all()
|
||||
.map(({ name }) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()
|
||||
.filter(r => name !== 'meta' || !['schema_version', 'schema_digest'].includes(r.key)).map(r => ({ ...r }))]));
|
||||
} finally { db.close(); }
|
||||
@@ -86,6 +86,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
function fresh(t) {
|
||||
@@ -107,7 +108,7 @@ test('3j copy migrates to 3k: every row kept, and sqlite_master gains only the t
|
||||
const { root, path } = source3j(t), before = rows(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(rows(path)), before);
|
||||
const now = master(path);
|
||||
assert.deepEqual(now.filter(r => !NEW.includes(r.name) && !later3l(r)), was.filter(r => !later3l(r)));
|
||||
@@ -133,7 +134,7 @@ test('a 3j→3k step that fails partway leaves the store at 3j with every row an
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
});
|
||||
|
||||
test('the 3j engine refuses a migrated store, migrating or not, and leaves it as it was', async t => {
|
||||
@@ -144,14 +145,14 @@ test('the 3j engine refuses a migrated store, migrating or not, and leaves it as
|
||||
schema: ddl3j,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3j).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3j';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3j';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 236 \(#1742[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3j/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3j';") && !pinned.includes('3j-3k'), 'the 3j engine has no 3j→3k step');
|
||||
assert.throws(() => new Store3j(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3j(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), after);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ const LATER = ['gitea_users', 'gitea_grants', 'sqlite_autoindex_gitea_users_1',
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function source3i(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'grant-migrate-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
@@ -42,7 +42,7 @@ function source3i(t) {
|
||||
function rows(path) {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('hosts','host_grants','gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','project_system_types','store_tasks')").all()
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('hosts','host_grants','gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','store_tasks')").all()
|
||||
.map(({ name }) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()
|
||||
.filter(r => name !== 'meta' || !['schema_version', 'schema_digest'].includes(r.key)).map(r => ({ ...r }))]));
|
||||
} finally { db.close(); }
|
||||
@@ -89,6 +89,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
function fresh(t) {
|
||||
@@ -112,7 +113,7 @@ test('3i copy migrates to 3j: every row kept, and sqlite_master gains only the t
|
||||
const { root, path } = source3i(t), before = rows(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(rows(path)), before);
|
||||
const now = master(path).filter(r => !LATER.includes(r.name));
|
||||
assert.deepEqual(now.filter(r => !NEW.includes(r.name) && !later3l(r)), was.filter(r => !later3l(r)));
|
||||
@@ -137,7 +138,7 @@ test('a 3i→3j step that fails partway leaves the store at 3i with every row an
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
});
|
||||
|
||||
test('the 3i engine refuses a migrated store, migrating or not, and leaves it as it was', async t => {
|
||||
@@ -148,14 +149,14 @@ test('the 3i engine refuses a migrated store, migrating or not, and leaves it as
|
||||
schema: ddl3i,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3i).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3i';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3i';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 234 \(#1740\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3i/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3i';") && !pinned.includes('3i-3j'), 'the 3i engine has no 3i→3j step');
|
||||
assert.throws(() => new Store3i(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3i(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), after);
|
||||
});
|
||||
|
||||
@@ -65,7 +65,7 @@ test('3f copy migrates to 3g preserving every old column/row, with an empty inst
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT to_name FROM messages') }, { to_name: null });
|
||||
assert.equal(store.get('SELECT count(*) AS n FROM instance_names').n, 0);
|
||||
assert.deepEqual({ ...store.get('SELECT spec_path,spec_commit FROM decisions') }, { spec_path: 'docs/spec.md', spec_commit: 'c'.repeat(40) });
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
// #1873 SP5: the pack, board and workflow verbs for an agent whose role file lists
|
||||
// organization.change, and hire.raise from a pack's recorded proposal (design section 3, "The
|
||||
// chief applying a pack", and section 8, SP5). The chief's authority is read from the shipped
|
||||
// roles/chief-of-staff.json, so the test pins the grant the stack runs.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { Broker } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { REFUSALS } from '../src/refusals.mjs';
|
||||
import { pluginHash } from '../../plugins/src/pinned.mjs';
|
||||
import { installPlugin } from '../../plugins/src/install.mjs';
|
||||
import { starterPack as codingPack } from '../../plugins/starter-pack/coding/index.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 { compositionOf, entryFromTemplate, readTemplate, templateHash } from '../../organization/src/definitions.mjs';
|
||||
import { canonicalJson } from '../../organization/src/util.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const shipped = (name) => JSON.parse(readFileSync(fileURLToPath(new URL(`../../../roles/${name}.json`, import.meta.url)), 'utf8'));
|
||||
const chiefAuthority = shipped('chief-of-staff').authority;
|
||||
const sha = (text) => createHash('sha256').update(text).digest('hex');
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
|
||||
// The SP4 harness (packs.test.mjs) with the shipped chief grant and a coder without it. With
|
||||
// fromFile, the broker boots from the loaded organization file, as autonomy-authority.test.mjs does,
|
||||
// so the reload after a write reaches the broker and a later verb reads what was written.
|
||||
async function harness(t, { mutate = () => {}, fromFile = false } = {}) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'packs5-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
mutate(doc);
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const data = join(root, 'data');
|
||||
mkdirSync(data, { mode: 0o700 });
|
||||
const roles = {
|
||||
chief: { definition: 'chief-of-staff', authority: chiefAuthority },
|
||||
coder: { definition: 'coder', authority: { withinRole: ['message.send'], crossRole: [] } },
|
||||
};
|
||||
const loaded = () => { const l = loadBusiness('demo', { dir: root, rolesDir }); return { ...l, roles: Object.fromEntries(Object.entries(l.roles).map(([n, e]) => [n, { ...l.definitions[e.definition], ...e }])) }; };
|
||||
const businesses = { demo: fromFile ? loaded() : { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles } };
|
||||
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
const thaw = (p) => { const st = lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) thaw(join(p, e)); } };
|
||||
t.after(async () => { await bus.close(); thaw(root); rmSync(root, { recursive: true, force: true }); });
|
||||
const b = bus.broker;
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const chief = b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi', address: 'chief-run' });
|
||||
const coder = b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
|
||||
b.request(chief, { verb: 'role.claim' });
|
||||
b.request(coder, { verb: 'role.claim' });
|
||||
const call = async (cap, verb, args = {}) => b.request(cap, { verb, args });
|
||||
const path = join(root, 'businesses/demo.json');
|
||||
const file = () => JSON.parse(readFileSync(path, 'utf8'));
|
||||
const revision = () => b.request(human, { verb: 'limits' }).revision;
|
||||
let n = 0;
|
||||
const install = (pack) => {
|
||||
const src = join(root, `src-${n++}`);
|
||||
mkdirSync(join(src, 'starter-pack'), { recursive: true });
|
||||
writeFileSync(join(src, 'starter-pack', 'index.mjs'), `export const interfaceVersion = 1;\nexport function starterPack() { return ${JSON.stringify(pack)}; }\n`);
|
||||
const manifest = { name: pack.id, version: '1.0.0', kinds: ['starter-pack'], interfaceVersions: { 'starter-pack': 1 }, sha256: '0'.repeat(64),
|
||||
source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
manifest.sha256 = pluginHash(src);
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
installPlugin({ dataRoot: data, source: src, expectedHash: manifest.sha256 });
|
||||
};
|
||||
// The broker's own database, read-only: grants spent and decisions raised.
|
||||
const query = (sql) => { const db = new DatabaseSync(join(data, 'bus/bus.sqlite'), { readOnly: true }); try { return db.prepare(sql).all(); } finally { db.close(); } };
|
||||
const spent = () => query("SELECT body FROM events WHERE kind='action.allowed' ORDER BY seq").map(e => JSON.parse(e.body)).filter(e => e.action === 'organization.change').length;
|
||||
const decisions = () => query('SELECT count(*) n FROM decisions')[0].n;
|
||||
return { b, root, rolesDir, path, human, chief, coder, call, file, revision, install, spent, decisions };
|
||||
}
|
||||
const variant = (id, patch = () => {}) => { const p = structuredClone(codingPack()); p.id = id; patch(p); return p; };
|
||||
const marks = (preview) => Object.fromEntries(preview.items.map(i => [i.path, i.mark]));
|
||||
|
||||
test('SP5 the chief applies the coding pack: board and workflows written, no definitions, template pins, one grant spent', async t => {
|
||||
const { call, chief, file, path, rolesDir, spent, decisions } = await harness(t);
|
||||
const before = file();
|
||||
const preview = await call(chief, 'pack.preview', { pack: 'coding' });
|
||||
assert.equal(spent(), 0);
|
||||
assert.deepEqual(readFileSync(path, 'utf8'), JSON.stringify(before, null, 2) + '\n');
|
||||
// A definition a human apply would add is not written for an agent; its hire pins the template.
|
||||
for (const name of ['coder', 'cto', 'merge-gate', 'pm', 'reviewer', 'security-reviewer']) assert.equal(marks(preview)[`definitions.${name}`], 'not-written');
|
||||
assert.equal(marks(preview).board, 'add');
|
||||
assert.equal(marks(preview)['workflows.change'], 'add');
|
||||
assert.equal(preview.plan.definitions, undefined);
|
||||
for (const h of preview.hires) {
|
||||
assert.equal(h.mark, 'propose');
|
||||
assert.deepEqual(h.pin, { template: h.definition, sha256: templateHash(rolesDir, h.definition) });
|
||||
}
|
||||
await call(chief, 'pack.apply', { pack: 'coding', digest: preview.digest });
|
||||
const after = file();
|
||||
assert.equal(after.board.layout, 'kanban');
|
||||
assert.deepEqual(after.board, codingPack().board);
|
||||
assert.deepEqual(after.workflows.change.steps.map(s => s.roles), [['pm'], ['coder'], ['reviewer'], ['human', 'merge-gate']]);
|
||||
assert.deepEqual(after.definitions ?? null, before.definitions ?? null);
|
||||
assert.equal(after.packs.length, 1);
|
||||
assert.equal(after.packs[0].by, 'chief-of-staff.chief');
|
||||
assert.deepEqual(after.packs[0].added.sort(), ['board', 'workflows.change']);
|
||||
assert.deepEqual(after.packs[0].proposedHires.map(h => [h.name, h.pin.template]), [['pm-1', 'pm'], ['coder-1', 'coder'], ['reviewer-1', 'reviewer']]);
|
||||
assert.equal(spent(), 1);
|
||||
assert.equal(decisions(), 0);
|
||||
});
|
||||
|
||||
test('SP5 a repeat apply that writes nothing spends no grant', async t => {
|
||||
const { call, chief, file, spent } = await harness(t);
|
||||
const first = await call(chief, 'pack.preview', { pack: 'coding' });
|
||||
await call(chief, 'pack.apply', { pack: 'coding', digest: first.digest });
|
||||
assert.equal(spent(), 1);
|
||||
const before = file();
|
||||
// The same pack again: the board and workflow are the same and the proposals unchanged, so the
|
||||
// runtime skips the write and the broker spends nothing.
|
||||
const again = await call(chief, 'pack.preview', { pack: 'coding' });
|
||||
const out = await call(chief, 'pack.apply', { pack: 'coding', digest: again.digest });
|
||||
assert.deepEqual(out.added, []);
|
||||
assert.deepEqual(file(), before);
|
||||
assert.equal(spent(), 1);
|
||||
});
|
||||
|
||||
test('SP5 end to end: the chief applies a pack, the organization reloads, and the chief raises a hire from the recorded proposal', async t => {
|
||||
const { call, chief, file, rolesDir, decisions } = await harness(t, { fromFile: true });
|
||||
const preview = await call(chief, 'pack.preview', { pack: 'coding' });
|
||||
await call(chief, 'pack.apply', { pack: 'coding', digest: preview.digest });
|
||||
assert.equal(decisions(), 0);
|
||||
// The raise reads the packs list the broker reloaded after the write, not a fixture's.
|
||||
const d = await call(chief, 'hire.raise', { proposal: { pack: 'coding', hire: 'coder-1' }, route: ROUTE });
|
||||
assert.equal(d.hire.name, 'coder-1');
|
||||
assert.equal(d.hire.level, 'org');
|
||||
assert.equal(decisions(), 1);
|
||||
const direct = await call(chief, 'hire.raise', { op: 'hire', level: 'org', name: 'coder-b', role: { template: 'coder', sha256: templateHash(rolesDir, 'coder') }, route: ROUTE, reason: 'Code.' });
|
||||
assert.deepEqual(d.hire.role, direct.hire.role);
|
||||
assert.deepEqual(d.hire.flagged, direct.hire.flagged);
|
||||
// A second preview leaves out the hire the open decision names; the file is unchanged by the raise.
|
||||
assert.equal((await call(chief, 'pack.preview', { pack: 'coding' })).hires.find(h => h.name === 'coder-1').mark, 'dropped');
|
||||
assert.equal(file().packs.length, 1);
|
||||
});
|
||||
|
||||
test('SP5 a project pack: the chief applies it to a code project and raises the project hire from it', async t => {
|
||||
const { call, chief, file, install, decisions } = await harness(t, { fromFile: true });
|
||||
install(variant('projkit', p => { p.scope = 'project'; }));
|
||||
const preview = await call(chief, 'pack.preview', { pack: 'projkit', project: 'stack' });
|
||||
assert.equal(marks(preview)['projects.stack.board'], 'add');
|
||||
assert.equal(marks(preview)['definitions.coder'], 'not-written');
|
||||
await call(chief, 'pack.apply', { pack: 'projkit', project: 'stack', digest: preview.digest });
|
||||
assert.deepEqual(file().projects.stack.board, codingPack().board);
|
||||
assert.equal(file().packs.at(-1).project, 'stack');
|
||||
// The proposal names its project; without it, no org-level entry matches.
|
||||
await assert.rejects(call(chief, 'hire.raise', { proposal: { pack: 'projkit', hire: 'coder-1' }, route: ROUTE }), { code: 'invalid-request' });
|
||||
const d = await call(chief, 'hire.raise', { proposal: { pack: 'projkit', project: 'stack', hire: 'coder-1' }, route: ROUTE });
|
||||
assert.equal(d.hire.level, 'project');
|
||||
assert.equal(d.hire.project, 'stack');
|
||||
assert.equal(decisions(), 1);
|
||||
});
|
||||
|
||||
test('SP5 an inline pack definition that shares a template name does not keep its workflow step', async t => {
|
||||
const { call, chief, install, rolesDir } = await harness(t);
|
||||
const { rev: _rev, ...entry } = entryFromTemplate(readTemplate(rolesDir, 'coder'));
|
||||
install(variant('shadowkit', p => {
|
||||
p.definitions = { reviewer: { ...entry, instructions: entry.instructions + '\nShadow.' } };
|
||||
p.hires = [];
|
||||
p.workflows = { check: { description: 'Check.', steps: [{ id: 'look', title: 'Look', state: 'todo', roles: ['human'] }, { id: 'review', title: 'Review it', state: 'in-review', roles: ['reviewer'] }] } };
|
||||
}));
|
||||
const preview = await call(chief, 'pack.preview', { pack: 'shadowkit' });
|
||||
const item = preview.items.find(i => i.path === 'workflows.check');
|
||||
assert.equal(item.mark, 'add');
|
||||
assert.deepEqual(item.leftOut, [{ step: 2, title: 'Review it', roles: ['reviewer'] }]);
|
||||
assert.deepEqual(preview.plan.workflows.check.steps.map(s => s.roles), [['human']]);
|
||||
});
|
||||
|
||||
test('SP5 a role without organization.change gets decision-required for the writes and human-required for the packs read', async t => {
|
||||
const { call, coder, chief, path, revision, install, spent } = await harness(t);
|
||||
const before = readFileSync(path);
|
||||
for (const [verb, args] of [['pack.apply', { pack: 'coding', digest: 'a'.repeat(64) }], ['board.set', { revision: revision(), board: null }],
|
||||
['workflow.set', { revision: revision(), name: 'x', workflow: null }], ['pack.preview', { pack: 'coding' }]])
|
||||
await assert.rejects(call(coder, verb, args), /decision-required/, verb);
|
||||
await assert.rejects(call(coder, 'packs'), /human-required/);
|
||||
// The console names stay the owner's.
|
||||
await assert.rejects(call(chief, 'pack.preview.console', { pack: 'coding' }), /human-required/);
|
||||
await assert.rejects(call(chief, 'packs.console'), /human-required/);
|
||||
assert.deepEqual(readFileSync(path), before);
|
||||
// The chief's packs read lists shipped and installed packs and spends nothing.
|
||||
install(variant('teamkit'));
|
||||
const listed = (await call(chief, 'packs')).packs;
|
||||
assert.ok(listed.some(p => p.id === 'coding' && p.origin === 'shipped'));
|
||||
assert.ok(listed.some(p => p.id === 'teamkit' && p.origin === 'installed'));
|
||||
assert.equal(spent(), 0);
|
||||
// The agent request carries no origin, actor or unknown key.
|
||||
await assert.rejects(call(chief, 'pack.preview', { pack: 'coding', actor: 'jason' }), /invalid-request/);
|
||||
await assert.rejects(call(chief, 'packs', { all: true }), /invalid-request/);
|
||||
});
|
||||
|
||||
test('SP5 the chief writes a board and a workflow, each spending the grant once, with its own actor', async t => {
|
||||
const { call, chief, file, revision, spent } = await harness(t);
|
||||
await call(chief, 'board.set', { revision: revision(), board: codingPack().board });
|
||||
assert.deepEqual(file().board, codingPack().board);
|
||||
assert.equal(spent(), 1);
|
||||
const workflow = { description: 'Intake.', steps: [{ title: 'Take it', state: 'todo', roles: ['human'] }, { title: 'Build it', state: 'in-progress', roles: ['coder'] }] };
|
||||
await call(chief, 'workflow.set', { revision: revision(), name: 'intake', workflow });
|
||||
assert.deepEqual(file().workflows.intake, workflow);
|
||||
assert.equal(spent(), 2);
|
||||
await call(chief, 'workflow.set', { revision: revision(), name: 'intake', workflow: null });
|
||||
assert.equal(file().workflows, undefined);
|
||||
assert.equal(spent(), 3);
|
||||
// A refused write spends nothing.
|
||||
await assert.rejects(call(chief, 'board.set', { revision: 'b'.repeat(64), board: null }), { code: 'revision-conflict' });
|
||||
await assert.rejects(call(chief, 'workflow.set', { revision: revision(), name: 'x', workflow: { description: 'x', steps: [{ title: 'Do', state: 'todo', roles: ['nobody-at-all'] }] } }), /invalid-request/);
|
||||
assert.equal(spent(), 3);
|
||||
});
|
||||
|
||||
test('SP5 an agent apply never writes a definition or a saved template: human-required', async t => {
|
||||
const { call, chief, path, root, rolesDir } = await harness(t);
|
||||
const before = readFileSync(path);
|
||||
// A definitions rename names a definition to write.
|
||||
await assert.rejects(call(chief, 'pack.preview', { pack: 'coding', as: ['definitions.coder=dev'] }), /human-required/);
|
||||
await assert.rejects(call(chief, 'pack.apply', { pack: 'coding', as: ['definitions.coder=dev'], digest: 'a'.repeat(64) }), /human-required/);
|
||||
// A saved template refuses before anything is read; the name need not exist.
|
||||
await assert.rejects(call(chief, 'pack.preview', { pack: 'saved:x' }), /human-required/);
|
||||
await assert.rejects(call(chief, 'pack.apply', { pack: 'saved:x', digest: 'a'.repeat(64) }), /human-required/);
|
||||
// A workflows rename is allowed.
|
||||
const renamed = await call(chief, 'pack.preview', { pack: 'coding', as: ['workflows.change=ship'] });
|
||||
assert.equal(marks(renamed)['workflows.ship'], 'add');
|
||||
assert.deepEqual(readFileSync(path), before);
|
||||
// The writer's own fence: the chief's actor with a definition in the plan, or a saved origin.
|
||||
const writer = organizationWriter({ dir: root, rolesDir });
|
||||
const { rev: _rev, ...entry } = entryFromTemplate(readTemplate(rolesDir, 'coder'));
|
||||
const pack = { id: 'kit', version: '1.0.0', sha256: 'a'.repeat(64), origin: 'installed', scope: 'org', project: null, proposedHires: [] };
|
||||
const opts = () => ({ revision: writer.read('demo').revision, actor: 'chief-of-staff.chief', assertClean: () => {}, detail: {} });
|
||||
assert.throws(() => writer.applyPack('demo', { definitions: { dev: entry }, packs: pack }, opts()), /human-required/);
|
||||
assert.throws(() => writer.applyPack('demo', { board: codingPack().board, packs: { ...pack, origin: 'saved' } }, opts()), /human-required/);
|
||||
assert.deepEqual(readFileSync(path), before);
|
||||
});
|
||||
|
||||
test('SP5 a workflow step naming a definition the agent apply cannot write is left out and marked', async t => {
|
||||
const { call, chief, file, install, rolesDir } = await harness(t);
|
||||
const { rev: _rev, ...scribe } = entryFromTemplate(readTemplate(rolesDir, 'coder'));
|
||||
install(variant('scribekit', p => {
|
||||
p.definitions = { scribe, pm: p.definitions.pm };
|
||||
p.hires = [{ name: 'scribe-1', definition: 'scribe', reason: 'Take notes.' }];
|
||||
p.workflows = {
|
||||
notes: { description: 'Notes.', steps: [{ id: 'plan', title: 'Plan it', state: 'todo', roles: ['pm'] }, { id: 'write', title: 'Write it', state: 'in-progress', roles: ['scribe', 'human'] }] },
|
||||
solo: { description: 'Solo.', steps: [{ id: 'write', title: 'Write it', state: 'todo', roles: ['scribe'] }] },
|
||||
};
|
||||
}));
|
||||
const preview = await call(chief, 'pack.preview', { pack: 'scribekit' });
|
||||
assert.equal(marks(preview)['definitions.scribe'], 'not-written');
|
||||
const items = Object.fromEntries(preview.items.map(i => [i.path, i]));
|
||||
assert.equal(items['workflows.notes'].mark, 'add');
|
||||
assert.deepEqual(items['workflows.notes'].leftOut, [{ step: 2, title: 'Write it', roles: ['scribe'] }]);
|
||||
assert.equal(items['workflows.solo'].mark, 'left-out');
|
||||
assert.deepEqual(items['workflows.solo'].leftOut, [{ step: 1, title: 'Write it', roles: ['scribe'] }]);
|
||||
assert.deepEqual(Object.keys(preview.plan.workflows), ['notes']);
|
||||
// The full-entry definition's hire pins the inline entry.
|
||||
const hire = preview.hires.find(h => h.name === 'scribe-1');
|
||||
assert.deepEqual(hire.pin, { inline: 'scribe', sha256: sha(canonicalJson(scribe)) });
|
||||
await call(chief, 'pack.apply', { pack: 'scribekit', digest: preview.digest });
|
||||
assert.deepEqual(file().workflows, { notes: { description: 'Notes.', steps: [{ title: 'Plan it', state: 'todo', roles: ['pm'] }] } });
|
||||
assert.equal(file().definitions?.scribe, undefined);
|
||||
assert.deepEqual(file().packs.at(-1).proposedHires[0].entry, scribe);
|
||||
});
|
||||
|
||||
// The hire-decisions.test.mjs fixture: a Broker on the loaded organization and the hire service.
|
||||
function fixture(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sp5-bus-')), rolesDir = rolesCopy(root);
|
||||
const file = writeJson(join(root, 'businesses/demo.json'), { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } });
|
||||
const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 });
|
||||
const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot);
|
||||
const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: () => {} });
|
||||
const loaded = () => { const doc = loadBusiness('demo', { dir: root, rolesDir }); return { ...doc, roles: Object.fromEntries(Object.entries(doc.roles).map(([n, e]) => [n, { ...doc.definitions[e.definition], ...e }])) }; };
|
||||
const b = new Broker({ store, businesses: { demo: loaded() }, hires: service });
|
||||
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' });
|
||||
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const call = (cap, verb, args = {}) => b.request(cap, { verb, args });
|
||||
// A packs entry as an owner's apply records it, then the broker's organization reloads.
|
||||
const record = (plan) => {
|
||||
writer.applyPack('demo', plan, { revision: writer.read('demo').revision, actor: 'jason', assertClean: () => {}, detail: {} });
|
||||
b.reloadBusiness('demo', loaded());
|
||||
};
|
||||
const pack = (proposedHires, extra = {}) => ({ id: 'kit', version: '1.0.0', sha256: 'a'.repeat(64), origin: 'installed', scope: 'org', project: null, proposedHires, ...extra });
|
||||
// Edit the organization file directly, as a later change would, then reload.
|
||||
const edit = (change) => { const doc = JSON.parse(readFileSync(file, 'utf8')); change(doc); writeJson(file, doc); b.reloadBusiness('demo', loaded()); };
|
||||
const raise = (proposal, extra = {}) => call(caps.chief, 'hire.raise', { proposal, route: ROUTE, ...extra });
|
||||
const count = () => store.get('SELECT count(*) n FROM decisions').n;
|
||||
return { root, rolesDir, b, store, file, writer, caps, call, record, pack, edit, raise, count, loaded };
|
||||
}
|
||||
|
||||
test('SP5 a hire raised from a template proposal carries the broker-computed role and lines, as a direct raise does', async t => {
|
||||
const { rolesDir, record, pack, raise, call, caps, count } = fixture(t);
|
||||
const pin = { template: 'reviewer', sha256: templateHash(rolesDir, 'reviewer') };
|
||||
record({ packs: pack([{ name: 'scout', reason: 'Review the pack work.', pin }]) });
|
||||
const d = await raise({ pack: 'kit', hire: 'scout' });
|
||||
assert.equal(d.hire.name, 'scout');
|
||||
assert.equal(d.hire.level, 'org');
|
||||
// The lines are the broker's, the same as a direct raise of the same role computes.
|
||||
const direct = await call(caps.chief, 'hire.raise', { op: 'hire', level: 'org', name: 'scout-b', role: pin, route: ROUTE, reason: 'Review.' });
|
||||
assert.deepEqual(d.hire.role, direct.hire.role);
|
||||
assert.deepEqual(d.hire.flagged, direct.hire.flagged);
|
||||
assert.deepEqual(d.hire.credentialLines, direct.hire.credentialLines);
|
||||
assert.ok(Array.isArray(d.hire.credentialLines));
|
||||
assert.equal(count(), 2);
|
||||
// hire.raise requires a reason and stores none. The raise above sent none, so the recorded one
|
||||
// filled it; a caller's own reason replaces it, and an empty one refuses as a direct raise does.
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'scout' }, { reason: '' }), { code: 'invalid-request' });
|
||||
assert.equal((await raise({ pack: 'kit', hire: 'scout' }, { reason: 'Mine.' })).hire.name, 'scout');
|
||||
assert.equal(count(), 3);
|
||||
});
|
||||
|
||||
test('SP5 a proposal raise: role-not-chief, decision-stale, definition-rev-conflict, starter-pack-proposal-stale, definition-not-hireable', async t => {
|
||||
const { rolesDir, record, pack, raise, call, caps, edit, count } = fixture(t);
|
||||
const { rev: _rev, ...scribe } = entryFromTemplate(readTemplate(rolesDir, 'coder'));
|
||||
const inline = { name: 'inl', reason: 'Inline.', pin: { inline: 'scribe', sha256: sha(canonicalJson(scribe)) }, entry: scribe };
|
||||
record({
|
||||
definitions: { helper: scribe },
|
||||
packs: pack([
|
||||
{ name: 'moved', reason: 'Moved.', pin: { template: 'reviewer', sha256: 'b'.repeat(64) } },
|
||||
{ name: 'def', reason: 'Def.', pin: { definition: 'helper', rev: 1 } },
|
||||
inline,
|
||||
]),
|
||||
});
|
||||
// Only the chief raises, with or without a proposal.
|
||||
await assert.rejects(call(caps.coder, 'hire.raise', { proposal: { pack: 'kit', hire: 'def' }, route: ROUTE }), { code: 'role-not-chief' });
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'moved' }), { code: 'decision-stale' });
|
||||
edit(doc => { doc.definitions.helper = { ...doc.definitions.helper, rev: 2, instructions: doc.definitions.helper.instructions + '\nAlso this.' }; });
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'def' }), { code: 'definition-rev-conflict' });
|
||||
// The inline entry stored with the proposal still hashes to its pin, so it raises.
|
||||
const ok = await raise({ pack: 'kit', hire: 'inl' });
|
||||
assert.equal(ok.hire.name, 'inl');
|
||||
const direct = await call(caps.chief, 'hire.raise', { op: 'hire', level: 'org', name: 'inl-b', role: { inline: compositionOf(scribe) }, route: ROUTE, reason: 'Inline.' });
|
||||
assert.deepEqual(ok.hire.role, direct.hire.role);
|
||||
assert.equal(count(), 2);
|
||||
// A later edit to the stored entry is caught at the raise.
|
||||
edit(doc => { doc.packs[0].proposedHires[2].entry.instructions += '\nAnd more.'; });
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'inl' }), { code: 'starter-pack-proposal-stale' });
|
||||
// An inline entry from a template launch.noHire names refuses, though prepare reads no ref for it.
|
||||
edit(doc => { doc.packs[0].proposedHires[2].entry = scribe; doc.launch.noHire = ['coder']; });
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'inl' }), { code: 'definition-not-hireable' });
|
||||
assert.equal(count(), 2);
|
||||
});
|
||||
|
||||
test('SP5 a chief without role.hire is refused a proposal raise before the packs list is read', async t => {
|
||||
const { record, pack, raise, b, loaded, rolesDir, count } = fixture(t);
|
||||
record({ packs: pack([{ name: 'scout', reason: 'Review.', pin: { template: 'reviewer', sha256: templateHash(rolesDir, 'reviewer') } }]) });
|
||||
const doc = loaded();
|
||||
const authority = doc.roles.chief.authority;
|
||||
b.reloadBusiness('demo', { ...doc, roles: { ...doc.roles, chief: { ...doc.roles.chief, authority: { ...authority, withinRole: authority.withinRole.filter(a => a !== 'role.hire') } } } });
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'scout' }), { code: 'not-authorized' });
|
||||
// A proposal that does not exist gets the same refusal, so the refusal leaks nothing.
|
||||
await assert.rejects(raise({ pack: 'nosuch', hire: 'nobody' }), { code: 'not-authorized' });
|
||||
assert.equal(count(), 0);
|
||||
});
|
||||
|
||||
test('SP5 a proposal raise names no role, name, level or other hire key; unknown proposals refuse; a plain raise is unchanged', async t => {
|
||||
const { rolesDir, record, pack, raise, call, caps, count } = fixture(t);
|
||||
const pin = { template: 'reviewer', sha256: templateHash(rolesDir, 'reviewer') };
|
||||
record({ packs: pack([{ name: 'scout', reason: 'Review.', pin }]) });
|
||||
for (const extra of [{ role: pin }, { name: 'other' }, { level: 'org' }, { op: 'hire' }, { credentials: {} }, { personality: 'x' }, { binding: {} }])
|
||||
await assert.rejects(raise({ pack: 'kit', hire: 'scout' }, extra), { code: 'invalid-request' }, JSON.stringify(extra));
|
||||
for (const proposal of [{ pack: 'kit' }, { pack: 'kit', hire: 'nobody' }, { pack: 'other', hire: 'scout' }, { pack: 'kit', hire: 'scout', project: 'stack' },
|
||||
{ pack: 'kit', hire: 'scout', role: 'x' }, { pack: 'kit', hire: 7 }, 'kit'])
|
||||
await assert.rejects(raise(proposal), { code: 'invalid-request' }, JSON.stringify(proposal));
|
||||
await assert.rejects(call(caps.chief, 'hire.raise', { proposal: { pack: 'kit', hire: 'scout' } }), { code: 'invalid-request' });
|
||||
assert.equal(count(), 0);
|
||||
// Without proposal, hire.raise is what it was.
|
||||
const INLINE = { tools: ['read'], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [], instructions: 'Read and report.' };
|
||||
const d = await call(caps.chief, 'hire.raise', { op: 'hire', level: 'org', name: 'plain', role: { inline: INLINE }, route: ROUTE, reason: 'Need help' });
|
||||
assert.equal(d.hire.name, 'plain');
|
||||
assert.equal(count(), 1);
|
||||
});
|
||||
|
||||
test('SP5 starter-pack-proposal-stale is in the refusal table with a rail and a next step that names no path', () => {
|
||||
const c = 'starter-pack-proposal-stale';
|
||||
assert.ok(Object.hasOwn(REFUSALS, c));
|
||||
assert.ok(REFUSALS[c].rail?.length > 5);
|
||||
assert.ok(REFUSALS[c].nextStep?.length > 20);
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[c].nextStep));
|
||||
});
|
||||
@@ -318,7 +318,10 @@ test('SP4 who may call: the owner only; the tester, a member, an agent and a con
|
||||
['pack.apply', { pack: 'coding', digest: 'a'.repeat(64) }], ['board.set', { revision: revision(), board: null }]])
|
||||
assert.throws(() => b.request(member, { verb, args }), /human-required/);
|
||||
const agent = b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
|
||||
assert.throws(() => b.request(agent, { verb: 'pack.apply', args: { pack: 'coding', digest: 'a'.repeat(64) } }), /human-required/);
|
||||
// SP5: an agent reaches the unsuffixed names through its role's organization.change; the coder
|
||||
// lists none, so its write needs a decision (packs-agent.test.mjs covers the chief).
|
||||
b.request(agent, { verb: 'role.claim' });
|
||||
assert.throws(() => b.request(agent, { verb: 'pack.apply', args: { pack: 'coding', digest: 'a'.repeat(64) } }), /decision-required/);
|
||||
assert.throws(() => b.request(agent, { verb: 'pack.preview.console', args: { pack: 'coding' } }), /human-required/);
|
||||
// The owner's console cap calls the .console names; the cli cap the unsuffixed ones.
|
||||
await assert.rejects(call('pack.preview', { pack: 'coding' }), /human-required/);
|
||||
|
||||
@@ -198,8 +198,7 @@ test('3p through 3s migration preserves existing request rows and the append-onl
|
||||
const path = join(root, 'bus/bus.sqlite'), ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
// 3s-3t (#797) adds project_archives; the 3p fixture predates it and the replayed chain recreates it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(",'prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced'", '');
|
||||
const db = new DatabaseSync(path); db.exec(ddl);
|
||||
@@ -216,7 +215,7 @@ test('3p through 3s migration preserves existing request rows and the append-onl
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true }); t.after(() => store.close());
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events'), before);
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
store.run("INSERT INTO request_events(business,request,revision,kind,at,body) VALUES('demo','r',2,'prd.submitted',?,'{}')", at);
|
||||
assert.throws(() => store.run('DELETE FROM request_events'), /append-only/);
|
||||
assert.throws(() => store.run("UPDATE request_events SET body='{}'"), /append-only/);
|
||||
|
||||
@@ -143,8 +143,8 @@ const here = (p) => new URL(p, import.meta.url);
|
||||
const migrationSQL = readFileSync(here('../src/migrations/3s-3t.sql'), 'utf8');
|
||||
const currentDDL = readFileSync(here('../schema.sql'), 'utf8');
|
||||
assert.equal(currentDDL.split(migrationSQL).length, 2, 'schema.sql holds the 3s→3t step exactly once');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after them; a 3s store has neither.
|
||||
const ddl3s = currentDDL.replace(migrationSQL, '').replace(readFileSync(here('../src/migrations/3t-3u.sql'), 'utf8'), '').replace(readFileSync(here('../src/migrations/3u-3v.sql'), 'utf8'), '');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after it; a 3s store has neither table.
|
||||
const ddl3s = currentDDL.replace(migrationSQL, '').replace(readFileSync(here('../src/migrations/3u-3v.sql'), 'utf8'), '');
|
||||
|
||||
function source3s(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'project-archive-3s-'));
|
||||
@@ -179,7 +179,7 @@ test('a 3s store migrates to 3t: project_archives is new and empty, every row st
|
||||
assert.deepEqual(master(path), was, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.equal(store.get("SELECT id FROM events").id, 'preserved');
|
||||
assert.equal(store.get("SELECT name FROM projects").name, 'kept');
|
||||
assert.deepEqual(store.all('SELECT seq,at,business,project,op,by FROM project_archives'), []);
|
||||
@@ -212,7 +212,7 @@ test('the 3s engine refuses a 3t store, migrating or not, and leaves it as it wa
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3s).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3s';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3s';")
|
||||
.replace(/\}, \{\n {2}\/\/ #797 MVP3[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3s';") && edited.includes('3r-3s') && !edited.includes('3s-3t'), 'the 3s engine has no 3s→3t step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -222,7 +222,7 @@ test('the 3s engine refuses a 3t store, migrating or not, and leaves it as it wa
|
||||
const Store3s = (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
assert.throws(() => new Store3s(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3s(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
// The same engine opens a fresh 3s store, so the refusal is the version's and not a broken copy.
|
||||
const { root: old } = source3s(t);
|
||||
|
||||
@@ -90,10 +90,12 @@ const ask = (x, state, extra = {}) => x.call('pm', 'request.question', { request
|
||||
options: [{ key: 'web', text: 'Web' }, { key: 'cli', text: 'CLI' }], ...extra });
|
||||
|
||||
test('the console verb list includes the artifact read and existing owner controls', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console']);
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
// Starter packs SP8 (#1873): the owner saves and lists templates.
|
||||
'template.save.console', 'template.list.console']);
|
||||
});
|
||||
|
||||
test('only the signed-in owner capability reaches the console verbs and it reaches nothing else', async t => {
|
||||
@@ -304,7 +306,7 @@ test('a cancel is refused when the owner-to-PM edge closed, with no withdrawn de
|
||||
});
|
||||
|
||||
test('3q through 3s widens the kind list to the union, keeps every 3q kind, row, seq and guard, and the chain matches the fresh digest', t => {
|
||||
assert.equal(SCHEMA_VERSION, '3v');
|
||||
assert.equal(SCHEMA_VERSION, '3w');
|
||||
const root = mkdtempSync(join(tmpdir(), 'request-migration-3r-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true })); mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite'), AT = '2026-11-03T00:00:00.000Z';
|
||||
@@ -312,11 +314,10 @@ test('3q through 3s widens the kind list to the union, keeps every 3q kind, row,
|
||||
// 3s-3t (#797) adds project_archives, outside request_events; the 3q fixture predates it and
|
||||
// the replayed chain recreates it, so the step's text is removed here like the kinds are.
|
||||
const step3t = readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8');
|
||||
// 3t-3u (#1873, SYS1) adds project_system_types the same way, and 3u-3v (U4a) adds store_tasks.
|
||||
const step3u = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks the same way.
|
||||
const step3v = readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8');
|
||||
// 3p-3q shipped the PRD kinds and mode.changed; 3q-3r adds the three Task 3 kinds after them.
|
||||
const ddl3q = current.replace(step3t, '').replace(step3u, '').replace(step3v, '').replace(",'advanced'", '').replace("'prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'", "'prd.invalidated','mode.changed','cancelled'");
|
||||
const ddl3q = current.replace(step3t, '').replace(step3v, '').replace(",'advanced'", '').replace("'prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'", "'prd.invalidated','mode.changed','cancelled'");
|
||||
assert.notEqual(ddl3q, current, 'the fixture is the narrower schema');
|
||||
const migration = readFileSync(new URL('../src/migrations/3q-3r.sql', import.meta.url), 'utf8');
|
||||
assert.ok(migration.includes("'prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'"), 'the step carries every 3q kind plus its own');
|
||||
@@ -333,7 +334,7 @@ test('3q through 3s widens the kind list to the union, keeps every 3q kind, row,
|
||||
db.close(); chmodSync(path, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n');
|
||||
const store = new Store(root);
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before, 'every row keeps its seq and bytes, including the 3q kinds');
|
||||
const fresh = new DatabaseSync(':memory:'); fresh.exec(current);
|
||||
|
||||
@@ -230,8 +230,7 @@ test('3r to 3s migration preserves journal and sequence and admits only the new
|
||||
// 3s-3t (#797) adds project_archives; the 3r fixture predates it and the replayed chain recreates it.
|
||||
db.exec(readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(",'advanced'", ''));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_version', '3r');
|
||||
@@ -253,7 +252,7 @@ test('3r to 3s migration preserves journal and sequence and admits only the new
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before);
|
||||
assert.deepEqual(store.all("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND tbl_name IN ('request_events','request_effects') ORDER BY name"), guards);
|
||||
assert.equal(store.get("SELECT name FROM sqlite_master WHERE type='index' AND name='request_events_request'").name, 'request_events_request');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
store.run("INSERT INTO request_events(business,request,revision,kind,at,body) VALUES('demo','r',16,'advanced',?,'{}')", at);
|
||||
assert.equal(store.get("SELECT max(seq) n FROM request_events").n, 42);
|
||||
assert.throws(() => store.run("UPDATE request_events SET kind='opened'"), /append-only/);
|
||||
|
||||
@@ -278,8 +278,7 @@ test('3n_to_3o_is_explicit_offline_preserves_rows_and_old_engine_refuses_new_sch
|
||||
// 3s-3t (#797) adds project_archives after the request tables; the pre-3t fixtures below
|
||||
// predate it and the replayed chain recreates it, so the step's text comes out here too.
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace("'setup.wait','bootstrap.stale','bootstrap.completed','prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced','cancelled'", "'setup.wait','cancelled'");
|
||||
const newDDL = readFileSync(new URL('../src/migrations/3n-3o.sql', import.meta.url), 'utf8');
|
||||
@@ -293,7 +292,7 @@ test('3n_to_3o_is_explicit_offline_preserves_rows_and_old_engine_refuses_new_sch
|
||||
db.close(); chmodSync(path, 0o600); const before = readFileSync(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/); assert.deepEqual(readFileSync(path), before);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n'); assert.equal(SCHEMA_VERSION, '3v');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n'); assert.equal(SCHEMA_VERSION, '3w');
|
||||
const store = new Store(root); assert.equal(store.get("SELECT id FROM events").id, 'preserved');
|
||||
for (const table of ['request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events']) assert.equal(store.get(`SELECT count(*) n FROM ${table}`).n, 0);
|
||||
store.close(); assert.equal(spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root]).status, 0);
|
||||
@@ -316,8 +315,7 @@ test('3o_to_3p_widens_only_the_event_kinds_and_keeps_rows_seq_and_guards', t =>
|
||||
// The 3o schema is the current one with the narrower kind list.
|
||||
const ddl3o = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace("'setup.wait','bootstrap.stale','bootstrap.completed','prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced','cancelled'", "'setup.wait','cancelled'");
|
||||
const { schemaDigest } = awaitImportStore, AT = '2026-11-03T00:00:00.000Z';
|
||||
@@ -335,7 +333,7 @@ test('3o_to_3p_widens_only_the_event_kinds_and_keeps_rows_seq_and_guards', t =>
|
||||
db.close(); chmodSync(path, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n');
|
||||
const store = new Store(root);
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before, 'every row keeps its seq and bytes');
|
||||
assert.deepEqual(store.all('SELECT * FROM request_effects ORDER BY seq'), effects);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { SCHEMA_VERSION, Store, schemaDigest } from '../src/store.mjs';
|
||||
|
||||
// #1873 SP9: bus schema step 3v-3w drops project_system_types with its index, its four triggers and
|
||||
// its rows (Jason's 2026-11-12 ruling removes the system-type kind outright).
|
||||
const TABLE = 'project_system_types';
|
||||
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
|
||||
const createdBy3u = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
const named = (path) => {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return {
|
||||
master: db.prepare('SELECT type,name FROM sqlite_master WHERE name LIKE ? OR tbl_name=? ORDER BY type,name').all(`${TABLE}%`, TABLE).map((r) => ({ ...r })),
|
||||
sequence: db.prepare('SELECT name FROM sqlite_sequence WHERE name=?').all(TABLE).map((r) => r.name),
|
||||
digest: schemaDigest(db),
|
||||
version: db.prepare("SELECT value FROM meta WHERE key='schema_version'").get().value,
|
||||
};
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
|
||||
test('SP9 a store opened at schema 3w has no project_system_types table', (t) => {
|
||||
assert.equal(SCHEMA_VERSION, '3w');
|
||||
assert.equal(ddl.includes(TABLE), false, 'schema.sql no longer creates the table');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sp9-fresh-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
new Store(root).close();
|
||||
const fresh = named(join(root, 'bus/bus.sqlite'));
|
||||
assert.equal(fresh.version, '3w');
|
||||
assert.deepEqual(fresh.master, []);
|
||||
});
|
||||
|
||||
test('SP9 a 3v store holding project_system_types rows migrates to 3w with nothing of the table left', (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sp9-3v-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite');
|
||||
const db = new DatabaseSync(path);
|
||||
// The 3v schema is today's schema.sql plus what 3t-3u created; the store's step check refuses any
|
||||
// other shape, so a migration that succeeds proves the fixture is a real 3v store.
|
||||
db.exec(ddl + createdBy3u);
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_version', '3v');
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('comment_cursor_epoch', '2026-11-12T00:00:00.000Z');
|
||||
db.prepare('INSERT INTO projects(id,at,business,name,repo,created_by) VALUES(?,?,?,?,?,?)').run('p1', '2026-11-12T00:00:00.000Z', 'acme', 'example', null, 'jason');
|
||||
const select = db.prepare(`INSERT INTO ${TABLE}(at,business,project,types,by) VALUES(?,?,?,?,?)`);
|
||||
select.run('2026-11-12T00:00:01.000Z', 'acme', 'p1', '["coding"]', 'jason');
|
||||
select.run('2026-11-12T00:00:02.000Z', 'acme', 'p1', '["coding","montage"]', 'jason');
|
||||
db.close();
|
||||
chmodSync(path, 0o600);
|
||||
const before = named(path);
|
||||
assert.deepEqual(before.master.map((r) => r.name).sort(), [TABLE, `${TABLE}_business`, `${TABLE}_no_delete`, `${TABLE}_no_replace`, `${TABLE}_no_update`, `${TABLE}_project`]);
|
||||
assert.deepEqual(before.sequence, [TABLE]);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
assert.deepEqual(named(path), before, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(store.get('SELECT name FROM projects WHERE id=?', 'p1').name, 'example', 'other rows stay');
|
||||
const after = named(path);
|
||||
assert.equal(after.version, '3w');
|
||||
assert.deepEqual(after.master, [], 'no table, index or trigger of that name is left');
|
||||
assert.deepEqual(after.sequence, [], 'no sqlite_sequence row of that name is left');
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'sp9-ref-'));
|
||||
t.after(() => rmSync(freshRoot, { recursive: true, force: true }));
|
||||
new Store(freshRoot).close();
|
||||
assert.equal(after.digest, named(join(freshRoot, 'bus/bus.sqlite')).digest, 'the migrated schema is the fresh one');
|
||||
});
|
||||
@@ -528,7 +528,8 @@ test('v3b prototype refusals, views and append-only mutations', (t) => {
|
||||
// Task 4 (3p to 3q), Task 3 (3q to 3r) and Task 6b (3r to 3s) widen request_events.kind in place.
|
||||
// #797 MVP3 (3s to 3t) adds project_archives and its five guards; project-archive.test.mjs tests them.
|
||||
// 3t to 3u adds project_system_types and four guards; U4a #1873 (3u to 3v) adds store_tasks and its seven guards.
|
||||
assert.equal(count('table') - 1, 33);
|
||||
assert.equal(count('trigger'), 130);
|
||||
// SP9 #1873 (3v to 3w) drops project_system_types and its four guards.
|
||||
assert.equal(count('table') - 1, 32);
|
||||
assert.equal(count('trigger'), 126);
|
||||
assert.equal(count('view'), 5);
|
||||
});
|
||||
@@ -530,9 +530,9 @@ test('T4 schema: a 3m store migrates to 3n, session_ops and message_cancels are
|
||||
const before = tables(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
const after = tables(path);
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'project_system_types', 'store_tasks']) {
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'store_tasks']) {
|
||||
assert.deepEqual(after[name], [], name);
|
||||
delete after[name];
|
||||
}
|
||||
@@ -571,7 +571,7 @@ async function engine3m(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3m).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3m';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3m';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 271 \(#1776\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3m';") && edited.includes('3l-3m') && !edited.includes('3m-3n'), 'the 3m engine has no 3m→3n step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -588,7 +588,7 @@ test('T4 schema: the 3m engine refuses a 3n store, migrating or not, and leaves
|
||||
const Store3m = await engine3m(root);
|
||||
assert.throws(() => new Store3m(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3m(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(tables(path), before);
|
||||
// The same engine opens a fresh 3m store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -374,7 +374,7 @@ test('T7: a 3k store migrates to 3l, each thread\'s default session has the thre
|
||||
const { root, path } = source3k(t);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
// The migrated schema is the fresh one, object for object.
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'sessions-fresh-'));
|
||||
t.after(() => rmSync(freshRoot, { recursive: true, force: true }));
|
||||
@@ -430,7 +430,7 @@ async function engine3k(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3k).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3k';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3k';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 264a \(#1769\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3k';") && edited.includes('3j-3k') && !edited.includes('3k-3l'), 'the 3k engine has no 3k→3l step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -447,7 +447,7 @@ test('T7 D9: the 3k engine refuses a 3l store, migrating or not, and leaves it a
|
||||
const Store3k = await engine3k(root);
|
||||
assert.throws(() => new Store3k(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3k(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
// The same engine opens a fresh 3k store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -63,7 +63,7 @@ test('3e copy migrates through 3f to 3g preserving every old column/row and addi
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT spec_path,spec_commit FROM decisions') }, { spec_path: null, spec_commit: null });
|
||||
assert.equal(store.get('PRAGMA quick_check').quick_check, 'ok');
|
||||
assert.deepEqual(store.all('PRAGMA foreign_key_check'), []);
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { Broker } from '../src/broker.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
|
||||
test('project selections require enabled types, retain inactive selections, and only the owner writes', t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-'));
|
||||
const store = new Store(root); t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: [], crossRole: [] } } }, projects: {}, plugins: { 'system-type': ['coding'] }, vars: { 'bus.tester': true } };
|
||||
const broker = new Broker({ store, businesses: { demo: business } });
|
||||
const owner = broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const tester = broker.bindTester({ business: 'demo' });
|
||||
const agent = broker.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' });
|
||||
const call = (verb, args = {}, cap = owner) => broker.request(cap, { verb, args });
|
||||
const project = call('project.create', { name: 'example' }).id;
|
||||
assert.deepEqual(call('project.system-types', { project }), { project, selected: [], active: [], inactive: [] });
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['montage'] }), /system-type-not-enabled/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding'] }, tester), /tester-refused/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding'] }, agent), /human-required/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding', 'coding'] }), /invalid-request/);
|
||||
call('project.system-types.set', { project, systemTypes: ['coding'] });
|
||||
assert.deepEqual(call('project.system-types', { project }).active, ['coding']);
|
||||
broker.reloadBusiness('demo', { ...business, plugins: { 'system-type': [] } });
|
||||
assert.deepEqual(call('project.system-types', { project }), { project, selected: ['coding'], active: [], inactive: ['coding'] });
|
||||
assert.deepEqual(store.all('SELECT by FROM project_system_types').map(r => r.by), ['jason']);
|
||||
assert.throws(() => store.run("UPDATE project_system_types SET types='[]'"), /append-only/);
|
||||
assert.throws(() => store.run('DELETE FROM project_system_types'), /append-only/);
|
||||
assert.throws(() => store.run("INSERT INTO project_system_types(at,business,project,types,by) VALUES(?,?,?,?,?)", new Date().toISOString(), 'other', project, '[]', 'jason'), /belongs to its project/);
|
||||
});
|
||||
|
||||
test('console owner can read system types but cannot write project selections', async t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-'));
|
||||
const store = new Store(root); t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: [], crossRole: [] } } }, projects: {}, plugins: { 'system-type': ['coding'] }, vars: { 'bus.tester': true } };
|
||||
let discoveries = 0, enabled = ['coding'];
|
||||
const broker = new Broker({ store, businesses: { demo: business }, organization: (_id, verb) => { if (verb === 'system-types.current') return enabled; if (verb === 'system-types.installed') { discoveries++; return installedSystemTypes(); } } });
|
||||
const owner = broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const consoleOwner = broker.bindConsole({ business: 'demo', human: 'jason', subject: { provider: 'test', iss: 'test', sub: 'owner' } });
|
||||
const tester = broker.bindTester({ business: 'demo' });
|
||||
assert.throws(() => broker.request(tester, { verb: 'plugins.set', args: { revision: 'a'.repeat(64), plugins: { 'system-type': ['coding'] } } }), /human-required/);
|
||||
const project = broker.request(owner, { verb: 'project.create', args: { name: 'example' } }).id;
|
||||
const result = await broker.request(consoleOwner, { verb: 'system-types.console', args: { project } });
|
||||
assert.deepEqual(result.enabled, ['coding']);
|
||||
assert.equal(result.installed.length, 5);
|
||||
assert.equal(discoveries, 1);
|
||||
broker.request(owner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } });
|
||||
enabled = [];
|
||||
assert.deepEqual(broker.request(owner, { verb: 'project.system-types', args: { project } }).inactive, ['coding']);
|
||||
assert.throws(() => broker.request(owner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } }), /system-type-not-enabled/);
|
||||
assert.deepEqual(result.project, { project, selected: [], active: [], inactive: [] });
|
||||
assert.throws(() => broker.request(consoleOwner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } }), /human-required/);
|
||||
});
|
||||
|
||||
test('3t store migrates offline without altering existing project rows', async t => {
|
||||
const { DatabaseSync } = await import('node:sqlite');
|
||||
const { readFileSync, mkdirSync, chmodSync } = await import('node:fs');
|
||||
const { schemaDigest } = await import('../src/store.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-migration-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const dbpath = join(root, 'bus/bus.sqlite');
|
||||
const db = new DatabaseSync(dbpath);
|
||||
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
|
||||
const step = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
assert.equal(ddl.split(step).length, 2);
|
||||
// 3u-3v (U4a) adds store_tasks after this step; a 3t store has neither.
|
||||
const later = readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8');
|
||||
db.exec(ddl.replace(step, '').replace(later, ''));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_version', '3t');
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('comment_cursor_epoch', '2026-01-01T00:00:00.000Z');
|
||||
db.prepare('INSERT INTO projects(id,at,business,name,repo,created_by) VALUES(?,?,?,?,?,?)').run('old', '2026-01-01T00:00:00.000Z', 'demo', 'old', null, 'jason');
|
||||
db.close(); chmodSync(dbpath, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const migrated = new Store(root, { migrateSchema: true }); t.after(() => migrated.close());
|
||||
assert.equal(migrated.get('SELECT name FROM projects WHERE id=?', 'old').name, 'old');
|
||||
assert.equal(migrated.get('SELECT count(*) AS n FROM project_system_types').n, 0);
|
||||
assert.equal(migrated.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
});
|
||||
|
||||
test('runtime reads the current organization file for project selections and console discovery', async t => {
|
||||
const { mkdirSync } = await import('node:fs');
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-runtime-'));
|
||||
const rolesDir = rolesCopy(root), doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { 'system-type': ['coding'] };
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: {chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: { authority: { withinRole: [], crossRole: [] } } } };
|
||||
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: business }, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
t.after(async () => { await bus.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const consoleOwner = bus.broker.bindConsole({ business: 'demo', human: 'jason', subject: { provider: 'test', iss: 'test', sub: 'owner' } });
|
||||
const call = (verb, args = {}, cap = human) => bus.broker.request(cap, { verb, args });
|
||||
const project = call('project.create', { name: 'example' }).id;
|
||||
call('project.system-types.set', { project, systemTypes: ['coding'] });
|
||||
const view = await call('system-types.console', { project }, consoleOwner);
|
||||
assert.deepEqual(view.enabled, ['coding']);
|
||||
assert.deepEqual(view.project.active, ['coding']);
|
||||
assert.equal(view.installed.length, 5);
|
||||
const plugins = call('plugins');
|
||||
call('plugins.set', { revision: plugins.revision, plugins: { 'system-type': [] } });
|
||||
assert.deepEqual(call('project.system-types', { project }).inactive, ['coding']);
|
||||
});
|
||||
@@ -402,7 +402,8 @@ test('REQ-TASK-1 a 3u store migrates to 3v: store_tasks is new and empty, every
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite'), db = new DatabaseSync(path);
|
||||
db.exec(currentDDL.replace(stepSQL, ''));
|
||||
// SP9 (#1873): a 3u store still has what 3t-3u created; 3v-3w drops it on the way to the fresh schema.
|
||||
db.exec(currentDDL.replace(stepSQL, '') + readFileSync(here('../src/migrations/3t-3u.sql'), 'utf8'));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_version', '3u');
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('comment_cursor_epoch', '2026-11-09T00:00:00.000Z');
|
||||
@@ -414,7 +415,7 @@ test('REQ-TASK-1 a 3u store migrates to 3v: store_tasks is new and empty, every
|
||||
assert.deepEqual(master(path), was, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.equal(store.get('SELECT id FROM events').id, 'preserved');
|
||||
assert.deepEqual(store.all('SELECT * FROM store_tasks'), []);
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'ts-fresh-'));
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// #1873 SP8: saving a template at the bus. Only the organization's owner saves or lists: the CLI's
|
||||
// human cap on the unsuffixed names, the owner's console cap on the .console ones. The saved file
|
||||
// applies through SP4 as saved:<name> for its saver.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { CONSOLE_VERBS, TEMPLATE_BUS_KEYS, TESTER_ORGANIZATION_VERBS } from '../src/broker.mjs';
|
||||
import { REFUSALS } from '../src/refusals.mjs';
|
||||
import { VERB_RIGHTS } from '../../organization/src/org-rights.mjs';
|
||||
|
||||
const TOKEN = 'fixture-held-token-sp8-bus-3a9d';
|
||||
const SUBJECT = { provider: 'test', iss: 'test', sub: 'owner' };
|
||||
|
||||
async function harness(t, { mutate = () => {} } = {}) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
|
||||
const { entryFromTemplate, readTemplate } = await import('../../organization/src/definitions.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'tmpl-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
const writer = entryFromTemplate(readTemplate(rolesDir, 'coder'));
|
||||
writer.instructions = 'Write code for demo. Ask jason.';
|
||||
doc.definitions = { writer };
|
||||
// An instance of the org definition, with its own token files and tracker bot.
|
||||
doc.roles.ana = { ...structuredClone(doc.roles.coder), definition: 'org:writer', tracker: { bot: 'bot-demo-ana', botId: 11 } };
|
||||
mutate(doc, root);
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const data = join(root, 'data');
|
||||
mkdirSync(data, { mode: 0o700 });
|
||||
const token = join(root, 'held.token');
|
||||
writeFileSync(token, TOKEN, { mode: 0o600 });
|
||||
chmodSync(token, 0o600);
|
||||
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } },
|
||||
coder: { authority: { withinRole: [], crossRole: [] }, credentials: { gitea: { file: token, rotateBy: '2099-01-01' } } } };
|
||||
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, vars: { 'bus.tester': true }, roles } };
|
||||
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
t.after(async () => { await bus.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const b = bus.broker;
|
||||
const consoleOwner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const call = async (verb, args = {}, cap = consoleOwner) => b.request(cap, { verb, args });
|
||||
const path = join(root, 'businesses/demo.json');
|
||||
const saved = (name, account = 'jason') => join(root, 'templates', account, `${name}.json`);
|
||||
return { bus, b, root, rolesDir, path, consoleOwner, human, call, saved };
|
||||
}
|
||||
|
||||
// Preview, then save with the preview's digest: the console names by default, the cli names for cap.
|
||||
const save = async (call, name, extra = {}, cap) => {
|
||||
const verb = cap ? 'template.save' : 'template.save.console';
|
||||
const preview = await call(verb, { name, preview: true, ...extra }, cap);
|
||||
return { preview, out: await call(verb, { name, digest: preview.digest, ...extra }, cap) };
|
||||
};
|
||||
|
||||
test('SP8 red before: the owner saves an organization whose instance holds credentials; neither credentials nor copy material reach the file', async t => {
|
||||
const { call, saved, root } = await harness(t);
|
||||
const { preview, out } = await save(call, 'demo-shape');
|
||||
assert.deepEqual(out, { name: 'demo-shape', scope: 'org', digest: preview.digest });
|
||||
const text = readFileSync(saved('demo-shape'), 'utf8');
|
||||
assert.equal(text, preview.json);
|
||||
for (const k of ['copyBindings', 'copyId', 'orgIncarnation', 'generation', 'tracker', 'holder']) assert.ok(!text.includes(`"${k}"`), k);
|
||||
assert.ok(!text.includes(join(root, 'secrets')), 'a token file path reached the template');
|
||||
assert.ok(!text.includes('"file"'));
|
||||
// The role's credential request lines are kept.
|
||||
assert.ok(JSON.parse(text).definitions.writer.role.credentials.length > 0);
|
||||
});
|
||||
|
||||
test('SP8 a saved template applies through SP4 as saved:<name> for its saver', async t => {
|
||||
const { call, path } = await harness(t);
|
||||
await save(call, 'demo-shape');
|
||||
const listed = await call('template.list.console');
|
||||
assert.deepEqual(listed.templates.map(x => [x.name, x.scope]), [['demo-shape', 'org']]);
|
||||
const preview = await call('pack.preview.console', { pack: 'saved:demo-shape' });
|
||||
assert.equal(preview.pack.origin, 'saved');
|
||||
assert.ok(preview.hires.some(h => h.name === 'coder-1'), JSON.stringify(preview.hires.map(h => h.name)));
|
||||
const before = JSON.parse(readFileSync(path, 'utf8'));
|
||||
const out = await call('pack.apply.console', { pack: 'saved:demo-shape', digest: preview.digest });
|
||||
const after = JSON.parse(readFileSync(path, 'utf8'));
|
||||
assert.equal(after.packs.length, (before.packs ?? []).length + 1);
|
||||
assert.equal(after.packs.at(-1).origin, 'saved');
|
||||
assert.equal(after.packs.at(-1).id, 'demo-shape');
|
||||
// writer is already the organization's own (same); the template references the coder template.
|
||||
assert.ok(out.added.includes('definitions.coder'), JSON.stringify(out.added));
|
||||
assert.equal(preview.hires.find(h => h.name === 'coder-1').definition, 'writer');
|
||||
});
|
||||
|
||||
test('SP8 the owner\'s CLI cap saves on the unsuffixed name and writes the file', async t => {
|
||||
const { call, human, saved } = await harness(t);
|
||||
const { out } = await save(call, 'cli-shape', {}, human);
|
||||
assert.equal(out.name, 'cli-shape');
|
||||
assert.ok(existsSync(saved('cli-shape')));
|
||||
assert.deepEqual((await call('template.list', {}, human)).templates.map(x => x.name), ['cli-shape']);
|
||||
});
|
||||
|
||||
test('SP8 who may call: a member\'s session, an agent and the tester refuse; the owner\'s console cap cannot call the cli name', async t => {
|
||||
const { b, call, human, root } = await harness(t);
|
||||
assert.deepEqual(TESTER_ORGANIZATION_VERBS, ['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
|
||||
const member = b.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read', 'org.setup'] });
|
||||
for (const verb of ['template.save', 'template.save.console']) assert.throws(() => b.request(member, { verb, args: { name: 'x', preview: true } }), /human-required/);
|
||||
for (const verb of ['template.list', 'template.list.console']) assert.throws(() => b.request(member, { verb, args: {} }), /human-required/);
|
||||
const tester = b.bindTester({ business: 'demo' });
|
||||
assert.throws(() => b.request(tester, { verb: 'template.save', args: { name: 'x', preview: true } }), /tester-refused/);
|
||||
const agent = b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
|
||||
b.request(agent, { verb: 'role.claim' });
|
||||
for (const verb of ['template.save', 'template.save.console']) assert.throws(() => b.request(agent, { verb, args: { name: 'x', preview: true } }), /human-required/);
|
||||
await assert.rejects(call('template.save', { name: 'x', preview: true }), /human-required/);
|
||||
await assert.rejects(call('template.save.console', { name: 'x', preview: true }, human), /human-required/);
|
||||
assert.ok(!existsSync(join(root, 'templates')));
|
||||
});
|
||||
|
||||
test('SP8 the real credential store: a held value in kept text refuses template-secret-suspected with the field path as its reason', async t => {
|
||||
// A definition holding one never loads (definition-holds-credential); workflow text is what save
|
||||
// must catch itself.
|
||||
const workflow = { description: `Ship it, key ${TOKEN}`, steps: [{ title: 'Write', state: 'todo', roles: ['writer'] }] };
|
||||
const { call, root } = await harness(t, { mutate: doc => { doc.workflows = { change: workflow }; } });
|
||||
await assert.rejects(call('template.save.console', { name: 'leaky', preview: true }), (e) => {
|
||||
assert.equal(e.code, 'template-secret-suspected');
|
||||
assert.equal(e.reason, 'workflows.change.description');
|
||||
assert.ok(!String(e.message).includes(TOKEN) && !JSON.stringify(e).includes(TOKEN));
|
||||
return true;
|
||||
});
|
||||
assert.ok(!existsSync(join(root, 'templates')));
|
||||
});
|
||||
|
||||
test('SP8 a key that holds a held value: the refusal reason masks it as [key], never the value', async t => {
|
||||
// A definition keyed by one never loads (definition-holds-credential); a workflow keyed by one is
|
||||
// what save sees. The broker also drops any reason its credential check refuses.
|
||||
const workflow = { description: 'Ship it.', steps: [{ title: 'Write', state: 'todo', roles: ['writer'] }] };
|
||||
const { call, root } = await harness(t, { mutate: doc => { doc.workflows = { [TOKEN]: workflow }; } });
|
||||
await assert.rejects(call('template.save.console', { name: 'leaky', preview: true }), (e) => {
|
||||
assert.equal(e.code, 'template-secret-suspected');
|
||||
assert.equal(e.reason, 'workflows[key]');
|
||||
assert.ok(!String(e.message).includes(TOKEN) && !JSON.stringify(e).includes(TOKEN));
|
||||
return true;
|
||||
});
|
||||
assert.ok(!existsSync(join(root, 'templates')));
|
||||
});
|
||||
|
||||
test('SP8 a save after a real pack.apply.console keeps each packs entry as {id, version}', async t => {
|
||||
const { call, saved } = await harness(t);
|
||||
const packs = await call('packs.console');
|
||||
const shipped = packs.packs.find(p => p.origin === 'shipped');
|
||||
assert.ok(shipped, JSON.stringify(packs.packs.map(p => [p.id, p.origin])));
|
||||
const pack = await call('pack.preview.console', { pack: shipped.id });
|
||||
await call('pack.apply.console', { pack: shipped.id, digest: pack.digest });
|
||||
await save(call, 'after-apply');
|
||||
const kept = JSON.parse(readFileSync(saved('after-apply'), 'utf8')).packs;
|
||||
assert.deepEqual(kept, [{ id: shipped.id, version: pack.pack.version }]);
|
||||
});
|
||||
|
||||
test('SP8 argument checks: a second save, a .. name, an unknown key, preview with a digest, and a stale digest', async t => {
|
||||
const { call, saved } = await harness(t);
|
||||
const { preview } = await save(call, 'demo-shape');
|
||||
const first = readFileSync(saved('demo-shape'));
|
||||
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'invalid-request' && e.reason === 'a template of this name is already saved');
|
||||
assert.deepEqual(readFileSync(saved('demo-shape')), first);
|
||||
for (const name of ['..', '../x', 'a/b']) await assert.rejects(call('template.save.console', { name, preview: true }), { code: 'invalid-request' });
|
||||
for (const args of [{ name: 'x', preview: true, account: 'alex' }, { name: 'x', preview: true, digest: preview.digest }, { name: 'x' }, { preview: true }, { name: 'x', preview: false }])
|
||||
await assert.rejects(call('template.save.console', args), { code: 'invalid-request' });
|
||||
await assert.rejects(call('template.list.console', { account: 'alex' }), { code: 'invalid-request' });
|
||||
await assert.rejects(call('template.save.console', { name: 'other', digest: preview.digest }), { code: 'pack-plan-stale' });
|
||||
});
|
||||
|
||||
test('SP8 the schema pins: both .console verbs are console verbs, owner-only in VERB_RIGHTS, and template-secret-suspected has a rail', () => {
|
||||
for (const verb of ['template.save.console', 'template.list.console']) {
|
||||
assert.ok(CONSOLE_VERBS.includes(verb), verb);
|
||||
assert.ok(Object.hasOwn(VERB_RIGHTS, verb) && VERB_RIGHTS[verb] === null, verb);
|
||||
assert.ok(Object.hasOwn(TEMPLATE_BUS_KEYS, verb));
|
||||
}
|
||||
assert.ok(!CONSOLE_VERBS.includes('template.save') && !CONSOLE_VERBS.includes('template.list'));
|
||||
const c = 'template-secret-suspected';
|
||||
assert.ok(Object.hasOwn(REFUSALS, c));
|
||||
assert.ok(REFUSALS[c].rail?.length > 5);
|
||||
assert.ok(REFUSALS[c].nextStep?.length > 20);
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[c].nextStep));
|
||||
});
|
||||
@@ -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 = '3v';", "export const SCHEMA_VERSION = '3d';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "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);
|
||||
@@ -101,7 +101,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, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
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.
|
||||
@@ -161,5 +161,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 3v ready', ''].join('\n'));
|
||||
assert.equal(migrated.stdout, [...REPORT, 'bus schema 3w ready', ''].join('\n'));
|
||||
});
|
||||
@@ -403,12 +403,12 @@ test('a 3l store migrates to 3m: thread_shares is new and empty, and every other
|
||||
const before = tables(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
const after = tables(path);
|
||||
assert.deepEqual(after.thread_shares, []);
|
||||
delete after.thread_shares;
|
||||
// Row 271 (#1776): the 3m→3n step's session_ops and message_cancels, new and empty too.
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'project_system_types', 'store_tasks']) {
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'store_tasks']) {
|
||||
assert.deepEqual(after[name], [], name);
|
||||
delete after[name];
|
||||
}
|
||||
@@ -439,7 +439,7 @@ async function engine3l(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3l).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3l';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3l';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 206 \(193b2[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3l';") && edited.includes('3k-3l') && !edited.includes('3l-3m'), 'the 3l engine has no 3l→3m step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -456,7 +456,7 @@ test('the 3l engine refuses a 3m store, migrating or not, and leaves it as it wa
|
||||
const Store3l = await engine3l(root);
|
||||
assert.throws(() => new Store3l(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3l(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(tables(path), before);
|
||||
// The same engine opens a fresh 3l store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -68,7 +68,7 @@ test('REQ-LIMIT-4 3g copy migrates through 3h, 3i, 3j and 3k to 3l preserving ev
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT to_name FROM messages') }, { to_name: null });
|
||||
assert.equal(store.get('SELECT count(*) AS n FROM usage_records').n, 0);
|
||||
assert.equal(store.get('SELECT name FROM instance_names').name, 'Builder');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// Old path of packages/organization/src/copy-binding-status.mjs (rename design r2, stage B).
|
||||
export * from "../../organization/src/copy-binding-status.mjs";
|
||||
@@ -0,0 +1,2 @@
|
||||
// Old path of packages/organization/src/template-save.mjs (rename design r2, stage B).
|
||||
export * from "../../organization/src/template-save.mjs";
|
||||
@@ -1370,15 +1370,6 @@ field, digest and archive checks. Edit and archive need the task's digest from
|
||||
`mosaic tasks --json` as `--expect`; a stale one is refused `task-conflict`
|
||||
(exit 2) and nothing is written. They refuse inside an agent run.
|
||||
|
||||
System types are installed plug-ins. `mosaic org system-types installed` prints
|
||||
module metadata; `mosaic org system-types enabled ID` prints an organization's enabled
|
||||
ids. The owner changes the enabled list through the existing organization file
|
||||
update or `mosaic plugins set`. `mosaic project system-types PROJECT --org ID`
|
||||
shows selected, active and inactive ids. The owner replaces the selection with
|
||||
`mosaic project system-types-set PROJECT --types coding,montage --org ID`; an
|
||||
empty `--types ''` clears it. Disabled selections stay recorded but become
|
||||
inactive. Project settings changes are append-only and require human proof.
|
||||
|
||||
## Accounts
|
||||
|
||||
`mosaic accounts` administers the instance-level accounts store locally, as the
|
||||
|
||||
@@ -75,7 +75,8 @@ export function readAccounting({ dataRoot,business,start,end }) {
|
||||
try {
|
||||
db.exec('BEGIN');
|
||||
// U4a (#1873) 3u-3v adds only store_tasks, which accounting never reads, so 3v joins the closed list.
|
||||
if (!['3s','3t','3u','3v'].includes(db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value)) fail('test-store-schema-refused');
|
||||
// SP9 (#1873) 3v-3w drops only the table 3t-3u added, which accounting never reads, so 3w joins too.
|
||||
if (!['3s','3t','3u','3v','3w'].includes(db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value)) fail('test-store-schema-refused');
|
||||
const store = { all:(sql,...args) => db.prepare(sql).all(...args) };
|
||||
const records = turnRecords(store,business);
|
||||
const raw = store.all("SELECT * FROM usage_records WHERE business=? AND source<>'@proxy/cliproxy-queue' ORDER BY seq",business);
|
||||
|
||||
@@ -79,7 +79,7 @@ test('accounting reads a real store at the current bus schema version',t=>{
|
||||
const records=readAccounting({dataRoot:f.dataRoot,business:f.c.business,start:f.c.start,end:f.c.end});
|
||||
assert.equal(records.length,1);assert.equal(records[0].input,1);
|
||||
});
|
||||
for(const version of ['3s','3r','3v',null]) test(`accounting ${version==='3s'?'accepts':'refuses'} schema ${version??'missing'}`,t=>{
|
||||
for(const version of ['3s','3r','3x',null]) test(`accounting ${version==='3s'?'accepts':'refuses'} schema ${version??'missing'}`,t=>{
|
||||
const f=setup(t,100);
|
||||
// Only this disposable fixture is altered; the production meta table is append-only.
|
||||
f.store.run('DROP TRIGGER meta_no_update');f.store.run('DROP TRIGGER meta_no_delete');
|
||||
|
||||
@@ -778,7 +778,7 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
|
||||
if (["inbox", "decide", "tasks", "agents", "trail"].includes(verb)) return human(verb, rest, io, deps);
|
||||
if (verb === "project" && rest[0] === "north-star") return northStarCommand(rest.slice(1), io, (p) => callFor(p, io, deps));
|
||||
if (verb === "project" && rest[0] === "interview") return interviewCommand(rest.slice(1), io);
|
||||
if (verb === "project") return ["create", "list", "archive", "unarchive", "system-types", "system-types-set"].includes(rest[0]) ? projectBusCommand(rest, io, (p) => channelCallFor(p, io, deps)) : projectCommand(rest, io, deps, (p) => callFor(p, io, deps));
|
||||
if (verb === "project") return ["create", "list", "archive", "unarchive"].includes(rest[0]) ? projectBusCommand(rest, io, (p) => channelCallFor(p, io, deps)) : projectCommand(rest, io, deps, (p) => callFor(p, io, deps));
|
||||
if (verb === "threads") return threadsCommand(rest, io, (p) => channelCallFor(p, io, deps));
|
||||
if (verb === "session") return sessionCommand(rest, io, (p) => channelCallFor(p, io, deps));
|
||||
if (verb === "thread") return threadCommand(rest, io, (p) => channelCallFor(p, io, deps), formatMessage);
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
// instance.request until the request closes or --wait runs out (D1.1 item 5).
|
||||
import { readFileSync } from "node:fs";
|
||||
import { CliError } from "./errors.mjs";
|
||||
import { copyBindingStatus } from "../../organization/src/copy-binding-status.mjs";
|
||||
import { SERVICES } from "../../organization/src/vocabulary.mjs";
|
||||
|
||||
export const INSTANCES_USAGE = "mosaic business instances BUSINESS [--json] [--tester] | " +
|
||||
"business instance add BUSINESS INSTANCE --definition DEF [--vars FILE] [--launch] [--bot BOT --bot-id N] --revision REV [--tester] | " +
|
||||
@@ -219,6 +221,16 @@ export function formatInstances(view) {
|
||||
const vars = Object.keys(entry.vars).length ? ` vars ${JSON.stringify(entry.vars)}` : "";
|
||||
lines.push(` ${name}: ${entry.definition}${marks.length ? ` (${marks.join(", ")})` : ""}${vars}`);
|
||||
}
|
||||
// #1873 CB5: each copy that needs a credential binding, with the bus's status code and its fixed
|
||||
// next step (organization copy-binding-status.mjs). A code the table doesn't know prints its own
|
||||
// fixed fallback; nothing else from the answer is printed for it.
|
||||
for (const [name, copy] of Object.entries(view.copies ?? {})) {
|
||||
if (!copy?.binding) continue;
|
||||
const { status, next } = copyBindingStatus(copy.binding.status);
|
||||
// The services the copy lacks, as registered service labels only; nothing else the bus sent.
|
||||
const missing = copy.state === "unbound" && Array.isArray(copy.missing) ? SERVICES.filter((s) => copy.missing.includes(s)) : [];
|
||||
lines.push(` ${name} (copy): ${status}${missing.length ? ` (missing ${missing.join(", ")})` : ""}. ${next}`);
|
||||
}
|
||||
const definitions = Object.entries(view.definitions);
|
||||
const accepted = definitions.filter(([, d]) => d.accepted).map(([name]) => name);
|
||||
const bound = definitions.filter(([, d]) => d.services.length).map(([name, d]) => `${name} (${d.services.join(", ")})`);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { basename } from 'node:path';
|
||||
import { listOrgs, orgLock, resolveOrg } from '../../organization/src/org-registry.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { templateRender, validateOrg, createOrg, showOrg, updateOrg, queueInit, queueShow, projectRepoInit, projectRepoShow, projectRepoSet, deleteOrg, archiveOrg, restoreOrg } from '../../organization/src/org-service.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
import { installedStarterPacks } from '../../plugins/src/starter-pack.mjs';
|
||||
import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs';
|
||||
import { loadSystem, orgPaths, rolesDir } from './config.mjs';
|
||||
@@ -17,7 +16,9 @@ import { definitionsCommand, DEFINITIONS_USAGE } from './org-definitions.mjs';
|
||||
import { orgOwnerCommand, ORG_OWNER_USAGE, ORG_OWNER_VERBS } from './org-owner.mjs';
|
||||
// Starter packs SP4 (design section 8): the owner's pack, board and workflow words.
|
||||
export const PACKS_USAGE = 'mosaic org pack list | pack preview ID PACK [--project P] [--as KIND.NAME=NEW]... | pack apply ID PACK --digest D [--project P] [--as KIND.NAME=NEW]... | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
|
||||
export const ORG_USAGE = 'mosaic org system-types installed | system-types enabled ID | lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
|
||||
// #1873 SP8: saving the organization, or one project, as a template; the owner's alone.
|
||||
export const TEMPLATE_USAGE = 'mosaic org template save ID NAME [--project P] (--preview | --digest D) | template list ID';
|
||||
export const ORG_USAGE = 'mosaic org lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | ' + TEMPLATE_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
|
||||
function parse(args) { const pos = [], values = {}, flags = new Set(); for (let i = 0; i < args.length; i++) { const a = args[i]; if (['--json', '--local-only', '--accept-local-loss-risk', '--no-bus'].includes(a)) { if (flags.has(a)) throw new CliError(`duplicate ${a}`, 4); flags.add(a); } else if (['--fixture', '--output', '--from', '--if-revision', '--remote', '--confirm'].includes(a)) { if (values[a] !== undefined || !args[i+1] || args[i+1].startsWith('--')) throw new CliError(`${a} needs one value`, 4); values[a] = args[++i]; } else if (a.startsWith('--')) throw new CliError(`unknown option ${a}`, 4); else pos.push(a); } return { pos, values, flags }; }
|
||||
// A refusal names the document by label and the error by its code, never by host path or bytes (PR #1916).
|
||||
const errorCode = e => typeof e?.code === 'string' && /^E[A-Z0-9]+$/.test(e.code) ? e.code : 'unreadable';
|
||||
@@ -90,8 +91,7 @@ async function packsCommand(args, io, deps) {
|
||||
else if (word === 'workflow' && sub === 'remove' && pos.length === 4) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: null, ...project }; }
|
||||
else throw new CliError(PACKS_USAGE, 4);
|
||||
// pack list names no organization, so it reads what the bus's `packs` verb reads (the shipped and
|
||||
// installed packs, never a saved template) from this instance's data root, as `system-types
|
||||
// installed` does.
|
||||
// installed packs, never a saved template) from this instance's data root.
|
||||
if (verb === 'packs') {
|
||||
const system = deps.system ?? loadSystem({ env: io.env, instance: devOwnerInstance(io.env) });
|
||||
const { packs } = await installedStarterPacks({ dataRoot: system.dataRoot, rolesDir: rolesDir(io.env) });
|
||||
@@ -114,6 +114,49 @@ async function packsCommand(args, io, deps) {
|
||||
}
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
// #1873 SP8: template save previews (--preview) or writes the previewed JSON (--digest); template
|
||||
// list prints the owner's saved templates. Both call the bus as the owner's human; an agent run is
|
||||
// refused before the bus is called.
|
||||
const TEMPLATE_REFUSALS = {
|
||||
'template-secret-suspected': 'a field the template would keep holds a credential the organization\'s bus holds; remove it and preview again (nothing was written)',
|
||||
'pack-plan-stale': 'the organization or a template changed since the preview; preview again and save its digest',
|
||||
'invalid-request': 'the bus refused the request: a bad name, a name already saved, an unknown project, or an organization the template cannot hold',
|
||||
'human-required': 'only the organization\'s owner, from a human shell, may do this',
|
||||
'not-configured': 'the templates directory is missing or not private to this instance\'s user',
|
||||
'starter-pack-invalid': 'the template would not be a valid pack: more than 8 hires, or a definition wider than its template',
|
||||
};
|
||||
async function templateCommand(args, io, deps) {
|
||||
const pos = [], values = {}, flags = new Set();
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i];
|
||||
if (['--project', '--digest'].includes(a)) {
|
||||
if (!args[i + 1] || args[i + 1].startsWith('--') || values[a] !== undefined) throw new CliError(`${a} needs one value`, 4);
|
||||
values[a] = args[++i];
|
||||
} else if (a === '--preview') { if (flags.has(a)) throw new CliError('--preview is given twice', 4); flags.add(a); }
|
||||
else if (a.startsWith('--')) throw new CliError(`unknown option ${a}`, 4);
|
||||
else pos.push(a);
|
||||
}
|
||||
const [, sub, id, name] = pos;
|
||||
refuseAgentRun(io);
|
||||
let verb, request;
|
||||
if (sub === 'save' && pos.length === 4 && flags.has('--preview') !== (values['--digest'] !== undefined)) {
|
||||
verb = 'template.save';
|
||||
request = { name, ...(values['--project'] === undefined ? {} : { project: values['--project'] }), ...(flags.has('--preview') ? { preview: true } : { digest: values['--digest'] }) };
|
||||
} else if (sub === 'list' && pos.length === 3 && !flags.size && !Object.keys(values).length) { verb = 'template.list'; request = {}; }
|
||||
else throw new CliError(TEMPLATE_USAGE, 4);
|
||||
let result;
|
||||
try { result = await packCall(id, io, deps)(verb, request); }
|
||||
catch (e) {
|
||||
// humanTransport throws a CliError named by the bus code alone: a known code gains its hint.
|
||||
const why = typeof e?.code !== 'string' ? undefined
|
||||
: Object.hasOwn(TEMPLATE_REFUSALS, e.code) ? TEMPLATE_REFUSALS[e.code] : Object.hasOwn(PACK_REFUSALS, e.code) ? PACK_REFUSALS[e.code] : undefined;
|
||||
if (!why) throw e;
|
||||
const error = new CliError(`${e.code}: ${why}`, busExit(e.code));
|
||||
error.code = e.code;
|
||||
throw error;
|
||||
}
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
const busStartVerb = id => `mosaic bus start ${id} --dev-local-owner --detach`;
|
||||
export async function orgCommand(args, io, deps = {}) {
|
||||
try {
|
||||
@@ -122,6 +165,7 @@ export async function orgCommand(args, io, deps = {}) {
|
||||
// E2 (#1873, P1-3): the hire form and the autonomy panel, through the running Console (org-owner.mjs).
|
||||
if (ORG_OWNER_VERBS.includes(args[0])) return await orgOwnerCommand(args, io, deps);
|
||||
if (['pack', 'board', 'workflow'].includes(args[0])) return await packsCommand(args, io, deps);
|
||||
if (args[0] === 'template' && ['save', 'list'].includes(args[1])) return await templateCommand(args, io, deps);
|
||||
const p = parse(args); const words = p.pos; let result; let accepted = [];
|
||||
const allowed = (flags, values) => { for (const f of p.flags) if (!flags.includes(f)) throw new CliError(`unexpected ${f}`, 4); for (const f of Object.keys(p.values)) if (!values.includes(f)) throw new CliError(`unexpected ${f}`, 4); };
|
||||
const need = key => { if (!p.values[key]) throw new CliError(`${key} is required`, 4); return p.values[key]; };
|
||||
@@ -133,10 +177,8 @@ export async function orgCommand(args, io, deps = {}) {
|
||||
let lifecycle = null;
|
||||
if (['archive', 'restore'].includes(words[0]) && words.length === 2) { allowed(['--json', ...(words[0] === 'restore' ? ['--no-bus'] : [])], ['--if-revision']); lifecycle = { ifRevision: revision(p.values['--if-revision'], true) }; if (words[0] === 'archive' || !p.flags.has('--no-bus')) refuseAgentRun(io); }
|
||||
else if (words[0] === 'delete' && words.length === 2) { allowed(['--json'], ['--confirm', '--if-revision']); const ifRevision = revision(p.values['--if-revision'], false); lifecycle = { confirm: need('--confirm'), ifRevision }; refuseAgentRun(io); }
|
||||
if (words[0] === 'system-types' && words[1] === 'installed' && words.length === 2) { allowed(['--json'], []); io.stdout.write(JSON.stringify(await installedSystemTypes(), null, 2) + '\n'); return; }
|
||||
const instance = devOwnerInstance(io.env); const system = deps.system ?? loadSystem({ env: io.env, instance }); const ctx = { configDir: configDir(io.env), dataRoot: system.dataRoot, instance, principal: DEV_OWNER };
|
||||
if (words[0] === 'system-types' && words[1] === 'enabled' && words.length === 3) { allowed(['--json'], []); const org = await showOrg(ctx, words[2]); result = { organization: words[2], enabled: org.doc.plugins?.['system-type'] ?? [] }; }
|
||||
else if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
else if (words[0] === 'create' && words.length === 2) { allowed([], ['--from']); result = await createOrg(ctx, words[1], await document(need('--from'))); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await updateOrg(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'archive' && words.length === 2) result = await archiveOrg(ctx, words[1], { ...lifecycle, busStop: busStopForDelete, copyRemote: await (deps.copyRemoteFor ?? copyRemoteFor)(ctx) });
|
||||
|
||||
@@ -14,8 +14,6 @@ export const PROJECT_USAGE = 'mosaic project init <business> <project> [--tester
|
||||
// and check above work on the repository on disk and never contact the bus, except that
|
||||
// init --tester (row 175, #1673) binds the tester once before it writes.
|
||||
export const PROJECT_BUS_USAGE = [
|
||||
'mosaic project system-types <name-or-id> [--business <id>] [--json]',
|
||||
'mosaic project system-types-set <name-or-id> --types <comma-separated-ids> [--business <id>]',
|
||||
'mosaic project create <name> [--repo <repo>] [--business <id>] [--tester]',
|
||||
'mosaic project list [--archived] [--business <id>] [--json] [--tester]',
|
||||
'mosaic project archive <name-or-id> [--business <id>]',
|
||||
@@ -30,8 +28,8 @@ export async function projectBusCommand(args, io, callFor) {
|
||||
? { flags: ['--tester'], values: ['--repo', '--business'] }
|
||||
: sub === 'list'
|
||||
? { flags: ['--json', '--tester', '--archived'], values: ['--business'] }
|
||||
: { flags: sub === 'system-types' ? ['--json'] : [], values: sub === 'system-types-set' ? ['--business', '--types'] : ['--business'] });
|
||||
const one = ['create', 'archive', 'unarchive', 'system-types', 'system-types-set'].includes(sub);
|
||||
: { flags: [], values: ['--business'] });
|
||||
const one = ['create', 'archive', 'unarchive'].includes(sub);
|
||||
if (parsed.positional.length !== (one ? 1 : 0))
|
||||
throw new CliError(`project ${sub} takes ${one ? (sub === 'create' ? 'one name' : 'one name or id') : 'no arguments'}\n${PROJECT_BUS_USAGE}`, 4);
|
||||
const call = callFor(parsed);
|
||||
@@ -47,17 +45,6 @@ export async function projectBusCommand(args, io, callFor) {
|
||||
}
|
||||
return io.stdout.write(`created project ${name} id ${made.id}\n`);
|
||||
}
|
||||
if (sub === 'system-types' || sub === 'system-types-set') {
|
||||
const projects = await call('project.list', { includeArchived: true });
|
||||
const ref = parsed.positional[0];
|
||||
const hit = projects.find(p => p.id === ref) ?? projects.find(p => p.name === ref);
|
||||
if (!hit) throw new CliError(`no project is named or numbered ${JSON.stringify(ref)}`, 2);
|
||||
const write = sub === 'system-types-set';
|
||||
if (write && parsed.values['--types'] === undefined) throw new CliError('--types is required (an empty string clears the list)', 4);
|
||||
const systemTypes = parsed.values['--types'] ? parsed.values['--types'].split(',') : [];
|
||||
const result = await call(write ? 'project.system-types.set' : 'project.system-types', { project: hit.id, ...(write ? { systemTypes } : {}) });
|
||||
return io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
// #797 MVP3: the owner's reversible archive. Resolution reads the full list, archived included,
|
||||
// so an archived project can be named for unarchive.
|
||||
if (sub === 'archive' || sub === 'unarchive') {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { requestHostOps } from './request-host-ops.mjs';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -24,10 +25,13 @@ import { startTimeOf } from "../src/host.mjs";
|
||||
import { createLauncher } from "../src/launcher.mjs";
|
||||
import { fakeHarnesses, fixture, tmp, withoutHostCredentials } from "./helpers.mjs";
|
||||
import { fakeGiteaApi } from "../../bus/tests/fake-gitea-api.mjs";
|
||||
import { send as giteaSend } from "../../bus/src/gitea-grant.mjs";
|
||||
import { giteaGrant, send as giteaSend } from "../../bus/src/gitea-grant.mjs";
|
||||
import { organizationWriter } from "../../organization/src/organization.mjs";
|
||||
import { activateOrg, reserveOrg } from "../../organization/src/org-registry.mjs";
|
||||
import { activateOrg, listOrgs, reserveOrg } from "../../organization/src/org-registry.mjs";
|
||||
import * as orgService from "../../organization/src/org-service.mjs";
|
||||
import { copyBotLogin } from "../../organization/src/copy-bindings.mjs";
|
||||
import { COPY_BINDING_STATUS } from "../../organization/src/copy-binding-status.mjs";
|
||||
import { formatInstances } from "../src/instances.mjs";
|
||||
|
||||
const FAKE = fileURLToPath(new URL("../../harness/tests/fixtures/fake-adapter.mjs", import.meta.url));
|
||||
const skip = sandboxProblem() ?? false;
|
||||
@@ -60,8 +64,8 @@ function gitRepo(dir) {
|
||||
// holds gate (merge-gate, no credential: bound), researcher (research, needs gitea: unbound in every
|
||||
// organization) and sec (security-reviewer, excluded from acme). The coder's gitea token file is
|
||||
// named for, and holds, the test secret, so it is bound elsewhere in the organization.
|
||||
function prepare(t, edit = (doc) => doc) {
|
||||
const root = tmp(t, "mosaic-copy-");
|
||||
function prepare(t, edit = (doc) => doc, prefix = "mosaic-copy-") {
|
||||
const root = tmp(t, prefix);
|
||||
const f = fixture(root, "acme", (doc) => {
|
||||
doc.roles.chief.vars = { harness: "pi", model: "claude-opus-5-5", thinking: "high" };
|
||||
doc.roles.coder.vars.model = "claude-sonnet-5-5";
|
||||
@@ -86,7 +90,7 @@ function prepare(t, edit = (doc) => doc) {
|
||||
return { root, f, adapter };
|
||||
}
|
||||
|
||||
async function start(t, { f, adapter }, { businessId = "acme", orgRoot, copyTransport = null, beforeBind = null } = {}) {
|
||||
async function start(t, { f, adapter }, { businessId = "acme", orgRoot, copyTransport = null, beforeBind = null, readOnly = [FAKE] } = {}) {
|
||||
const system = loadSystem({ env: f.env });
|
||||
const { trackers, ...boot } = bootConfig({ system, businessId, env: f.env, ...(orgRoot ? { orgRoot } : {}) });
|
||||
const runtime = await startBroker({ ...boot, ...(copyTransport ? { copyTransport } : {}) });
|
||||
@@ -143,7 +147,7 @@ async function start(t, { f, adapter }, { businessId = "acme", orgRoot, copyTran
|
||||
makeLoader: await fakeHarnesses(t, { pi: adapter, "claude-code": adapter }),
|
||||
sessionDefaults: { pollInterval: 100 },
|
||||
harnessVersion: "0.85.1",
|
||||
readOnly: [FAKE],
|
||||
readOnly,
|
||||
threadTickMs: 3600000,
|
||||
stopTimeoutMs: 1000,
|
||||
log: (l) => logs.push(l),
|
||||
@@ -605,11 +609,11 @@ test("A3: a second organization boots its own copies from the same root file and
|
||||
|
||||
// #1873 CB3: the researcher copy (research, gitea alone) bound and granted on a fake Gitea, through
|
||||
// the real bus, its boot check and the launcher. `sent` is every request the bus sends to the service.
|
||||
async function boundCopy(t) {
|
||||
async function boundCopy(t, edit = (doc) => doc) {
|
||||
const api = await fakeGiteaApi(t, tmp(t, "cb3-api-"));
|
||||
const p = prepare(t, (doc) => {
|
||||
doc.projects.stack.remote = `${api.url}/owner/stack`;
|
||||
return doc;
|
||||
return edit(doc);
|
||||
});
|
||||
const ctx = { configDir: join(p.root, "config"), dataRoot: p.f.dataRoot, instance: "test" };
|
||||
chmodSync(ctx.configDir, 0o700);
|
||||
@@ -756,3 +760,352 @@ test("CB3 race: an organization file change between the launcher's admission and
|
||||
assert.ok(events.some((e) => e.event === "refused" && e.why === "launch bind refused: organization-changed"), JSON.stringify(events));
|
||||
assert.ok(!events.some((e) => e.event === "launch"), JSON.stringify(events));
|
||||
});
|
||||
|
||||
// #1873 CB5 (CB4 review P3-2): startBroker's own wiring for a former copy a named instance now
|
||||
// shadows. At start the named instance's slot is held (never loaded as its credential), and the first
|
||||
// pass begins the shadowed revoke without waiting for the minute's sweep; the revoke deletes the copy's
|
||||
// token at the service through the organization's admin slot.
|
||||
test("CB5 runtime: a restart over a named instance that shadows a bound copy holds the slot, and the start's own pass revokes the copy at the service", { skip, timeout: 120000 }, async (t) => {
|
||||
const p = await boundCopy(t);
|
||||
const first = await start(t, p, { copyTransport: p.copyTransport });
|
||||
const login = await p.bind(first);
|
||||
await first.close();
|
||||
const day = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
|
||||
giteaGrant({ configDir: join(p.root, "config") }).writeAdmin("acme", p.api.adminToken, { url: p.api.url, account: "mosaic-grant", rotateBy: day(60), setAt: new Date().toISOString() });
|
||||
// The owner names an instance over the copy, through the writer; the binding record stays as it was.
|
||||
const writer = organizationWriter({ dir: join(p.root, "config"), rolesDir: p.f.roles, dataRoot: p.f.dataRoot });
|
||||
const { document, revision } = writer.read("acme");
|
||||
const bindings = JSON.stringify(document.copyBindings);
|
||||
const d = structuredClone(document);
|
||||
d.roles.researcher = { definition: "research", vars: VARS, credentials: { gitea: { store: true, rotateBy: day(30) } } };
|
||||
writer.write("acme", d, { revision, actor: "local-dev-owner" });
|
||||
assert.equal(JSON.stringify(writer.read("acme").document.copyBindings), bindings);
|
||||
// The token's delete waits until the test has looked at the held slot.
|
||||
let go, arrived;
|
||||
const deleting = new Promise((r) => { arrived = r; });
|
||||
const release = new Promise((r) => { go = r; });
|
||||
p.api.rule((e) => e.method === "DELETE" && e.path.includes("/tokens/"), async () => { arrived(); await release; return { pass: true }; });
|
||||
const s = await start(t, p, { copyTransport: p.copyTransport });
|
||||
// The start's own pass, not the minute's sweep, begins it.
|
||||
await Promise.race([deleting, new Promise((_, no) => setTimeout(() => no(new Error("no revoke began at start")), 20000).unref())]);
|
||||
assert.equal(p.rec().state, "revoking");
|
||||
assert.equal(p.rec().revoke.cause, "shadowed");
|
||||
// The slot went before the remote step. Had start loaded it as the named instance's credential
|
||||
// (no hold), the discard would have refused and the record would never finish.
|
||||
const slot = join(p.root, "config", "secrets", "agents", "acme", "researcher", "gitea");
|
||||
assert.equal(existsSync(slot), false);
|
||||
assert.deepEqual(s.runtime.credentialStatus("acme", "researcher").map((c) => [c.service, c.state]), [["gitea", "not-issued"]]);
|
||||
go();
|
||||
await until(() => p.rec().state === "unbound" && p.rec().revoke?.done === true);
|
||||
assert.deepEqual(p.rec().revoke.remote, { gitea: "revoked" });
|
||||
assert.deepEqual(p.rec().revoke.failed ?? null, null);
|
||||
assert.deepEqual(p.api.tokens(login), []);
|
||||
assert.ok(p.api.requests.some((e) => e.method === "DELETE" && e.as === "mosaic-grant"));
|
||||
});
|
||||
|
||||
// #1873 CB5 (CB4 review P3-2): the gate's loss at boot reaches the revoker through startBroker's
|
||||
// onLoss. A bound copy whose slot is gone at the next start is lost `credential-unavailable`, and its
|
||||
// binding is revoked at the service with cause `unavailable`, without waiting for a sweep.
|
||||
test("CB5 runtime: a bound copy whose slot is gone at restart is lost at boot, and onLoss revokes it at the service", { skip, timeout: 120000 }, async (t) => {
|
||||
const p = await boundCopy(t);
|
||||
const first = await start(t, p, { copyTransport: p.copyTransport });
|
||||
const login = await p.bind(first);
|
||||
await first.close();
|
||||
const day = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
|
||||
giteaGrant({ configDir: join(p.root, "config") }).writeAdmin("acme", p.api.adminToken, { url: p.api.url, account: "mosaic-grant", rotateBy: day(60), setAt: new Date().toISOString() });
|
||||
const slot = join(p.root, "config", "secrets", "agents", "acme", "researcher", "gitea");
|
||||
assert.ok(existsSync(slot));
|
||||
renameSync(slot, slot + ".gone");
|
||||
const s = await start(t, p, { copyTransport: p.copyTransport });
|
||||
assert.deepEqual(s.runtime.copyBound, {});
|
||||
await until(() => p.rec().state === "unbound" && p.rec().revoke?.done === true, 20000);
|
||||
assert.equal(p.rec().revoke.cause, "unavailable");
|
||||
assert.deepEqual(p.rec().revoke.remote, { gitea: "revoked" });
|
||||
assert.deepEqual(p.api.tokens(login), []);
|
||||
assert.equal(refusedAt(s, "researcher").code, "credential-unavailable");
|
||||
});
|
||||
|
||||
// #1873 CB5 two-organization acceptance (A3's deferred test). acme and beta each bind the shipped
|
||||
// research copy (researcher, gitea alone) on one fake Gitea, each run by its own bus with its own
|
||||
// transport. beta is registered as the organization service makes one (registry entry, owner proof,
|
||||
// the derived project root), so archive and delete run on it. A transport keeps the sha256 of every
|
||||
// credential its bus sends, never the value.
|
||||
const LOCAL = { provider: "local-dev", iss: "local-dev", sub: "local-dev-owner" };
|
||||
const THREAD_ADAPTER = fileURLToPath(new URL("./fixtures/thread-adapter.mjs", import.meta.url));
|
||||
const sha = (x) => createHash("sha256").update(String(x)).digest("hex");
|
||||
function hashingTransport(api) {
|
||||
const auth = [];
|
||||
return { auth, ca: api.ca, send: (req) => {
|
||||
auth.push({ op: `${req.method} ${req.path.split("?")[0]}`, hash: sha(req.auth?.basic ? req.auth.basic.slice(1).join(":") : req.auth?.token) });
|
||||
return giteaSend(req);
|
||||
} };
|
||||
}
|
||||
async function twoOrgs(t) {
|
||||
const api = await fakeGiteaApi(t, tmp(t, "cb5-api-"));
|
||||
const p = prepare(t, (doc) => {
|
||||
doc.projects.stack.remote = `${api.url}/owner/stack`;
|
||||
return doc;
|
||||
// A short root: beta's data root is the registry's <dataRoot>/org-runtime/beta, and a run's socket
|
||||
// path under it must fit 107 bytes.
|
||||
}, "c5-");
|
||||
// The thread adapter keeps a history in the thread's store and answers with what it found there.
|
||||
writeFileSync(p.adapter, `exec '${process.execPath}' '${THREAD_ADAPTER}'\n`);
|
||||
const configDir = join(p.root, "config");
|
||||
const dataRoot = p.f.dataRoot;
|
||||
const ctx = { configDir, dataRoot, instance: "test", principal: LOCAL };
|
||||
chmodSync(configDir, 0o700);
|
||||
chmodSync(join(configDir, "businesses"), 0o700);
|
||||
await reserveOrg(ctx, "acme");
|
||||
await activateOrg(ctx, "acme");
|
||||
const beta = businessDoc(p.root, "beta");
|
||||
for (const r of Object.values(beta.roles)) r.vars = { ...VARS, ...r.vars, model: r.vars?.model ?? "claude-sonnet-5-5" };
|
||||
beta.roles.chief.vars = { harness: "pi", model: "claude-opus-5-5", thinking: "high" };
|
||||
beta.launch = launchDoc("chief", ["coder"], { opus: 1, sonnet: 4 });
|
||||
beta.plugins = { ...beta.plugins, harness: ["pi", "claude-code"] };
|
||||
beta.projects.stack.remote = `${api.url}/beta/stack`;
|
||||
beta.projects.stack.root = join(dataRoot, "org-runtime", "beta", "projects", "stack");
|
||||
writeJson(join(configDir, "businesses", "beta.json"), beta);
|
||||
const entry = await reserveOrg(ctx, "beta");
|
||||
writeFileSync(join(entry.root, "owner.json"), JSON.stringify(LOCAL) + "\n", { mode: 0o600, flag: "wx" });
|
||||
gitRepo(beta.projects.stack.root);
|
||||
await activateOrg(ctx, "beta");
|
||||
const writer = organizationWriter({ dir: configDir, rolesDir: p.f.roles, dataRoot });
|
||||
const day = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
|
||||
const orgs = {
|
||||
acme: { id: "acme", repo: api.addRepo("owner", "stack"), transport: hashingTransport(api), orgRoot: undefined },
|
||||
beta: { id: "beta", repo: api.addRepo("beta", "stack"), transport: hashingTransport(api), orgRoot: entry.root },
|
||||
};
|
||||
for (const o of Object.values(orgs)) {
|
||||
o.rec = () => writer.read(o.id).document.copyBindings?.researcher;
|
||||
o.slot = join(configDir, "secrets", "agents", o.id, "researcher", "gitea");
|
||||
o.start = () => start(t, p, { businessId: o.id, orgRoot: o.orgRoot, copyTransport: o.transport, readOnly: [THREAD_ADAPTER] });
|
||||
// Bind (the owner's console) and issue (the human), on a bus that is already up.
|
||||
o.bind = async (s) => {
|
||||
const owner = s.runtime.broker.bindConsole({ business: o.id, human: writer.read(o.id).document.human, subject: { provider: "test", iss: "https://issuer.test", sub: "owner" } });
|
||||
await s.runtime.broker.request(owner, { verb: "hire.start.console", args: { op: "change", level: "root", name: "researcher", reason: "Bind the copy",
|
||||
binding: { services: { gitea: { scopes: ["read:repository", "read:user"], projects: ["stack"] } } } } });
|
||||
const r = o.rec();
|
||||
o.login = copyBotLogin(r.orgIncarnation, r.copyId, "gitea");
|
||||
api.addUser(o.login);
|
||||
o.repo.collaborators.push(o.login); o.repo.permissions[o.login] = "read";
|
||||
o.token = api.addToken(o.login, "t1", ["read:repository", "read:user"]).sha1;
|
||||
await s.call("credentials.issue", { agent: "researcher", service: "gitea", date: day(30), token: o.token });
|
||||
giteaGrant({ configDir }).writeAdmin(o.id, api.adminToken, { url: api.url, account: "mosaic-grant", rotateBy: day(60), setAt: new Date().toISOString() });
|
||||
};
|
||||
}
|
||||
return { p, api, ctx, writer, orgs, day };
|
||||
}
|
||||
const orgLaunches = (s) => existsSync(launchLogFile(s.dataRoot, s.host.business))
|
||||
? readFileSync(launchLogFile(s.dataRoot, s.host.business), "utf8").trim().split("\n").map((l) => JSON.parse(l)) : [];
|
||||
// Send to a thread and wait for the copy's RESULT reply; the reply says what the thread's store held.
|
||||
async function askThread(s, thread, body) {
|
||||
const sent = s.call("thread.send", { thread, body });
|
||||
await s.launcher.tick();
|
||||
const reply = await until(() => s.call("thread.messages", { thread }).find((m) => m.in_reply_to === sent.id && m.class === "RESULT"), 30000)
|
||||
.catch((e) => { throw new Error(`no reply: ${JSON.stringify(orgLaunches(s).slice(-3))}`, { cause: e }); });
|
||||
return { sent, reply, saw: JSON.parse(reply.body.match(/THREAD (\{.*\})/)[1]) };
|
||||
}
|
||||
|
||||
test("CB5 two organizations: each binds and runs its own research copy in a thread; identities, records and tokens stay apart; B works through A's revoke, archive and delete; A's raw binding or grant replayed in B is refused", { skip, timeout: 240000 }, async (t) => {
|
||||
const { api, ctx, writer, orgs, day } = await twoOrgs(t);
|
||||
const A = orgs.beta, B = orgs.acme;
|
||||
// Bind each, then restart each so its boot proves the slot live.
|
||||
for (const o of [A, B]) {
|
||||
const first = await o.start();
|
||||
await o.bind(first);
|
||||
await first.close();
|
||||
o.s = await o.start();
|
||||
assert.deepEqual(o.s.runtime.copyBound, { researcher: ["gitea"] }, o.id);
|
||||
}
|
||||
assert.notEqual(A.login, B.login);
|
||||
assert.notEqual(A.rec().copyId, B.rec().copyId);
|
||||
assert.notEqual(A.rec().orgIncarnation, B.rec().orgIncarnation);
|
||||
assert.notEqual(sha(readFileSync(A.slot, "utf8")), sha(readFileSync(B.slot, "utf8")));
|
||||
|
||||
// One thread per organization, launched, written and read.
|
||||
for (const o of [A, B]) {
|
||||
const project = o.s.call("project.create", { name: "stack work", repo: "stack" }).id;
|
||||
o.thread = o.s.call("thread.create", { project, name: `work-${o.id}`, instance: "researcher" }).id;
|
||||
const first = await askThread(o.s, o.thread, `hello ${o.id}`);
|
||||
assert.deepEqual(first.saw.before, [], o.id);
|
||||
const launch = orgLaunches(o.s).find((e) => e.event === "launch" && e.thread === o.thread);
|
||||
assert.ok(launch, o.id);
|
||||
o.run = launch.run;
|
||||
[o.entry] = o.s.running("researcher");
|
||||
assert.equal(o.entry.run, o.run, o.id);
|
||||
o.session = o.s.runtime.threadsState(o.id).find((x) => x.thread === o.thread).session;
|
||||
o.store = join(o.s.dataRoot, "threads", o.id, o.thread, "sessions", o.session);
|
||||
assert.equal(readFileSync(join(o.store, "session", "history"), "utf8"), `hello ${o.id}\n`, o.id);
|
||||
}
|
||||
// Distinct session, run, trail, workspace and slot identities.
|
||||
assert.notEqual(A.s.dataRoot, B.s.dataRoot);
|
||||
for (const k of ["thread", "session", "run"]) assert.notEqual(A[k], B[k], k);
|
||||
assert.notEqual(A.entry.workspace, B.entry.workspace);
|
||||
assert.notEqual(A.slot, B.slot);
|
||||
for (const [mine, other] of [[A, B], [B, A]]) {
|
||||
assert.ok(mine.entry.workspace.startsWith(mine.s.dataRoot + "/"), mine.id);
|
||||
assert.ok(mine.entry.runDir.startsWith(join(mine.s.dataRoot, "launches", mine.id) + "/"), mine.id);
|
||||
// No record of the other's is visible here: not its thread, its session, its run or its request.
|
||||
const seen = trail(mine.s.dataRoot);
|
||||
for (const k of ["thread", "session", "run"]) assert.equal(seen.includes(other[k]), false, `${mine.id} trail holds ${other.id}'s ${k}`);
|
||||
// The default organization's data root is the instance's, and every named organization's root
|
||||
// sits under its org-runtime: that subtree is the other bus's, not this one's.
|
||||
const own = readdirSync(mine.s.dataRoot, { recursive: true }).filter((x) => mine.orgRoot || !x.startsWith("org-runtime/"));
|
||||
assert.equal(own.join("\n").includes(other.run), false, mine.id);
|
||||
assert.ok(!mine.s.call("thread.list").some((x) => x.id === other.thread), mine.id);
|
||||
assert.throws(() => mine.s.call("thread.messages", { thread: other.thread }), BusError, mine.id);
|
||||
assert.ok(!mine.s.running("researcher").some((x) => x.run === other.run), mine.id);
|
||||
}
|
||||
|
||||
// Reopen each: a restart of its bus, and the same thread finds its own history and session.
|
||||
for (const o of [A, B]) {
|
||||
await o.s.close();
|
||||
o.s = await o.start();
|
||||
const again = await askThread(o.s, o.thread, `again ${o.id}`);
|
||||
assert.deepEqual(again.saw.before, [`hello ${o.id}`], o.id);
|
||||
assert.equal(o.s.runtime.threadsState(o.id).find((x) => x.thread === o.thread).session, o.session, o.id);
|
||||
}
|
||||
|
||||
// So far no request of B's bus carried A's token, and none of A's carried B's.
|
||||
// The issue's identity check (copy-grant verifyGiteaToken): the server version, then the token's owner.
|
||||
const CHECK = ["GET /api/v1/version", "GET /api/v1/token"];
|
||||
const carried = (o, token) => o.transport.auth.filter((x) => x.hash === sha(token)).map((x) => x.op);
|
||||
assert.deepEqual(carried(B, A.token), []);
|
||||
assert.deepEqual(carried(A, B.token), []);
|
||||
assert.ok(carried(B, B.token).length > 0);
|
||||
|
||||
// A's raw binding record written into B's file is refused, and B's file is as it was.
|
||||
const { document, revision } = writer.read(B.id);
|
||||
const replay = structuredClone(document);
|
||||
replay.copyBindings = { ...replay.copyBindings, researcher: A.rec() };
|
||||
assert.throws(() => writer.write(B.id, replay, { revision, actor: "local-dev-owner" }), (e) => e.code === "organization-bindings-protected");
|
||||
assert.equal(writer.read(B.id).revision, revision);
|
||||
// A's grant (its live token) issued to B's copy is refused at the service's identity check. The
|
||||
// issue deactivates first (design section 5): the record is left pending with no grant and the
|
||||
// staged file goes, so A's token is never B's credential. B's copy keeps its own identity.
|
||||
const bound = B.rec();
|
||||
await assert.rejects(Promise.resolve().then(() => B.s.call("credentials.issue", { agent: "researcher", service: "gitea", date: day(30), token: A.token })),
|
||||
(e) => e instanceof BusError && e.code === "credential-identity-refused");
|
||||
assert.equal(B.rec().state, "pending");
|
||||
assert.equal(B.rec().services.gitea.grantId, undefined);
|
||||
for (const k of ["copyId", "orgIncarnation", "decision"]) assert.equal(B.rec()[k], bound[k], k);
|
||||
assert.equal(existsSync(B.slot), false);
|
||||
// The only requests that carried A's token from B's bus are the identity check that refused it.
|
||||
assert.deepEqual(carried(B, A.token), CHECK);
|
||||
// The owner's recovery is a new verified issue of B's own token, then a restart.
|
||||
B.token = api.addToken(B.login, "t2", ["read:repository", "read:user"]).sha1;
|
||||
await B.s.call("credentials.issue", { agent: "researcher", service: "gitea", date: day(30), token: B.token });
|
||||
assert.equal(B.rec().state, "bound");
|
||||
await B.s.close();
|
||||
B.s = await B.start();
|
||||
assert.deepEqual(B.s.runtime.copyBound, { researcher: ["gitea"] });
|
||||
const bTokens = api.tokens(B.login).length;
|
||||
|
||||
// B keeps working through each of A's lifecycle steps.
|
||||
const bWorks = async (label) => {
|
||||
const r = await askThread(B.s, B.thread, `after ${label}`);
|
||||
assert.equal(r.saw.body, `after ${label}`, label);
|
||||
assert.equal(B.rec().state, "bound", label);
|
||||
assert.ok(existsSync(B.slot), label);
|
||||
assert.equal(api.tokens(B.login).length, bTokens, label);
|
||||
assert.deepEqual(B.s.runtime.copyBound, { researcher: ["gitea"] }, label);
|
||||
};
|
||||
const out = await A.s.call("credentials.revoke", { agent: "researcher", service: "gitea", reason: "Owner revoke" });
|
||||
assert.equal(out.state, "unbound");
|
||||
assert.deepEqual(out.remote, { gitea: "revoked" });
|
||||
assert.deepEqual(api.tokens(A.login), []);
|
||||
await until(() => A.s.running("researcher").length === 0);
|
||||
await bWorks("revoke");
|
||||
const rev = async () => (await listOrgs(ctx)).find((o) => o.id === A.id).revision;
|
||||
const busStop = async () => { await A.s.close(); return { stopped: true, reason: "stopped" }; };
|
||||
const archived = await orgService.archiveOrg(ctx, A.id, { ifRevision: await rev(), busStop });
|
||||
assert.equal(archived.outcome, "done");
|
||||
await bWorks("archive");
|
||||
const deleted = await orgService.deleteOrg(ctx, A.id, { confirm: A.id, ifRevision: await rev(), busStop });
|
||||
assert.equal(deleted.outcome ?? "done", "done");
|
||||
assert.equal(existsSync(A.slot), false);
|
||||
await bWorks("delete");
|
||||
|
||||
// Through all of it, B's bus sent A's token only in the refused issue's check, and A's never sent B's.
|
||||
assert.deepEqual(carried(B, A.token), CHECK);
|
||||
assert.deepEqual(carried(A, B.token), []);
|
||||
assert.ok(carried(B, B.token).length > 0);
|
||||
});
|
||||
|
||||
// #1873 CB5 operator flow: the copy's binding status in the owner's instances read and in
|
||||
// `mosaic org instances`, at each step a binding takes, as fixed text. The copy's token is the
|
||||
// sentinel: it, its hash and its leading fragment never appear in a read, the CLI text, the trail,
|
||||
// the launcher's log or the bus's own stderr.
|
||||
test("CB5 operator: the owner's instances read and mosaic org instances show each copy's binding status and next step in fixed text; the token never appears", { skip, timeout: 120000 }, async (t) => {
|
||||
// bus.tester on, so the tester's read below is answered and its exclusion is the broker's.
|
||||
const p = await boundCopy(t, (doc) => ({ ...doc, vars: { ...(doc.vars ?? {}), "bus.tester": true } }));
|
||||
const said = [];
|
||||
const write = process.stderr.write;
|
||||
process.stderr.write = function (chunk, ...rest) { said.push(String(chunk)); return write.call(this, chunk, ...rest); };
|
||||
t.after(() => { process.stderr.write = write; });
|
||||
const first = await start(t, p, { copyTransport: p.copyTransport });
|
||||
const seen = [];
|
||||
const status = (s) => { const v = s.call("instances"); seen.push(JSON.stringify(v), formatInstances(v)); return v.copies.researcher.binding; };
|
||||
const fixed = (code) => ({ status: code, next: COPY_BINDING_STATUS[code] });
|
||||
// Nothing approved yet.
|
||||
assert.deepEqual(status(first), fixed("credential-unbound"));
|
||||
// Approved: the owner's next step is the issue.
|
||||
const owner = first.runtime.broker.bindConsole({ business: "acme", human: p.f.doc.human, subject: { provider: "test", iss: "https://issuer.test", sub: "owner" } });
|
||||
await first.runtime.broker.request(owner, { verb: "hire.start.console", args: { op: "change", level: "root", name: "researcher", reason: "Bind the copy",
|
||||
binding: { services: { gitea: { scopes: ["read:repository", "read:user"], projects: ["stack"] } } } } });
|
||||
assert.equal(p.rec().state, "pending");
|
||||
assert.deepEqual(status(first), fixed("issue-required"));
|
||||
// Issued: a restart verifies it.
|
||||
const r = p.rec();
|
||||
const login = copyBotLogin(r.orgIncarnation, r.copyId, "gitea");
|
||||
p.api.addUser(login);
|
||||
const repo = p.api.repos.find((x) => x.owner === "owner" && x.name === "stack");
|
||||
repo.collaborators.push(login); repo.permissions[login] = "read";
|
||||
const token = p.api.addToken(login, "t1", ["read:repository", "read:user"]).sha1;
|
||||
await first.call("credentials.issue", { agent: "researcher", service: "gitea", date: new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10), token });
|
||||
assert.equal(p.rec().state, "bound");
|
||||
assert.deepEqual(status(first), fixed("restart-required"));
|
||||
await first.close();
|
||||
// Verified at the next start.
|
||||
const s = await start(t, p, { copyTransport: p.copyTransport });
|
||||
assert.deepEqual(s.runtime.copyBound, { researcher: ["gitea"] });
|
||||
assert.deepEqual(status(s), fixed("ready"));
|
||||
// A tester's read lists the copy and never its binding status (design section 4).
|
||||
const tester = s.runtime.broker.bindTester({ business: "acme" });
|
||||
const asTester = await s.runtime.broker.request(tester, { verb: "instances" });
|
||||
assert.ok(asTester.copies?.researcher, "the tester sees the copy");
|
||||
assert.equal(Object.hasOwn(asTester.copies.researcher, "binding"), false);
|
||||
seen.push(JSON.stringify(asTester));
|
||||
// The owner's revoke.
|
||||
await s.call("credentials.revoke", { agent: "researcher", service: "gitea", reason: "Owner revoke" });
|
||||
assert.deepEqual(status(s), fixed("credential-revoked"));
|
||||
// The CLI prints the status code and its next step for the copy.
|
||||
const text = formatInstances(s.call("instances"));
|
||||
assert.ok(text.includes(` researcher (copy): credential-revoked. ${COPY_BINDING_STATUS["credential-revoked"]}\n`), text);
|
||||
// The sentinel never appears.
|
||||
const leaks = (x) => [token, sha(token), token.slice(0, 8)].filter((v) => x.includes(v));
|
||||
assert.deepEqual(leaks(seen.join("\n")), []);
|
||||
assert.deepEqual(leaks(trail(p.f.dataRoot)), []);
|
||||
assert.deepEqual(leaks(said.join("")), []);
|
||||
assert.deepEqual(leaks([...first.logs, ...s.logs].map((l) => (typeof l === "string" ? l : JSON.stringify(l))).join("\n")), []);
|
||||
});
|
||||
|
||||
// #1873 CB5 review: a shipped role that needs gitea and vikunja. Boot denies such a copy whatever it
|
||||
// binds, so its status must not send the owner to approve a gitea binding.
|
||||
test("CB5 operator: a copy whose role needs a service a copy cannot bind reads copy-service-unbindable and names its missing services", { skip, timeout: 60000 }, async (t) => {
|
||||
const p = prepare(t);
|
||||
const file = join(p.root, "config", "agents.json");
|
||||
const doc = JSON.parse(readFileSync(file, "utf8"));
|
||||
doc.agents.rev = { definition: "reviewer", vars: VARS };
|
||||
writeJson(file, doc, 0o600);
|
||||
const s = await start(t, p);
|
||||
const v = s.call("instances");
|
||||
assert.equal(v.copies.rev.state, "unbound");
|
||||
assert.deepEqual(v.copies.rev.binding, { status: "copy-service-unbindable", next: COPY_BINDING_STATUS["copy-service-unbindable"] });
|
||||
// The gitea-only copy beside it still reads credential-unbound.
|
||||
assert.deepEqual(v.copies.researcher.binding, { status: "credential-unbound", next: COPY_BINDING_STATUS["credential-unbound"] });
|
||||
const text = formatInstances(v);
|
||||
assert.ok(text.includes(` rev (copy): copy-service-unbindable (missing gitea, vikunja). ${COPY_BINDING_STATUS["copy-service-unbindable"]}\n`), text);
|
||||
assert.ok(text.includes(` researcher (copy): credential-unbound (missing gitea). ${COPY_BINDING_STATUS["credential-unbound"]}\n`), text);
|
||||
assert.equal(COPY_BINDING_STATUS["copy-service-unbindable"].includes("credentials.gitea"), false);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
// Starter packs SP8: `mosaic org template save|list`. Each word goes through the organization's bus as
|
||||
// its human; save --preview writes nothing, save --digest writes the previewed JSON under the owner's
|
||||
// account, and template render keeps its own words.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, lstatSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { main } from '../src/cli.mjs';
|
||||
import { ORG_USAGE, TEMPLATE_USAGE } from '../src/org.mjs';
|
||||
import { bootConfig, loadSystem } from '../src/config.mjs';
|
||||
import { CliError } from '../src/errors.mjs';
|
||||
import { busExit } from '../src/transport.mjs';
|
||||
import { BusError } from '../../bus/src/broker.mjs';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { fixture, io, tmp } from './helpers.mjs';
|
||||
|
||||
async function setup(t) {
|
||||
const root = tmp(t);
|
||||
const f = fixture(root, 'acme');
|
||||
const file = join(root, 'config/businesses/acme.json');
|
||||
const boot = bootConfig({ system: loadSystem({ env: f.env }), businessId: 'acme', env: f.env });
|
||||
const b = await startBroker({ dataRoot: f.dataRoot, businesses: boot.businesses, organization: boot.organization });
|
||||
t.after(() => b.close());
|
||||
const human = b.broker.bindHuman({ business: 'acme', human: f.doc.human, via: 'cli', outsideAgent: true });
|
||||
const calls = [];
|
||||
const deps = { system: { dataRoot: f.dataRoot }, transport: () => async (verb, args = {}) => {
|
||||
calls.push([verb, Object.keys(args).sort()]);
|
||||
try { return structuredClone(await b.broker.request(human, { verb, args })); }
|
||||
// What humanTransport throws for a bus refusal: a CliError named by the code alone.
|
||||
catch (e) { if (!(e instanceof BusError)) throw e; throw Object.assign(new CliError(e.code, busExit(e.code)), { code: e.code }); }
|
||||
} };
|
||||
const run = async (args, env = f.env) => { const x = io(env); await main(['org', ...args], x, deps); return JSON.parse(x.out.text); };
|
||||
const saved = (name) => join(boot.organization.dir, 'templates', f.doc.human, `${name}.json`);
|
||||
return { root, f, file, calls, run, saved };
|
||||
}
|
||||
|
||||
test('SP8 mosaic org template save: --preview writes nothing, --digest writes the previewed JSON, a second save refuses, list shows it', async (t) => {
|
||||
const s = await setup(t);
|
||||
assert.ok(ORG_USAGE.includes(TEMPLATE_USAGE.slice('mosaic org '.length)));
|
||||
const before = readFileSync(s.file);
|
||||
const preview = await s.run(['template', 'save', 'acme', 'acme-shape', '--preview']);
|
||||
assert.match(preview.digest, /^[0-9a-f]{64}$/);
|
||||
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.replacements));
|
||||
assert.ok(!existsSync(s.saved('acme-shape')), 'preview writes no file');
|
||||
|
||||
const out = await s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]);
|
||||
assert.deepEqual(out, { name: 'acme-shape', scope: 'org', digest: preview.digest });
|
||||
assert.equal(readFileSync(s.saved('acme-shape'), 'utf8'), preview.json);
|
||||
assert.equal(lstatSync(s.saved('acme-shape')).mode & 0o777, 0o600);
|
||||
assert.deepEqual(readFileSync(s.file), before, 'save writes nothing to the organization file');
|
||||
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'invalid-request' && /already saved/.test(e.message));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'other', '--digest', preview.digest]), (e) => e.code === 'pack-plan-stale' && /preview again/.test(e.message));
|
||||
const listed = await s.run(['template', 'list', 'acme']);
|
||||
assert.deepEqual(listed.templates.map((x) => x.name), ['acme-shape']);
|
||||
assert.deepEqual(s.calls.map(([verb, keys]) => [verb, keys.join(',')]), [
|
||||
['template.save', 'name,preview'], ['template.save', 'digest,name'], ['template.save', 'digest,name'], ['template.save', 'digest,name'], ['template.list', ''],
|
||||
]);
|
||||
});
|
||||
|
||||
test('SP8 template words: a bad shape prints the usage; an agent shell refuses before the bus is called; template render keeps its words', async (t) => {
|
||||
const s = await setup(t);
|
||||
for (const args of [['template', 'save', 'acme', 'x'], ['template', 'save', 'acme', 'x', '--preview', '--digest', 'a'.repeat(64)], ['template', 'save', 'acme'], ['template', 'list'], ['template', 'list', 'acme', '--preview']]) {
|
||||
await assert.rejects(s.run(args), (e) => e.exitCode === 4 && e.message === TEMPLATE_USAGE, args.join(' '));
|
||||
}
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'x', '--force']), (e) => e.exitCode === 4 && /unknown option --force/.test(e.message));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', '..', '--preview']), (e) => e.code === 'invalid-request');
|
||||
const agent = { ...s.f.env, MOSAIC_RUN_ID: 'run-1' };
|
||||
const calls = s.calls.length;
|
||||
for (const args of [['template', 'save', 'acme', 'x', '--preview'], ['template', 'save', 'acme', 'x', '--digest', 'a'.repeat(64)], ['template', 'list', 'acme']]) {
|
||||
await assert.rejects(s.run(args, agent), (e) => e.exitCode === 3 && /human shell/.test(e.message), args.join(' '));
|
||||
}
|
||||
assert.equal(s.calls.length, calls);
|
||||
// template render is still routed to its own words (it needs --output).
|
||||
await assert.rejects(s.run(['template', 'render', 'acme']), (e) => e.exitCode === 4 && /--output/.test(e.message));
|
||||
});
|
||||
@@ -12,7 +12,6 @@ test('organization CLI renders, validates, creates, updates and initializes git'
|
||||
const file = join(home, 'alpha.json'); const invoke = (...args) => { const r = run(env, ...args); assert.equal(r.status, 0, r.stderr); return r.stdout; };
|
||||
invoke('org', 'template', 'render', 'alpha', '--fixture', 'local', '--output', file);
|
||||
invoke('org', 'validate', file); invoke('org', 'create', 'alpha', '--from', file);
|
||||
assert.deepEqual(JSON.parse(invoke('org', 'system-types', 'enabled', 'alpha')), { organization: 'alpha', enabled: [] });
|
||||
const bootCheck = spawnSync(process.execPath, ['--input-type=module', '-e', `import {loadSystem, bootConfig} from './packages/cli/src/config.mjs'; const system=loadSystem({env:process.env, instance:'orgtest'}); bootConfig({system,businessId:'alpha',env:process.env});`], { cwd: repo, env, encoding: 'utf8' }); assert.equal(bootCheck.status, 0, bootCheck.stderr);
|
||||
let info = JSON.parse(invoke('org', 'show', 'alpha', '--json')); assert.equal(info.id, 'alpha'); assert.equal(JSON.parse(invoke('org', 'list', '--json')).length, 1);
|
||||
invoke('org', 'update', 'alpha', '--from', file, '--if-revision', String(info.revision));
|
||||
|
||||
@@ -306,7 +306,7 @@ test('#811 migration readers follow the engine order and refuse malformed pairs'
|
||||
assert.notEqual(engineSource,source);
|
||||
const engine=await import(`data:text/javascript;base64,${Buffer.from(engineSource).toString('base64')}`);
|
||||
const pairs=engine.migrations.map(({from,to})=>[from,to]);
|
||||
assert.equal(pairs.length,20);assert.deepEqual(pairs.at(-1),['3u','3v']);
|
||||
assert.equal(pairs.length,21);assert.deepEqual(pairs.at(-1),['3v','3w']);
|
||||
const release=readFileSync(join(ROOT,'scripts/stack-release.sh'),'utf8');
|
||||
const fn=(name)=>{const m=release.match(new RegExp(`^${name}\\(\\) \{[\\s\\S]*?^\}`, 'm'));assert.ok(m,name);return m[0]};
|
||||
const functions=['copy_schema','target_schema','plan_steps'].map(fn).join('\n');
|
||||
@@ -885,7 +885,7 @@ const COUNTED=/^COUNTED="([^"]*)"$/m.exec(srText)[1].split(' ');
|
||||
const STORE_JS=/^STORE_JS='([\s\S]*?)'$/m.exec(srText)[1];
|
||||
// sage-1163's list 2, written out so that a table dropped from the script's COUNTED fails T45 as
|
||||
// well as T46.
|
||||
const LISTED=['role_claims','thread_claims','decision_events','messages','deliveries','task_snapshots','projects','project_archives','threads','sessions','session_defaults','thread_opens','thread_shares','instance_names','usage_records','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_system_types'];
|
||||
const LISTED=['role_claims','thread_claims','decision_events','messages','deliveries','task_snapshots','projects','project_archives','threads','sessions','session_defaults','thread_opens','thread_shares','instance_names','usage_records','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events'];
|
||||
const LATE='2999-01-01T00:00:00.000Z';
|
||||
const addRow=(file,table,at=LATE)=>{const db=new DatabaseSync(file);db.exec(`CREATE TABLE IF NOT EXISTS ${table} (seq INTEGER PRIMARY KEY, at TEXT NOT NULL)`);db.prepare(`INSERT INTO ${table} (at) VALUES (?)`).run(at);db.close()};
|
||||
|
||||
@@ -903,7 +903,7 @@ test('T45 row 181 items 2 and 3: the restore guard counts events and every COUNT
|
||||
both(store('3f.sqlite',['events'],['events','instance_names']),'1\t1 event(s)\n');
|
||||
both(store('none.sqlite',[],['instance_names']),'0\t0 event(s)\n');
|
||||
});
|
||||
for(const x of ['instance_names','usage_records','project_system_types'])await t.test(`one ${x} row and no event refuses before any stop; --events 1 restores`,async(t)=>{
|
||||
for(const x of ['instance_names','usage_records','request_project_events'])await t.test(`one ${x} row and no event refuses before any stop; --events 1 restores`,async(t)=>{
|
||||
const e=await mk(t);await seed(e);
|
||||
assert.equal((await run(e,'activate',C,'acme','--migrate')).code,0);const act=pointer(e).activation;
|
||||
addRow(e.store,x);
|
||||
@@ -925,7 +925,7 @@ test('T45 row 181 items 2 and 3: the restore guard counts events and every COUNT
|
||||
assert.equal(r.code,3,r.out+r.err);assert.ok(r.err.endsWith(`stack-release: refusing restore-mismatch: cannot count the rows after ${stamp}\n`),r.err);
|
||||
assert.deepEqual(fp(e),before);assert.deepEqual(startsStops(e,n),[]);assert.equal(logLines(e).at(-1).code,'restore-mismatch');
|
||||
});
|
||||
for(const x of ['thread_opens','project_system_types'])await t.test(`the in-run recount counts the listed tables too (${x})`,async(t)=>{
|
||||
for(const x of ['thread_opens','project_archives'])await t.test(`the in-run recount counts the listed tables too (${x})`,async(t)=>{
|
||||
const e=await mk(t);await seed(e);
|
||||
assert.equal((await run(e,'activate',C,'acme','--migrate')).code,0);const act=pointer(e).activation;
|
||||
fault(e,'stop-writes-row',x);
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { orgCommand } from '../src/org.mjs';
|
||||
import { projectBusCommand } from '../src/project.mjs';
|
||||
|
||||
test('org installed system types and project selection reads print JSON', async () => {
|
||||
let output = '';
|
||||
const io = { stdout: { write: s => { output += s; } }, env: {} };
|
||||
await orgCommand(['system-types', 'installed'], io);
|
||||
assert.deepEqual(JSON.parse(output).map(x => x.id), ['business-management', 'coding', 'creative-writing', 'marketing', 'montage']);
|
||||
output = '';
|
||||
const calls = [];
|
||||
await projectBusCommand(['system-types', 'work', '--business', 'demo', '--json'], io, () => async (verb, args) => {
|
||||
calls.push([verb, args]);
|
||||
return verb === 'project.list' ? [{ id: 'project-id', name: 'work' }] : { project: 'project-id', selected: ['coding'], active: ['coding'], inactive: [] };
|
||||
});
|
||||
assert.deepEqual(calls.map(x => x[0]), ['project.list', 'project.system-types']);
|
||||
assert.deepEqual(JSON.parse(output).active, ['coding']);
|
||||
});
|
||||
|
||||
// sys1-review P2: both commands go through run() and the real CLI channel module, so a verb the
|
||||
// channel does not admit fails here. A disabled channel and an agent run still refuse.
|
||||
test('project system-types and system-types-set pass the CLI channel', async t => {
|
||||
const { run } = await import('../src/cli.mjs');
|
||||
const { fixture, humanEnv, io: mkio, tmp } = await import('./helpers.mjs');
|
||||
const root = tmp(t), f = fixture(root);
|
||||
const P = '10000000-0000-4000-8000-000000000001';
|
||||
const transportFor = channels => {
|
||||
const calls = [];
|
||||
const transport = () => async (verb, args) => {
|
||||
if (verb === 'plugins') return { business: 'acme', revision: 'a'.repeat(64), plugins: { channel: channels } };
|
||||
calls.push([verb, args]);
|
||||
if (verb === 'project.list') return [{ id: P, at: '2026-11-09T00:00:00.000Z', name: 'work', repo: null }];
|
||||
if (verb === 'project.system-types') return { project: P, selected: ['coding'], active: ['coding'], inactive: [] };
|
||||
if (verb === 'project.system-types.set') return { project: P, selected: args.systemTypes, active: args.systemTypes, inactive: [] };
|
||||
throw Object.assign(new Error(verb), { code: 'bus-refused' });
|
||||
};
|
||||
return { calls, transport };
|
||||
};
|
||||
const read = transportFor(['cli']), rx = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types', 'work', '--business', 'acme'], rx, { transport: read.transport }), 0, rx.err?.text);
|
||||
assert.deepEqual(read.calls, [['project.list', { includeArchived: true }], ['project.system-types', { project: P }]]);
|
||||
assert.deepEqual(JSON.parse(rx.out.text).active, ['coding']);
|
||||
const write = transportFor(['cli']), wx = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types-set', 'work', '--types', 'coding,marketing', '--business', 'acme'], wx, { transport: write.transport }), 0, wx.err?.text);
|
||||
assert.deepEqual(write.calls.at(-1), ['project.system-types.set', { project: P, systemTypes: ['coding', 'marketing'] }]);
|
||||
const off = transportFor(['webui']), ox = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types', 'work', '--business', 'acme'], ox, { transport: off.transport }), 3);
|
||||
assert.deepEqual(off.calls, []);
|
||||
const agent = transportFor(['cli']);
|
||||
assert.notEqual(await run(['project', 'system-types-set', 'work', '--types', 'coding', '--business', 'acme'], mkio({ ...humanEnv(f.env), CODEX_THREAD_ID: 'fixture-agent' }), { transport: agent.transport }), 0);
|
||||
assert.deepEqual(agent.calls, []);
|
||||
});
|
||||
@@ -615,11 +615,6 @@ selection on this release's throwaway development instances. Receipt subjects
|
||||
name that principal, not Jason. The dev-purpose bootstrap fence is a separate
|
||||
follow-up before person-used deployment.
|
||||
|
||||
The optional `plugins.system-type` list enables installed system-type modules for
|
||||
an organization. Missing means none. Unknown ids refuse validation. Changes
|
||||
are owner-only; project selections are separate bus settings and a selection
|
||||
whose type is disabled remains recorded as inactive.
|
||||
|
||||
## Instance accounts (Phase M2)
|
||||
|
||||
`src/accounts.mjs` validates `<configDir>/accounts.json` without a dependency or
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// #1873 CB5: an agent copy's credential binding status in its owner's views (the bus instances read,
|
||||
// the Console agents table and `mosaic org instances`), with the one next step each status names.
|
||||
// The texts are design docs/plans/2026-11-11_copy-credential-binding-design.md section 6's, and the
|
||||
// three steps a binding takes before it is usable (approved, issued, verified at a bus start). Every
|
||||
// string is fixed: none interpolates a name, a path, a URL, a service answer or anything from a token.
|
||||
// A code this table does not know is credential-unavailable, never echoed.
|
||||
export const COPY_BINDING_STATUS = Object.freeze({
|
||||
ready: "credentials.gitea is bound and was verified at the last bus start.",
|
||||
"issue-required": "The binding is approved; the owner must issue the copy's token with mosaic credentials issue, then restart the organization bus.",
|
||||
"restart-required": "Restart the organization bus so it verifies the binding before the copy launches.",
|
||||
"credential-unbound": "credentials.gitea needs an owner-approved binding.",
|
||||
// Boot denies a copy whose role needs a service a copy cannot bind yet, whatever it binds.
|
||||
"copy-service-unbindable": "this copy's role needs a credential service a copy cannot bind yet, so it cannot launch in this organization; binding gitea alone does not change that.",
|
||||
"credential-revoking": "credentials.gitea revocation is in progress; read the copy's status again when it finishes.",
|
||||
"credential-revoke-failed": "credentials.gitea revocation is incomplete; the owner must retry cleanup.",
|
||||
"credential-revoked": "credentials.gitea was revoked; the owner must approve a new binding.",
|
||||
"credential-unavailable": "credentials.gitea is unavailable; the owner must verify the slot.",
|
||||
"credential-expired": "credentials.gitea has expired; the owner must approve a replacement.",
|
||||
"credential-role-changed": "credentials.gitea no longer matches the approved definition; the owner must review the binding.",
|
||||
"credential-scope-exceeded": "credentials.gitea.scopes exceeds the approved role.",
|
||||
"credential-scope-unverified": "credentials.gitea permissions could not be verified.",
|
||||
"copy-unavailable": "copy is no longer active in this organization.",
|
||||
"copy-refused": "copy identity is ambiguous; the owner must resolve the definition collision.",
|
||||
"org-archived": "organization is archived.",
|
||||
"org-unavailable": "organization is not active.",
|
||||
"organization-unreadable": "the organization file could not be read; the owner must check it before the copy launches.",
|
||||
});
|
||||
|
||||
export function copyBindingStatus(code) {
|
||||
const status = typeof code === "string" && Object.hasOwn(COPY_BINDING_STATUS, code) ? code : "credential-unavailable";
|
||||
return Object.freeze({ status, next: COPY_BINDING_STATUS[status] });
|
||||
}
|
||||
@@ -87,7 +87,6 @@ export const VERB_RIGHTS = record({
|
||||
'request.draft.console': 'request.write',
|
||||
'prd.revoke.console': 'request.write',
|
||||
'plugins.set': 'org.setup',
|
||||
'system-types.console': 'org.setup',
|
||||
'project.remote.get.console': 'org.setup',
|
||||
'project.remote.set.console': 'org.setup',
|
||||
// #1873 SP4: starter packs, the board and workflows. The list is a board read; every write is
|
||||
@@ -97,6 +96,10 @@ export const VERB_RIGHTS = record({
|
||||
'pack.apply.console': null,
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// #1873 SP8: saving a template, and listing the saved ones, are the owner's alone: a template is a
|
||||
// copy of the organization's roles, and the files live under the owner's account.
|
||||
'template.save.console': null,
|
||||
'template.list.console': null,
|
||||
});
|
||||
|
||||
function refuse(code) {
|
||||
|
||||
@@ -14,8 +14,6 @@ import { loadRole } from "./role.mjs";
|
||||
import { checkDefinition, checkDefinitions, checkDefinitionName, orgDefinitionName, ORG_PREFIX } from "./definitions.mjs";
|
||||
import { END_PROTECTED, parseRepoRemote } from "./vocabulary.mjs";
|
||||
import { checkPlugins, checkUsageSettings, NAME as KIND_NAME } 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";
|
||||
@@ -505,14 +503,6 @@ export function validateOrganizationDocument(document, file, { rolesDir, dataRoo
|
||||
// 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) {
|
||||
|
||||
@@ -126,13 +126,6 @@ function autonomyFence(old, document, actor) {
|
||||
if(actor!==old.human || actor==='tester' || agents.includes(actor))fail('human-required');
|
||||
}
|
||||
|
||||
function systemTypesFence(old, document, actor) {
|
||||
if (canonicalJson(old.plugins?.['system-type'] ?? []) === canonicalJson(document?.plugins?.['system-type'] ?? [])) return;
|
||||
const agents = Object.entries(old.roles ?? {}).flatMap(([name, role]) => [name, `${role?.definition}.${name}`]);
|
||||
if (actor === old.human && actor !== 'tester' && !agents.includes(actor)) return;
|
||||
fail('organization-system-types-human-only');
|
||||
}
|
||||
|
||||
// C2-06 M11: replyLimits is the human's alone. Any setter that changes it refuses unless the actor is
|
||||
// the business's human as the file stood before the write, and no agent or the tester under that
|
||||
// name. Compared as M9 compares projects, on the document and again on what lands on disk.
|
||||
@@ -320,7 +313,6 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
replyLimitsFence(old, document, actor);
|
||||
modelQuotaFence(old, document, actor);
|
||||
usageFence(old, document, actor);
|
||||
systemTypesFence(old, document, actor);
|
||||
autonomyFence(old, document, actor);
|
||||
validateBusinessDocument(document, file, { rolesDir, dataRoot });
|
||||
const bytes = JSON.stringify(document, null, 2) + "\n";
|
||||
@@ -332,7 +324,6 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
replyLimitsFence(old, written, actor);
|
||||
modelQuotaFence(old, written, actor);
|
||||
usageFence(old, written, actor);
|
||||
systemTypesFence(old, written, actor);
|
||||
autonomyFence(old, written, actor);
|
||||
validateBusinessDocument(written, file, { rolesDir, dataRoot });
|
||||
if (beforeWrite) {
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
// Starter packs SP8 (#1873): saving an organization, or one of its projects, as a template. Design:
|
||||
// starter-packs-design section 5 and SP8 in section 8.
|
||||
//
|
||||
// A saved template is a pack document (packVersion 1) written to
|
||||
// <configDir>/templates/<account>/<name>.json and read later with origin `saved`
|
||||
// (plugins/src/starter-pack.mjs readSavedTemplate). Save copies what section 5 captures and nothing
|
||||
// else: definitions (role, instructions, personality, from), one hire proposal per agent, the board,
|
||||
// the workflows, the union of the captured roles' skills and {id, version} for each pack applied
|
||||
// before. Everything else stays in the organization: members, identities, credential material
|
||||
// (instance credentials, copyBindings, copyId, orgIncarnation, generation), launch, plugins, vars,
|
||||
// project roots and git state, definition revs and hire decisions, and everything on the bus.
|
||||
//
|
||||
// Free text is kept, with the organization id, its project ids, its agent names, the owner's
|
||||
// account and the project roots replaced by {org}, {project}, {agent}, {owner} and {root}. The
|
||||
// preview lists each replacement and every kept free-text field by path, and the exact JSON save
|
||||
// writes; save takes that JSON's digest. Every string and key is passed to the credential store's
|
||||
// assertClean; a hit refuses template-secret-suspected naming the path, never the text.
|
||||
//
|
||||
// A refusal is a TemplateError: a bus code and a reason that names a path or a checked name only,
|
||||
// never a value from the document and never a host path.
|
||||
|
||||
import { closeSync, constants, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { ORG_PREFIX, checkDefinition, readTemplate } from "./definitions.mjs";
|
||||
import { sha256 } from "./util.mjs";
|
||||
import { ID_PATTERN } from "./vocabulary.mjs";
|
||||
import { NAME } from "../../plugins/src/kinds.mjs";
|
||||
import {
|
||||
PACK_BOUNDS, PACK_VERSION, SAVED_MAX_BYTES, checkPack, narrowsTemplate, readSavedTemplate,
|
||||
} from "../../plugins/src/starter-pack.mjs";
|
||||
|
||||
// A template name is a pack id (NAME), at most 64 characters, the length of every other pack name.
|
||||
export const TEMPLATE_NAME_MAX = 64;
|
||||
// list reads at most this many files; a longer directory refuses rather than truncating silently.
|
||||
export const TEMPLATE_LIST_MAX = 256;
|
||||
const CHIEF = "chief-of-staff";
|
||||
const ASSISTANT = "assistant";
|
||||
const HIRE_DEFINITION = /^hire-/;
|
||||
// The board a template carries when the organization (or project) has none: the five task states in
|
||||
// store order, with plain labels, as a kanban. A pack must carry a board (SP1 checkPack).
|
||||
export const DEFAULT_BOARD = Object.freeze({
|
||||
columns: Object.freeze([
|
||||
Object.freeze({ state: "todo", label: "To do" }),
|
||||
Object.freeze({ state: "in-progress", label: "In progress" }),
|
||||
Object.freeze({ state: "in-review", label: "In review" }),
|
||||
Object.freeze({ state: "blocked", label: "Blocked" }),
|
||||
Object.freeze({ state: "done", label: "Done" }),
|
||||
]),
|
||||
layout: "kanban",
|
||||
});
|
||||
const HIRE_REASON = "The organization this template was saved from ran this agent.";
|
||||
// A word boundary for placeholder replacement: an identifier character on either side means the
|
||||
// literal is part of a longer name, which stays as it is.
|
||||
const WORD = "A-Za-z0-9_-";
|
||||
|
||||
export class TemplateError extends Error {
|
||||
constructor(code, reason) {
|
||||
super(reason ? `${code}: ${reason}` : code);
|
||||
this.name = "TemplateError";
|
||||
this.code = code;
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
const refuse = (code, reason) => {
|
||||
throw new TemplateError(code, reason);
|
||||
};
|
||||
|
||||
const plain = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
&& [Object.prototype, null].includes(Object.getPrototypeOf(value));
|
||||
|
||||
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
// The account (the caller's s.human) and the name are checked before any path is built from them.
|
||||
export function checkAccount(account) {
|
||||
if (typeof account !== "string" || !ID_PATTERN.test(account)) refuse("human-required", "the saving account is not a valid account name");
|
||||
return account;
|
||||
}
|
||||
|
||||
export function checkTemplateName(name) {
|
||||
if (typeof name !== "string" || name.length > TEMPLATE_NAME_MAX || !NAME.test(name)) {
|
||||
refuse("invalid-request", `a template name must match ${NAME}, at most ${TEMPLATE_NAME_MAX} characters`);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
// One template, read now, or null when the name is no usable version 2 template.
|
||||
function templateOrNull(rolesDir, name, cache) {
|
||||
if (!cache.has(name)) {
|
||||
let value = null;
|
||||
if (typeof name === "string" && ID_PATTERN.test(name)) {
|
||||
try {
|
||||
value = readTemplate(rolesDir, name);
|
||||
} catch (error) {
|
||||
if (error?.name !== "BusinessError") throw error;
|
||||
}
|
||||
}
|
||||
cache.set(name, value);
|
||||
}
|
||||
return cache.get(name);
|
||||
}
|
||||
|
||||
// ---- Placeholders ----
|
||||
|
||||
// The literals section 5 replaces, longest first so a root path is replaced before the ids inside
|
||||
// it. A name that is also a template or a definition name is a role's name, not a person's or a
|
||||
// client's, and stays: replacing "coder" would rewrite every role text that says coder.
|
||||
function literals(document, { rolesDir, cache }) {
|
||||
const out = [];
|
||||
const add = (text, placeholder) => {
|
||||
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, placeholder });
|
||||
};
|
||||
for (const project of Object.values(document.projects ?? {})) {
|
||||
add(project?.root, "{root}");
|
||||
add(project?.repo, "{root}");
|
||||
}
|
||||
add(document.id, "{org}");
|
||||
for (const id of Object.keys(document.projects ?? {})) add(id, "{project}");
|
||||
add(document.human, "{owner}");
|
||||
const role = (name) => Object.hasOwn(document.definitions ?? {}, name) || templateOrNull(rolesDir, name, cache) !== null;
|
||||
const agents = new Set([...Object.keys(document.roles ?? {}), ...(Array.isArray(document.retired) ? document.retired : [])]);
|
||||
for (const project of Object.values(document.projects ?? {})) for (const name of Object.keys(project?.agents ?? {})) agents.add(name);
|
||||
for (const name of agents) if (!role(name)) add(name, "{agent}");
|
||||
out.sort((a, b) => b.text.length - a.text.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Returns the text with every literal replaced, and counts each placeholder used. One pass over the
|
||||
// text with one alternation, longest literal first: a placeholder written in never matches a later
|
||||
// literal, so an instance named "root" or "agent" cannot rewrite {root} or {agent}.
|
||||
const combined = new WeakMap();
|
||||
function replace(text, list, counts) {
|
||||
if (list.length === 0) return text;
|
||||
let entry = combined.get(list);
|
||||
if (!entry) {
|
||||
const by = new Map(list.map((l) => [l.text, l.placeholder]));
|
||||
entry = { by, pattern: new RegExp(`(?<![${WORD}])(?:${list.map((l) => escape(l.text)).join("|")})(?![${WORD}])`, "g") };
|
||||
combined.set(list, entry);
|
||||
}
|
||||
return text.replace(entry.pattern, (match) => {
|
||||
const placeholder = entry.by.get(match);
|
||||
counts[placeholder] = (counts[placeholder] ?? 0) + 1;
|
||||
return placeholder;
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Capture ----
|
||||
|
||||
// Builds the template document. With list null, free text is kept as it is (the scan's second
|
||||
// copy); otherwise each replacement and each kept free-text field is recorded by path.
|
||||
function capture(document, { name, project, rolesDir, list, record }) {
|
||||
const cache = new Map();
|
||||
const text = (value, path) => {
|
||||
if (list === null) return value;
|
||||
const counts = {};
|
||||
const out = replace(value, list, counts);
|
||||
for (const [placeholder, count] of Object.entries(counts)) record.replacements.push({ path, placeholder, count });
|
||||
record.freeText.push({ path, text: out });
|
||||
return out;
|
||||
};
|
||||
const orgDefinitions = plain(document.definitions) ? document.definitions : {};
|
||||
const scope = project === undefined ? "org" : "project";
|
||||
let source;
|
||||
if (scope === "project") {
|
||||
if (!plain(document.projects) || !Object.hasOwn(document.projects, project)) refuse("invalid-request", "the project is not declared in this organization");
|
||||
source = document.projects[project];
|
||||
if (source?.kind === "library") refuse("invalid-request", "a library project has no agents, board or workflows to save");
|
||||
} else {
|
||||
source = document;
|
||||
}
|
||||
|
||||
// The agents: one hire per org instance, or per project agent that defines one. Never the chief
|
||||
// or the assistant, which every organization already has.
|
||||
const agentEntries = scope === "org"
|
||||
? Object.entries(plain(document.roles) ? document.roles : {})
|
||||
: Object.entries(plain(source.agents) ? source.agents : {}).filter(([, e]) => typeof e?.definition === "string");
|
||||
agentEntries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
const agents = [];
|
||||
for (const [, entry] of agentEntries) {
|
||||
const definition = entry?.definition;
|
||||
if (typeof definition !== "string") continue;
|
||||
const org = definition.startsWith(ORG_PREFIX) ? definition.slice(ORG_PREFIX.length) : null;
|
||||
const base = org === null ? definition : orgDefinitions[org]?.from?.template;
|
||||
if (base === CHIEF || base === ASSISTANT) continue;
|
||||
if (org !== null && !Object.hasOwn(orgDefinitions, org)) refuse("invalid-request", "an agent names an organization definition the file does not hold");
|
||||
agents.push({ org, template: org === null ? definition : null });
|
||||
}
|
||||
|
||||
// Which org definitions are copied: every one for an org template; for a project template the
|
||||
// ones its agents and workflows name.
|
||||
const sourceWorkflows = plain(source.workflows) ? source.workflows : {};
|
||||
let copied;
|
||||
if (scope === "org") {
|
||||
copied = Object.keys(orgDefinitions);
|
||||
} else {
|
||||
const named = new Set(agents.filter((a) => a.org !== null).map((a) => a.org));
|
||||
for (const workflow of Object.values(sourceWorkflows)) {
|
||||
for (const step of Array.isArray(workflow?.steps) ? workflow.steps : []) {
|
||||
for (const role of Array.isArray(step?.roles) ? step.roles : []) if (Object.hasOwn(orgDefinitions, role)) named.add(role);
|
||||
}
|
||||
}
|
||||
copied = Object.keys(orgDefinitions).filter((n) => named.has(n));
|
||||
}
|
||||
|
||||
// Names. A definition named hire-<decision> becomes <from>-<n>, so no decision id leaves the
|
||||
// organization; every other copied definition keeps its name.
|
||||
const taken = new Set(copied.filter((n) => !HIRE_DEFINITION.test(n)));
|
||||
const free = (base) => {
|
||||
if (!taken.has(base)) { taken.add(base); return base; }
|
||||
for (let n = 1; ; n++) if (!taken.has(`${base}-${n}`)) { taken.add(`${base}-${n}`); return `${base}-${n}`; }
|
||||
};
|
||||
const numbered = (base) => {
|
||||
for (let n = 1; ; n++) if (!taken.has(`${base}-${n}`)) { taken.add(`${base}-${n}`); return `${base}-${n}`; }
|
||||
};
|
||||
const renamed = new Map();
|
||||
for (const n of copied) {
|
||||
if (!HIRE_DEFINITION.test(n)) { renamed.set(n, n); continue; }
|
||||
renamed.set(n, numbered(orgDefinitions[n]?.from?.template ?? "role"));
|
||||
}
|
||||
|
||||
// Definitions: role, instructions, personality and from. No rev.
|
||||
const definitions = {};
|
||||
const skills = [];
|
||||
const addSkills = (list) => { for (const s of Array.isArray(list) ? list : []) if (!skills.includes(s)) skills.push(s); };
|
||||
for (const n of copied) {
|
||||
const entry = orgDefinitions[n];
|
||||
const key = renamed.get(n);
|
||||
const at = `definitions.${key}`;
|
||||
if (!plain(entry) || !plain(entry.role)) refuse("invalid-request", `${at} is not a definition entry`);
|
||||
const out = {};
|
||||
if (entry.from !== undefined) {
|
||||
const template = templateOrNull(rolesDir, entry.from?.template, cache);
|
||||
if (!template) refuse("starter-pack-invalid", `${at}.from names a template that is not a version 2 role`);
|
||||
// A template that changed since the definition copied it: the saved from names its current
|
||||
// hash, and the role must still narrow the current template. The preview lists the re-pin.
|
||||
if (template.sha256 !== entry.from.sha256 && list !== null) record.repinned.push(`${at}.from`);
|
||||
out.from = { template: template.name, sha256: template.sha256 };
|
||||
let composition;
|
||||
try {
|
||||
({ composition } = checkDefinition(key, { ...entry, rev: 1, from: out.from }, { where: "definitions" }));
|
||||
} catch (error) {
|
||||
if (error?.name === "BusinessError") refuse("starter-pack-invalid", `${at} fails the composition check`);
|
||||
throw error;
|
||||
}
|
||||
if (!narrowsTemplate(composition, template.role)) refuse("starter-pack-invalid", `${at}.role is wider than template ${template.name}`);
|
||||
}
|
||||
out.role = structuredClone(entry.role);
|
||||
if (typeof entry.instructions === "string") out.instructions = text(entry.instructions, `${at}.instructions`);
|
||||
if (entry.personality !== undefined) {
|
||||
const p = structuredClone(entry.personality);
|
||||
if (plain(p)) {
|
||||
if (typeof p.summary === "string") p.summary = text(p.summary, `${at}.personality.summary`);
|
||||
if (typeof p.voice === "string") p.voice = text(p.voice, `${at}.personality.voice`);
|
||||
if (Array.isArray(p.traits)) p.traits = p.traits.map((t, i) => (typeof t === "string" ? text(t, `${at}.personality.traits[${i}]`) : t));
|
||||
}
|
||||
out.personality = p;
|
||||
}
|
||||
definitions[key] = out;
|
||||
addSkills(entry.role.skills);
|
||||
}
|
||||
|
||||
// Hires: <from>-<n> and the definition. A template agent hires a template reference; an org
|
||||
// definition agent hires the copied definition.
|
||||
const refs = new Map();
|
||||
const hireNames = new Set();
|
||||
const hires = [];
|
||||
for (const agent of agents) {
|
||||
let definition;
|
||||
let base;
|
||||
if (agent.template !== null) {
|
||||
const template = templateOrNull(rolesDir, agent.template, cache);
|
||||
if (!template) refuse("starter-pack-invalid", `an agent uses template ${agent.template}, which is not a version 2 role`);
|
||||
if (!refs.has(agent.template)) {
|
||||
const key = free(agent.template);
|
||||
definitions[key] = { template: template.name, sha256: template.sha256 };
|
||||
refs.set(agent.template, key);
|
||||
addSkills(template.role.skills);
|
||||
}
|
||||
definition = refs.get(agent.template);
|
||||
base = agent.template;
|
||||
} else {
|
||||
definition = renamed.get(agent.org);
|
||||
base = orgDefinitions[agent.org]?.from?.template ?? definition;
|
||||
}
|
||||
let hireName;
|
||||
for (let n = 1; ; n++) if (!hireNames.has(`${base}-${n}`)) { hireName = `${base}-${n}`; break; }
|
||||
hireNames.add(hireName);
|
||||
hires.push({ name: hireName, definition, reason: HIRE_REASON });
|
||||
}
|
||||
if (hires.length > PACK_BOUNDS.hires) refuse("starter-pack-invalid", `a template holds at most ${PACK_BOUNDS.hires} hires; this one would hold ${hires.length}`);
|
||||
|
||||
// The board, or the default when there is none.
|
||||
const sourceBoard = plain(source.board) ? source.board : DEFAULT_BOARD;
|
||||
const board = {
|
||||
columns: sourceBoard.columns.map((c, i) => ({ state: c.state, label: text(c.label, `board.columns[${i}].label`) })),
|
||||
layout: sourceBoard.layout,
|
||||
};
|
||||
|
||||
// Workflows. A pack step carries an id; the organization's steps have none, so save numbers them.
|
||||
// A pack workflow has no title: a workflow without a description takes its title as one.
|
||||
const workflows = {};
|
||||
for (const [wname, workflow] of Object.entries(sourceWorkflows)) {
|
||||
const at = `workflows.${wname}`;
|
||||
const description = typeof workflow?.description === "string" ? text(workflow.description, `${at}.description`)
|
||||
: typeof workflow?.title === "string" ? text(workflow.title, `${at}.description`)
|
||||
: `The ${wname} workflow.`;
|
||||
const steps = (Array.isArray(workflow?.steps) ? workflow.steps : []).map((step, i) => ({
|
||||
id: `step-${i + 1}`,
|
||||
title: text(step.title, `${at}.steps[${i}].title`),
|
||||
roles: (Array.isArray(step.roles) ? step.roles : []).map((r) => (renamed.has(r) ? renamed.get(r) : r)),
|
||||
state: step.state,
|
||||
}));
|
||||
workflows[wname] = { description, steps };
|
||||
}
|
||||
|
||||
// packs: {id, version} for each pack applied before at this scope, once each, the latest 32.
|
||||
const seen = new Set();
|
||||
const packs = [];
|
||||
for (const entry of Array.isArray(document.packs) ? document.packs : []) {
|
||||
if (scope === "org" ? entry?.scope !== "org" : entry?.project !== project) continue;
|
||||
const k = `${entry.id}\n${entry.version}`;
|
||||
if (seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
packs.push({ id: entry.id, version: entry.version });
|
||||
}
|
||||
if (list !== null) record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
|
||||
const keptPacks = packs.slice(Math.max(0, packs.length - PACK_BOUNDS.packs));
|
||||
|
||||
const label = name.slice(0, PACK_BOUNDS.label);
|
||||
const descriptionText = scope === "org" ? "Saved from {org}." : "Saved from {project} in {org}.";
|
||||
return {
|
||||
packVersion: PACK_VERSION, id: name, version: "1.0.0", label, description: descriptionText, scope,
|
||||
definitions, hires, board, workflows, skills, packs: keptPacks,
|
||||
};
|
||||
}
|
||||
|
||||
// Every string and every key, by path, through the credential store's check. A hit refuses
|
||||
// template-secret-suspected and names the path; the text never leaves.
|
||||
function scan(value, path, assertClean) {
|
||||
const check = (v, where) => {
|
||||
try {
|
||||
assertClean(v);
|
||||
} catch (error) {
|
||||
if (error?.code === "credential-leak") refuse("template-secret-suspected", where);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
if (typeof value === "string") return check(value, path);
|
||||
if (Array.isArray(value)) return value.forEach((v, i) => scan(v, `${path}[${i}]`, assertClean));
|
||||
if (value !== null && typeof value === "object") {
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
const where = path ? `${path}.${k}` : k;
|
||||
check(k, `${path || "template"}[key]`);
|
||||
scan(v, where, assertClean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The preview: the exact JSON save writes, its digest, each replacement and each kept free-text
|
||||
// field by path. Refuses before returning when any string or key holds a held credential value.
|
||||
export function templatePreview({ document, name, project, rolesDir, assertClean }) {
|
||||
checkTemplateName(name);
|
||||
if (project !== undefined && (typeof project !== "string" || !ID_PATTERN.test(project))) refuse("invalid-request", "the project id is invalid");
|
||||
if (typeof assertClean !== "function") throw new TypeError("templatePreview needs the credential store's assertClean");
|
||||
if (!plain(document)) refuse("invalid-request", "the organization file is not readable");
|
||||
const scope = { name, project, rolesDir };
|
||||
// The scan reads both copies: the kept text before replacement (a held value a placeholder would
|
||||
// break up still refuses) and the document save writes.
|
||||
const raw = capture(document, { ...scope, list: null, record: null });
|
||||
scan(raw, "", assertClean);
|
||||
const record = { replacements: [], freeText: [], repinned: [], packsDropped: 0 };
|
||||
const template = capture(document, { ...scope, list: literals(document, { rolesDir, cache: new Map() }), record });
|
||||
scan(template, "", assertClean);
|
||||
let checked;
|
||||
try {
|
||||
checked = checkPack(template, { origin: "saved", rolesDir });
|
||||
} catch (error) {
|
||||
if (error?.name === "PluginError") {
|
||||
refuse(/^starter-pack-[a-z-]+$/.test(error.code ?? "") ? error.code : "starter-pack-invalid", typeof error.message === "string" ? error.message.slice(0, 300) : undefined);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const json = `${JSON.stringify(checked, null, 2)}\n`;
|
||||
if (Buffer.byteLength(json) > SAVED_MAX_BYTES) refuse("starter-pack-invalid", `a saved template is at most ${SAVED_MAX_BYTES} bytes`);
|
||||
const byPath = (a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
||||
return {
|
||||
name, scope: checked.scope, ...(project === undefined ? {} : { project }),
|
||||
template: checked, json, digest: sha256(json),
|
||||
replacements: record.replacements.sort(byPath), freeText: record.freeText.sort(byPath),
|
||||
repinned: record.repinned.sort(), packsDropped: record.packsDropped,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- The file ----
|
||||
|
||||
// A directory save writes under: real, the uid's own, writable by nobody else. The account's own
|
||||
// directory is private (0700 or narrower), as readSavedTemplate requires.
|
||||
function directory(path, uid, { private: closed }) {
|
||||
try {
|
||||
mkdirSync(path, { mode: 0o700 });
|
||||
} catch (error) {
|
||||
if (error?.code !== "EEXIST") refuse("not-configured", `the ${closed ? "account" : "templates"} directory cannot be created`);
|
||||
}
|
||||
let st;
|
||||
try {
|
||||
st = lstatSync(path);
|
||||
} catch {
|
||||
refuse("not-configured", `the ${closed ? "account" : "templates"} directory is unreadable`);
|
||||
}
|
||||
if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== uid || (st.mode & 0o022) !== 0 || (closed && (st.mode & 0o077) !== 0)) {
|
||||
refuse("not-configured", `the ${closed ? "account" : "templates"} directory is not private to this instance's user`);
|
||||
}
|
||||
}
|
||||
|
||||
// Save: the preview again, its digest compared, then the file created exclusively (wx, 0600). A
|
||||
// name already saved refuses; nothing is replaced.
|
||||
export function templateSave({ document, name, project, digest, rolesDir, assertClean, configDir, account, uid = process.getuid() }) {
|
||||
checkAccount(account);
|
||||
checkTemplateName(name);
|
||||
if (typeof digest !== "string" || !/^[0-9a-f]{64}$/.test(digest)) refuse("invalid-request", "save takes the preview's digest");
|
||||
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
|
||||
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
|
||||
const templates = join(configDir, "templates");
|
||||
const home = join(templates, account);
|
||||
directory(templates, uid, { private: false });
|
||||
directory(home, uid, { private: true });
|
||||
const file = join(home, `${name}.json`);
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
} catch (error) {
|
||||
if (error?.code === "EEXIST") refuse("invalid-request", "a template of this name is already saved");
|
||||
refuse("not-configured", "the template file cannot be created");
|
||||
}
|
||||
try {
|
||||
fchmodSync(fd, 0o600);
|
||||
const bytes = Buffer.from(preview.json);
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) offset += writeSync(fd, bytes, offset);
|
||||
fsyncSync(fd);
|
||||
} catch (error) {
|
||||
// A partial file would hold the name: remove the file this call created, then report the failure.
|
||||
const open = fd;
|
||||
fd = undefined;
|
||||
try { closeSync(open); } catch { /* the write failure is the one reported */ }
|
||||
try { unlinkSync(file); } catch { /* already gone */ }
|
||||
throw error;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
return { name, scope: preview.scope, ...(project === undefined ? {} : { project }), digest };
|
||||
}
|
||||
|
||||
// List: the caller's own saved templates, each read through readSavedTemplate. A file that does not
|
||||
// read is listed as unreadable, by name only. No account directory yet is an empty list.
|
||||
export function templateList({ configDir, account, rolesDir, uid = process.getuid() }) {
|
||||
checkAccount(account);
|
||||
const home = join(configDir, "templates", account);
|
||||
let names;
|
||||
try {
|
||||
const st = lstatSync(home);
|
||||
if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== uid || (st.mode & 0o077) !== 0) {
|
||||
refuse("not-configured", "the account directory is not private to this instance's user");
|
||||
}
|
||||
names = readdirSync(home);
|
||||
} catch (error) {
|
||||
if (error instanceof TemplateError) throw error;
|
||||
if (error?.code === "ENOENT") return { templates: [] };
|
||||
refuse("not-configured", "the account directory is unreadable");
|
||||
}
|
||||
const files = names.filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -".json".length))
|
||||
.filter((n) => n.length <= TEMPLATE_NAME_MAX && NAME.test(n)).sort();
|
||||
if (files.length > TEMPLATE_LIST_MAX) refuse("invalid-request", `the account holds more than ${TEMPLATE_LIST_MAX} saved templates`);
|
||||
const templates = files.map((n) => {
|
||||
try {
|
||||
const { pack } = readSavedTemplate({ configDir, account, name: n, rolesDir, uid });
|
||||
return { name: n, version: pack.version, label: pack.label, description: pack.description, scope: pack.scope, hires: pack.hires.length };
|
||||
} catch (error) {
|
||||
if (error?.name === "PluginError") return { name: n, readable: false, code: error.code };
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
return { templates };
|
||||
}
|
||||
@@ -79,7 +79,6 @@ const VERBS = {
|
||||
'request.draft.console': 'request.write',
|
||||
'prd.revoke.console': 'request.write',
|
||||
'plugins.set': 'org.setup',
|
||||
'system-types.console': 'org.setup',
|
||||
'project.remote.get.console': 'org.setup',
|
||||
'project.remote.set.console': 'org.setup',
|
||||
// #1873 SP4: starter packs, the board and workflows. The list is a board read; every write is
|
||||
@@ -89,6 +88,9 @@ const VERBS = {
|
||||
'pack.apply.console': null,
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// Starter packs SP8 (#1873): saving a template and listing the saved ones are the owner's alone.
|
||||
'template.save.console': null,
|
||||
'template.list.console': null,
|
||||
};
|
||||
|
||||
test('M1/R1 the eleven rights pin the grantable flags, including compulsory org.view', () => {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { join } from 'node:path';
|
||||
import { KINDS, checkPlugins } from '../../plugins/src/kinds.mjs';
|
||||
import { validateBusinessDocument } from '../src/organization-config.mjs';
|
||||
import { businessDoc, REPO_ROLES, tmp } from './helpers.mjs';
|
||||
|
||||
// #1873 SP9: the system-type kind is removed outright (Jason, 2026-11-12). An org file that still
|
||||
// names it refuses as an unknown kind, like any other name not in KINDS, even with an empty list.
|
||||
test('SP9 an org file naming the removed system-type kind refuses unknown-kind', () => {
|
||||
assert.equal(Object.hasOwn(KINDS, 'system-type'), false);
|
||||
for (const list of [['coding'], []]) {
|
||||
assert.throws(() => checkPlugins({ 'system-type': list }, 'acme.json plugins'),
|
||||
(e) => e.code === 'unknown-kind' && /unknown kind "system-type"/.test(e.message));
|
||||
const root = tmp(), doc = businessDoc(root), file = join(root, 'businesses/acme.json');
|
||||
doc.plugins = { 'system-type': list };
|
||||
assert.throws(() => validateBusinessDocument(doc, file, { rolesDir: REPO_ROLES }), /unknown kind "system-type"/);
|
||||
}
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { join } from 'node:path';
|
||||
import { validateBusinessDocument } from '../src/organization-config.mjs';
|
||||
import { businessDoc, REPO_ROLES, tmp } from './helpers.mjs';
|
||||
|
||||
test('organization enables only installed system types; absent means none', () => {
|
||||
const root = tmp(), doc = businessDoc(root), file = join(root, 'businesses/acme.json');
|
||||
const validate = () => validateBusinessDocument(doc, file, { rolesDir: REPO_ROLES });
|
||||
assert.deepEqual(validate().plugins['system-type'] ?? [], []);
|
||||
doc.plugins = { 'system-type': ['coding', 'montage'] };
|
||||
assert.deepEqual(validate().plugins['system-type'], ['coding', 'montage']);
|
||||
doc.plugins['system-type'] = ['not-installed'];
|
||||
assert.throws(validate, /system-type.*not-installed/);
|
||||
});
|
||||
|
||||
test('system type changes through the organization writer are owner-only', async t => {
|
||||
const { rolesCopy, writeJson } = await import('./helpers.mjs');
|
||||
const { pluginSettings } = await import('../src/plugin-settings.mjs');
|
||||
const { rmSync } = await import('node:fs');
|
||||
const root = tmp(); t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const rolesDir = rolesCopy(root), doc = businessDoc(root), file = join(root, 'businesses/acme.json');
|
||||
writeJson(file, doc);
|
||||
const settings = pluginSettings({ dir: root, rolesDir });
|
||||
const revision = settings.read('acme').revision;
|
||||
assert.throws(() => settings.set('acme', { revision, plugins: { 'system-type': ['coding'] } }, 'tester'), /human-only/);
|
||||
assert.deepEqual(settings.read('acme').plugins, {});
|
||||
assert.deepEqual(settings.set('acme', { revision, plugins: { 'system-type': ['coding'] } }, doc.human).plugins['system-type'], ['coding']);
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
// Starter packs SP8 (#1873): saving an organization or one of its projects as a template. The saved
|
||||
// file carries no credential material and no member, keeps each role's credential request lines,
|
||||
// replaces the organization's own names with placeholders, and reads back as an origin-saved pack.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { businessDoc, rolesCopy } from "./helpers.mjs";
|
||||
import { entryFromTemplate, readTemplate } from "../src/definitions.mjs";
|
||||
import {
|
||||
DEFAULT_BOARD, TemplateError, templateList, templatePreview, templateSave,
|
||||
} from "../src/template-save.mjs";
|
||||
import { checkPack, readSavedTemplate } from "../../plugins/src/starter-pack.mjs";
|
||||
|
||||
const TOKEN = "fixture-held-token-sp8-91c4e7";
|
||||
// The credential store's check, as the bus passes it: a held value anywhere in the text refuses.
|
||||
const assertClean = (value) => {
|
||||
if (JSON.stringify(value).includes(TOKEN)) throw Object.assign(new Error("credential-leak"), { name: "BusError", code: "credential-leak" });
|
||||
};
|
||||
const STRIPPED = ["copyBindings", "copyId", "orgIncarnation", "generation", "holder", "tracker", "vars", "launch", "members", "rev", "hireDecision"];
|
||||
|
||||
function fixture(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), "tsave-"));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, "acme");
|
||||
const coder = readTemplate(rolesDir, "coder");
|
||||
const writer = entryFromTemplate(coder);
|
||||
writer.instructions = `Write code for acme in ${doc.projects.stack.root}/src. Ask jason; pair with ana on stack.`;
|
||||
writer.personality = { summary: "Careful acme engineer.", traits: ["works with ana", "plain"], voice: "short" };
|
||||
const hired = entryFromTemplate(readTemplate(rolesDir, "reviewer"));
|
||||
hired.instructions = "Review what ana writes.";
|
||||
doc.definitions = { writer, "hire-0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0": hired };
|
||||
doc.roles.ana = { definition: "org:writer", credentials: { gitea: { file: join(root, "secrets", "ana.token"), rotateBy: "2099-01-01" } } };
|
||||
doc.roles.bo = { definition: "org:hire-0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0" };
|
||||
doc.retired = ["cy"];
|
||||
// Credential material the save must never copy.
|
||||
doc.copyBindings = { ana: { copyId: "copy-1", orgIncarnation: "inc-1", generation: 3, state: "bound", source: { level: "root", name: "ana", project: null } } };
|
||||
doc.board = { columns: [
|
||||
{ state: "todo", label: "acme backlog" }, { state: "in-progress", label: "Doing" }, { state: "in-review", label: "Review" },
|
||||
{ state: "blocked", label: "Stuck" }, { state: "done", label: "Done" },
|
||||
], layout: "list" };
|
||||
doc.workflows = { change: { title: "Change for stack", steps: [
|
||||
{ title: "ana writes it", state: "in-progress", roles: ["writer"] },
|
||||
{ title: "Review it", state: "in-review", roles: ["hire-0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0", "human"] },
|
||||
] } };
|
||||
doc.packs = [
|
||||
{ id: "coding", version: "1.0.0", origin: "shipped", scope: "org", appliedAt: "2026-11-01T00:00:00Z", revision: "r1", added: ["board"], proposedHires: [] },
|
||||
{ id: "coding", version: "1.0.0", origin: "shipped", scope: "org", appliedAt: "2026-11-02T00:00:00Z", revision: "r2", added: [], proposedHires: [] },
|
||||
{ id: "intake", version: "2.1.0", origin: "installed", project: "stack", appliedAt: "2026-11-03T00:00:00Z", revision: "r3", added: [], proposedHires: [] },
|
||||
];
|
||||
const configDir = join(root, "config");
|
||||
mkdirSync(configDir, { mode: 0o700 });
|
||||
return { root, rolesDir, doc, configDir };
|
||||
}
|
||||
|
||||
const keysDeep = (value, out = []) => {
|
||||
if (Array.isArray(value)) value.forEach((v) => keysDeep(v, out));
|
||||
else if (value && typeof value === "object") for (const [k, v] of Object.entries(value)) { out.push(k); keysDeep(v, out); }
|
||||
return out;
|
||||
};
|
||||
const refused = (fn, code, reason) => assert.throws(fn, (e) => {
|
||||
assert.ok(e instanceof TemplateError, `${e?.name}: ${e?.message}`);
|
||||
assert.equal(e.code, code);
|
||||
if (reason !== undefined) assert.equal(e.reason, reason);
|
||||
return true;
|
||||
});
|
||||
|
||||
test("SP8 red before: an instance's credentials and copyBindings never reach the saved file", (t) => {
|
||||
const { doc, rolesDir, configDir, root } = fixture(t);
|
||||
const preview = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
templateSave({ document: doc, name: "acme-shape", digest: preview.digest, rolesDir, assertClean, configDir, account: "jason" });
|
||||
const file = join(configDir, "templates", "jason", "acme-shape.json");
|
||||
const text = readFileSync(file, "utf8");
|
||||
const saved = JSON.parse(text);
|
||||
const keys = keysDeep(saved);
|
||||
for (const k of STRIPPED) assert.ok(!keys.includes(k), `the saved file holds ${k}`);
|
||||
assert.ok(!text.includes(join(root, "secrets")), "the saved file names a token file");
|
||||
assert.ok(!text.includes("copy-1") && !text.includes("inc-1"));
|
||||
// credentials appears only as a definition's request lines: {service, scopes?}, never a file.
|
||||
for (const [name, entry] of Object.entries(saved.definitions)) {
|
||||
if (!entry.role) continue;
|
||||
assert.ok(Array.isArray(entry.role.credentials), name);
|
||||
for (const line of entry.role.credentials) assert.deepEqual(Object.keys(line).filter((k) => k !== "scopes"), ["service"]);
|
||||
}
|
||||
assert.equal(text, preview.json);
|
||||
});
|
||||
|
||||
test("SP8 the saved file keeps each role's credential request lines", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const { template } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
assert.deepEqual(template.definitions.writer.role.credentials, doc.definitions.writer.role.credentials);
|
||||
assert.ok(template.definitions.writer.role.credentials.length > 0);
|
||||
});
|
||||
|
||||
test("SP8 placeholders replace the org and project ids, the owner, agent names and project roots, in free text only", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
|
||||
const { template } = preview;
|
||||
assert.equal(template.definitions.writer.instructions, "Write code for {org} in {root}/src. Ask {owner}; pair with {agent} on {project}.");
|
||||
assert.equal(template.definitions.writer.personality.summary, "Careful {org} engineer.");
|
||||
assert.deepEqual(template.definitions.writer.personality.traits, ["works with {agent}", "plain"]);
|
||||
assert.equal(template.board.columns[0].label, "{org} backlog");
|
||||
assert.equal(template.workflows.change.description, "Change for {project}");
|
||||
assert.equal(template.workflows.change.steps[0].title, "{agent} writes it");
|
||||
// Agent names that are role names (pm, coder) stay; role text says "coder" on purpose.
|
||||
const all = JSON.stringify(template);
|
||||
for (const literal of ["acme", "jason", "ana", doc.projects.stack.root]) assert.ok(!all.includes(literal), literal);
|
||||
assert.equal(template.description, "Saved from {org}.");
|
||||
// Each replacement is listed by path.
|
||||
const at = (path) => preview.replacements.filter((r) => r.path === path).map((r) => r.placeholder).sort();
|
||||
assert.deepEqual(at("definitions.writer.instructions"), ["{agent}", "{org}", "{owner}", "{project}", "{root}"]);
|
||||
});
|
||||
|
||||
test("SP8 an instance named root, org or agent never rewrites a placeholder already written in", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.roles.root = { definition: "org:writer" };
|
||||
doc.roles.org = { definition: "org:writer" };
|
||||
doc.definitions.writer.instructions = "Work for acme with root on stack. Ask org, then jason.";
|
||||
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
|
||||
assert.equal(preview.template.definitions.writer.instructions, "Work for {org} with {agent} on {project}. Ask {agent}, then {owner}.");
|
||||
const at = preview.replacements.filter((r) => r.path === "definitions.writer.instructions").map((r) => r.placeholder).sort();
|
||||
assert.deepEqual(at, ["{agent}", "{org}", "{owner}", "{project}"]);
|
||||
});
|
||||
|
||||
test("SP8 the preview lists every kept free-text field with its saved text", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const preview = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
const { template } = preview;
|
||||
const expected = [];
|
||||
for (const [name, entry] of Object.entries(template.definitions)) {
|
||||
if (typeof entry.instructions === "string") expected.push([`definitions.${name}.instructions`, entry.instructions]);
|
||||
if (entry.personality) {
|
||||
if (entry.personality.summary !== undefined) expected.push([`definitions.${name}.personality.summary`, entry.personality.summary]);
|
||||
if (entry.personality.voice !== undefined) expected.push([`definitions.${name}.personality.voice`, entry.personality.voice]);
|
||||
(entry.personality.traits ?? []).forEach((v, i) => expected.push([`definitions.${name}.personality.traits[${i}]`, v]));
|
||||
}
|
||||
}
|
||||
template.board.columns.forEach((c, i) => expected.push([`board.columns[${i}].label`, c.label]));
|
||||
for (const [w, wf] of Object.entries(template.workflows)) {
|
||||
expected.push([`workflows.${w}.description`, wf.description]);
|
||||
wf.steps.forEach((s, i) => expected.push([`workflows.${w}.steps[${i}].title`, s.title]));
|
||||
}
|
||||
expected.sort(([a], [b]) => (a < b ? -1 : 1));
|
||||
assert.deepEqual(preview.freeText.map((f) => [f.path, f.text]), expected);
|
||||
});
|
||||
|
||||
test("SP8 a held credential in kept text refuses template-secret-suspected naming the field path, never the text", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.definitions.writer.personality.voice = `short, key ${TOKEN}`;
|
||||
refused(() => templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }), "template-secret-suspected", "definitions.writer.personality.voice");
|
||||
try { templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }); } catch (e) { assert.ok(!e.message.includes(TOKEN)); }
|
||||
// A held value a placeholder would split still refuses: the scan reads the text before replacement.
|
||||
const second = fixture(t);
|
||||
second.doc.workflows.change.steps[1].title = `acme${TOKEN}`;
|
||||
refused(() => templatePreview({ document: second.doc, name: "acme-shape", rolesDir: second.rolesDir, assertClean }), "template-secret-suspected", "workflows.change.steps[1].title");
|
||||
// A workflow key that holds one is named by its parent and [key].
|
||||
const third = fixture(t);
|
||||
third.doc.workflows[TOKEN.replace(/-/g, "")] = third.doc.workflows.change;
|
||||
const keyed = (v) => { if (JSON.stringify(v).includes(TOKEN.replace(/-/g, ""))) throw Object.assign(new Error("x"), { code: "credential-leak" }); };
|
||||
refused(() => templatePreview({ document: third.doc, name: "acme-shape", rolesDir: third.rolesDir, assertClean: keyed }), "template-secret-suspected", "workflows[key]");
|
||||
});
|
||||
|
||||
test("SP8 a second save to the same name refuses and leaves the first file", (t) => {
|
||||
const { doc, rolesDir, configDir } = fixture(t);
|
||||
const { digest } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" });
|
||||
const file = join(configDir, "templates", "jason", "acme-shape.json");
|
||||
const first = readFileSync(file);
|
||||
doc.definitions.writer.instructions = "Changed.";
|
||||
const next = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest: next.digest, rolesDir, assertClean, configDir, account: "jason" }), "invalid-request", "a template of this name is already saved");
|
||||
assert.deepEqual(readFileSync(file), first);
|
||||
assert.equal(lstatSync(file).mode & 0o777, 0o600);
|
||||
assert.equal(lstatSync(join(configDir, "templates", "jason")).mode & 0o777, 0o700);
|
||||
});
|
||||
|
||||
test("SP8 a name that is no pack id refuses before any path is built", (t) => {
|
||||
const { doc, rolesDir, configDir } = fixture(t);
|
||||
for (const name of ["..", ".", "a/b", "../x", ".hidden", "", "A", "x".repeat(65), 7]) {
|
||||
refused(() => templatePreview({ document: doc, name, rolesDir, assertClean }), "invalid-request");
|
||||
refused(() => templateSave({ document: doc, name, digest: "0".repeat(64), rolesDir, assertClean, configDir, account: "jason" }), "invalid-request");
|
||||
}
|
||||
for (const account of ["..", "a/b", ""]) refused(() => templateList({ configDir, account, rolesDir }), "human-required");
|
||||
assert.ok(!existsSync(join(configDir, "templates")));
|
||||
});
|
||||
|
||||
test("SP8 a ninth hire refuses", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
// pm, cto, coder, reviewer, ana and bo are six; three more make nine.
|
||||
doc.roles.dee = { definition: "coder" };
|
||||
doc.roles.eve = { definition: "coder" };
|
||||
assert.equal(templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }).template.hires.length, 8);
|
||||
doc.roles.fay = { definition: "reviewer" };
|
||||
refused(() => templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }), "starter-pack-invalid", "a template holds at most 8 hires; this one would hold 9");
|
||||
});
|
||||
|
||||
test("SP8 each packs entry holds only id and version, once, at the saved scope", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const org = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }).template;
|
||||
assert.deepEqual(org.packs, [{ id: "coding", version: "1.0.0" }]);
|
||||
const project = templatePreview({ document: doc, name: "stack-shape", project: "stack", rolesDir, assertClean }).template;
|
||||
assert.deepEqual(project.packs, [{ id: "intake", version: "2.1.0" }]);
|
||||
for (const entry of [...org.packs, ...project.packs]) assert.deepEqual(Object.keys(entry).sort(), ["id", "version"]);
|
||||
});
|
||||
|
||||
test("SP8 hires and names: no chief, no assistant, no decision id; hire-<decision> becomes <template>-<n>", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.roles.helper = { definition: "assistant" };
|
||||
const preview = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
const { template } = preview;
|
||||
assert.ok(!preview.json.includes("0f1e2d3c"), "a decision id left the organization");
|
||||
assert.ok(Object.hasOwn(template.definitions, "reviewer-1"));
|
||||
assert.deepEqual(template.workflows.change.steps[1].roles, ["reviewer-1", "human"]);
|
||||
assert.deepEqual(template.workflows.change.steps.map((s) => s.id), ["step-1", "step-2"]);
|
||||
const hires = Object.fromEntries(template.hires.map((h) => [h.name, h.definition]));
|
||||
assert.deepEqual(hires, { "coder-1": "writer", "coder-2": "coder", "cto-1": "cto", "pm-1": "pm", "reviewer-1": "reviewer-1", "reviewer-2": "reviewer" });
|
||||
for (const h of template.hires) assert.deepEqual(Object.keys(h).sort(), ["definition", "name", "reason"]);
|
||||
assert.ok(!Object.values(hires).some((d) => /chief|assistant/.test(d)));
|
||||
assert.deepEqual(template.definitions.coder, { template: "coder", sha256: readTemplate(rolesDir, "coder").sha256 });
|
||||
assert.equal(template.board.layout, "list");
|
||||
});
|
||||
|
||||
test("SP8 the saved file reads back as an origin-saved pack, and list shows it", (t) => {
|
||||
const { doc, rolesDir, configDir } = fixture(t);
|
||||
assert.deepEqual(templateList({ configDir, account: "jason", rolesDir }), { templates: [] });
|
||||
const { digest } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" });
|
||||
const { pack } = readSavedTemplate({ configDir, account: "jason", name: "acme-shape", rolesDir, uid: process.getuid() });
|
||||
assert.equal(pack.id, "acme-shape");
|
||||
writeFileSync(join(configDir, "templates", "jason", "broken.json"), "{", { mode: 0o600 });
|
||||
const listed = templateList({ configDir, account: "jason", rolesDir });
|
||||
assert.deepEqual(listed.templates.map((x) => x.name), ["acme-shape", "broken"]);
|
||||
assert.equal(listed.templates[0].hires, 6);
|
||||
assert.equal(listed.templates[1].readable, false);
|
||||
// Another account's list is its own.
|
||||
assert.deepEqual(templateList({ configDir, account: "alex", rolesDir }), { templates: [] });
|
||||
});
|
||||
|
||||
test("SP8 a project template carries the project's agents, the definitions it names and the default board", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.projects.stack.agents = { ana: { definition: "org:writer" }, rev: { definition: "reviewer" }, chief: { exclude: true } };
|
||||
const { template, scope } = templatePreview({ document: doc, name: "stack-shape", project: "stack", rolesDir, assertClean });
|
||||
assert.equal(scope, "project");
|
||||
assert.deepEqual(Object.keys(template.definitions).sort(), ["reviewer", "writer"]);
|
||||
assert.deepEqual(template.board, JSON.parse(JSON.stringify(DEFAULT_BOARD)));
|
||||
assert.deepEqual(template.workflows, {});
|
||||
assert.equal(template.description, "Saved from {project} in {org}.");
|
||||
refused(() => templatePreview({ document: doc, name: "x", project: "nope", rolesDir, assertClean }), "invalid-request");
|
||||
});
|
||||
|
||||
test("SP8 a from the template moved under is re-pinned when the role still narrows it, and refused when it widens", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.definitions.writer.from.sha256 = "1".repeat(64);
|
||||
const preview = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
assert.deepEqual(preview.repinned, ["definitions.writer.from"]);
|
||||
assert.equal(preview.template.definitions.writer.from.sha256, readTemplate(rolesDir, "coder").sha256);
|
||||
doc.definitions.writer.role.tools = [...doc.definitions.writer.role.tools, "not-a-coder-tool"];
|
||||
assert.throws(() => templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }), (e) => e instanceof TemplateError && /^starter-pack-invalid$/.test(e.code));
|
||||
});
|
||||
|
||||
test("SP8 save takes the preview's digest; a changed organization refuses pack-plan-stale and writes nothing", (t) => {
|
||||
const { doc, rolesDir, configDir } = fixture(t);
|
||||
const { digest } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
doc.board.columns[1].label = "Now";
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" }), "pack-plan-stale");
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest: "zz", rolesDir, assertClean, configDir, account: "jason" }), "invalid-request");
|
||||
assert.ok(!existsSync(join(configDir, "templates", "jason", "acme-shape.json")));
|
||||
});
|
||||
|
||||
test("SP8 save refuses a templates directory another user can write, or an account directory that is a link", (t) => {
|
||||
const { doc, rolesDir, configDir, root } = fixture(t);
|
||||
const { digest } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
mkdirSync(join(configDir, "templates"), { mode: 0o700 });
|
||||
chmodSync(join(configDir, "templates"), 0o777);
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" }), "not-configured");
|
||||
chmodSync(join(configDir, "templates"), 0o700);
|
||||
const elsewhere = join(root, "elsewhere");
|
||||
mkdirSync(elsewhere, { mode: 0o700 });
|
||||
symlinkSync(elsewhere, join(configDir, "templates", "jason"));
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" }), "not-configured");
|
||||
refused(() => templateList({ configDir, account: "jason", rolesDir }), "not-configured");
|
||||
assert.ok(!existsSync(join(elsewhere, "acme-shape.json")));
|
||||
// A file planted as a link at the name is not followed.
|
||||
rmSync(join(configDir, "templates", "jason"));
|
||||
mkdirSync(join(configDir, "templates", "jason"), { mode: 0o700 });
|
||||
symlinkSync(join(elsewhere, "target.json"), join(configDir, "templates", "jason", "acme-shape.json"));
|
||||
assert.throws(() => templateSave({ document: doc, name: "acme-shape", digest, rolesDir, assertClean, configDir, account: "jason" }), TemplateError);
|
||||
assert.ok(!existsSync(join(elsewhere, "target.json")));
|
||||
});
|
||||
|
||||
test("SP8 the saved template is a pack checkPack accepts as saved", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const { template } = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
assert.deepEqual(checkPack(structuredClone(template), { origin: "saved", rolesDir }), template);
|
||||
});
|
||||
@@ -499,15 +499,6 @@ record separation, bounded reads and per-key quota settings.
|
||||
|
||||
A harness declares `outputPolicy({ proxy })` as `adapter`, `non-newline-stdout`, or `stdout`. The launcher validates and serializes that declaration; old sessions retain their recorded activity behavior.
|
||||
|
||||
### System types
|
||||
|
||||
`system-type` modules export `interfaceVersion = 1` and `systemType()`, returning
|
||||
`{ id, label, description, toolsets }`. The id is the module directory name;
|
||||
`toolsets` is a distinct list of toolset ids. The installed list is discovered
|
||||
from module directories, and malformed modules refuse discovery. An organization
|
||||
selects modules with `plugins.system-type`; an omitted list enables none. The
|
||||
initial five modules declare no toolsets yet.
|
||||
|
||||
### Instance-installed packages (PL1, #1873)
|
||||
|
||||
The instance owner may install trusted plugin code from the host shell:
|
||||
|
||||
@@ -6,8 +6,6 @@ const VERBS = new Set([
|
||||
"project.create",
|
||||
"project.archive",
|
||||
"project.unarchive",
|
||||
"project.system-types",
|
||||
"project.system-types.set",
|
||||
"thread.list",
|
||||
"thread.create",
|
||||
"thread.messages",
|
||||
|
||||
@@ -80,10 +80,6 @@ export const KINDS = Object.freeze({
|
||||
"model-provider": Object.freeze({
|
||||
kind: "model-provider", interfaceVersion: 1, exports: Object.freeze(["catalogue", "preflight", "route"]), switch: "list",
|
||||
}),
|
||||
// Project system types are installed modules, enabled per organization.
|
||||
"system-type": Object.freeze({
|
||||
kind: "system-type", interfaceVersion: 1, exports: Object.freeze(["systemType"]), switch: "list",
|
||||
}),
|
||||
// A starter pack (#1873 SP1): starterPack() takes nothing and returns a pack document, which
|
||||
// starter-pack.mjs checks with the origin of where it was read. A pack is copied into an
|
||||
// organization, never switched on, so its switch is "none": `plugins` can never name one.
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { loadInstalled } from './loader.mjs';
|
||||
import { NAME } from './kinds.mjs';
|
||||
|
||||
// Discovery is fail-closed: malformed or unloadable installed modules cannot be advertised.
|
||||
export async function installedSystemTypes({dataRoot = null} = {}) {
|
||||
const { modules, refused } = await loadInstalled('system-type',{dataRoot});
|
||||
if (refused.length) throw Object.assign(new Error('system type module refused'), { code: 'system-type-invalid' });
|
||||
return modules.map(({ name, module }) => {
|
||||
const value = module.systemType();
|
||||
if (!value || Object.keys(value).sort().join(',') !== 'description,id,label,toolsets' || value.id !== name ||
|
||||
typeof value.label !== 'string' || !value.label.trim() || /[\r\n]/.test(value.label) ||
|
||||
typeof value.description !== 'string' || !value.description.trim() || /[\r\n]/.test(value.description) ||
|
||||
!Array.isArray(value.toolsets) || value.toolsets.some(t => typeof t !== 'string' || !NAME.test(t)) ||
|
||||
new Set(value.toolsets).size !== value.toolsets.length) {
|
||||
throw Object.assign(new Error(`invalid system type ${name}`), { code: 'system-type-invalid' });
|
||||
}
|
||||
return structuredClone(value);
|
||||
});
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
export function systemType() {
|
||||
return { id: "business-management", label: "Business management", description: "Coordinate and manage business operations.", toolsets: [] };
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
export function systemType() {
|
||||
return { id: "coding", label: "Coding", description: "Build and maintain software.", toolsets: [] };
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
export function systemType() {
|
||||
return { id: "creative-writing", label: "Creative writing", description: "Develop and write creative works.", toolsets: [] };
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
export function systemType() {
|
||||
return { id: "marketing", label: "Marketing", description: "Plan and produce marketing work.", toolsets: [] };
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
export function systemType() {
|
||||
return { id: "montage", label: "Mosaic Montage", description: "Create and manage media productions.", toolsets: [] };
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { KINDS, NAME, PluginError, checkPlugins } from "../src/kinds.mjs";
|
||||
const code = expected => e => e instanceof PluginError && e.code === expected;
|
||||
|
||||
test("REQ-PLUG-1 REQ-LIMIT-4 the registry: usage-source at interface version 1, limit-check at 2 (row 125), each a list", () => {
|
||||
assert.deepEqual(Object.keys(KINDS), ["usage-source", "limit-check", "search-source", "channel", "harness", "usage", "model-provider", "system-type", "starter-pack", "theme", "task-tracker"]);
|
||||
assert.deepEqual(Object.keys(KINDS), ["usage-source", "limit-check", "search-source", "channel", "harness", "usage", "model-provider", "starter-pack", "theme", "task-tracker"]);
|
||||
assert.deepEqual({ ...KINDS["task-tracker"], exports: [...KINDS["task-tracker"].exports] }, { kind: "task-tracker", interfaceVersion: 1, exports: ["adapter"], switch: "one" });
|
||||
assert.ok(Object.isFrozen(KINDS["task-tracker"]) && Object.isFrozen(KINDS["task-tracker"].exports));
|
||||
// Stream S4 (PLAN C5): a theme is data. interfaceVersion 1, one export, a list switch.
|
||||
|
||||
@@ -12,7 +12,7 @@ import { validateBusinessDocument } from "../../organization/src/organization-co
|
||||
|
||||
const GOOD = { "usage-source": ["meter"], "limit-check": ["cap"] };
|
||||
// What loaded() reports for GOOD: search-source is a kind too, switched off here.
|
||||
const GOOD_LOADED = { ...GOOD, "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "system-type": [], "starter-pack": [], theme: [], "task-tracker": [] };
|
||||
const GOOD_LOADED = { ...GOOD, "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "starter-pack": [], theme: [], "task-tracker": [] };
|
||||
|
||||
// A tree with one good module of each kind, already loaded.
|
||||
async function loadedTree(t, options) {
|
||||
@@ -56,7 +56,7 @@ test("REQ-PLUG-1 fixture modules of each kind switch on from a test organization
|
||||
const loader = await s.loader();
|
||||
const result = await loader.load(business.plugins);
|
||||
assert.deepEqual(result.refused, []);
|
||||
assert.deepEqual(result.loaded, { ...doc.plugins, "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "system-type": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.deepEqual(result.loaded, { ...doc.plugins, "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.equal(loader.modules("usage-source")[0].readTurn(), "fixture-usage");
|
||||
assert.equal(loader.modules("limit-check")[0].mayLaunch(), "fixture-limit");
|
||||
assert.equal(loader.modules("limit-check")[0].mustStop(), false);
|
||||
@@ -171,7 +171,7 @@ test("REQ-PLUG-1 a path that becomes unreadable after the lstat checks refuses a
|
||||
assert.match(result.refused[0].message, /packages\/plugins can't be read \(EACCES\)/);
|
||||
assert.deepEqual(result.refused[0].kept, ["meter"]);
|
||||
assert.deepEqual(s.loader.logged.slice(before), result.refused);
|
||||
assert.deepEqual(s.loader.loaded(), { "usage-source": ["meter"], "limit-check": [], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "system-type": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.deepEqual(s.loader.loaded(), { "usage-source": ["meter"], "limit-check": [], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
} finally {
|
||||
if (lock) chmodSync(lock, 0o755);
|
||||
}
|
||||
@@ -233,7 +233,7 @@ test("REQ-PLUG-1 a kind refused on its first load has nothing switched on, and t
|
||||
const loader = await s.loader();
|
||||
// meter loads, absent refuses: the whole kind stays off, not half on.
|
||||
const result = await loader.load({ "usage-source": ["meter", "absent"], "limit-check": ["cap"] });
|
||||
assert.deepEqual(result.loaded, { "usage-source": [], "limit-check": ["cap"], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "system-type": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.deepEqual(result.loaded, { "usage-source": [], "limit-check": ["cap"], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.deepEqual(loader.loaded(), result.loaded);
|
||||
assert.deepEqual(loader.modules("usage-source"), []);
|
||||
assert.equal(loader.logged.length, 1);
|
||||
@@ -261,7 +261,7 @@ test("REQ-PLUG-1 the setting's shape: unknown kinds refuse alone, a bad whole se
|
||||
await refusesKeepingOld(s, ["meter", "meter"], "bad-setting", "meter", /twice/);
|
||||
// An absent key switches the kind off.
|
||||
result = await s.loader.load({ "limit-check": ["cap"] });
|
||||
assert.deepEqual(result.loaded, { "usage-source": [], "limit-check": ["cap"], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "system-type": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
assert.deepEqual(result.loaded, { "usage-source": [], "limit-check": ["cap"], "search-source": [], channel: [], harness: [], usage: [], "model-provider": [], "starter-pack": [], theme: [], "task-tracker": [] });
|
||||
});
|
||||
|
||||
test("REQ-PLUG-1 loads run one at a time, so the last requested setting wins", async t => {
|
||||
|
||||
@@ -207,22 +207,6 @@ test('PL1 tool exceptions cannot impersonate trusted refusals or echo payload by
|
||||
await assert.rejects(service.call('acme','writer','acmeplug.echo',{text:'hello'}),e=>e.code==='plugin-tool-failed' && e.plugin==='acmeplug' && !e.message.includes(SECRET));
|
||||
});
|
||||
|
||||
test('PL1 A3 organization copy readers preserve the derived installed-plugin root',async t=>{
|
||||
const {withCopies,loadWithCopies}=await import('../../organization/src/agent-copies.mjs');
|
||||
const f=fixture(t);f.manifest.kinds=['system-type'];f.manifest.interfaceVersions={'system-type':1};
|
||||
mkdirSync(join(f.src,'system-type'));writeFileSync(join(f.src,'system-type/index.mjs'),'export const interfaceVersion=1;export function systemType(){return {}};');
|
||||
const hash=f.seal();f.install(f.src,{expectedHash:hash});
|
||||
const doc=businessDoc(f.root),rolesDir=rolesCopy(f.root);doc.plugins={...doc.plugins,'system-type':['acmeplug']};writeJson(join(f.root,'businesses/acme.json'),doc);
|
||||
const options={rolesDir,dataRoot:f.dataRoot,snapshot:null};
|
||||
assert.deepEqual(withCopies(doc,join(f.root,'businesses/acme.json'),options).plugins['system-type'],['acmeplug']);
|
||||
assert.deepEqual(loadWithCopies('acme',{...options,dir:f.root}).plugins['system-type'],['acmeplug']);
|
||||
const installed=join(f.dataRoot,'plugins/acmeplug/system-type/index.mjs');chmodSync(installed,0o600);writeFileSync(installed,SECRET);
|
||||
// Config checks names only; the loader owns bad-pin refusal and preserves core.
|
||||
assert.deepEqual(withCopies(doc,join(f.root,'businesses/acme.json'),options).plugins['system-type'],['acmeplug']);
|
||||
doc.plugins['system-type']=['defualt'];
|
||||
assert.throws(()=>withCopies(doc,join(f.root,'businesses/acme.json'),options),/unknown module/);
|
||||
});
|
||||
|
||||
test('PL1 replacement pins refuse across loader and host tools until a fresh process',async t=>{
|
||||
for(const first of ['loader','tool']) {
|
||||
const f=fixture(t);
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createLoader, loadInstalled } from '../src/loader.mjs';
|
||||
|
||||
test('installed system types describe the five modules and unknown names refuse', async () => {
|
||||
const { modules, refused } = await loadInstalled('system-type');
|
||||
assert.deepEqual(refused, []);
|
||||
assert.deepEqual(modules.map(m => m.name), ['business-management', 'coding', 'creative-writing', 'marketing', 'montage']);
|
||||
for (const { name, module } of modules) {
|
||||
const info = module.systemType();
|
||||
assert.equal(info.id, name);
|
||||
assert.ok(info.label && info.description && Array.isArray(info.toolsets));
|
||||
if (name === 'montage') assert.equal(info.label, 'Mosaic Montage');
|
||||
}
|
||||
const loader = createLoader({ log() {} });
|
||||
const result = await loader.load({ 'system-type': ['unknown'] });
|
||||
assert.equal(result.refused.length, 1);
|
||||
assert.deepEqual(result.loaded['system-type'], []);
|
||||
});
|
||||
@@ -70,8 +70,8 @@
|
||||
{ "id": "REQ-LIMIT-4", "title": "Usage sources and limit checks are the first plug-in kinds; an unknown turn is logged and shown, never counted as zero" },
|
||||
{ "id": "REQ-PLUG-1", "title": "Every part the core calls out to is a plug-in kind; modules load from packages/plugins, switched on in the org file" },
|
||||
{ "id": "REQ-PLUG-2", "title": "New call-outs go through a plug-in kind from the start; a hard-coded part converts when a row changes it" },
|
||||
{ "id": "REQ-SYS-1", "title": "System types are a plug-in kind; organizations enable a list of modules" },
|
||||
{ "id": "REQ-SYS-2", "title": "Projects use enabled system types and their agents receive the corresponding toolsets" },
|
||||
{ "id": "REQ-SYS-1", "title": "Starter packs are a plug-in kind; an organization or project copies one in once and owns the copy" },
|
||||
{ "id": "REQ-SYS-2", "title": "Applying a pack grants nothing; every proposed agent is hired through the hire decision" },
|
||||
{ "id": "REQ-HARN-1", "title": "The meta-harness generates each session's launch bundle from role and variables" },
|
||||
{ "id": "REQ-HARN-2", "title": "Credential scope, verbs, the tool limit and a container enforce the rules" },
|
||||
{ "id": "REQ-EVT-1", "title": "Every slice 1 step emits an event; measures come from events" },
|
||||
|
||||
@@ -6,8 +6,8 @@ import { startServer, previewOptions, proofOptions, DEFAULT_BOARD } from './serv
|
||||
import { busCaller, busBusiness, userCaller, consoleCall } from './bus.mjs';
|
||||
import { organizationConsole } from './organizations.mjs';
|
||||
import { consoleBus, userOptionsFor, agentCaller, TESTER_AGENT_VERBS } from './console-bus.mjs';
|
||||
import { SYSTEM_TYPE_VERBS } from './system-types-http.mjs';
|
||||
import { packsCaller } from './packs-http.mjs';
|
||||
import { templatesCaller } from './template-http.mjs';
|
||||
import { autonomyCaller } from './autonomy-http.mjs';
|
||||
import { consoleAccess } from './access.mjs';
|
||||
import { accessContextFor } from '../../cli/src/access.mjs';
|
||||
@@ -191,9 +191,6 @@ try {
|
||||
// The owner reads request status on the selected organization's bus, as on the root Console. Request
|
||||
// writes stay off: the README "Console actions" inventory marks them unavailable for the organizations release.
|
||||
requestRead: session.user === undefined ? consoleCall({ dataRoot: root, socket: paths.socket, business: id }) : null,
|
||||
// Phase P2 (#1873): the owner's System types writes, the organization's enable switch (plugins.set
|
||||
// with its revision) and a project's selection, over the owner's human transport under --send only.
|
||||
systemTypesWrite: session.user === undefined && sendOn ? agentCaller(owner, SYSTEM_TYPE_VERBS) : null,
|
||||
// D1 (#1873): the owner's autonomy writes (save, review, confirm, reverse) on this organization's bus.
|
||||
// These options exist only on a --dev-local-owner Console (`organizations` above). The fence passes
|
||||
// those four verbs and nothing else the console transport carries.
|
||||
@@ -201,6 +198,9 @@ try {
|
||||
// Starter packs SP4 (#1873): the owner's pack apply, board and workflow writes, the three write
|
||||
// .console verbs only. Preview and the pack list are reads over requestRead.
|
||||
packsWrite: session.user === undefined && sendOn ? packsCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
|
||||
// Starter packs SP8 (#1873): the owner's template save, template.save.console with a digest only. The list
|
||||
// and the preview are reads over requestRead.
|
||||
templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
|
||||
// Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the
|
||||
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names.
|
||||
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template) }) : null,
|
||||
|
||||
@@ -57,6 +57,18 @@ const HIRE_START_REFUSALS = {
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it. Nothing was applied.'],
|
||||
'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it. Nothing was applied.'],
|
||||
};
|
||||
// #1873 CB5: the owner's next step once a copy credential binding decision is approved, fixed text
|
||||
// (design section 6 and its three steps). Nothing in it comes from the decision, the bus or a token.
|
||||
export const BINDING_NEXT = Object.freeze({
|
||||
bind: "Binding approved. Issue the copy's token with mosaic credentials issue, then restart the organization bus. The copy's status on the Agents grid names each next step.",
|
||||
unbind: "Unbind approved. The bus stops the copy's runs and revokes its credential. The copy's status on the Agents grid shows when the revoke finishes.",
|
||||
});
|
||||
// A binding decision's preview names its copy and whether it binds or unbinds. Only those two leave
|
||||
// this server: the copy id, incarnation, definition pin and services stay with the bus. The owner's
|
||||
// preview verb is the one bus answer that carries them; the inbox and the trail send the same two.
|
||||
const bindingOf = (v) => (v?.binding && typeof v.binding === 'object' && subjectOk(v.binding.instance) &&
|
||||
(v.binding.after === null || (typeof v.binding.after === 'object' && !Array.isArray(v.binding.after)))
|
||||
? { instance: v.binding.instance, change: v.binding.after === null ? 'unbind' : 'bind' } : null);
|
||||
const BODY_MAX = 4096;
|
||||
const TOKEN = /^[a-f0-9]{64}$/;
|
||||
const DIGEST = /^[a-f0-9]{64}$/;
|
||||
@@ -150,7 +162,10 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
if(step==='start' && (typeof result?.id!=='string'||result.op!=='resolved'||result.choice!=='yes'))return refuse('outcome-unknown');
|
||||
if(step==='templates' && !Array.isArray(result?.templates))return refuse('confirmation-unavailable');
|
||||
line(step==='start'?'hire=recorded':'templates=read');
|
||||
return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice}:result);
|
||||
// CB5: an approved binding start says what the owner does next, fixed text by its shape.
|
||||
const change=step==='start' && value.hire?.binding && typeof value.hire.binding==='object' && 'services' in value.hire.binding
|
||||
? (value.hire.binding.services===null?'unbind':'bind') : null;
|
||||
return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice,...(change?{next:BINDING_NEXT[change]}:{})}:result);
|
||||
} catch(err) {
|
||||
if(step!=='start' || !(err instanceof BusReadError) || !Object.hasOwn(HIRE_START_REFUSALS,err.code))
|
||||
return refuse(busCode(err,step==='start'?'outcome-unknown':'confirmation-unavailable'));
|
||||
@@ -171,11 +186,12 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
const action = ordinary ? 'answer' : value.choice === v.approve.key ? 'approve' : 'deny';
|
||||
if (live() !== session) return refuse('sign-in-required');
|
||||
if(value.adjust!==undefined && v.kind!=='hire')return refuse('invalid-request');
|
||||
const confirmation = confirmations.issue({ session, business: v.business, decision: id, choice: value.choice, digest: v.digest, ...(v.kind==='hire'?{kind:'hire',...(value.adjust===undefined?{}:{adjust:structuredClone(value.adjust)})}:{}) });
|
||||
const binding = v.kind === 'hire' ? bindingOf(v) : null;
|
||||
const confirmation = confirmations.issue({ session, business: v.business, decision: id, choice: value.choice, digest: v.digest, ...(v.kind==='hire'?{kind:'hire',...(value.adjust===undefined?{}:{adjust:structuredClone(value.adjust)}),...(binding?{change:binding.change}:{})}:{}) });
|
||||
if (!confirmation) return refuse('confirmation-unavailable');
|
||||
line(`action=${action}`);
|
||||
return json(res, 200, { id, question: typeof v.question === 'string' ? v.question : '', action, choice: value.choice, text: chosen.text,
|
||||
...(v.kind==='hire'?{kind:'hire',flagged:v.flagged,credentialLines:v.credentialLines,expiresAt:v.expiresAt}:ordinary ? { kind: 'decision' } : { grant: v.grant }), confirmation });
|
||||
...(v.kind==='hire'?{kind:'hire',flagged:v.flagged,credentialLines:v.credentialLines,expiresAt:v.expiresAt,...(binding?{binding}:{})}:ordinary ? { kind: 'decision' } : { grant: v.grant }), confirmation });
|
||||
}
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length !== 2 || !keys.includes('choice') || !keys.includes('confirmation') || typeof value.choice !== 'string') return refuse('invalid-request');
|
||||
@@ -189,7 +205,8 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
} catch (err) { return refuse(busCode(err, 'outcome-unknown')); }
|
||||
if (r?.id !== id || r.op !== 'resolved' || r.choice !== held.choice) return refuse('outcome-unknown');
|
||||
line(`choice=${JSON.stringify(held.choice.slice(0, 64))}${r.grant ? ` grant=${r.grant}` : ''}`);
|
||||
return json(res, 200, { id, op: 'resolved', choice: r.choice, ...(r.grant === 'started' ? { grant: 'started' } : {}) });
|
||||
return json(res, 200, { id, op: 'resolved', choice: r.choice, ...(r.grant === 'started' ? { grant: 'started' } : {}),
|
||||
...(held.change && r.choice === 'yes' ? { next: BINDING_NEXT[held.change] } : {}) });
|
||||
}
|
||||
function json(res, status, body) {
|
||||
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||
|
||||
@@ -396,7 +396,12 @@
|
||||
let canDecide = false, ssoOn = false, answer = null;
|
||||
document.addEventListener('mosaic-signed-out', () => { answer = null; });
|
||||
const ACTIONS = { approve: 'Approve', deny: 'Deny' };
|
||||
const hireLines = c => c?.kind !== 'hire' ? '' : `<h3>Flagged grants — owner approval required</h3><ul>${c.flagged.map(l=>`<li>${txt(l.field)}: ${txt(l.value)}</li>`).join('')||'<li>None</li>'}</ul><h3>Requested credential scopes — owner approval required</h3><ul>${c.credentialLines.map(l=>`<li>${txt(l.service)}${l.scope?`: ${txt(l.scope)}`:''}</li>`).join('')||'<li>None</li>'}</ul><p>Expires ${txt(c.expiresAt)}</p>`;
|
||||
const hireLines = c => c?.kind !== 'hire' ? '' : `<h3>Flagged grants — owner approval required</h3><ul>${c.flagged.map(l=>`<li>${txt(l.field)}: ${txt(l.value)}</li>`).join('')||'<li>None</li>'}</ul><h3>Requested credential scopes — owner approval required</h3><ul>${c.credentialLines.map(l=>`<li>${txt(l.service)}${l.scope?`: ${txt(l.scope)}`:''}</li>`).join('')||'<li>None</li>'}</ul><p>Expires ${txt(c.expiresAt)}</p>${bindingLine(c)}`;
|
||||
// #1873 CB5: a copy credential binding decision names its copy and whether it binds or unbinds;
|
||||
// the scope lines above are the bus's computed ones. The confirmation says `change`; the inbox
|
||||
// row carries the bus's preview, where an unbind is `after: null`.
|
||||
const bindingChange = b => b.change === 'unbind' ? 'unbind' : 'bind';
|
||||
const bindingLine = c => c?.binding && typeof c.binding === 'object' ? `<h3>Credential binding</h3><p data-binding-change="${bindingChange(c.binding)}">${bindingChange(c.binding) === 'unbind' ? 'Unbind and revoke the credentials of' : 'Bind credentials for'} copy <code>${txt(c.binding.instance)}</code>.</p>` : '';
|
||||
const hireAdjustment = c => {
|
||||
if(c?.kind!=='hire' || !c.role)return '';
|
||||
const list=(key,values)=>(values??[]).map((v,i)=>`<label><input type="checkbox" data-hire-list="${esc(key)}" data-index="${i}" checked> ${txt(v)}</label>`).join(' ');
|
||||
@@ -478,7 +483,7 @@
|
||||
let body;
|
||||
if (a.result) {
|
||||
const r = a.result;
|
||||
body = `<p class="receipt" id="decide-status" tabindex="-1">${['decision','hire'].includes(r.kind) ? 'Recorded' : r.action === 'approve' ? 'Approved' : 'Denied'}: you chose “${txt(r.choice)}”, ${txt(r.text)}.${['decision','hire'].includes(r.kind) ? '' : ` ${r.grant === 'started' ? 'The grant executor started.' : r.action === 'approve' ? 'The bus started no grant for it.' : 'Nothing starts for a denial.'}`} History below shows it once the bus is read again.</p>${window.MosaicInbox?.receipt?.(r, a.decision) ?? ''}`;
|
||||
body = `<p class="receipt" id="decide-status" tabindex="-1">${['decision','hire'].includes(r.kind) ? 'Recorded' : r.action === 'approve' ? 'Approved' : 'Denied'}: you chose “${txt(r.choice)}”, ${txt(r.text)}.${['decision','hire'].includes(r.kind) ? '' : ` ${r.grant === 'started' ? 'The grant executor started.' : r.action === 'approve' ? 'The bus started no grant for it.' : 'Nothing starts for a denial.'}`} History below shows it once the bus is read again.</p>${r.next ? `<p class="receipt" data-binding-next>${txt(r.next)}</p>` : ''}${window.MosaicInbox?.receipt?.(r, a.decision) ?? ''}`;
|
||||
} else if (a.confirm) {
|
||||
const c = a.confirm, label = `Confirm ${c.action}`;
|
||||
body = `<div class="s1-confirm" role="group" aria-labelledby="b-confirm"><h3 id="b-confirm" class="small">${label}</h3>
|
||||
@@ -548,7 +553,7 @@
|
||||
if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); else render(false); return; }
|
||||
if (res?.type === 'opaqueredirect') { a.error = { code: 'sign-in-required', message: 'Sign in again before answering. The sign-in proxy redirected the answer, so it never reached the Console.' }; paintDecide('#decide-status'); signOut(); return; }
|
||||
if (res?.ok && json?.id === a.id && json.op === 'resolved' && json.choice === c.choice) {
|
||||
a.result = { kind: c.kind, action: c.action, choice: c.choice, text: c.text, grant: json.grant ?? null, grantDetails: c.grant ?? null };
|
||||
a.result = { kind: c.kind, action: c.action, choice: c.choice, text: c.text, grant: json.grant ?? null, grantDetails: c.grant ?? null, next: typeof json.next === 'string' ? json.next : null };
|
||||
paintDecide('#decide-status'); announce(['decision','hire'].includes(c.kind) ? 'Recorded' : c.action === 'approve' ? 'Approved' : 'Denied'); render(false);
|
||||
} else { a.error = decideRefusal(res, json, 'outcome-unknown'); paintDecide('#decide-status'); announce(`Not answered: ${a.error.message}`); }
|
||||
}
|
||||
@@ -1923,7 +1928,7 @@
|
||||
if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr);
|
||||
};
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {});
|
||||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line and system types now, not at the next poll.
|
||||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line now, not at the next poll.
|
||||
document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') { applyConfig(e.detail); if (window.MosaicOrg && routeOf().split('?')[0] === '/organization') render(false); } });
|
||||
// The cross-organization pages ask for a repaint after a filter, sort or selection change,
|
||||
// and report the inbox count across organizations for the sidebar.
|
||||
|
||||
@@ -620,7 +620,7 @@
|
||||
html += p && !c.refused && redesigned ? window.MosaicProjects.header(p, c.section, c.threads) : heading(p?.name ?? 'Project unavailable');
|
||||
if (p && !c.refused) {
|
||||
if (p.archived && redesigned && !c.canSend) html += '<p class="project-panel" role="status">This project is archived. Its saved conversations and records stay readable.</p>';
|
||||
if (c.settings) html += `<p><a href="#/projects/${esc(c.id)}">Project overview</a></p><h2>Project information</h2><p>Repository: ${txt(p.repo || 'Not linked')}</p><div data-chat-remote>Repository setting unavailable.</div><div data-chat-system-types>System types unavailable.</div>`;
|
||||
if (c.settings) html += `<p><a href="#/projects/${esc(c.id)}">Project overview</a></p><h2>Project information</h2><p>Repository: ${txt(p.repo || 'Not linked')}</p><div data-chat-remote>Repository setting unavailable.</div>`;
|
||||
else if (c.section === 'conversations' && redesigned) html += `<div class="project-section-title"><h2>Conversations</h2></div><div data-project-conversations>${c.threads.filter(t=>!t.shared && t.project===p.id).map(t=>`<a class="project-conversation-row" href="${threadPath(esc(t.id))}" data-conversation-id="${esc(t.id)}"><span class="project-conversation-icon" aria-hidden="true">◌</span><span><strong>${txt(t.name)}</strong><small>With ${txt(t.instance)}</small></span><span data-conversation-status></span><span aria-hidden="true">›</span></a>`).join('') || '<p>No conversations yet. Start one to begin work.</p>'}</div>${p.archived ? '' : `<details class="project-new-conversation"${location.hash.includes('new=1')?' open':''}><summary class="btn primary">New conversation</summary>${creation('thread', c.id)}</details>`}<h2>Shared with me</h2>${c.threads.some(t=>t.shared && t.project===p.id)?threads(c.threads.filter(t=>t.shared && t.project===p.id)):'<p>Nothing is shared with you yet.</p>'}`;
|
||||
else if (c.section === 'conversations') html += '<h2>Conversations</h2>' + threads(c.threads.filter(t => !t.shared)) + (p.archived ? '' : creation('thread', c.id));
|
||||
else if (redesigned) html += '<div data-project-content>Reading…</div>';
|
||||
@@ -687,9 +687,6 @@
|
||||
// which names the project as the organization file does: the chat project's repo key.
|
||||
if (remote && roomOwner() && window.MosaicOrg && typeof window.MosaicProjectRepo?.mount === 'function') window.MosaicProjectRepo.mount({ container: remote, project: project?.repo ?? null, archived: !!c.projectArchived });
|
||||
else if (remote && roomOwner() && typeof window.MosaicProjectRemote?.mount === 'function') { remote.replaceChildren(); window.MosaicProjectRemote.mount({ container: remote, projectId: c.id, repositoryKey: project?.repo ?? null, projectArchived: !!c.projectArchived, preserve: true }); }
|
||||
// Phase P2 (#1873): the project's System types selection, the owner's, mounted like the remote.
|
||||
const types = c.container.querySelector('[data-chat-system-types]');
|
||||
if (types && roomOwner() && typeof window.MosaicSystemTypes?.mount === 'function') window.MosaicSystemTypes.mount({ container: types, projectId: c.id, archived: !!c.projectArchived });
|
||||
if (!window.MosaicOrg && (!redesigned || c.kind !== 'project' || c.settings || c.projectArchived)) window.MosaicProjectArchive?.mount(c.container, c);
|
||||
if (redesigned && c.kind === 'project' && c.projectArchived && !c.settings) {
|
||||
const controls = c.container.querySelector('.project-archive-control');
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="stylesheet" href="/processing.css"><script src="/processing.js" defer></script>
|
||||
<link rel="stylesheet" href="/org-create.css"><script src="/org-create.js" defer></script>
|
||||
<link rel="stylesheet" href="/onboarding.css"><script src="/onboarding.js" defer></script><link rel="stylesheet" href="/panes.css">
|
||||
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/system-types.css"><script src="/system-types.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/panes.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
|
||||
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/panes.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
|
||||
<body>
|
||||
<div hidden aria-hidden="true"><select id="palette"></select><select id="mode"><option value="system">system</option><option value="light">light</option><option value="dim">dim</option><option value="dark">dark</option></select></div>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
|
||||
@@ -487,8 +487,8 @@ html[data-organizations] .ws-meta code{color:var(--text)}
|
||||
html[data-organizations] .ws-meta .ws-dot{color:var(--muted)}
|
||||
html[data-organizations] .ws-meta .ws-dot.s-working b{color:var(--success)}
|
||||
html[data-organizations] .ws-meta .ws-dot.s-offline b,html[data-organizations] .ws-meta .ws-dot.s-error b{color:var(--danger)}
|
||||
html[data-organizations] .ws-typechips,html[data-organizations] .ws-docrow{margin-top:8px}
|
||||
html[data-organizations] .ws-typechips .ws-label,html[data-organizations] .ws-docrow .ws-label{min-width:104px}
|
||||
html[data-organizations] .ws-docrow{margin-top:8px}
|
||||
html[data-organizations] .ws-docrow .ws-label{min-width:104px}
|
||||
html[data-organizations] .ws-doc{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:2px 8px;font-size:12.5px;font-weight:600;color:var(--strong);text-decoration:none}
|
||||
html[data-organizations] .ws-doc:hover{background:var(--raised)}
|
||||
html[data-organizations] .ws-doc svg.i{width:14px;height:14px;color:var(--muted)}
|
||||
@@ -697,7 +697,7 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-busctl,html[data-organizations] .ws-busctl .bus-restart{align-items:flex-start}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart-receipt]{text-align:left}
|
||||
html[data-organizations] .ws-busctl .bus-buttons{justify-content:flex-start}
|
||||
html[data-organizations] .ws-typechips .ws-label,html[data-organizations] .ws-docrow .ws-label{min-width:0}
|
||||
html[data-organizations] .ws-docrow .ws-label{min-width:0}
|
||||
html[data-organizations] .ws-levels{grid-template-columns:minmax(0,1fr)!important}
|
||||
html[data-organizations] .ws-levels>div{border-right:0}
|
||||
html[data-organizations] .ws-levels>.hide-m,html[data-organizations] .ws .hide-m{display:none}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
/* Phase P2 (#1873): System types on the organization dashboard (.ws-types, the chips and the
|
||||
Settings row's Open) and on a project's information page (.project-types). */
|
||||
html[data-organizations] .ws-chip{display:inline-flex;align-items:center;font-size:12px;font-weight:500;padding:1px 7px;border:1px solid var(--line);border-radius:4px;color:var(--text);white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg button.go{border:0;background:none;padding:0;cursor:pointer;font:inherit;font-size:12.5px;font-weight:600;color:var(--action)}
|
||||
html[data-organizations] .ws-cfg button.go:hover{text-decoration:underline}
|
||||
html[data-organizations] .ws-types-list{display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)}
|
||||
html[data-organizations] .ws-types-list li{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:4px 12px;padding:8px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
html[data-organizations] .ws-types-list li:last-child{border-bottom:0}
|
||||
html[data-organizations] .ws-types-list .t{display:flex;flex-direction:column;min-width:0}
|
||||
html[data-organizations] .ws-types-list .t b{font-size:13px;font-weight:600;color:var(--strong)}
|
||||
html[data-organizations] .ws-types-list .t .d{font-size:12px;color:var(--muted);overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-types-list .ws-dot{font-size:12.5px}
|
||||
html[data-organizations] .ws-types-list .ws-btn[aria-disabled="true"]{color:var(--muted);cursor:progress}
|
||||
html[data-organizations] .ws-types>.note{margin:8px 0 0}
|
||||
html[data-organizations] .ws-types-status:empty{display:none}
|
||||
html[data-organizations] .ws-types-status code{overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-types h2:focus{outline:none}
|
||||
@media (max-width:759px){
|
||||
html[data-organizations] .ws-types-list li{grid-template-columns:minmax(0,1fr) auto}
|
||||
html[data-organizations] .ws-types-list .t{grid-column:1/-1}
|
||||
}
|
||||
|
||||
.project-types{border:1px solid var(--border, var(--line, #aaa));border-radius:4px;padding:1rem;margin-top:1rem;overflow-wrap:anywhere}
|
||||
.project-types fieldset{border:0;margin:0;padding:0;display:grid;gap:.5rem}
|
||||
.project-types legend{font-weight:600;margin-bottom:.25rem}
|
||||
.project-types-option{display:flex;align-items:flex-start;gap:.5rem;min-height:44px}
|
||||
.project-types-option input{margin-top:.2rem;width:20px;height:20px;flex:none}
|
||||
.project-types-option span{display:flex;flex-direction:column;min-width:0}
|
||||
.project-types-option small{color:var(--muted, inherit)}
|
||||
.project-types button{min-height:44px;margin-top:.75rem}
|
||||
.project-types-tag{font-size:.8em;font-weight:600;padding:0 .4em;border:1px solid currentColor;border-radius:4px;color:var(--warning, inherit)}
|
||||
.project-types [role="status"]:empty{display:none}
|
||||
.project-types [role="status"]:focus{outline:none}
|
||||
@@ -1,195 +0,0 @@
|
||||
// Phase P2 (#1873): System types, the owner's control on the organization dashboard and on a project's
|
||||
// information page. The modules, their labels and descriptions come from the system-type plug-ins
|
||||
// through /api/system-types; nothing here lists a module. Writes go to the same route, which uses the
|
||||
// organization writer (revision, owner fence, receipt) or project.system-types.set; the server and the
|
||||
// bus recheck every write, so a control shown here grants nothing.
|
||||
(() => {
|
||||
'use strict';
|
||||
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const enc = encodeURIComponent;
|
||||
const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
|
||||
const orgPath = (org, rest) => (org ? `/api/orgs/${enc(org)}/${rest}` : `/api/${rest}`);
|
||||
const LINES = {
|
||||
'sign-in-required': 'Sign in again to see or change system types.',
|
||||
'owner-only': "System types are the organization owner's.",
|
||||
'read-only': 'This Console only reads. Changing system types needs signed-in send mode.',
|
||||
'human-required': "Only the organization's owner can change system types.",
|
||||
'organization-system-types-human-only': "Only the organization's owner can change system types.",
|
||||
'revision-conflict': 'The organization file changed after this page read it. The list was read again; try again.',
|
||||
'organization-busy': 'The organization file is being written. Try again in a moment.',
|
||||
'system-type-not-enabled': 'A chosen type is not enabled in the organization any more. The list was read again.',
|
||||
'system-type-unknown': 'A chosen type is not installed in this tree.',
|
||||
'project-not-found': 'This project was not found.',
|
||||
'not-configured': 'System types are not configured on this Console.',
|
||||
'system-type-invalid': 'An installed system type module is invalid, so none can be read.',
|
||||
'no-bus-host': 'The bus is not running.',
|
||||
'invalid-request': 'The request was refused as invalid.',
|
||||
};
|
||||
const line = code => LINES[code] || 'The bus did not confirm the outcome. The list was read again; check it before you retry.';
|
||||
|
||||
// One request; a refusal keeps its code so the page can say why.
|
||||
async function call(path, body) {
|
||||
const init = body === undefined ? { cache: 'no-store', redirect: 'manual' }
|
||||
: { method: 'POST', cache: 'no-store', redirect: 'manual', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) };
|
||||
let response;
|
||||
try { response = await fetch(path, init); } catch { return { ok: false, code: 'outcome-unknown' }; }
|
||||
if (response.type === 'opaqueredirect') return { ok: false, code: 'sign-in-required' };
|
||||
const value = await response.json().catch(() => null);
|
||||
if (!response.ok) return { ok: false, code: typeof value?.error === 'string' ? value.error : 'outcome-unknown' };
|
||||
return value && typeof value === 'object' ? { ok: true, value } : { ok: false, code: 'outcome-unknown' };
|
||||
}
|
||||
const read = (org, project = null) => call(orgPath(org, project === null ? 'system-types' : `system-types/projects/${enc(project)}`));
|
||||
const labelOf = (value, id) => value.installed.find(m => m.id === id)?.label || id;
|
||||
const valid = value => value && Array.isArray(value.installed) && Array.isArray(value.enabled);
|
||||
|
||||
// ---------- organization dashboard ----------
|
||||
// Per organization: the last read, the type a write is pending on, and the last outcome line.
|
||||
const orgs = new Map();
|
||||
const slot = org => { if (!orgs.has(org)) orgs.set(org, { value: null, code: null, pending: null, outcome: null }); return orgs.get(org); };
|
||||
function remember(org, result) {
|
||||
const s = slot(org);
|
||||
if (result.ok && valid(result.value)) { s.value = result.value; s.code = null; } else { s.value = null; s.code = result.ok ? 'outcome-unknown' : result.code; }
|
||||
return s;
|
||||
}
|
||||
// The chip row under the header: the enabled modules' labels.
|
||||
function chips(org) {
|
||||
const s = slot(org), v = s.value;
|
||||
const body = !v ? `<span class="note">${esc(s.code === 'owner-only' ? line('owner-only') : 'System types unavailable')}</span>`
|
||||
: !v.installed.length ? '<span class="note">No system type modules are installed.</span>'
|
||||
: v.enabled.length ? `${v.enabled.map(id => `<span class="ws-chip">${esc(labelOf(v, id))}</span>`).join('')}<span class="note">Each project picks from these; none is required.</span>`
|
||||
: '<span class="note">None enabled. Enable them under System types below; each project picks from the enabled ones.</span>';
|
||||
return `<div class="ws-typechips ws-chips" data-system-type-chips><span class="ws-label">System types</span>${body}</div>`;
|
||||
}
|
||||
// The Settings row's value.
|
||||
function summary(org) {
|
||||
const v = slot(org).value;
|
||||
return v ? `${v.enabled.filter(id => v.installed.some(m => m.id === id)).length} of ${v.installed.length} installed enabled` : 'Could not be read';
|
||||
}
|
||||
// A side-by-side pane (U5) passes { pane: true, idPrefix }: it shows the types without the switch,
|
||||
// which stays in the organization's full view, and its heading id carries the pane's prefix.
|
||||
function section(org, { pane = false, idPrefix = '' } = {}) {
|
||||
const s = slot(org), v = s.value;
|
||||
const head = `<div class="ws-sec-h"><h2 id="${esc(idPrefix)}ws-types-h" tabindex="-1" data-system-types-heading>System types</h2><span class="note">installed modules; each project picks from the enabled ones</span></div>`;
|
||||
const status = `<p class="note ws-types-status" role="status" data-system-types-status>${s.outcome ? s.outcome : ''}</p>`;
|
||||
if (!v) return `<div class="ws-types" data-system-types>${head}<p class="ws-panel tight note">${esc(s.code === 'owner-only' ? line('owner-only') : `System types unavailable. ${line(s.code)}`)}</p>${status}</div>`;
|
||||
if (!v.installed.length) return `<div class="ws-types" data-system-types>${head}<p class="ws-panel tight note">No system type modules are installed.</p>${status}</div>`;
|
||||
const rows = v.installed.map(m => {
|
||||
const on = v.enabled.includes(m.id), busy = s.pending !== null;
|
||||
const state = `<span class="ws-dot ${on ? 's-working' : 's-idle'}"><b aria-hidden="true">${on ? '●' : '–'}</b>${on ? 'enabled' : 'off'}</span>`;
|
||||
const control = v.writable && !pane
|
||||
? `<button type="button" class="ws-btn" data-system-type-toggle="${esc(m.id)}" data-on="${on}" data-focus-key="${esc(`st:${m.id}`)}" aria-label="${esc(`${on ? 'Disable' : 'Enable'} ${m.label}`)}"${busy ? ' aria-disabled="true"' : ''}>${s.pending === m.id ? 'Saving…' : on ? 'Disable' : 'Enable'}</button>`
|
||||
: '';
|
||||
return `<li data-system-type="${esc(m.id)}"><span class="t"><b>${esc(m.label)}</b><span class="d">${esc(m.description)}</span></span>${state}${control}</li>`;
|
||||
}).join('');
|
||||
const why = pane ? "<p class=\"note\">Change system types from this organization's full view.</p>"
|
||||
: v.writable ? '<p class="note">Disabling a type keeps it in the projects that pick it; they show it as inactive until it is enabled again.</p>'
|
||||
: `<p class="note">${esc(line('read-only'))}</p>`;
|
||||
return `<div class="ws-types" data-system-types>${head}<ul class="ws-types-list">${rows}</ul>${why}${status}</div>`;
|
||||
}
|
||||
// The dashboard asks for this before it paints; the result stays for chips(), summary() and section().
|
||||
const load = async org => remember(org, await read(org));
|
||||
// After a write, the three parts are repainted in place; the 10 s dashboard repaint reads again anyway.
|
||||
function repaint(org) {
|
||||
if (window.MosaicOrg?.id !== org) return;
|
||||
const view = [...document.querySelectorAll('[data-org-dashboard]')].find(v => !v.closest('[data-pane]')); if (!view) return;
|
||||
const a = document.activeElement, key = view.contains(a) ? a.dataset?.focusKey || null : null;
|
||||
const swap = (selector, html) => { const el = view.querySelector(selector); if (el) el.outerHTML = html; };
|
||||
swap('[data-system-type-chips]', chips(org));
|
||||
swap('[data-system-types]', section(org));
|
||||
const value = view.querySelector('[data-org-setting="System types"] .v'); if (value) { value.textContent = summary(org); value.title = summary(org); }
|
||||
if (key) view.querySelector(`[data-focus-key="${CSS.escape(key)}"]`)?.focus({ preventScroll: true });
|
||||
}
|
||||
async function toggle(button) {
|
||||
const org = window.MosaicOrg?.id, s = org ? slot(org) : null, type = button.dataset.systemTypeToggle;
|
||||
if (!s?.value?.writable || s.pending !== null || typeof s.value.revision !== 'string') return;
|
||||
const on = s.value.enabled.includes(type);
|
||||
const enabled = on ? s.value.enabled.filter(id => id !== type) : [...s.value.enabled, type];
|
||||
s.pending = type; s.outcome = null; repaint(org);
|
||||
const result = await call(orgPath(org, 'system-types'), { revision: s.value.revision, enabled });
|
||||
s.pending = null;
|
||||
const label = labelOf(s.value, type);
|
||||
if (result.ok && typeof result.value.transaction === 'string') {
|
||||
s.outcome = `${esc(label)} ${on ? 'disabled' : 'enabled'}. Receipt <code>${esc(result.value.transaction)}</code>.`;
|
||||
} else s.outcome = esc(result.ok ? line('outcome-unknown') : line(result.code));
|
||||
await load(org);
|
||||
repaint(org);
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const button = e.target.closest?.('[data-system-type-toggle]');
|
||||
// A pending write marks the buttons aria-disabled, not disabled, so focus stays on the one pressed.
|
||||
if (button) { e.preventDefault(); if (button.getAttribute('aria-disabled') !== 'true' && !button.closest('[data-pane]')) toggle(button); return; }
|
||||
const open = e.target.closest?.('[data-system-types-open]');
|
||||
if (open) { e.preventDefault(); const h = (open.closest('[data-org-dashboard]') || document).querySelector('[data-system-types-heading]'); h?.scrollIntoView({ block: 'start' }); h?.focus({ preventScroll: true }); }
|
||||
});
|
||||
|
||||
// ---------- project information page ----------
|
||||
let active = null;
|
||||
document.addEventListener('mosaic-signed-out', () => { active?.dispose(); active = null; });
|
||||
// The chat view mounts again on every repaint and keeps the section; leaving the page marks it stale,
|
||||
// so coming back (say, after the dashboard changed the enabled set) reads again.
|
||||
window.addEventListener('hashchange', () => { if (active) active.stale = true; });
|
||||
function mount({ container, projectId, archived = false }) {
|
||||
if (!(container instanceof Element)) return;
|
||||
const org = window.MosaicOrg?.id ?? null;
|
||||
if (active && active.org === org && active.projectId === projectId) {
|
||||
container.replaceChildren(active.section);
|
||||
if (active.archived !== archived) { active.archived = archived; active.paint(); }
|
||||
if (active.stale) { active.stale = false; active.refresh(); }
|
||||
return;
|
||||
}
|
||||
active?.dispose();
|
||||
const section = document.createElement('section');
|
||||
section.className = 'project-types';
|
||||
section.setAttribute('data-project-system-types', '');
|
||||
container.replaceChildren(section);
|
||||
let value = null, code = null, outcome = '', saving = false, disposed = false, generation = 0;
|
||||
const state = { org, projectId, section, archived, stale: false, paint, refresh: () => refresh(), dispose: () => { disposed = true; generation++; section.replaceChildren(); } };
|
||||
active = state;
|
||||
function paint() {
|
||||
if (disposed) return;
|
||||
const head = '<h2 tabindex="-1">System types</h2>';
|
||||
const status = `<p role="status" tabindex="-1" data-project-system-types-status>${outcome}</p>`;
|
||||
if (!ID.test(projectId ?? '')) { section.innerHTML = `${head}<p>System types unavailable.</p>`; return; }
|
||||
if (!value) { section.innerHTML = `${head}<p>${esc(code ? `System types unavailable. ${line(code)}` : 'Reading system types…')}</p>${status}`; return; }
|
||||
const sel = value.project, enabled = value.installed.filter(m => value.enabled.includes(m.id));
|
||||
const inactive = sel.inactive.length
|
||||
? `<div data-project-system-types-inactive><p>Inactive, because the organization has disabled them:</p><ul>${sel.inactive.map(id => `<li data-inactive-type="${esc(id)}">${esc(labelOf(value, id))} <span class="project-types-tag">inactive</span></li>`).join('')}</ul>${value.writable && !state.archived ? '<p class="muted">Saving keeps only enabled types, so it removes these from the project.</p>' : ''}</div>`
|
||||
: '';
|
||||
const intro = '<p>This project picks from the system types its organization has enabled. None is required.</p>';
|
||||
const canWrite = value.writable && !state.archived;
|
||||
if (!enabled.length) {
|
||||
// With nothing enabled the only change left is clearing what the project still selects.
|
||||
const clear = canWrite && sel.inactive.length
|
||||
? `<form data-project-system-types-form><button type="submit" class="btn"${saving ? ' disabled' : ''}>${saving ? 'Saving…' : 'Clear the inactive types'}</button></form>` : '';
|
||||
section.innerHTML = `${head}${intro}<p>The organization has no system types enabled. The owner enables them on the organization dashboard.</p>${inactive}${clear}${status}`;
|
||||
return;
|
||||
}
|
||||
const boxes = enabled.map(m => `<label class="project-types-option"><input type="checkbox" name="system-type" value="${esc(m.id)}"${sel.active.includes(m.id) ? ' checked' : ''}${canWrite && !saving ? '' : ' disabled'}><span><strong>${esc(m.label)}</strong><small>${esc(m.description)}</small></span></label>`).join('');
|
||||
const why = state.archived ? '<p class="muted">This project is archived; its selection is shown read only.</p>' : value.writable ? '' : `<p class="muted">${esc(line('read-only'))}</p>`;
|
||||
section.innerHTML = `${head}${intro}<form data-project-system-types-form><fieldset><legend>Selected system types</legend>${boxes}</fieldset>${inactive}${canWrite ? `<button type="submit" class="btn"${saving ? ' disabled' : ''}>${saving ? 'Saving…' : 'Save system types'}</button>` : ''}</form>${why}${status}`;
|
||||
}
|
||||
async function refresh() {
|
||||
const turn = ++generation;
|
||||
const result = await read(org, projectId);
|
||||
if (disposed || turn !== generation) return;
|
||||
if (result.ok && valid(result.value) && result.value.project) { value = result.value; code = null; } else { value = null; code = result.ok ? 'outcome-unknown' : result.code; }
|
||||
paint();
|
||||
}
|
||||
section.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
if (saving || !value?.writable || state.archived) return;
|
||||
const chosen = [...section.querySelectorAll('input[name="system-type"]:checked')].map(i => i.value);
|
||||
saving = true; outcome = ''; paint();
|
||||
const result = await call(orgPath(org, `system-types/projects/${enc(projectId)}`), { systemTypes: chosen });
|
||||
if (disposed) return;
|
||||
saving = false;
|
||||
outcome = result.ok ? esc(result.value.selected.length ? `Saved. Selected: ${result.value.selected.map(id => labelOf(value, id)).join(', ')}.` : 'Saved. No system types selected.') : esc(line(result.code));
|
||||
await refresh();
|
||||
section.querySelector('[data-project-system-types-status]')?.focus({ preventScroll: true });
|
||||
});
|
||||
paint();
|
||||
refresh();
|
||||
}
|
||||
|
||||
window.MosaicSystemTypes = Object.freeze({ load, chips, summary, section, mount });
|
||||
})();
|
||||
@@ -1,8 +1,7 @@
|
||||
// The unified workspace screens in organization mode: the sidebar's Organizations and Projects
|
||||
// groups (sample 01), the organization dashboard (sample 03) and the Agents levels (sample 08).
|
||||
// Every read goes through MosaicWorkspaceData (workspace-data.js). Nothing here writes; the bus
|
||||
// restart button is console-restart.js's own control, with its gating and trail unchanged, and the
|
||||
// System types chips, row and section are system-types.js's (Phase P2), with its own reads and writes.
|
||||
// restart button is console-restart.js's own control, with its gating and trail unchanged.
|
||||
(() => {
|
||||
'use strict';
|
||||
if (!document.documentElement.hasAttribute('data-organizations')) return;
|
||||
@@ -158,7 +157,7 @@
|
||||
const secH = (title, note = '', link = '') => `<div class="ws-sec-h"><h2>${title}</h2>${note ? `<span class="note">${note}</span>` : ''}${link}</div>`;
|
||||
|
||||
function settingsList(org, ctx) {
|
||||
const { business, settings, instances, orgCount, types } = ctx;
|
||||
const { business, settings, instances, orgCount } = ctx;
|
||||
const b = business?.business, s = settings;
|
||||
const unread = 'Could not be read';
|
||||
const names = instances ? Object.keys(instances) : null;
|
||||
@@ -170,7 +169,6 @@
|
||||
const rows = [
|
||||
['business', 'Identity', b ? `${label(org)} · ${org.id} · kind not recorded` : unread, 'org file', 'business'],
|
||||
['flag', 'Appearance', `${titleCase(theme)} theme · ${initials(org)} avatar`, b?.appearance?.theme || org.theme ? 'org file' : 'system', 'appearance'],
|
||||
['cube', 'System types', types ? types.summary(org.id) : 'Could not be read', 'org file', types ? '@system-types' : null],
|
||||
['folder', 'Projects', b ? (Array.isArray(b.projects) && b.projects.length ? plural(b.projects.length, 'project') : 'No projects') : unread, 'org file', '#/projects'],
|
||||
['people', 'Agents and roles', names ? (names.length ? `${plural(names.length, 'agent')} · ${Object.values(instances).filter(running).length} running` : 'No agents') : unread, 'org file', 'agents'],
|
||||
['term', 'Models and routing', models ? (models.length ? models.join(' · ') : 'No models set') : unread, 'org file', 'routing'],
|
||||
@@ -189,10 +187,8 @@
|
||||
['close', 'Archive or delete', "Archive or delete this organization's file", 'danger', 'organizations'],
|
||||
];
|
||||
return `<ul class="ws-cfg one" data-org-settings>${rows.map(([ic, name, value, tag, page]) => {
|
||||
const href = page === null || page.startsWith('@') ? null : page.startsWith('#') ? page : `#/settings/${page}`;
|
||||
// '@system-types' is the System types section further down this page, not a route.
|
||||
const go = page === '@system-types' ? `<button type="button" class="go" data-system-types-open data-focus-key="${esc(`set:${name}`)}" aria-label="Open ${esc(name)}">Open</button>`
|
||||
: href ? `<a class="go" href="${esc(href)}" data-focus-key="${esc(`set:${name}`)}" aria-label="Open ${esc(name)}">Open</a>` : '<span class="go" aria-hidden="true"></span>';
|
||||
const href = page === null ? null : page.startsWith('#') ? page : `#/settings/${page}`;
|
||||
const go = href ? `<a class="go" href="${esc(href)}" data-focus-key="${esc(`set:${name}`)}" aria-label="Open ${esc(name)}">Open</a>` : '<span class="go" aria-hidden="true"></span>';
|
||||
return `<li${tag === 'danger' ? ' class="danger"' : ''} data-org-setting="${esc(name)}">${icon(ic)}<span class="k">${esc(name)}</span><span class="v" title="${esc(value)}">${esc(value)}</span><span class="src-tag">${esc(tag)}</span>${go}</li>`;
|
||||
}).join('')}</ul>`;
|
||||
}
|
||||
@@ -206,8 +202,7 @@
|
||||
const list = Array.isArray(listRead) ? listRead : null;
|
||||
const org = list?.find(o => o.id === id && !o.invalid);
|
||||
if (!org) return `<article class="ws ws-dash" data-org-dashboard data-org-unavailable><div class="ws-vh"><h1 tabindex="-1">Organization unavailable</h1><p class="sub">${list ? 'This organization is not on your list.' : 'The organization list could not be read.'}</p></div></article>`;
|
||||
const types = window.MosaicSystemTypes || null;
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), types ? types.load(id) : null, window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)]);
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)]);
|
||||
const value = i => (reads[i].status === 'fulfilled' ? reads[i].value : null);
|
||||
const business = value(0), settings = value(1), instances = instancesOf(value(2));
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
|
||||
@@ -228,7 +223,6 @@
|
||||
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
|
||||
|
||||
const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid;
|
||||
const typechips = types ? types.chips(id) : '<div class="ws-typechips ws-chips"><span class="ws-label">System types</span><span class="note">System types unavailable</span></div>';
|
||||
const docChips = !docRead ? '<span class="note">Docs unavailable</span>' : docRead.failed ? '<span class="note">Docs unavailable</span>' : docRead.rows.length ? docRead.rows.slice(0, 6).map(d => `<a class="ws-doc" href="#/docs/${enc(d.project)}/${enc(d.path)}" data-focus-key="${esc(`doc:${d.project}:${d.path}`)}" title="${esc(`${d.project}/${d.path}`)}">${icon('doc')}${esc(docName(d.path))}<small>${esc(projectName(d.project))}</small></a>`).join('') : '<span class="note">No docs yet</span>';
|
||||
const docrow = `<div class="ws-docrow ws-chips"><span class="ws-label">Docs</span>${docChips}<a class="ws-more" href="#/docs" data-focus-key="docs-all">All docs</a></div>`;
|
||||
|
||||
@@ -255,7 +249,7 @@
|
||||
return `<article class="ws ws-dash" data-org-dashboard>
|
||||
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/settings/organizations">Organizations</a><span aria-hidden="true">›</span><span>${name}</span></nav>
|
||||
<div class="ws-orghead ws-o" style="${colours(org)}">${av(org, 'lg')}<h1 tabindex="-1">${name}</h1><div class="ws-right">${bus}${reload}</div>${meta}</div>
|
||||
${typechips}${docrow}
|
||||
${docrow}
|
||||
<div class="ws-split">
|
||||
<section aria-label="Measures and sessions">
|
||||
${tiles('KPIs', 'defined in the organization file', 'No KPIs defined in the organization file')}
|
||||
@@ -266,8 +260,7 @@
|
||||
</section>
|
||||
<section aria-label="Settings">
|
||||
${secH('Settings', 'every setting, with where its value comes from')}
|
||||
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null, types })}
|
||||
${types ? types.section(id, { pane, idPrefix: opts.idPrefix || '' }) : ''}
|
||||
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null })}
|
||||
${window.MosaicAutonomy?.section(id)??''}
|
||||
${window.MosaicPacks?.section(id) ?? ''}
|
||||
${window.MosaicWorkflows?.section(id) ?? ''}
|
||||
@@ -283,8 +276,14 @@
|
||||
const NOT_RUNNING = ['s-idle', '–', 'not running'];
|
||||
// A copy's status: running or not as the bus reports its runs, or why it can't launch.
|
||||
const CANT = ['s-error', '▲', "can't launch"];
|
||||
const copyWhy = (c) => (c.state === 'unbound' ? `no binding in this organization for ${(c.missing || []).join(', ')}` : c.reason || 'refused');
|
||||
const copyDot = (name, c, agents) => (c.state === 'instance' ? activity(name, c, agents) : CANT);
|
||||
// #1873 CB5: the bus adds `binding` to a copy that needs a credential binding: its status code and
|
||||
// the owner's next step, fixed text from the bus. A booted copy whose binding is not ready can't
|
||||
// launch, and says why.
|
||||
const bindingNext = (c) => (typeof c?.binding?.next === 'string' && c.binding.status !== 'ready' ? c.binding.next : '');
|
||||
const copyBlocked = (c) => c.state !== 'instance' || Boolean(bindingNext(c));
|
||||
const copyWhy = (c) => (c.state === 'unbound' ? [`no binding in this organization for ${(c.missing || []).join(', ')}`, bindingNext(c)].filter(Boolean).join('. ')
|
||||
: c.state === 'instance' ? bindingNext(c) : c.reason || 'refused');
|
||||
const copyDot = (name, c, agents) => (copyBlocked(c) ? CANT : activity(name, c, agents));
|
||||
// The bus names each copy's instance. Find an agent's copy by its name and project, never by
|
||||
// rebuilding the instance name: a collision refuses one entry that lists every claimant.
|
||||
const copyFor = (copies, name, project = null) => {
|
||||
@@ -329,7 +328,7 @@
|
||||
if (inst === null) return '<span class="muted">status unavailable</span>';
|
||||
const { key, copy: c } = copyFor(mine?.copies, a.name, a.level === 'project' ? a.project : null);
|
||||
if (!c) return '<span class="muted">starts with the next bus start</span>';
|
||||
return `${dot(...copyDot(key, c, mine.agents), true)}${c.state === 'instance' ? '' : `<span class="t2">${esc(copyWhy(c))}</span>`}`;
|
||||
return `${dot(...copyDot(key, c, mine.agents), true)}${copyBlocked(c) ? `<span class="t2">${esc(copyWhy(c))}</span>` : ''}`;
|
||||
}
|
||||
if (inst === null) return '<span class="muted">status unavailable</span>';
|
||||
return dot(...(inst[a.name] ? activity(a.name, inst[a.name], mine.agents) : NOT_RUNNING), true);
|
||||
@@ -378,7 +377,7 @@
|
||||
const copyPill = (copies, agents, name, project, small) => {
|
||||
const { key, copy: c } = copyFor(copies, name, project);
|
||||
const mark = copies === null ? ['s-unknown', '?', 'status unavailable'] : !c ? ['s-unknown', '?', 'starts with the next bus start'] : copyDot(key, c, agents);
|
||||
const why = c && c.state !== 'instance' ? `<span class="note ws-off" data-copy-why="${esc(key)}">${esc(name)}: ${esc(copyWhy(c))}</span>` : '';
|
||||
const why = c && copyBlocked(c) ? `<span class="note ws-off" data-copy-why="${esc(key)}">${esc(name)}: ${esc(copyWhy(c))}</span>` : '';
|
||||
return `<span class="ws-agent" data-level-agent="${esc(name)}" data-copy-state="${esc(c?.state || 'unknown')}">${dot(...mark)}${esc(name)} <small>${esc(small)}</small></span>${why}`;
|
||||
};
|
||||
// Root: one copy per organization, each running inside that organization; an opt-out is said.
|
||||
|
||||
@@ -12,6 +12,7 @@ import { BusReadError, busStatus as coreBusStatus, subjectOk, sendOutcome } from
|
||||
const busStatus = code => ['tester-off', 'tester-required'].includes(code) ? 403 : coreBusStatus(code);
|
||||
import { ReadError, readStatus, fieldTable } from './reads.mjs';
|
||||
import { THREAD_DEFINITION, THREAD_DEFINITIONS } from '../../organization/src/vocabulary.mjs';
|
||||
import { copyBindingStatus } from '../../organization/src/copy-binding-status.mjs';
|
||||
import { OnboardingError, approveNorthStarDraft, interviewMessage, loadInterviewTemplate, northStarTemplateText } from '../../project/src/onboarding.mjs';
|
||||
import { chatHTTP } from './chat-http.mjs';
|
||||
import { projectArchiveHTTP } from './project-archive-http.mjs';
|
||||
@@ -20,8 +21,8 @@ import { themesHTTP } from './themes-http.mjs';
|
||||
import { DECISION_ROUTE, decisionHTTP, decisionRefuse, createConfirmations } from './decision-http.mjs';
|
||||
import { REQUEST_ROUTE, requestHTTP, requestRefuse } from './request-http.mjs';
|
||||
import { PROJECT_REMOTE_ROUTE, projectRemoteHTTP } from './project-remote-http.mjs';
|
||||
import { SYSTEM_TYPES_ROUTE, systemTypesHTTP } from './system-types-http.mjs';
|
||||
import { PACKS_ROUTE, packsHTTP, packsServes } from './packs-http.mjs';
|
||||
import { TEMPLATES_ROUTE, templatesHTTP } from './template-http.mjs';
|
||||
import { orgAdminHTTP, defaultOrgAdmin } from './org-admin.mjs';
|
||||
import { consoleRestartHTTP } from './console-restart-http.mjs';
|
||||
import { workspaceHTTP } from './workspace-read.mjs';
|
||||
@@ -80,14 +81,11 @@ const files = new Map([
|
||||
['/editor.css', ['editor.css', 'text/css; charset=utf-8']],
|
||||
['/icons.svg', ['icons.svg', 'image/svg+xml']],
|
||||
['/project-remote.css', ['project-remote.css', 'text/css; charset=utf-8']],
|
||||
// Phase P2 (#1873): the owner's System types control (dashboard section and project selection).
|
||||
['/autonomy.js', ['autonomy.js', 'text/javascript; charset=utf-8']],
|
||||
['/autonomy.css', ['autonomy.css', 'text/css; charset=utf-8']],
|
||||
['/packs.js', ['packs.js', 'text/javascript; charset=utf-8']],
|
||||
['/workflows.js', ['workflows.js', 'text/javascript; charset=utf-8']],
|
||||
['/packs.css', ['packs.css', 'text/css; charset=utf-8']],
|
||||
['/system-types.js', ['system-types.js', 'text/javascript; charset=utf-8']],
|
||||
['/system-types.css', ['system-types.css', 'text/css; charset=utf-8']],
|
||||
...[400, 500, 600, 700].map(w => [`/assets/fonts/manrope-${w}.woff2`, [`assets/fonts/manrope-${w}.woff2`, 'font/woff2']]),
|
||||
...[400, 500, 700].map(w => [`/assets/fonts/jetbrains-mono-${w}.woff2`, [`assets/fonts/jetbrains-mono-${w}.woff2`, 'font/woff2']]),
|
||||
]);
|
||||
@@ -179,7 +177,12 @@ async function busRead(res, bus, verb, search) {
|
||||
try {
|
||||
const value = await bus.instances();
|
||||
if (!/^[a-f0-9]{64}$/.test(value?.revision ?? '') || !value.instances || typeof value.instances !== 'object' || !value.definitions || typeof value.definitions !== 'object') throw new BusReadError('invalid-response');
|
||||
return json(res, 200, { rows: [value], at: new Date().toISOString() });
|
||||
// #1873 CB5: a copy's binding status reaches the page as the fixed table's { status, next }
|
||||
// for its code, never as text the bus sent; an unknown code reads credential-unavailable.
|
||||
const copies = value.copies && typeof value.copies === 'object' && !Array.isArray(value.copies)
|
||||
? Object.fromEntries(Object.entries(value.copies).map(([n, c]) => [n, c && typeof c === 'object' && 'binding' in c ? { ...c, binding: copyBindingStatus(c.binding?.status) } : c]))
|
||||
: value.copies;
|
||||
return json(res, 200, { rows: [copies === undefined ? value : { ...value, copies }], at: new Date().toISOString() });
|
||||
} catch (err) {
|
||||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||||
return json(res, busStatus(code), { error: code, message: code });
|
||||
@@ -526,10 +529,10 @@ const AGENT_ROUTES = {
|
||||
// F3: the writes the owner makes on a selected organization's bus from Settings (dev org Console).
|
||||
const ORG_OWNER_WRITE = path => AUTONOMY_ROUTE.test(path) || path === '/api/settings' || path === '/api/instances' || path === '/api/routes'
|
||||
|| Object.hasOwn(SEAT_ROUTES, path) || Object.hasOwn(AGENT_ROUTES, path) || path.startsWith('/api/proxy/')
|
||||
// Phase P2 (#1873): the System types enable switch and a project's selection; the route keeps its own checks.
|
||||
|| SYSTEM_TYPES_ROUTE.test(path)
|
||||
// Starter packs SP4 (#1873): pack apply, board and workflow writes; the route keeps its own checks.
|
||||
|| PACKS_ROUTE.test(path);
|
||||
|| PACKS_ROUTE.test(path)
|
||||
// Starter packs SP8 (#1873): saving a template; the route keeps its own checks.
|
||||
|| TEMPLATES_ROUTE.test(path);
|
||||
async function agentSend(req, res, { route, agentWrite, preview, log, note = null }) {
|
||||
let target = null;
|
||||
// The instance or name is quoted and cut short so a crafted value can't forge a log line. A reason is never logged.
|
||||
@@ -802,7 +805,7 @@ async function libraryStatusRead(res, read, search) {
|
||||
// `log` takes one line per send attempt that got past sign-in; never the body. `fieldsFile` is for
|
||||
// tests; the field table is otherwise the committed packages/tasks/fields.json.
|
||||
// `agentWrite` (row 194, D7) is `(verb, args) => Promise` for the Agents section's verbs and instance.request.
|
||||
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, systemTypesWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
|
||||
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
|
||||
// org-lan-bind: the dev owner on the LAN is an explicit opt-in. `devAllowHosts` names the Host
|
||||
// names (without a port) a remote browser may use; only the dev owner takes them, and only with
|
||||
// them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback.
|
||||
@@ -828,8 +831,6 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
// #797 / #1839 Task 3: the request intake reads need --sso, the writes also --send; never the tester.
|
||||
if ((requestRead !== null || requestWrite !== null) && (tester || sso === null || (requestRead !== null && typeof requestRead !== 'function') || (requestWrite !== null && (send === null || typeof requestWrite !== 'function'))))
|
||||
throw new Error('Console requests need --sso (and --send for the writes) on the main listener');
|
||||
// Phase P2 (#1873): the owner's System types writes need --sso and --send, never the tester.
|
||||
if (systemTypesWrite !== null && (tester || sso === null || send === null || typeof systemTypesWrite !== 'function')) throw new Error('System types writes need --sso and --send on the main listener');
|
||||
const confirmations = createConfirmations();
|
||||
const registered = routeTable();
|
||||
for (const registerRoutes of routes) registerRoutes(registered);
|
||||
@@ -852,7 +853,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
// `userOptions` (FED R6, #1800) is `session => options`, the bus-backed options over that session
|
||||
// user's own transport (console-bus.mjs). Only a signed-in listener has user sessions.
|
||||
if (userOptions !== null && (sso === null || typeof userOptions !== 'function')) throw new Error('user sessions need --sso');
|
||||
const owner = { bus, reads, send, settingsWrite, projectFiles, projectFile, projectSave, libraryStatus, libraryRevert, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, processing, decisionWrite, requestRead, requestWrite, systemTypesWrite, upstream, files };
|
||||
const owner = { bus, reads, send, settingsWrite, projectFiles, projectFile, projectSave, libraryStatus, libraryRevert, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, processing, decisionWrite, requestRead, requestWrite, upstream, files };
|
||||
const hub = federationView(federation);
|
||||
// An object with none of the three is refused too: asking for the preview never serves without it.
|
||||
if (preview !== null && !(preview = previewOptions({ publicHost: preview.host, authHeader: preview.header, allowUser: preview.user }))) {
|
||||
@@ -866,7 +867,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
let boundAddress = null, boundPort = null;
|
||||
const server = createServer(async (req, res) => {
|
||||
// A granted user's request rebinds these below; every other request keeps the owner's.
|
||||
let { bus, reads, send, settingsWrite, projectFiles, projectFile, projectSave, libraryStatus, libraryRevert, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, processing, decisionWrite, requestRead, requestWrite, systemTypesWrite, upstream, files } = owner, granted = false, chatGrants = [], autonomyWrite = null, packsWrite = null, workflowsRead = null;
|
||||
let { bus, reads, send, settingsWrite, projectFiles, projectFile, projectSave, libraryStatus, libraryRevert, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, processing, decisionWrite, requestRead, requestWrite, upstream, files } = owner, granted = false, chatGrants = [], autonomyWrite = null, packsWrite = null, workflowsRead = null, templatesWrite = null;
|
||||
res.setHeader('x-content-type-options', 'nosniff');
|
||||
res.setHeader('referrer-policy', 'no-referrer');
|
||||
// Under --sso the Sign out form's POST is redirected to the provider's end-session endpoint, and
|
||||
@@ -936,9 +937,9 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
// alone stays open on a loopback Host for the status and release gates (Q-C).
|
||||
if (sso !== null && !named && !(path === '/healthz' && req.method === 'GET')) return json(res, 403, { error: 'public Host required' });
|
||||
// No CORS. JSON content type and same-origin checks keep browser forms out.
|
||||
const decisionPath = DECISION_ROUTE.test(path), requestPath = REQUEST_ROUTE.test(path), remotePath = PROJECT_REMOTE_ROUTE.test(path), systemTypesPath = SYSTEM_TYPES_ROUTE.test(path), autonomyPath = AUTONOMY_ROUTE.test(path),
|
||||
const decisionPath = DECISION_ROUTE.test(path), requestPath = REQUEST_ROUTE.test(path), remotePath = PROJECT_REMOTE_ROUTE.test(path), autonomyPath = AUTONOMY_ROUTE.test(path),
|
||||
// GET and HEAD /api/board stay the Board read; every other method on it is the pack route's (POST writes, the rest 405).
|
||||
packsPath = packsServes(path, req.method);
|
||||
packsPath = packsServes(path, req.method), templatesPath = TEMPLATES_ROUTE.test(path);
|
||||
if (req.headers.origin && req.headers.origin !== (named ? (sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`) : `http://${req.headers.host}`))
|
||||
return decisionPath ? decisionRefuse(res, 'cross-origin') : requestPath ? requestRefuse(res, 'cross-origin') : json(res, 403, { error: 'cross-origin request refused' });
|
||||
let signer = preview, ssoSession = null;
|
||||
@@ -950,7 +951,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
if (!session && path !== '/healthz') {
|
||||
if (decisionPath) return decisionRefuse(res, 'sign-in-required');
|
||||
if (requestPath) return requestRefuse(res, 'sign-in-required');
|
||||
if (remotePath || systemTypesPath || autonomyPath || packsPath) return json(res, 401, { error: 'sign-in-required' });
|
||||
if (remotePath || autonomyPath || packsPath || templatesPath) return json(res, 401, { error: 'sign-in-required' });
|
||||
if (path.startsWith('/api/') || req.method !== 'GET') return json(res, 401, { error: 'sign-in required' });
|
||||
res.writeHead(303, { location: `/auth/login?return=${encodeURIComponent(path + search)}`, 'cache-control': 'no-store' });
|
||||
return res.end();
|
||||
@@ -963,7 +964,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
const instanceAction = originalPath === '/api/console/restart';
|
||||
if (session && !session.rootOwner && session.user === undefined && orgId === null && !orgList && !hook?.publicRead && !instanceAction && path !== '/api/config' && path !== '/healthz' && !files.has(path)) return json(res, 404, { error: 'not-found' });
|
||||
if (session && !session.rootOwner && session.user === undefined) {
|
||||
bus = reads = send = settingsWrite = projectFiles = projectFile = projectSave = libraryStatus = libraryRevert = chat = nameWrite = assistantStop = instancesWrite = routesWrite = agentWrite = proxyCall = processing = decisionWrite = requestRead = requestWrite = systemTypesWrite = autonomyWrite = packsWrite = workflowsRead = upstream = null;
|
||||
bus = reads = send = settingsWrite = projectFiles = projectFile = projectSave = libraryStatus = libraryRevert = chat = nameWrite = assistantStop = instancesWrite = routesWrite = agentWrite = proxyCall = processing = decisionWrite = requestRead = requestWrite = autonomyWrite = packsWrite = workflowsRead = templatesWrite = upstream = null;
|
||||
}
|
||||
if (session?.user !== undefined && !session.rootOwner && !instanceAction) {
|
||||
// #1873: proxy setup answers a grant holder the way the bus answers an agent.
|
||||
@@ -971,7 +972,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
if (!organizations && !userRoute(path, req.method)) return json(res, 403, { error: 'owner-only', message: 'this part of the Console is the business owner\'s' });
|
||||
if (!organizations && userOptions === null) return json(res, 503, { error: 'not-configured', message: 'the Console has no user transport' });
|
||||
if (!organizations) ({ bus, send, settingsWrite, projectFiles, projectFile, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, processing } = userOptions(session));
|
||||
reads = null; upstream = null; libraryStatus = null; libraryRevert = null; files = USER_FILES; granted = true; proxyCall = null; systemTypesWrite = null; packsWrite = null; workflowsRead = null;
|
||||
reads = null; upstream = null; libraryStatus = null; libraryRevert = null; files = USER_FILES; granted = true; proxyCall = null; packsWrite = null; workflowsRead = null; templatesWrite = null;
|
||||
chatGrants = sso.chatGrants?.(session) ?? [];
|
||||
}
|
||||
}
|
||||
@@ -1002,7 +1003,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
({ bus = null, reads = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null,
|
||||
projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null,
|
||||
assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null,
|
||||
processing = null, decisionWrite = null, requestRead = null, requestWrite = null, systemTypesWrite = null, autonomyWrite = null, packsWrite = null, workflowsRead = null, upstream = null } = selected);
|
||||
processing = null, decisionWrite = null, requestRead = null, requestWrite = null, autonomyWrite = null, packsWrite = null, workflowsRead = null, templatesWrite = null, upstream = null } = selected);
|
||||
}
|
||||
// F3: the owner's settings writes reach the selected organization's bus too (limits, routing,
|
||||
// agents, assistant, instances, model proxy). The routes below keep their own checks.
|
||||
@@ -1065,7 +1066,6 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
return projectRemoteHTTP(req, res, { path, read: requestRead, write: send ? requestWrite : null,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso.publicOrigin });
|
||||
}
|
||||
// Phase P2 (#1873): the owner's System types read and writes on the selected organization.
|
||||
if(autonomyPath) {
|
||||
if(tester || granted || !named || sso===null)return json(res,403,{error:'owner-only'});
|
||||
// D1 (#1873): an organization's own autonomy writer (`autonomyWrite`, the four autonomy verbs only);
|
||||
@@ -1073,18 +1073,19 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
return autonomyHTTP(req,res,{path,read:requestRead,write:send?(autonomyWrite??requestWrite):null,session:ssoSession,
|
||||
live:()=>{const live=sso.session(req);return live?.rootOwner===true?live:null;},origin:localOrigin??sso.publicOrigin});
|
||||
}
|
||||
if (systemTypesPath) {
|
||||
if (tester || granted || !named || sso === null) return json(res, 403, { error: 'owner-only' });
|
||||
return systemTypesHTTP(req, res, { path, read: requestRead, write: send ? systemTypesWrite : null,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso.publicOrigin });
|
||||
}
|
||||
// Starter packs SP4 (#1873): the owner's pack, board and workflow routes on the selected organization.
|
||||
if (packsPath) {
|
||||
const owner = !(tester || granted || !named || sso === null);
|
||||
return packsHTTP(req, res, { path, owner, read: requestRead, write: send ? packsWrite : null, workflows: workflowsRead,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso?.publicOrigin });
|
||||
}
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/system-types.js', '/system-types.css', '/packs.js', '/packs.css', '/workflows.js'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
// Starter packs SP8 (#1873): the owner saves the selected organization's shape as a template and lists theirs.
|
||||
if (templatesPath) {
|
||||
const owner = !(tester || granted || !named || sso === null);
|
||||
return templatesHTTP(req, res, { path, owner, read: requestRead, write: send ? templatesWrite : null,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso?.publicOrigin });
|
||||
}
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/packs.js', '/packs.css', '/workflows.js'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
// Row 194 (#1692, D4.1): the tester also launches and terminates.
|
||||
if (tester && !['GET', 'HEAD'].includes(req.method) && !['/api/instances', '/api/routes', '/api/name', '/api/agent/launch', '/api/agent/terminate'].includes(path) && !TESTER_CHAT_WRITE.test(path))
|
||||
return json(res, 403, { error: 'read-only', sent: false });
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
// Phase P2 (#1873): the owner's System types routes on a selected organization. Owner Console
|
||||
// transports only; no caller-supplied business, actor or subject reaches the bus.
|
||||
//
|
||||
// GET /api/system-types installed modules (label, description) and the enabled set,
|
||||
// plus the plugin revision when writes are on
|
||||
// POST /api/system-types {revision, enabled}: plugins.set {'system-type': enabled},
|
||||
// the organization writer's owner fence, revision and receipt
|
||||
// GET /api/system-types/projects/<id> the same, with the project's selection, active and inactive
|
||||
// POST /api/system-types/projects/<id> {systemTypes}: project.system-types.set
|
||||
//
|
||||
// `read` is the owner's Console call (consoleCall): it reaches only `system-types.console`, which the
|
||||
// broker answers to the business human's console cap. `write` is the owner's human transport limited
|
||||
// to SYSTEM_TYPE_VERBS, present only for the owner's own session under --send.
|
||||
export const SYSTEM_TYPES_ROUTE = /^\/api\/system-types(?:\/projects\/([^/]+))?$/;
|
||||
export const SYSTEM_TYPE_VERBS = Object.freeze(['plugins', 'plugins.set', 'project.system-types.set']);
|
||||
const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
|
||||
// A module name, as plugins/src/kinds.mjs NAME.
|
||||
const NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
||||
const REVISION = /^[a-f0-9]{64}$/;
|
||||
const TRANSACTION = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
const MAX_TYPES = 64;
|
||||
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
|
||||
const codes = {
|
||||
'invalid-request': 400, 'invalid-plugins': 400, 'unknown-plugin': 400, 'system-type-unknown': 400,
|
||||
'project-not-found': 404, 'revision-conflict': 409, 'organization-busy': 409, 'system-type-not-enabled': 409,
|
||||
'human-required': 403, 'organization-system-types-human-only': 403, 'read-only': 403,
|
||||
'not-configured': 503, 'system-type-invalid': 503, 'no-bus-host': 503,
|
||||
};
|
||||
function json(res, status, value) {
|
||||
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||
res.end(JSON.stringify(value));
|
||||
}
|
||||
const names = list => Array.isArray(list) && list.length <= MAX_TYPES && list.every(x => typeof x === 'string' && NAME.test(x)) && new Set(list).size === list.length;
|
||||
const text = value => typeof value === 'string' && value.trim() !== '' && value.length <= 400 && !/[\r\n]/.test(value);
|
||||
function consoleShape(result, project) {
|
||||
if (!result || !Array.isArray(result.installed) || !names(result.enabled)) return null;
|
||||
const installed = [];
|
||||
for (const m of result.installed) {
|
||||
if (!m || !NAME.test(m.id ?? '') || !text(m.label) || !text(m.description)) return null;
|
||||
installed.push({ id: m.id, label: m.label, description: m.description });
|
||||
}
|
||||
if (new Set(installed.map(m => m.id)).size !== installed.length) return null;
|
||||
let selection = null;
|
||||
if (project !== null) {
|
||||
const p = result.project;
|
||||
if (!p || p.project !== project || !names(p.selected) || !names(p.active) || !names(p.inactive)) return null;
|
||||
selection = { project, selected: p.selected, active: p.active, inactive: p.inactive };
|
||||
} else if (result.project !== null) return null;
|
||||
return { installed, enabled: result.enabled, project: selection };
|
||||
}
|
||||
const selectionShape = (r, project) => r && r.project === project && names(r.selected) && names(r.active) && names(r.inactive)
|
||||
? { project, selected: r.selected, active: r.active, inactive: r.inactive } : null;
|
||||
|
||||
async function body(req, keys) {
|
||||
if (one(req, 'content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') return null;
|
||||
const chunks = []; let size = 0;
|
||||
for await (const chunk of req) { size += chunk.length; if (size > 4096) return 'too-large'; chunks.push(chunk); }
|
||||
let value;
|
||||
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== keys.length || !keys.every(k => Object.hasOwn(value, k))) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function systemTypesHTTP(req, res, { path, read, write, session, live, origin }) {
|
||||
const refuse = (status, error) => json(res, status, { error });
|
||||
const fail = error => { const code = codes[error?.code] ? error.code : 'outcome-unknown'; return refuse(codes[code] ?? 503, code); };
|
||||
if (!['GET', 'POST'].includes(req.method)) return refuse(405, 'method-not-allowed');
|
||||
if (!session) return refuse(401, 'sign-in-required');
|
||||
if (!read) return refuse(503, 'not-configured');
|
||||
if (req.method === 'POST' && !write) return refuse(403, 'read-only');
|
||||
const site = one(req, 'sec-fetch-site'), from = one(req, 'origin');
|
||||
if (req.method === 'POST' ? from !== origin || site !== 'same-origin'
|
||||
: (req.headersDistinct.origin && from !== origin) || (req.headersDistinct['sec-fetch-site'] && !['same-origin', 'none'].includes(site)))
|
||||
return refuse(403, 'cross-origin');
|
||||
let project = null;
|
||||
const match = SYSTEM_TYPES_ROUTE.exec(path);
|
||||
if (match?.[1] !== undefined) {
|
||||
try { project = decodeURIComponent(match[1]); } catch { return refuse(404, 'project-not-found'); }
|
||||
if (!ID.test(project)) return refuse(404, 'project-not-found');
|
||||
}
|
||||
let args = null;
|
||||
if (req.method === 'POST') {
|
||||
const value = await body(req, project === null ? ['revision', 'enabled'] : ['systemTypes']);
|
||||
if (value === 'too-large') return refuse(413, 'invalid-request');
|
||||
if (!value) return refuse(400, 'invalid-request');
|
||||
if (project === null ? typeof value.revision !== 'string' || !REVISION.test(value.revision) || !names(value.enabled) : !names(value.systemTypes))
|
||||
return refuse(400, 'invalid-request');
|
||||
args = value;
|
||||
}
|
||||
if (live() !== session) return refuse(401, 'sign-in-required');
|
||||
const subject = { provider: session.provider, iss: session.iss, sub: session.sub };
|
||||
// The read comes first on every request: a write names only modules this organization has installed.
|
||||
let current;
|
||||
try { current = consoleShape(await read('system-types.console', project === null ? {} : { project }, { subject }), project); }
|
||||
catch (error) { return fail(error); }
|
||||
if (!current) return refuse(503, 'outcome-unknown');
|
||||
const installed = new Set(current.installed.map(m => m.id));
|
||||
|
||||
if (req.method === 'GET') {
|
||||
let revision = null;
|
||||
if (write && project === null) {
|
||||
// The enabled set and its revision come from one plugins read. The page sends back a whole
|
||||
// replacement list, so a list older than its revision would undo a change made in between.
|
||||
let plugins;
|
||||
try { plugins = await write('plugins', {}); } catch (error) { return fail(error); }
|
||||
revision = plugins?.revision ?? null;
|
||||
const enabled = plugins?.plugins?.['system-type'] ?? [];
|
||||
if (!REVISION.test(revision ?? '') || !names(enabled)) return refuse(503, 'outcome-unknown');
|
||||
current.enabled = enabled;
|
||||
}
|
||||
if (live() !== session) return refuse(401, 'sign-in-required');
|
||||
return json(res, 200, { ...current, writable: Boolean(write), ...(project === null && write ? { revision } : {}) });
|
||||
}
|
||||
|
||||
// The session is checked again after the read: a sign-out while it ran dispatches no write.
|
||||
if (live() !== session) return refuse(401, 'sign-in-required');
|
||||
|
||||
if (project === null) {
|
||||
if (args.enabled.some(id => !installed.has(id))) return refuse(400, 'system-type-unknown');
|
||||
let result;
|
||||
try { result = await write('plugins.set', { revision: args.revision, plugins: { 'system-type': args.enabled } }); }
|
||||
catch (error) { return fail(error); }
|
||||
// A write admitted at spawn may already have committed: its receipt is returned even if the
|
||||
// session ended meanwhile, never reported as not done.
|
||||
const enabled = result?.plugins?.['system-type'] ?? [];
|
||||
if (!result || !REVISION.test(result.revision ?? '') || !TRANSACTION.test(result.transaction ?? '') || !names(enabled)
|
||||
|| JSON.stringify(enabled) !== JSON.stringify(args.enabled))
|
||||
return refuse(503, 'outcome-unknown');
|
||||
return json(res, 200, { enabled, revision: result.revision, transaction: result.transaction });
|
||||
}
|
||||
|
||||
// The broker refuses a type the organization has not enabled (system-type-not-enabled); a type that
|
||||
// is not installed is refused here first.
|
||||
if (args.systemTypes.some(id => !installed.has(id))) return refuse(400, 'system-type-unknown');
|
||||
let result;
|
||||
try { result = selectionShape(await write('project.system-types.set', { project, systemTypes: args.systemTypes }), project); }
|
||||
catch (error) { return fail(error); }
|
||||
if (!result || JSON.stringify(result.selected) !== JSON.stringify(args.systemTypes)) return refuse(503, 'outcome-unknown');
|
||||
return json(res, 200, result);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Starter packs SP8 (#1873, design section 5): the owner saves the selected organization's shape as a
|
||||
// template under their own account, and lists the templates they saved. Owner Console transports only;
|
||||
// no caller-supplied business, account, subject or origin reaches the bus.
|
||||
//
|
||||
// serve.mjs strips /api/orgs/<id> before the route is matched, so the paths below reach this module as
|
||||
// /api/templates and /api/templates/preview.
|
||||
//
|
||||
// GET /api/orgs/<id>/templates {templates, writable}: template.list.console, the owner's saved templates
|
||||
// POST /api/orgs/<id>/templates/preview {name, project?}: template.save.console with preview true. Writes nothing;
|
||||
// answers the template JSON, every free-text field and the digest
|
||||
// POST /api/orgs/<id>/templates {name, digest, project?}: template.save.console with the preview's digest
|
||||
//
|
||||
// `read` is the owner's Console call (consoleCall), used for the list and the preview, which write nothing.
|
||||
// `write` is the owner's Console call fenced to template.save.console (templatesCaller), present only for
|
||||
// the owner's own session under --send. The broker answers both .console verbs to the business human's
|
||||
// console cap alone and runs the capture, the held-credential scan and the digest check itself.
|
||||
export const TEMPLATES_ROUTE = /^\/api\/templates(?:\/(preview))?$/;
|
||||
export const TEMPLATE_WRITE_VERBS = Object.freeze(['template.save.console']);
|
||||
export const templatesCaller = call => async (verb, args, options) => {
|
||||
if (!TEMPLATE_WRITE_VERBS.includes(verb)) throw new Error(`the template writer does not call ${verb}`);
|
||||
if (args?.preview !== undefined) throw new Error('the template writer does not preview');
|
||||
return call(verb, args, options);
|
||||
};
|
||||
// A template or project name: the bus's own rule (template-save.mjs checkTemplateName, vocabulary KIND_NAME).
|
||||
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const DIGEST = /^[a-f0-9]{64}$/;
|
||||
const LIMIT = 4096;
|
||||
const codes = {
|
||||
'invalid-request': 400, 'template-secret-suspected': 400, 'starter-pack-invalid': 400,
|
||||
'project-not-found': 404,
|
||||
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409,
|
||||
'human-required': 403, 'read-only': 403,
|
||||
'not-configured': 503, 'no-bus-host': 503,
|
||||
};
|
||||
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
|
||||
function json(res, status, value) {
|
||||
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||
res.end(JSON.stringify(value));
|
||||
}
|
||||
const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
// The body names exactly the required keys and any of the optional ones; nothing else reaches the bus.
|
||||
async function body(req, required, optional) {
|
||||
if (one(req, 'content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') return null;
|
||||
const chunks = []; let size = 0;
|
||||
for await (const chunk of req) { size += chunk.length; if (size > LIMIT) return 'too-large'; chunks.push(chunk); }
|
||||
let value;
|
||||
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
|
||||
if (!plain(value) || !required.every(k => Object.hasOwn(value, k)) || Object.keys(value).some(k => !required.includes(k) && !optional.includes(k))) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function templatesHTTP(req, res, { path, owner, read, write, session, live, origin }) {
|
||||
const refuse = (status, error) => json(res, status, { error });
|
||||
const fail = error => { const code = codes[error?.code] ? error.code : 'outcome-unknown'; return refuse(codes[code] ?? 503, code); };
|
||||
const match = TEMPLATES_ROUTE.exec(path);
|
||||
if (!match) return refuse(404, 'not-found');
|
||||
const preview = match[1] === 'preview';
|
||||
const list = !preview && req.method === 'GET';
|
||||
const allowed = preview ? ['POST'] : ['GET', 'POST'];
|
||||
if (!allowed.includes(req.method)) return refuse(405, 'method-not-allowed');
|
||||
// A method the route never serves answers 405 first; every served method is the root owner's.
|
||||
if (!owner) return refuse(403, 'owner-only');
|
||||
if (!session) return refuse(401, 'sign-in-required');
|
||||
if (!read) return refuse(503, 'not-configured');
|
||||
const writes = !list && !preview;
|
||||
if (writes && !write) return refuse(403, 'read-only');
|
||||
const site = one(req, 'sec-fetch-site'), from = one(req, 'origin');
|
||||
if (req.method !== 'GET' ? from !== origin || site !== 'same-origin'
|
||||
: (req.headersDistinct.origin && from !== origin) || (req.headersDistinct['sec-fetch-site'] && !['same-origin', 'none'].includes(site)))
|
||||
return refuse(403, 'cross-origin');
|
||||
|
||||
let verb, args = {};
|
||||
if (list) verb = 'template.list.console';
|
||||
else {
|
||||
const value = await body(req, preview ? ['name'] : ['name', 'digest'], ['project']);
|
||||
if (value === 'too-large') return refuse(413, 'invalid-request');
|
||||
if (!value || typeof value.name !== 'string' || !NAME.test(value.name)
|
||||
|| (!preview && (typeof value.digest !== 'string' || !DIGEST.test(value.digest)))
|
||||
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project))))
|
||||
return refuse(400, 'invalid-request');
|
||||
verb = 'template.save.console';
|
||||
args = preview ? { ...value, preview: true } : value;
|
||||
}
|
||||
|
||||
// The session is checked again after the body is read: a sign-out meanwhile dispatches nothing.
|
||||
if (live() !== session) return refuse(401, 'sign-in-required');
|
||||
const subject = { provider: session.provider, iss: session.iss, sub: session.sub };
|
||||
let result;
|
||||
try { result = writes ? await write(verb, args, { subject }) : await read(verb, args, { subject }); }
|
||||
catch (error) { return fail(error); }
|
||||
if (!plain(result)) return refuse(503, 'outcome-unknown');
|
||||
if (list) {
|
||||
if (!Array.isArray(result.templates)) return refuse(503, 'outcome-unknown');
|
||||
return json(res, 200, { templates: result.templates, writable: Boolean(write) });
|
||||
}
|
||||
if (!DIGEST.test(result.digest ?? '')) return refuse(503, 'outcome-unknown');
|
||||
if (preview) return json(res, 200, result);
|
||||
// A save admitted may already have written its file: the receipt is returned even if the session
|
||||
// ended meanwhile, never reported as not done.
|
||||
return json(res, 200, { name: result.name, scope: result.scope, digest: result.digest });
|
||||
}
|
||||
@@ -16,7 +16,6 @@ for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','d
|
||||
if(verb==='autonomy.set.console'){assert.equal(args.revision,revision);writes++;setting=args.autonomy;revision='b'.repeat(64);return {revision,transaction:'10000000-0000-4000-8000-000000000001'};}
|
||||
if(verb==='decision.confirm.console'){if(args.confirm)confirms++;else{declines++;assert.equal(args.reason,'Revise the plan');}return {op:args.confirm?'confirmed':'declined'};}
|
||||
if(verb==='decision.reverse.console'){reverses++;return {reversed:true};}
|
||||
if(verb==='system-types.console')return {installed:[],enabled:[],project:null};
|
||||
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
|
||||
};
|
||||
const ids=['10000000-0000-4000-8000-000000000001','10000000-0000-4000-8000-000000000002','10000000-0000-4000-8000-000000000003'];
|
||||
|
||||
@@ -19,10 +19,13 @@ process.once('exit', () => { for (const child of live) killGroup(child); });
|
||||
// so by default every page this browser opens starts with Show machine sessions on, as if the
|
||||
// person had turned it on before. Pass { machine: false } to see the page as a first visit does.
|
||||
// `args` adds Chromium flags, for example --host-resolver-rules for a test host name.
|
||||
// #1873 CB5: the system Chromium starts with --disable-extensions, so no host extension (and no
|
||||
// native host it would start) runs in a test. A CHROMIUM launcher is the zoom tests' wrapper, which
|
||||
// loads their one extension with --disable-extensions-except, so it gets no blanket flag.
|
||||
export async function browser({ machine = true, args = [] } = {}) {
|
||||
const profile = await mkdtemp(join(tmpdir(), 'dewey-brand-browser-'));
|
||||
const child = spawn(process.env.CHROMIUM || '/usr/bin/chromium', [
|
||||
'--headless', '--no-first-run', '--no-default-browser-check',
|
||||
'--headless', '--no-first-run', '--no-default-browser-check', ...(process.env.CHROMIUM ? [] : ['--disable-extensions']),
|
||||
'--disable-dev-shm-usage', '--remote-debugging-pipe', `--user-data-dir=${profile}`, ...args,
|
||||
], { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
|
||||
live.add(child);
|
||||
|
||||
@@ -18,8 +18,8 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t
|
||||
assert.equal(await b.evaluate('document.querySelector("#session-count").textContent'), '3 of 4');
|
||||
await b.evaluate('document.querySelector("#hide-offline").click()');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("table.sessions tbody tr").length'), 4);
|
||||
// Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. U5 (#1873) adds panes.js (Side by side) just before bus.js, which mounts it. P2 (#1873) adds system-types.js after project-remote.js.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/system-types.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/panes.js', '/bus.js', '/requests.js']);
|
||||
// Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. U5 (#1873) adds panes.js (Side by side) just before bus.js, which mounts it.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/panes.js', '/bus.js', '/requests.js']);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/processing.js"]').length`), 1);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/chat.js"]').length`), 1);
|
||||
assert.equal(await b.evaluate('!!window.injected'), false);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { BusReadError } from '../src/bus.mjs';
|
||||
import { DECISION_REFUSALS, createConfirmations, decisionHTTP } from '../src/decision-http.mjs';
|
||||
import { BINDING_NEXT, DECISION_REFUSALS, createConfirmations, decisionHTTP } from '../src/decision-http.mjs';
|
||||
|
||||
const ORIGIN = 'https://console.test';
|
||||
const DIGEST = 'a'.repeat(64);
|
||||
@@ -353,3 +353,60 @@ test('D4 templates, confirmation and resolve keep their open mapping for a defin
|
||||
const ok=await s.confirm('yes');assert.equal(ok.status,200);
|
||||
refused(await s.resolve({choice:'yes',confirmation:ok.json().confirmation}),'outcome-unknown');
|
||||
});
|
||||
|
||||
// #1873 CB5: a copy credential binding decision on the Console. The confirmation carries the bus's
|
||||
// computed scope lines, the copy's name and whether it binds or unbinds, and nothing else of the
|
||||
// binding; the approved answer carries the owner's fixed next step. The sentinel stands for a token
|
||||
// the bus should never send: placed in every binding field the bus could add, it never reaches a
|
||||
// response or a log line.
|
||||
const SENTINEL='sentinel-0123456789abcdef0123456789abcdef01234567';
|
||||
const bindingPreview=(after)=>({id:'d1',business:'demo',kind:'hire',question:'bind credentials for copy researcher?',digest:DIGEST,
|
||||
options:[{key:'yes',text:'Approve'},{key:'no',text:'Deny'}],flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z',
|
||||
binding:{instance:'researcher',source:{level:'root',name:SENTINEL,project:null},copyId:SENTINEL,fresh:true,orgIncarnation:SENTINEL,definition:{ref:SENTINEL,sha256:SENTINEL},
|
||||
before:{gitea:{slot:SENTINEL,grantId:SENTINEL,scopes:['read:repository'],resources:{projects:['stack']}}},after,generation:0}});
|
||||
const leaks=(s,...texts)=>texts.filter(t=>t.includes(SENTINEL)||t.includes(SENTINEL.slice(0,16))).length;
|
||||
test('CB5 binding confirmation names the copy and the change with the computed scope lines, and the approval names the next step; nothing else of the binding leaves',async()=>{
|
||||
const after={gitea:{slot:'self',scopes:['read:repository'],resources:{projects:['stack']},token:SENTINEL}};
|
||||
const s=setup({answer:()=>bindingPreview(after),resolve:a=>({id:a.id,op:'resolved',choice:a.choice,transaction:SENTINEL,binding:{token:SENTINEL}})});
|
||||
const c=await s.confirm('yes');assert.equal(c.status,200,c.text);
|
||||
const body=c.json();
|
||||
assert.deepEqual({...body,confirmation:'x'},{id:'d1',question:'bind credentials for copy researcher?',action:'answer',choice:'yes',text:'Approve',kind:'hire',
|
||||
flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z',binding:{instance:'researcher',change:'bind'},confirmation:'x'});
|
||||
const r=await s.resolve({choice:'yes',confirmation:body.confirmation});assert.equal(r.status,200,r.text);
|
||||
assert.deepEqual(r.json(),{id:'d1',op:'resolved',choice:'yes',next:BINDING_NEXT.bind});
|
||||
assert.equal(s.calls[1].verb,'hire.resolve.console');
|
||||
assert.equal(leaks(s,c.text,r.text,...s.lines),0);
|
||||
assert.match(s.lines[0],/ step=confirmation action=answer$/);assert.match(s.lines[1],/ step=resolve choice="yes"$/);
|
||||
});
|
||||
test('CB5 an unbind says the bus revokes; a denial carries no next step; a malformed binding is not echoed',async()=>{
|
||||
const u=setup({answer:()=>bindingPreview(null),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})});
|
||||
const uc=await u.confirm('yes');assert.deepEqual(uc.json().binding,{instance:'researcher',change:'unbind'});
|
||||
const ur=await u.resolve({choice:'yes',confirmation:uc.json().confirmation});
|
||||
assert.deepEqual(ur.json(),{id:'d1',op:'resolved',choice:'yes',next:BINDING_NEXT.unbind});
|
||||
const d=setup({answer:()=>bindingPreview(null),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})});
|
||||
const dc=await d.confirm('no');
|
||||
assert.deepEqual((await d.resolve({choice:'no',confirmation:dc.json().confirmation})).json(),{id:'d1',op:'resolved',choice:'no'});
|
||||
// An instance name the subject check refuses, or an after that is neither null nor an object, sends
|
||||
// no binding field (the copy name is the only binding value the page shows).
|
||||
for(const bad of [{instance:'../'+SENTINEL,after:null},{instance:'researcher',after:[SENTINEL]},{instance:'researcher',after:SENTINEL}]){
|
||||
const b=setup({answer:()=>({...bindingPreview(null),binding:{...bindingPreview(null).binding,...bad}}),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})});
|
||||
const bc=await b.confirm('yes');assert.equal(bc.status,200,bc.text);
|
||||
assert.equal(Object.hasOwn(bc.json(),'binding'),false,bc.text);
|
||||
const br=await b.resolve({choice:'yes',confirmation:bc.json().confirmation});
|
||||
assert.equal(Object.hasOwn(br.json(),'next'),false,br.text);
|
||||
assert.equal(leaks(b,bc.text,br.text,...b.lines),0);
|
||||
}
|
||||
assert.equal(leaks(u,uc.text,ur.text,...u.lines,...d.lines),0);
|
||||
});
|
||||
test('CB5 a binding recorded and approved through the Console start names the next step by its shape, and only a binding start does',async()=>{
|
||||
const s=setup({resolve:()=>({id:'b1',op:'resolved',choice:'yes',binding:{token:SENTINEL}})});
|
||||
const bind={op:'change',level:'root',name:'researcher',reason:'token '+SENTINEL,binding:{services:{gitea:{scopes:['read:repository'],projects:['stack']}}}};
|
||||
const r=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:bind}}));
|
||||
assert.equal(r.status,200,r.text);assert.deepEqual(r.json(),{id:'b1',op:'resolved',choice:'yes',next:BINDING_NEXT.bind});
|
||||
const u=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:{...bind,binding:{services:null}}}}));
|
||||
assert.deepEqual(u.json(),{id:'b1',op:'resolved',choice:'yes',next:BINDING_NEXT.unbind});
|
||||
const h=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:START_HIRE}}));
|
||||
assert.deepEqual(h.json(),{id:'b1',op:'resolved',choice:'yes'});
|
||||
assert.equal(leaks(s,r.text,u.text,h.text,...s.lines),0);
|
||||
for(const t of Object.values(BINDING_NEXT))assert.equal(leaks(s,t),0);
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { installedSystemTypes } from '../../../plugins/src/system-types.mjs';
|
||||
|
||||
// Phase P2 (#1873): a per-organization stand-in for the two transports the System types routes use,
|
||||
// shaped as the broker answers them. `requestRead` answers system-types.console with the installed
|
||||
// modules (the plug-in data itself, read from packages/plugins), the enabled set and a project's
|
||||
// selection. `systemTypesWrite` answers plugins, plugins.set (revision checked, a transaction
|
||||
// returned) and project.system-types.set (enabled types only). `owner: false` makes plugins.set
|
||||
// refuse as the organization writer's owner fence does for anyone but the human.
|
||||
export async function systemTypesFake({ enabled = [], projects = {}, owner = true } = {}) {
|
||||
const installed = await installedSystemTypes();
|
||||
const state = { enabled: [...enabled], projects: structuredClone(projects), n: 0, writes: [] };
|
||||
const revision = () => createHash('sha256').update(`system-types-${state.n}`).digest('hex');
|
||||
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
||||
const selection = project => {
|
||||
const selected = state.projects[project];
|
||||
return { project, selected: [...selected], active: selected.filter(x => state.enabled.includes(x)), inactive: selected.filter(x => !state.enabled.includes(x)) };
|
||||
};
|
||||
const requestRead = async (verb, args) => {
|
||||
if (verb !== 'system-types.console') fail('invalid-request');
|
||||
if (args.project !== undefined && !Object.hasOwn(state.projects, args.project)) fail('project-not-found');
|
||||
return { installed: structuredClone(installed), enabled: [...state.enabled], project: args.project === undefined ? null : selection(args.project) };
|
||||
};
|
||||
const systemTypesWrite = async (verb, args) => {
|
||||
state.writes.push(verb);
|
||||
if (verb === 'plugins') return { business: 'fake', revision: revision(), plugins: { 'system-type': [...state.enabled] } };
|
||||
if (verb === 'plugins.set') {
|
||||
if (args.revision !== revision()) fail('revision-conflict');
|
||||
if (!owner) fail('organization-system-types-human-only');
|
||||
state.enabled = [...args.plugins['system-type']]; state.n++;
|
||||
return { business: 'fake', revision: revision(), plugins: { 'system-type': [...state.enabled] }, transaction: randomUUID() };
|
||||
}
|
||||
if (verb === 'project.system-types.set') {
|
||||
if (!Object.hasOwn(state.projects, args.project)) fail('project-not-found');
|
||||
if (args.systemTypes.some(x => !state.enabled.includes(x))) fail('system-type-not-enabled');
|
||||
state.projects[args.project] = [...args.systemTypes];
|
||||
return selection(args.project);
|
||||
}
|
||||
fail('invalid-request');
|
||||
};
|
||||
return { requestRead, systemTypesWrite, state, installed };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {fixture} from './fixture.mjs';
|
||||
import {mkdir} from 'node:fs/promises';
|
||||
import {join} from 'node:path';
|
||||
import {browser} from './browser.mjs';
|
||||
import {BINDING_NEXT} from '../src/decision-http.mjs';
|
||||
for(const width of [1440,390])test(`A4 Console hire start and narrowed confirmation at ${width}px`,{timeout:120000},async t=>{
|
||||
const f=await fixture(),b=await browser({machine:false});t.after(async()=>{await b.close();await f.close();});
|
||||
await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{
|
||||
@@ -48,3 +49,50 @@ for(const width of [1440,390])test(`A4 Console hire start and narrowed confirmat
|
||||
await b.evaluate('document.querySelector("[data-decide=confirm]").click()');await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")');
|
||||
posts=await b.evaluate('window.__posts');assert.deepEqual(Object.keys(posts.find(x=>x.p.endsWith('/resolve')).body).sort(),['choice','confirmation']);
|
||||
});
|
||||
// #1873 CB5: a copy credential binding decision on its decision page. The inbox row carries the bus's
|
||||
// summary, the copy and its change; the page names both and lists the computed scope lines, the
|
||||
// confirmation says the change, and the receipt adds decision-http's fixed next step. Nothing besides
|
||||
// the copy's instance reaches the page: a sentinel in any other field never shows, and an `after`
|
||||
// that contradicts `change` (a bus older than the summary) never decides the line.
|
||||
for(const change of ['bind','unbind'])test(`CB5 Console binding decision: ${change} confirmation and receipt`,{timeout:120000},async t=>{
|
||||
const SENTINEL='cb5-sentinel-7f3a9c41d2e8b6a0';
|
||||
const f=await fixture(),b=await browser({machine:false,args:['--disable-extensions']});t.after(async()=>{await b.close();await f.close();});
|
||||
const after=change==='unbind'?{gitea:{scopes:['read:repository'],projects:['web'],slot:SENTINEL}}:null;
|
||||
const binding={instance:'acme/researcher',change,copyId:SENTINEL,orgIncarnation:SENTINEL,definition:SENTINEL,before:{gitea:{grantId:SENTINEL}},after};
|
||||
const hire={kind:'hire',flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z',binding,options:[{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]};
|
||||
const d={id:'d2',at:'2026-11-12T00:00:00.000Z',raised_by_role:'jason',raised_by_run:null,class:'gated',action:'role.hire',route_to:'human',question:`${change} credentials for copy acme/researcher?`,options:hire.options,blocking:false,console:hire};
|
||||
await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{
|
||||
const real=fetch;window.__posts=[];const d=${JSON.stringify(d)};
|
||||
const json=v=>new Response(JSON.stringify(v),{headers:{'content-type':'application/json'}});
|
||||
window.fetch=async(url,init={})=>{
|
||||
const p=new URL(url,location.href).pathname;
|
||||
if(p==='/api/config')return json({sso:true,send:true,decide:true});
|
||||
if(p==='/api/business')return json({business:{id:'acme',projects:[]}});
|
||||
if(p==='/api/bus/inbox')return json({rows:[d]});
|
||||
if(p==='/api/bus/trail')return json({rows:[{...d,table:'decisions'}]});
|
||||
if(p==='/api/bus/agents'||p==='/api/bus/messages'||p==='/api/chat/projects'||p==='/api/chat/threads')return json({rows:[]});
|
||||
if(p.startsWith('/api/decisions/')){
|
||||
const body=JSON.parse(init.body);window.__posts.push({p,body});
|
||||
if(p.endsWith('/confirmation'))return json({id:'d2',kind:'hire',action:'answer',question:d.question,choice:body.choice,text:'Approve',flagged:[],credentialLines:d.console.credentialLines,expiresAt:d.console.expiresAt,binding:{instance:'acme/researcher',change:${JSON.stringify(change)}},confirmation:'c'.repeat(64)});
|
||||
return json({id:'d2',op:'resolved',choice:body.choice,next:${JSON.stringify(BINDING_NEXT[change])}});
|
||||
}
|
||||
if(p==='/api/processing'||p==='/api/bus-status')return json({error:'unavailable'});
|
||||
return real(url,init);
|
||||
};
|
||||
})()`});
|
||||
const wait=expr=>b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expr})return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+${JSON.stringify(expr)})})()`);
|
||||
const text=()=>b.evaluate('document.body.innerText');
|
||||
const line=change==='unbind'?'Unbind and revoke the credentials of copy acme/researcher.':'Bind credentials for copy acme/researcher.';
|
||||
await b.viewport(1440,900);await b.navigate(f.base+'/#/inbox/d2');await wait('document.querySelector("#decide-section [data-binding-change]")');
|
||||
assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").dataset.bindingChange'),change);
|
||||
assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").textContent'),line);
|
||||
assert.match(await b.evaluate('document.querySelector("#decide-section").innerText'),/gitea: read:repository/);
|
||||
assert.equal(await b.evaluate('!!document.querySelector("#hire-adjust")'),false);
|
||||
await b.evaluate('document.querySelector(\'[data-decide="option-0"]\').click()');await wait('document.querySelector("[data-decide=confirm]")');
|
||||
assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").textContent'),line);
|
||||
await b.evaluate('document.querySelector("[data-decide=confirm]").click()');await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")');
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-binding-next]")?.textContent'),BINDING_NEXT[change]);
|
||||
const posts=await b.evaluate('window.__posts');assert.deepEqual(Object.keys(posts.find(x=>x.p.endsWith('/resolve')).body).sort(),['choice','confirmation']);
|
||||
assert.equal(JSON.stringify(posts).includes(SENTINEL),false);
|
||||
const page=await text();assert.equal(page.includes(SENTINEL),false);assert.equal(page.includes(SENTINEL.slice(0,16)),false);
|
||||
});
|
||||
@@ -14,7 +14,6 @@ import { busStopForDelete } from '../../cli/src/org-bus.mjs';
|
||||
import { CliError } from '../../cli/src/errors.mjs';
|
||||
import { actionTrail } from '../src/action-trail.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { systemTypesFake } from './helpers/system-types-fake.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
// E1: `bus` adds verbs to the admin's bus (busStart for a restore); `trail` gives the Console its action trail;
|
||||
@@ -146,10 +145,9 @@ test('E1 (P1-4): restoring the only organization reloads into it and still shows
|
||||
assert.equal(await f.b.evaluate(`Object.keys(sessionStorage).filter(k=>k.startsWith('mosaic-org-restored:')).length`), 0);
|
||||
});
|
||||
|
||||
test('E1 (P1-5): after restoring another organization, its dashboard shows the bus running and its System types', { timeout: 45000 }, async t => {
|
||||
const health = { up: false }, bus = startingBus(health), st = await systemTypesFake({ enabled: ['coding'] });
|
||||
test('E1 (P1-5): after restoring another organization, its dashboard shows the bus running and its organization file', { timeout: 45000 }, async t => {
|
||||
const health = { up: false }, bus = startingBus(health);
|
||||
const extra = id => ({
|
||||
requestRead: st.requestRead,
|
||||
reads: { business: async () => ({ business: { id, human: 'local-dev-owner', arbiters: [], projects: [], vars: {}, instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: { instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }), messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] },
|
||||
});
|
||||
@@ -158,8 +156,8 @@ test('E1 (P1-5): after restoring another organization, its dashboard shows the b
|
||||
await f.wait(`/Bus started\. It answers\./.test(document.querySelector('#org-archive-success')?.innerText || '')`);
|
||||
await f.wait(`!!document.querySelector('#workspace-nav [data-workspace-org=beta]')`);
|
||||
await f.b.evaluate(`location.hash = '#/orgs/beta/organization'`);
|
||||
await f.wait(`/bus running, read/.test(document.querySelector('[data-org-dashboard]')?.innerText || '') && !!document.querySelector('[data-org-dashboard] [data-system-type-chips] .ws-chip')`);
|
||||
assert.doesNotMatch(await f.b.evaluate(`document.querySelector('[data-org-dashboard] [data-system-type-chips]').textContent`), /unavailable/);
|
||||
await f.wait(`/bus running, read/.test(document.querySelector('[data-org-dashboard]')?.innerText || '')`);
|
||||
assert.match(await f.b.evaluate(`document.querySelector('[data-org-dashboard] [data-org-setting="Identity"] .v').textContent`), / · beta · /);
|
||||
assert.deepEqual(bus.starts.map(([id]) => id), ['beta']);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// E1 (P1-5): pages follow a state change without a reload. Restart bus redraws the organization
|
||||
// dashboard's bus line and System types at once, and Quick Setup puts the new organization in the
|
||||
// dashboard's bus line and its settings at once, and Quick Setup puts the new organization in the
|
||||
// sidebar. Neither waits for the 10 s repaint: each check runs well inside that window.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
@@ -13,16 +13,14 @@ import { actionTrail } from '../src/action-trail.mjs';
|
||||
import * as service from '../../organization/src/org-service.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
import { systemTypesFake } from './helpers/system-types-fake.mjs';
|
||||
|
||||
const waitFor = (b, tries = 150) => expression => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
|
||||
// One organization whose bus state the fake bus below owns. A stopped bus has no reads, as
|
||||
// organizations.mjs resolves it; a running one answers the dashboard's reads and System types.
|
||||
// organizations.mjs resolves it; a running one answers the dashboard's reads.
|
||||
async function westOrgs(state) {
|
||||
const st = await systemTypesFake({ enabled: ['coding'] });
|
||||
const running = () => ({
|
||||
busHealthy: true, requestRead: st.requestRead, systemTypesWrite: null,
|
||||
busHealthy: true,
|
||||
reads: { business: async () => ({ business: { id: 'west', human: 'jason', arbiters: [], projects: [], vars: {}, instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: { instances: async () => ({ business: 'west', revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }), messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] },
|
||||
chat: { projects: async () => [], threads: async () => [] },
|
||||
@@ -33,7 +31,7 @@ async function westOrgs(state) {
|
||||
};
|
||||
}
|
||||
|
||||
test('E1 (P1-5b): Restart bus redraws the dashboard bus line and System types without a reload or the 10 s repaint', { timeout: 45000 }, async t => {
|
||||
test('E1 (P1-5b): Restart bus redraws the dashboard bus line and settings without a reload or the 10 s repaint', { timeout: 45000 }, async t => {
|
||||
const state = { running: false }; const starts = [];
|
||||
const bus = {
|
||||
busStatus: async (ctx, id) => ({ org: id, healthy: state.running, pid: state.running ? 4242 : null }),
|
||||
@@ -47,16 +45,16 @@ test('E1 (P1-5b): Restart bus redraws the dashboard bus line and System types wi
|
||||
const wait = waitFor(b);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/west/organization`);
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-bus-restart]") && /bus unavailable, read/.test(document.querySelector("[data-org-dashboard]").innerText)');
|
||||
assert.match(await b.evaluate('document.querySelector("[data-org-dashboard] [data-system-type-chips]").textContent'), /System types unavailable/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-dashboard] [data-org-setting=\\"Identity\\"] .v").textContent'), 'Could not be read');
|
||||
// The page's own repaint is 10 s after its last draw; mark the draw this test starts from.
|
||||
await b.evaluate('window.__drawn = Date.now(); window.__first = document.querySelector("[data-org-dashboard]")');
|
||||
await b.evaluate('document.querySelector("[data-org-dashboard] [data-bus-restart]").click()');
|
||||
await wait('/It answers/.test(document.querySelector("[data-org-dashboard] [data-bus-restart-receipt]")?.textContent || "")');
|
||||
// No reload: the page keeps its globals, and the dashboard shows the running bus and the enabled type.
|
||||
await wait('/bus running, read/.test(document.querySelector("[data-org-dashboard]")?.innerText || "") && !!document.querySelector("[data-org-dashboard] [data-system-type-chips] .ws-chip")');
|
||||
// No reload: the page keeps its globals, and the dashboard shows the running bus and its organization file.
|
||||
await wait('/bus running, read/.test(document.querySelector("[data-org-dashboard]")?.innerText || "")');
|
||||
assert.ok(await b.evaluate('Date.now() - window.__drawn') < 8000, 'the dashboard redrew before the 10 s repaint');
|
||||
assert.equal(await b.evaluate('typeof window.__first'), 'object', 'the page was not reloaded');
|
||||
assert.doesNotMatch(await b.evaluate('document.querySelector("[data-org-dashboard] [data-system-type-chips]").textContent'), /unavailable/);
|
||||
assert.match(await b.evaluate('document.querySelector("[data-org-dashboard] [data-org-setting=\\"Identity\\"] .v").textContent'), /^West · west · /);
|
||||
assert.match(await b.evaluate('document.querySelector("[data-org-dashboard] [data-bus-restart-receipt]").textContent'), /^Bus started at .*It answers\./);
|
||||
assert.deepEqual(starts.map(([id]) => id), ['west']);
|
||||
});
|
||||
|
||||
@@ -52,7 +52,6 @@ async function fixture(t, { send = true } = {}) {
|
||||
if (verb === 'packs.console') return { packs: PACKS };
|
||||
if (verb === 'pack.preview.console') return { ...PREVIEW, project: args.project ?? null };
|
||||
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
|
||||
if (verb === 'system-types.console') return { installed: [], enabled: [], project: null };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const write = async (verb, args) => {
|
||||
|
||||
@@ -407,7 +407,7 @@ test('the same project, dashboard and Agents page in both panes draw no duplicat
|
||||
await wait(`document.querySelector('#pane-a-pick option[value="ddigital/projects/${P}"]')`);
|
||||
const both = route => `location.hash = '#/orgs/ddigital/side-by-side?a=ddigital${route}&b=ddigital${route}'`;
|
||||
const pages = [
|
||||
['/organization', `${title('a')}.startsWith('Dashboard') && ${title('b')}.startsWith('Dashboard') && document.querySelectorAll('[data-pane-body] [data-system-types-heading]').length === 2`],
|
||||
['/organization', `${title('a')}.startsWith('Dashboard') && ${title('b')}.startsWith('Dashboard') && document.querySelectorAll('[data-pane-body] [data-org-settings]').length === 2`],
|
||||
['/agents', `${title('a')}.startsWith('Agents') && ${title('b')}.startsWith('Agents') && document.querySelectorAll('[data-pane-body] [data-agents-available] tr[data-agent]').length >= 2`],
|
||||
[`/projects/${P}`, `${title('a')}.startsWith('Pomodoro Timer') && ${title('b')}.startsWith('Pomodoro Timer') && !${text('a')}.includes('Reading…') && !${text('b')}.includes('Reading…')`],
|
||||
[`/projects/${P}/conversations`, `${title('a')}.includes('Conversations') && ${title('b')}.includes('Conversations')`],
|
||||
@@ -425,8 +425,8 @@ test('the same project, dashboard and Agents page in both panes draw no duplicat
|
||||
drawn[page] = await b.evaluate(`[...document.querySelectorAll('#pane-a [data-pane-body] [id]')].map(e => e.id)`);
|
||||
}
|
||||
assert.deepEqual(found, Object.fromEntries(pages.map(([route]) => [route.replace(P, 'P'), { duplicates: [], stray: [] }])));
|
||||
// The audit is not vacuous: the dashboard draws its system types heading and the requirements page
|
||||
// its request select, north star and PRD headings, each with the pane's prefix.
|
||||
assert.deepEqual(drawn['/organization'], ['pane-a-ws-reload-why', 'pane-a-ws-types-h']);
|
||||
// The audit is not vacuous: the dashboard draws its reload note and the requirements page its
|
||||
// request select, north star and PRD headings, each with the pane's prefix.
|
||||
assert.deepEqual(drawn['/organization'], ['pane-a-ws-reload-why']);
|
||||
assert.deepEqual(drawn['/projects/P/requirements'], ['pane-a-project-request-select', 'pane-a-project-north-star', 'pane-a-project-prd']);
|
||||
});
|
||||
@@ -1,244 +0,0 @@
|
||||
// Phase P2 (#1873): System types on the organization dashboard (sample 03) and on a project's information
|
||||
// page. The Console, its per-organization routes and the pages are real; only the two bus transports are
|
||||
// the fake in helpers/system-types-fake.mjs, which reads the installed modules from packages/plugins. The
|
||||
// server-side admission checks and the real organization writer are in system-types-http.test.mjs.
|
||||
// MOSAIC_UX_SHOTS=<dir> also writes light and dark shots at 1440x900 and 390x844.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
import { systemTypesFake } from './helpers/system-types-fake.mjs';
|
||||
|
||||
const P = '10000000-0000-4000-8000-0000000000b1';
|
||||
const RECEIPT = /Receipt ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\./;
|
||||
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)}+' | '+(document.querySelector('main')?.innerText||'').slice(0,1500))})()`);
|
||||
|
||||
// One running organization with one project. `send` is the owner's signed-in send mode; without it the
|
||||
// Console only reads and the route gets no writer.
|
||||
function organizations(st, { send = true } = {}) {
|
||||
const business = { business: { id: 'acme', human: 'jason', arbiters: [], projects: [P], vars: {}, instances: [], appearance: { theme: null } } };
|
||||
return {
|
||||
list: async () => [{ id: 'acme', label: 'Acme', theme: null, busHealthy: true }],
|
||||
resolve: async id => id !== 'acme' ? null : ({
|
||||
busHealthy: true, requestRead: st.requestRead, systemTypesWrite: send ? st.systemTypesWrite : null, ...(send ? { send: async () => ({}) } : {}),
|
||||
reads: { business: async () => business, settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: { instances: async () => ({ business: 'acme', revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }),
|
||||
messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] },
|
||||
chat: { projects: async () => [{ id: P, name: 'Work', repo: null }], threads: async () => [] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function page(t, st, { send = true, width = 1440, height = 900 } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), ...(send ? { send: async () => ({}) } : {}), organizations: organizations(st, { send }), log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const errors = [];
|
||||
b.on('Runtime.exceptionThrown', p => errors.push(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text ?? 'exception'));
|
||||
await b.viewport(width, height);
|
||||
const base = `http://127.0.0.1:${server.address().port}/`;
|
||||
return { b, base, wait: waitFor(b), errors };
|
||||
}
|
||||
const dashboard = async ({ b, base, wait }) => {
|
||||
await b.navigate(`${base}#/orgs/acme/organization`);
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-system-types]") && !/Reading/.test(document.querySelector("[data-system-types]").textContent)');
|
||||
};
|
||||
const settings = async ({ b, base, wait }) => {
|
||||
await b.navigate(`${base}#/orgs/acme/projects/${P}/settings`);
|
||||
await wait('document.querySelector("[data-project-system-types]") && !/Reading system types/.test(document.querySelector("[data-project-system-types]").textContent)');
|
||||
};
|
||||
const text = (b, selector) => b.evaluate(`(document.querySelector(${JSON.stringify(selector)})?.innerText ?? '').replace(/\\s+/g, ' ').trim()`);
|
||||
const chips = b => b.evaluate(`[...document.querySelectorAll('[data-system-type-chips] .ws-chip')].map(c => c.textContent)`);
|
||||
const click = (b, selector) => b.evaluate(`(document.querySelector(${JSON.stringify(selector)}).click(), true)`);
|
||||
|
||||
test('the dashboard lists the installed modules from the plug-in data and the owner switches one with a receipt', { timeout: 60000 }, async t => {
|
||||
const st = await systemTypesFake({ enabled: ['coding'], projects: { [P]: [] } });
|
||||
const p = await page(t, st); const { b, wait } = p;
|
||||
await dashboard(p);
|
||||
// Every row is a module the plug-ins declare, in their order, with their label and description.
|
||||
const rows = await b.evaluate(`[...document.querySelectorAll('[data-system-types] li')].map(li => [li.dataset.systemType, li.querySelector('.t b').textContent, li.querySelector('.t .d').textContent, li.querySelector('.ws-dot').textContent.replace(/[●–]/, '')])`);
|
||||
assert.deepEqual(rows, st.installed.map(m => [m.id, m.label, m.description, m.id === 'coding' ? 'enabled' : 'off']));
|
||||
assert.ok(st.installed.length >= 2, 'the tree installs more than one system type module');
|
||||
assert.deepEqual(await chips(b), ['Coding']);
|
||||
assert.match(await text(b, '[data-system-type-chips]'), /Each project picks from these; none is required\.$/);
|
||||
assert.match(await text(b, '[data-org-setting="System types"]'), new RegExp(`1 of ${st.installed.length} installed enabled`));
|
||||
// The Settings row's Open moves focus to the section heading.
|
||||
await click(b, '[data-org-setting="System types"] [data-system-types-open]');
|
||||
assert.equal(await b.evaluate('document.activeElement?.dataset.systemTypesHeading'), '');
|
||||
|
||||
// Enable Marketing from the keyboard; the receipt is the organization writer's transaction.
|
||||
await b.evaluate(`document.querySelector('[data-system-type-toggle="marketing"]').focus(), true`);
|
||||
assert.equal(await b.evaluate(`document.activeElement.getAttribute('aria-label')`), 'Enable Marketing');
|
||||
await b.key('Enter');
|
||||
await wait(`/Receipt/.test(document.querySelector('[data-system-types-status]')?.textContent)`);
|
||||
assert.match(await text(b, '[data-system-types-status]'), new RegExp(`^Marketing enabled\\. ${RECEIPT.source}$`));
|
||||
assert.deepEqual(st.state.enabled, ['coding', 'marketing']);
|
||||
assert.deepEqual(await chips(b), ['Coding', 'Marketing']);
|
||||
assert.match(await text(b, '[data-org-setting="System types"]'), new RegExp(`2 of ${st.installed.length} installed enabled`));
|
||||
// Focus stays on the switch it pressed, which now says Disable.
|
||||
assert.deepEqual(await b.evaluate(`[document.activeElement.dataset.focusKey, document.activeElement.getAttribute('aria-label')]`), ['st:marketing', 'Disable Marketing']);
|
||||
|
||||
// Disable Coding; another write changed the organization file meanwhile, so the first try is refused.
|
||||
st.state.n++;
|
||||
await click(b, '[data-system-type-toggle="coding"]');
|
||||
await wait(`/changed after this page read it/.test(document.querySelector('[data-system-types-status]')?.textContent)`);
|
||||
assert.deepEqual(st.state.enabled, ['coding', 'marketing']);
|
||||
await click(b, '[data-system-type-toggle="coding"]');
|
||||
await wait(`/Coding disabled/.test(document.querySelector('[data-system-types-status]')?.textContent)`);
|
||||
assert.match(await text(b, '[data-system-types-status]'), RECEIPT);
|
||||
assert.deepEqual(st.state.enabled, ['marketing']);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-system-type="coding"] .ws-dot').textContent.replace(/[●–]/, '')`), 'off');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
test('without the owner proof the switch is refused, and a read-only Console offers none', { timeout: 60000 }, async t => {
|
||||
// The writer's owner fence refuses: the page says so and nothing changes.
|
||||
const fenced = await systemTypesFake({ enabled: ['coding'], projects: { [P]: [] }, owner: false });
|
||||
const p = await page(t, fenced); const { b, wait } = p;
|
||||
await dashboard(p);
|
||||
await click(b, '[data-system-type-toggle="marketing"]');
|
||||
await wait(`/owner can change/.test(document.querySelector('[data-system-types-status]')?.textContent)`);
|
||||
assert.equal(await text(b, '[data-system-types-status]'), "Only the organization's owner can change system types.");
|
||||
assert.deepEqual(fenced.state.enabled, ['coding']);
|
||||
assert.doesNotMatch(await text(b, '[data-system-types]'), /Receipt/);
|
||||
|
||||
// A Console without send mode reads the list and shows no switch; no write reaches the transport.
|
||||
const readOnly = await systemTypesFake({ enabled: ['coding'], projects: { [P]: ['coding'] } });
|
||||
const q = await page(t, readOnly, { send: false });
|
||||
await dashboard(q);
|
||||
assert.equal(await q.b.evaluate(`document.querySelectorAll('[data-system-types] li').length`), readOnly.installed.length);
|
||||
assert.equal(await q.b.evaluate(`document.querySelectorAll('[data-system-type-toggle]').length`), 0);
|
||||
assert.match(await text(q.b, '[data-system-types]'), /This Console only reads\. Changing system types needs signed-in send mode\./);
|
||||
// The project page shows the selection read only too.
|
||||
await settings(q);
|
||||
assert.equal(await q.b.evaluate(`[...document.querySelectorAll('[data-project-system-types] input')].every(i => i.disabled)`), true);
|
||||
assert.equal(await q.b.evaluate(`document.querySelector('[data-project-system-types] button[type=submit]')`), null);
|
||||
assert.deepEqual(readOnly.state.writes, []);
|
||||
});
|
||||
|
||||
test('a project selects only enabled modules and a disabled selection shows as inactive', { timeout: 60000 }, async t => {
|
||||
// Montage was selected, then disabled in the organization.
|
||||
const st = await systemTypesFake({ enabled: ['coding', 'marketing'], projects: { [P]: ['montage'] } });
|
||||
const p = await page(t, st); const { b, wait } = p;
|
||||
await settings(p);
|
||||
const label = id => st.installed.find(m => m.id === id).label;
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-project-system-types] input[name=system-type]')].map(i => [i.value, i.checked, i.closest('label').querySelector('strong').textContent])`),
|
||||
[['coding', false, label('coding')], ['marketing', false, label('marketing')]]);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-inactive-type]')].map(li => [li.dataset.inactiveType, li.innerText.replace(/\\s+/g, ' ').trim()])`), [['montage', `${label('montage')} inactive`]]);
|
||||
assert.match(await text(b, '[data-project-system-types-inactive]'), /Saving keeps only enabled types/);
|
||||
|
||||
// Pick Marketing and save: the inactive one goes, the saved selection is the bus's answer.
|
||||
await b.evaluate(`document.querySelector('[data-project-system-types] input[value=marketing]').click(), true`);
|
||||
await click(b, '[data-project-system-types] button[type=submit]');
|
||||
await wait(`/Saved/.test(document.querySelector('[data-project-system-types-status]')?.textContent)`);
|
||||
assert.equal(await text(b, '[data-project-system-types-status]'), `Saved. Selected: ${label('marketing')}.`);
|
||||
assert.equal(await b.evaluate(`document.activeElement?.hasAttribute('data-project-system-types-status')`), true);
|
||||
assert.deepEqual(st.state.projects[P], ['marketing']);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-inactive-type]')`), null);
|
||||
|
||||
// The organization disables Coding after the page read it; saving it is refused and the list is read again.
|
||||
await b.evaluate(`document.querySelector('[data-project-system-types] input[value=coding]').click(), true`);
|
||||
st.state.enabled = ['marketing'];
|
||||
await click(b, '[data-project-system-types] button[type=submit]');
|
||||
await wait(`/not enabled in the organization/.test(document.querySelector('[data-project-system-types-status]')?.textContent)`);
|
||||
assert.deepEqual(st.state.projects[P], ['marketing']);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-project-system-types] input[name=system-type]')].map(i => i.value)`), ['marketing']);
|
||||
|
||||
// The owner disables Marketing on the dashboard; back on the project it stays selected, shown inactive.
|
||||
await dashboard(p);
|
||||
await click(b, '[data-system-type-toggle="marketing"]');
|
||||
await wait(`/Marketing disabled/.test(document.querySelector('[data-system-types-status]')?.textContent)`);
|
||||
assert.deepEqual(st.state.enabled, []);
|
||||
await settings(p);
|
||||
assert.match(await text(b, '[data-project-system-types]'), /The organization has no system types enabled\./);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-inactive-type]')].map(li => li.dataset.inactiveType)`), ['marketing']);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-project-system-types] input').length`), 0);
|
||||
// With nothing enabled the owner can still clear the inactive selection, without enabling a type first.
|
||||
assert.equal(await text(b, '[data-project-system-types] button[type=submit]'), 'Clear the inactive types');
|
||||
await click(b, '[data-project-system-types] button[type=submit]');
|
||||
await wait(`/Saved/.test(document.querySelector('[data-project-system-types-status]')?.textContent)`);
|
||||
assert.equal(await text(b, '[data-project-system-types-status]'), 'Saved. No system types selected.');
|
||||
assert.deepEqual(st.state.projects[P], []);
|
||||
assert.deepEqual(st.state.enabled, []);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-inactive-type]')`), null);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-project-system-types] button[type=submit]')`), null);
|
||||
assert.deepEqual(p.errors, []);
|
||||
|
||||
// A read-only Console shows the same inactive selection and offers no clear button.
|
||||
const readOnly = await systemTypesFake({ enabled: [], projects: { [P]: ['coding'] } });
|
||||
const q = await page(t, readOnly, { send: false });
|
||||
await settings(q);
|
||||
assert.deepEqual(await q.b.evaluate(`[...document.querySelectorAll('[data-inactive-type]')].map(li => li.dataset.inactiveType)`), ['coding']);
|
||||
assert.equal(await q.b.evaluate(`document.querySelector('[data-project-system-types] button[type=submit]')`), null);
|
||||
assert.deepEqual(readOnly.state.writes, []);
|
||||
});
|
||||
|
||||
test('the dashboard section and the project page fit a phone screen in light and dark', { timeout: 90000 }, async t => {
|
||||
const st = await systemTypesFake({ enabled: ['coding', 'marketing'], projects: { [P]: ['coding', 'montage'] } });
|
||||
const shots = process.env.MOSAIC_UX_SHOTS;
|
||||
if (shots) mkdirSync(shots, { recursive: true });
|
||||
for (const [width, height] of [[1440, 900], [390, 844]]) {
|
||||
const p = await page(t, st, { width, height }); const { b } = p;
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: mode }] });
|
||||
await dashboard(p);
|
||||
// The default appearance is Harbor in the dark whatever the OS says; the header switch picks the mode.
|
||||
if (await b.evaluate(`document.getElementById('theme-switch').getAttribute('aria-checked')`) !== String(mode === 'dark')) {
|
||||
await b.evaluate(`document.getElementById('theme-switch').click(), true`);
|
||||
await p.wait(`document.getElementById('theme-switch').getAttribute('aria-checked') === '${mode === 'dark'}'`);
|
||||
}
|
||||
await b.evaluate(`document.querySelector('[data-system-types-heading]').scrollIntoView({ block: 'start' }), true`);
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `dashboard ${width} ${mode}`);
|
||||
assert.equal(await b.evaluate(`[...document.querySelectorAll('[data-system-types] li')].every(li => li.scrollWidth <= li.clientWidth)`), true, `dashboard rows ${width} ${mode}`);
|
||||
if (shots) await b.screenshot(join(shots, `p2-dashboard-types-${width}-${mode}.png`));
|
||||
await settings(p);
|
||||
await b.evaluate(`document.querySelector('[data-project-system-types]').scrollIntoView({ block: 'start' }), true`);
|
||||
// At 1440 a project page taller than the window already overflows by its header's primary action
|
||||
// (projects.css, before P2), so the wide check is the section's own box; the phone check is the page.
|
||||
if (width === 390) assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `project ${width} ${mode}`);
|
||||
assert.equal(await b.evaluate(`(s => s.scrollWidth <= s.clientWidth && s.getBoundingClientRect().right <= document.documentElement.clientWidth)(document.querySelector('[data-project-system-types]'))`), true, `project section ${width} ${mode}`);
|
||||
assert.equal(await b.evaluate(`[...document.querySelectorAll('[data-project-system-types] .project-types-option')].every(o => o.getBoundingClientRect().height >= 44)`), true, `targets ${width} ${mode}`);
|
||||
if (shots) await b.screenshot(join(shots, `p2-project-types-${width}-${mode}.png`));
|
||||
}
|
||||
assert.deepEqual(p.errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
// U5's Side by side draws an organization dashboard into a pane. Each pane reads its own organization's
|
||||
// system types; a pane only shows them (the switch stays in the organization's full view, as the bus
|
||||
// restart does), and its Settings row opens the section in the same pane.
|
||||
test('a side-by-side pane shows its own organization\'s system types and offers no switch', { timeout: 60000 }, async t => {
|
||||
const acme = await systemTypesFake({ enabled: ['coding'], projects: { [P]: [] } });
|
||||
const beta = await systemTypesFake({ enabled: ['marketing'], projects: {} });
|
||||
const one = organizations(acme);
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: {
|
||||
list: async () => [{ id: 'acme', label: 'Acme', theme: null, busHealthy: true }, { id: 'beta', label: 'Beta', theme: null, busHealthy: true }],
|
||||
resolve: async id => id === 'acme' ? one.resolve('acme') : id === 'beta' ? { ...(await one.resolve('acme')), requestRead: beta.requestRead, systemTypesWrite: beta.systemTypesWrite,
|
||||
chat: { projects: async () => [], threads: async () => [] } } : null,
|
||||
} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const errors = [];
|
||||
b.on('Runtime.exceptionThrown', p => errors.push(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text ?? 'exception'));
|
||||
await b.viewport(1440, 900);
|
||||
const wait = waitFor(b);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/side-by-side?a=acme/organization&b=beta/organization`);
|
||||
const ready = key => `document.querySelector('#pane-${key} [data-system-types]') && !/Reading/.test(document.querySelector('#pane-${key} [data-system-types]').textContent)`;
|
||||
await wait(`${ready('a')} && ${ready('b')}`);
|
||||
const paneChips = key => b.evaluate(`[...document.querySelectorAll('#pane-${key} [data-system-type-chips] .ws-chip')].map(c => c.textContent)`);
|
||||
assert.deepEqual(await paneChips('a'), ['Coding']);
|
||||
assert.deepEqual(await paneChips('b'), ['Marketing']);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('.panes [data-system-type-toggle]').length`), 0);
|
||||
for (const key of ['a', 'b'])
|
||||
assert.match(await text(b, `#pane-${key} [data-system-types]`), /Change system types from this organization's full view\./);
|
||||
const ids = await b.evaluate(`[...document.querySelectorAll('[data-system-types-heading]')].map(h => h.id)`);
|
||||
assert.equal(ids.length, 2); assert.equal(new Set(ids).size, 2);
|
||||
await click(b, '#pane-b [data-org-setting="System types"] [data-system-types-open]');
|
||||
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('#pane-b [data-system-types-heading]')`), true);
|
||||
assert.deepEqual([acme.state.writes.includes('plugins.set'), beta.state.writes.includes('plugins.set')], [false, false]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
@@ -1,250 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { request } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { busOrganization } from '../../bus/src/organization-context.mjs';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { serve } from '../../bus/src/server.mjs';
|
||||
import { Client } from '../../bus/src/client.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
// Phase P2 (#1873): the owner's System types routes on a selected organization, end to end. An
|
||||
// ephemeral organization with the real runtime writer (plugins.set, the system types owner fence,
|
||||
// changes.jsonl) and the broker's console socket for the read; the SSO session is a fixture
|
||||
// authority. `writer` picks the cap the write transport binds: the owner's human cap, or the tester.
|
||||
async function fixture(t, { writer = 'owner', send = true, afterRead = null, beforeWrite = null } = {}) {
|
||||
// Cleanups run last-made first, registered as soon as each resource exists.
|
||||
const undo = []; t.after(async () => { for (const step of undo.reverse()) await step(); });
|
||||
const root = mkdtempSync(join(tmpdir(), 'st-'));
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { ...(doc.plugins ?? {}), 'system-type': ['coding'], harness: ['pi'] };
|
||||
doc.vars = { ...doc.vars, 'bus.tester': true };
|
||||
const file = writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const business = loadBusiness('demo', { dir: root, rolesDir });
|
||||
const resolved = Object.fromEntries(Object.keys(business.roles).map(instance => [instance, resolveInstance({ system, business, instance })]));
|
||||
undo.push(() => rmSync(root, { recursive: true, force: true }));
|
||||
const runtime = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: busOrganization(business, resolved) }, organization: { dir: root, rolesDir, system } });
|
||||
undo.push(() => runtime.close());
|
||||
const path = join(root, 'b.sock');
|
||||
const socketServer = await serve({ broker: runtime.broker, path, peerReader: { read: async () => ({}), close: () => {} },
|
||||
authenticateConsole: proof => runtime.broker.bindConsole({ business: 'demo', human: 'jason', subject: proof.subject }) });
|
||||
undo.push(() => socketServer.close());
|
||||
const owner = runtime.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const role = Object.keys(business.roles)[0];
|
||||
const cap = writer === 'tester' ? runtime.broker.bindTester({ business: 'demo' })
|
||||
: writer === 'agent' ? runtime.broker.bindLaunch({ business: 'demo', role, run: 'agent-run', harness: 'pi' }) : owner;
|
||||
const calls = [];
|
||||
// afterRead and beforeWrite let a test act between the route's read and its write.
|
||||
const requestRead = async (verb, args, ctx) => { calls.push(['read', verb]); const r = await new Client({ path, console: { subject: ctx.subject } }).call(verb, args); await afterRead?.(); return r; };
|
||||
const systemTypesWrite = async (verb, args) => { await beforeWrite?.(verb); calls.push(['write', verb]); return runtime.broker.request(cap, { verb, args }); };
|
||||
const session = { provider: 'fixture', iss: 'https://issuer.example', sub: 'owner', name: 'jason', rootOwner: true };
|
||||
let active = true;
|
||||
const sso = { publicOrigin: '', publicHost: '', formTargets: () => [], session: () => active ? session : null, handle: () => {}, health: () => ({}) };
|
||||
const organizations = {
|
||||
list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }],
|
||||
resolve: async id => id !== 'demo' ? null : { busHealthy: true, send: send ? async () => ({}) : null, requestRead, systemTypesWrite: send ? systemTypesWrite : null,
|
||||
reads: { business: async () => ({ business: { id: 'demo' } }) }, bus: {}, chat: { projects: async () => [], threads: async () => [] } },
|
||||
};
|
||||
const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso, send: async () => ({}), organizations, log: () => {} });
|
||||
const base = `http://127.0.0.1:${web.address().port}`;
|
||||
sso.publicOrigin = base; sso.publicHost = new URL(base).host;
|
||||
undo.push(() => close(web));
|
||||
const project = runtime.broker.request(owner, { verb: 'project.create', args: { name: 'example' } }).id;
|
||||
const onDisk = () => JSON.parse(readFileSync(file)).plugins['system-type'];
|
||||
const ownerRequest = (verb, args) => runtime.broker.request(owner, { verb, args });
|
||||
return { base, file, project, calls, onDisk, ownerRequest, signOut: () => { active = false; }, revokeOwner: () => { session.rootOwner = false; session.user = 'legacy-user'; } };
|
||||
}
|
||||
|
||||
function call(f, path, method = 'GET', body, headers = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const data = body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body);
|
||||
const req = request(f.base + path, { method, headers: { ...(data !== undefined ? { origin: f.base, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}), ...headers } }, res => {
|
||||
let text = ''; res.on('data', chunk => { text += chunk; }); res.on('end', () => resolve([res.statusCode, JSON.parse(text)]));
|
||||
});
|
||||
req.on('error', reject); req.setTimeout(10000, () => req.destroy(new Error('fixture request timed out'))); req.end(data);
|
||||
});
|
||||
}
|
||||
const ORG = '/api/orgs/demo/system-types';
|
||||
|
||||
test('the owner reads the installed modules and enables one with the revision, getting a receipt', async t => {
|
||||
const f = await fixture(t);
|
||||
const [status, before] = await call(f, ORG);
|
||||
assert.equal(status, 200, JSON.stringify(before));
|
||||
// Labels and descriptions are the modules' own, never a list in the WebUI.
|
||||
const modules = (await installedSystemTypes()).map(({ id, label, description }) => ({ id, label, description }));
|
||||
assert.deepEqual(before.installed, modules);
|
||||
assert.deepEqual(before.enabled, ['coding']);
|
||||
assert.equal(before.project, null); assert.equal(before.writable, true); assert.match(before.revision, /^[a-f0-9]{64}$/);
|
||||
const [saved, receipt] = await call(f, ORG, 'POST', { revision: before.revision, enabled: ['coding', 'montage'] });
|
||||
assert.equal(saved, 200, JSON.stringify(receipt));
|
||||
assert.deepEqual(receipt.enabled, ['coding', 'montage']);
|
||||
assert.match(receipt.transaction, /^[0-9a-f-]{36}$/); assert.notEqual(receipt.revision, before.revision);
|
||||
assert.deepEqual(f.onDisk(), ['coding', 'montage']);
|
||||
const [, after] = await call(f, ORG);
|
||||
assert.deepEqual(after.enabled, ['coding', 'montage']); assert.equal(after.revision, receipt.revision);
|
||||
// The revision is the proof: the old one is refused and nothing is written.
|
||||
const [stale, conflict] = await call(f, ORG, 'POST', { revision: before.revision, enabled: [] });
|
||||
assert.deepEqual([stale, conflict.error], [409, 'revision-conflict']);
|
||||
assert.deepEqual(f.onDisk(), ['coding', 'montage']);
|
||||
});
|
||||
|
||||
test('the admission checks refuse before any write', async t => {
|
||||
const f = await fixture(t);
|
||||
const [, { revision }] = await call(f, ORG);
|
||||
const good = { revision, enabled: [] };
|
||||
for (const [label, body, headers, expected] of [
|
||||
['unknown module', { revision, enabled: ['nope'] }, {}, [400, 'system-type-unknown']],
|
||||
['duplicate', { revision, enabled: ['coding', 'coding'] }, {}, [400, 'invalid-request']],
|
||||
['extra field', { ...good, actor: 'jason' }, {}, [400, 'invalid-request']],
|
||||
['business field', { ...good, business: 'other' }, {}, [400, 'invalid-request']],
|
||||
['no revision', { enabled: [] }, {}, [400, 'invalid-request']],
|
||||
['bad revision', { revision: 'x', enabled: [] }, {}, [400, 'invalid-request']],
|
||||
['not JSON', '{', {}, [400, 'invalid-request']],
|
||||
['too large', JSON.stringify({ revision, enabled: [], pad: 'x'.repeat(5000) }), {}, [413, 'invalid-request']],
|
||||
['form post', good, { 'content-type': 'text/plain' }, [400, 'invalid-request']],
|
||||
// The Console's own origin check answers a foreign Origin first; the route's own check answers Sec-Fetch-Site.
|
||||
['cross origin', good, { origin: 'https://other.example' }, [403, 'cross-origin request refused']],
|
||||
['cross site', good, { 'sec-fetch-site': 'cross-site' }, [403, 'cross-origin']],
|
||||
]) {
|
||||
const writes = f.calls.filter(c => c[0] === 'write' && c[1] === 'plugins.set').length;
|
||||
const [status, result] = await call(f, ORG, 'POST', body, headers);
|
||||
assert.deepEqual([status, result.error], expected, label);
|
||||
assert.equal(f.calls.filter(c => c[0] === 'write' && c[1] === 'plugins.set').length, writes, label);
|
||||
assert.deepEqual(f.onDisk(), ['coding'], label);
|
||||
}
|
||||
const [method] = await call(f, ORG, 'PUT');
|
||||
assert.equal(method, 405);
|
||||
const [cross, crossBody] = await call(f, ORG, 'GET', undefined, { origin: 'https://other.example' });
|
||||
assert.equal(cross, 403); assert.match(crossBody.error, /^cross-origin/);
|
||||
const [badProject, badProjectBody] = await call(f, `${ORG}/projects/${encodeURIComponent('../x')}`);
|
||||
assert.deepEqual([badProject, badProjectBody.error], [404, 'project-not-found']);
|
||||
f.signOut();
|
||||
const [signedOut, signedOutBody] = await call(f, ORG, 'POST', good);
|
||||
assert.deepEqual([signedOut, signedOutBody.error], [401, 'sign-in-required']);
|
||||
assert.deepEqual(f.onDisk(), ['coding']);
|
||||
});
|
||||
|
||||
test('a sign-out while the read runs dispatches no write on either route', async t => {
|
||||
let signOutOnRead = false;
|
||||
const f = await fixture(t, { afterRead: () => { if (signOutOnRead) f.signOut(); } });
|
||||
const [, { revision }] = await call(f, ORG);
|
||||
signOutOnRead = true;
|
||||
const writes = () => f.calls.filter(c => c[0] === 'write' && c[1] !== 'plugins').length;
|
||||
for (const [path, body] of [[ORG, { revision, enabled: [] }], [`${ORG}/projects/${f.project}`, { systemTypes: ['coding'] }]]) {
|
||||
const [status, result] = await call(f, path, 'POST', body);
|
||||
assert.deepEqual([status, result.error], [401, 'sign-in-required'], path);
|
||||
}
|
||||
assert.equal(writes(), 0);
|
||||
assert.deepEqual(f.onDisk(), ['coding']);
|
||||
});
|
||||
|
||||
test('root authority revoked during a read cannot write through a surviving user session', async t => {
|
||||
for (const projectRoute of [false, true]) {
|
||||
let revokeOnRead = false;
|
||||
const f = await fixture(t, { afterRead: () => { if (revokeOnRead) f.revokeOwner(); } });
|
||||
const [, { revision }] = await call(f, ORG);
|
||||
revokeOnRead = true;
|
||||
const path = projectRoute ? `${ORG}/projects/${f.project}` : ORG;
|
||||
const body = projectRoute ? { systemTypes: ['coding'] } : { revision, enabled: [] };
|
||||
const [status, result] = await call(f, path, 'POST', body);
|
||||
assert.deepEqual([status, result.error], [401, 'sign-in-required'], path);
|
||||
assert.equal(f.calls.filter(c => c[0] === 'write' && c[1] !== 'plugins').length, 0);
|
||||
assert.deepEqual(f.onDisk(), ['coding']);
|
||||
}
|
||||
});
|
||||
|
||||
test('the enabled set and its revision come from one read, so a change in between is not undone', async t => {
|
||||
let raced = false;
|
||||
const f = await fixture(t, { beforeWrite: async verb => {
|
||||
// Another owner action enables Marketing after the route's Console read and before its plugins read.
|
||||
if (verb !== 'plugins' || raced) return;
|
||||
raced = true;
|
||||
const { revision } = await f.ownerRequest('plugins', {});
|
||||
await f.ownerRequest('plugins.set', { revision, plugins: { 'system-type': ['coding', 'marketing'] } });
|
||||
} });
|
||||
const [, view] = await call(f, ORG);
|
||||
assert.equal(raced, true);
|
||||
assert.deepEqual(view.enabled, ['coding', 'marketing']);
|
||||
const [saved, receipt] = await call(f, ORG, 'POST', { revision: view.revision, enabled: view.enabled.filter(x => x !== 'coding') });
|
||||
assert.equal(saved, 200, JSON.stringify(receipt));
|
||||
assert.deepEqual(f.onDisk(), ['marketing']);
|
||||
});
|
||||
|
||||
test('without the owner human proof the enable switch is refused', async t => {
|
||||
// A Console without --send has no write transport: the read works, the write is read-only.
|
||||
const readOnly = await fixture(t, { send: false });
|
||||
const [status, view] = await call(readOnly, ORG);
|
||||
assert.equal(status, 200); assert.equal(view.writable, false); assert.equal(view.revision, undefined);
|
||||
const [refused, body] = await call(readOnly, ORG, 'POST', { revision: 'a'.repeat(64), enabled: [] });
|
||||
assert.deepEqual([refused, body.error], [403, 'read-only']);
|
||||
assert.deepEqual(readOnly.onDisk(), ['coding']);
|
||||
// A write transport bound as the tester or as an agent, not the owner's human cap, is refused by the
|
||||
// broker, and the receipt-bearing path never runs.
|
||||
for (const writer of ['tester', 'agent']) {
|
||||
const f = await fixture(t, { writer });
|
||||
const [fenced, fence] = await call(f, ORG, 'POST', { revision: 'b'.repeat(64), enabled: [] });
|
||||
assert.deepEqual([fenced, fence.error], [403, 'human-required'], writer);
|
||||
assert.deepEqual(f.onDisk(), ['coding'], writer);
|
||||
}
|
||||
});
|
||||
|
||||
test('a project selects only enabled modules and a disabled selection reads as inactive', async t => {
|
||||
const f = await fixture(t);
|
||||
const path = `${ORG}/projects/${f.project}`;
|
||||
const [status, empty] = await call(f, path);
|
||||
assert.equal(status, 200, JSON.stringify(empty));
|
||||
assert.deepEqual(empty.project, { project: f.project, selected: [], active: [], inactive: [] });
|
||||
assert.equal(empty.revision, undefined);
|
||||
const [notEnabled, notEnabledBody] = await call(f, path, 'POST', { systemTypes: ['montage'] });
|
||||
assert.deepEqual([notEnabled, notEnabledBody.error], [409, 'system-type-not-enabled']);
|
||||
const [unknown, unknownBody] = await call(f, path, 'POST', { systemTypes: ['nope'] });
|
||||
assert.deepEqual([unknown, unknownBody.error], [400, 'system-type-unknown']);
|
||||
const [saved, selection] = await call(f, path, 'POST', { systemTypes: ['coding'] });
|
||||
assert.equal(saved, 200, JSON.stringify(selection));
|
||||
assert.deepEqual(selection, { project: f.project, selected: ['coding'], active: ['coding'], inactive: [] });
|
||||
// The owner disables coding for the organization; the project keeps its selection, now inactive.
|
||||
const [, { revision }] = await call(f, ORG);
|
||||
assert.equal((await call(f, ORG, 'POST', { revision, enabled: [] }))[0], 200);
|
||||
const [, after] = await call(f, path);
|
||||
assert.deepEqual(after.enabled, []);
|
||||
assert.deepEqual(after.project, { project: f.project, selected: ['coding'], active: [], inactive: ['coding'] });
|
||||
const [missing, missingBody] = await call(f, `${ORG}/projects/no-such-project`);
|
||||
assert.deepEqual([missing, missingBody.error], [404, 'project-not-found']);
|
||||
const [missingWrite, missingWriteBody] = await call(f, `${ORG}/projects/no-such-project`, 'POST', { systemTypes: [] });
|
||||
assert.deepEqual([missingWrite, missingWriteBody.error], [404, 'project-not-found']);
|
||||
});
|
||||
|
||||
test('the tester listener and a Console without SSO never reach the routes or the files', async t => {
|
||||
const { createDevOwner } = await import('../src/dev-owner.mjs');
|
||||
let reached = 0;
|
||||
const hit = async () => { reached++; return {}; };
|
||||
const organizations = { list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }],
|
||||
resolve: async () => ({ busHealthy: true, send: hit, requestRead: hit, systemTypesWrite: hit, reads: { business: async () => ({ business: { id: 'demo' } }) }, bus: {}, chat: { projects: async () => [], threads: async () => [] } }) };
|
||||
const root = mkdtempSync(join(tmpdir(), 'stt-')), socket = join(root, 't.sock');
|
||||
const tester = await startServer({ tester: true, testerSocket: socket, board: 'http://127.0.0.1:9', organizations, log: () => {} });
|
||||
t.after(async () => { await close(tester); rmSync(root, { recursive: true, force: true }); });
|
||||
const viaTester = (path, method = 'GET') => new Promise((resolve, reject) => {
|
||||
const req = request({ socketPath: socket, path, method, headers: { host: 'mosaic-tester.invalid' } }, res => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
|
||||
req.on('error', reject); req.end();
|
||||
});
|
||||
for (const path of ['/system-types.js', '/system-types.css']) assert.equal(await viaTester(path), 403, path);
|
||||
// The tester has no organization session, so the per-organization routes answer org-unavailable.
|
||||
for (const [path, method] of [[ORG, 'GET'], [ORG, 'POST'], [`${ORG}/projects/p1`, 'GET']]) assert.ok([403, 404].includes(await viaTester(path, method)), path);
|
||||
const plain = await startServer({ port: 0, organizations, log: () => {} }); t.after(() => close(plain));
|
||||
const plainBase = `http://127.0.0.1:${plain.address().port}`;
|
||||
assert.ok((await fetch(`${plainBase}${ORG}`)).status >= 400);
|
||||
// The owner's dev session on a Console with the routes: the file is served.
|
||||
const owner = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations, log: () => {} }); t.after(() => close(owner));
|
||||
assert.equal((await fetch(`http://127.0.0.1:${owner.address().port}/system-types.js`)).status, 200);
|
||||
assert.equal(reached, 0);
|
||||
await assert.rejects(startServer({ port: 0, sso: createDevOwner(), systemTypesWrite: hit, log: () => {} }), /System types writes need/);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
// Starter packs SP8 (#1873): the owner's template routes on a selected organization, end to end. An
|
||||
// ephemeral organization with the real runtime and the broker's console socket for every call: the read
|
||||
// and the fenced write both bind the business human's console cap, as the Console's consoleCall does.
|
||||
// The SSO session is a fixture authority.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { request } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { busOrganization } from '../../bus/src/organization-context.mjs';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { serve } from '../../bus/src/server.mjs';
|
||||
import { Client } from '../../bus/src/client.mjs';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { TEMPLATE_WRITE_VERBS, TEMPLATES_ROUTE, templatesCaller } from '../src/template-http.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
async function fixture(t, { send = true } = {}) {
|
||||
const undo = []; t.after(async () => { for (const step of undo.reverse()) await step(); });
|
||||
const root = mkdtempSync(join(tmpdir(), 'th-'));
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { ...(doc.plugins ?? {}), harness: ['pi'] };
|
||||
const file = writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const business = loadBusiness('demo', { dir: root, rolesDir });
|
||||
const resolved = Object.fromEntries(Object.keys(business.roles).map(instance => [instance, resolveInstance({ system, business, instance })]));
|
||||
undo.push(() => rmSync(root, { recursive: true, force: true }));
|
||||
const runtime = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: busOrganization(business, resolved) }, organization: { dir: root, rolesDir, system } });
|
||||
undo.push(() => runtime.close());
|
||||
const path = join(root, 'b.sock');
|
||||
const socketServer = await serve({ broker: runtime.broker, path, peerReader: { read: async () => ({}), close: () => {} },
|
||||
authenticateConsole: proof => runtime.broker.bindConsole({ business: 'demo', human: 'jason', subject: proof.subject }) });
|
||||
undo.push(() => socketServer.close());
|
||||
const calls = [];
|
||||
const consoleCall = kind => async (verb, args, ctx) => { calls.push([kind, verb, Object.keys(args).sort()]); return new Client({ path, console: { subject: ctx.subject } }).call(verb, args); };
|
||||
const requestRead = consoleCall('read');
|
||||
const templatesWrite = templatesCaller(consoleCall('write'));
|
||||
const session = { provider: 'fixture', iss: 'https://issuer.example', sub: 'owner', name: 'jason', rootOwner: true };
|
||||
let active = true;
|
||||
const sso = { publicOrigin: '', publicHost: '', formTargets: () => [], session: () => active ? session : null, handle: () => {}, health: () => ({}) };
|
||||
const organizations = {
|
||||
list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }],
|
||||
resolve: async id => id !== 'demo' ? null : { busHealthy: true, send: send ? async () => ({}) : null, requestRead, templatesWrite: send ? templatesWrite : null,
|
||||
reads: { business: async () => ({ business: { id: 'demo' } }) }, bus: {}, chat: { projects: async () => [], threads: async () => [] } },
|
||||
};
|
||||
const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso, send: async () => ({}), organizations, log: () => {} });
|
||||
const base = `http://127.0.0.1:${web.address().port}`;
|
||||
sso.publicOrigin = base; sso.publicHost = new URL(base).host;
|
||||
undo.push(() => close(web));
|
||||
const saved = name => join(root, 'templates', 'jason', `${name}.json`);
|
||||
return { base, file, root, calls, saved, signOut: () => { active = false; }, revokeOwner: () => { session.rootOwner = false; session.user = 'legacy-user'; } };
|
||||
}
|
||||
|
||||
function call(f, path, method = 'GET', body, headers = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const data = body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body);
|
||||
const req = request(f.base + path, { method, headers: { ...(data !== undefined ? { origin: f.base, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}), ...headers } }, res => {
|
||||
let text = ''; res.on('data', chunk => { text += chunk; }); res.on('end', () => resolve([res.statusCode, JSON.parse(text)]));
|
||||
});
|
||||
req.on('error', reject); req.setTimeout(10000, () => req.destroy(new Error('fixture request timed out'))); req.end(data);
|
||||
});
|
||||
}
|
||||
const ORG = '/api/orgs/demo';
|
||||
|
||||
test('SP8 the owner previews a template (nothing written), saves it with the digest, and lists it', async t => {
|
||||
const f = await fixture(t);
|
||||
const [empty, none] = await call(f, `${ORG}/templates`);
|
||||
assert.deepEqual([empty, none], [200, { templates: [], writable: true }]);
|
||||
const before = readFileSync(f.file);
|
||||
const [previewed, preview] = await call(f, `${ORG}/templates/preview`, 'POST', { name: 'demo-shape' });
|
||||
assert.equal(previewed, 200, JSON.stringify(preview));
|
||||
assert.match(preview.digest, /^[a-f0-9]{64}$/);
|
||||
assert.ok(typeof preview.json === 'string' && Array.isArray(preview.freeText));
|
||||
assert.ok(!existsSync(f.saved('demo-shape')), 'preview writes nothing');
|
||||
|
||||
const [stale, staleBody] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: '0'.repeat(64) });
|
||||
assert.deepEqual([stale, staleBody.error], [409, 'pack-plan-stale']);
|
||||
const [savedStatus, out] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: preview.digest });
|
||||
assert.deepEqual([savedStatus, out], [200, { name: 'demo-shape', scope: 'org', digest: preview.digest }]);
|
||||
assert.equal(readFileSync(f.saved('demo-shape'), 'utf8'), preview.json);
|
||||
assert.deepEqual(readFileSync(f.file), before, 'the organization file is unchanged');
|
||||
const [again, againBody] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: preview.digest });
|
||||
assert.deepEqual([again, againBody.error], [400, 'invalid-request']);
|
||||
const [, list] = await call(f, `${ORG}/templates`);
|
||||
assert.deepEqual(list.templates.map(x => [x.name, x.scope]), [['demo-shape', 'org']]);
|
||||
// The preview and the list went over the read; only the saves used the fenced writer.
|
||||
assert.deepEqual(f.calls.map(([kind, verb, keys]) => `${kind} ${verb} ${keys.join(',')}`), [
|
||||
'read template.list.console ', 'read template.save.console name,preview',
|
||||
'write template.save.console digest,name', 'write template.save.console digest,name', 'write template.save.console digest,name',
|
||||
'read template.list.console ',
|
||||
]);
|
||||
});
|
||||
|
||||
test('SP8 the admission checks refuse before any bus call; the writer is fenced to a digest save', async t => {
|
||||
const f = await fixture(t);
|
||||
const digest = 'a'.repeat(64);
|
||||
for (const [label, path, method, body, headers, expected] of [
|
||||
['account field', `${ORG}/templates/preview`, 'POST', { name: 'x', account: 'alex' }, {}, [400, 'invalid-request']],
|
||||
['preview field on save', `${ORG}/templates`, 'POST', { name: 'x', digest, preview: true }, {}, [400, 'invalid-request']],
|
||||
['save without digest', `${ORG}/templates`, 'POST', { name: 'x' }, {}, [400, 'invalid-request']],
|
||||
['bad digest', `${ORG}/templates`, 'POST', { name: 'x', digest: 'zz' }, {}, [400, 'invalid-request']],
|
||||
['dot-dot name', `${ORG}/templates/preview`, 'POST', { name: '..' }, {}, [400, 'invalid-request']],
|
||||
['path name', `${ORG}/templates/preview`, 'POST', { name: 'a/b' }, {}, [400, 'invalid-request']],
|
||||
['bad project', `${ORG}/templates/preview`, 'POST', { name: 'x', project: '../p' }, {}, [400, 'invalid-request']],
|
||||
['not JSON', `${ORG}/templates/preview`, 'POST', '{', {}, [400, 'invalid-request']],
|
||||
['too large', `${ORG}/templates/preview`, 'POST', JSON.stringify({ name: 'x', project: 'p'.repeat(5000) }), {}, [413, 'invalid-request']],
|
||||
['form post', `${ORG}/templates`, 'POST', { name: 'x', digest }, { 'content-type': 'text/plain' }, [400, 'invalid-request']],
|
||||
['cross site', `${ORG}/templates`, 'POST', { name: 'x', digest }, { 'sec-fetch-site': 'cross-site' }, [403, 'cross-origin']],
|
||||
['cross site read', `${ORG}/templates`, 'GET', undefined, { 'sec-fetch-site': 'cross-site' }, [403, 'cross-origin']],
|
||||
['preview by GET', `${ORG}/templates/preview`, 'GET', undefined, {}, [405, 'method-not-allowed']],
|
||||
['list by DELETE', `${ORG}/templates`, 'DELETE', { name: 'x' }, {}, [405, 'method-not-allowed']],
|
||||
]) {
|
||||
const [status, result] = await call(f, path, method, body, headers);
|
||||
assert.deepEqual([status, result.error], expected, label);
|
||||
}
|
||||
assert.equal(f.calls.length, 0, 'no refused request reached the bus');
|
||||
assert.ok(!existsSync(join(f.root, 'templates')));
|
||||
assert.deepEqual(TEMPLATE_WRITE_VERBS, ['template.save.console']);
|
||||
await assert.rejects(templatesCaller(async () => ({}))('template.list.console', {}, {}), /does not call template\.list\.console/);
|
||||
await assert.rejects(templatesCaller(async () => ({}))('template.save.console', { name: 'x', preview: true }, {}), /does not preview/);
|
||||
assert.ok(TEMPLATES_ROUTE.test('/api/templates') && TEMPLATES_ROUTE.test('/api/templates/preview') && !TEMPLATES_ROUTE.test('/api/templates/x'));
|
||||
f.signOut();
|
||||
assert.deepEqual((await call(f, `${ORG}/templates`))[0], 401);
|
||||
});
|
||||
|
||||
test('SP8 without --send the save is read-only; the list and preview still answer', async t => {
|
||||
const f = await fixture(t, { send: false });
|
||||
const [listed, list] = await call(f, `${ORG}/templates`);
|
||||
assert.deepEqual([listed, list.writable], [200, false]);
|
||||
const [previewed, preview] = await call(f, `${ORG}/templates/preview`, 'POST', { name: 'demo-shape' });
|
||||
assert.equal(previewed, 200, JSON.stringify(preview));
|
||||
const [status, result] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: preview.digest });
|
||||
assert.deepEqual([status, result.error], [403, 'read-only']);
|
||||
assert.ok(!existsSync(join(f.root, 'templates')));
|
||||
});
|
||||
|
||||
test('SP8 a session that is not the root owner reaches no template route; neither does a Console without sign-in', async t => {
|
||||
const f = await fixture(t);
|
||||
f.revokeOwner();
|
||||
for (const [path, method, body] of [[`${ORG}/templates`, 'GET'], [`${ORG}/templates/preview`, 'POST', { name: 'x' }], [`${ORG}/templates`, 'POST', { name: 'x', digest: 'a'.repeat(64) }]]) {
|
||||
const [status, result] = await call(f, path, method, body);
|
||||
assert.deepEqual([status, result.error], [403, 'owner-only'], `${method} ${path}`);
|
||||
}
|
||||
assert.equal(f.calls.length, 0);
|
||||
const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', log: () => {} });
|
||||
t.after(() => close(web));
|
||||
const bare = { base: `http://127.0.0.1:${web.address().port}` };
|
||||
for (const [path, method, body] of [['/api/templates', 'GET'], ['/api/templates/preview', 'POST', { name: 'x' }]]) {
|
||||
const [status, result] = await call(bare, path, method, body);
|
||||
assert.deepEqual([status, result.error], [403, 'owner-only'], `${method} ${path}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('SP8 a sign-out while the body is still arriving dispatches nothing', async t => {
|
||||
const f = await fixture(t);
|
||||
const data = JSON.stringify({ name: 'demo-shape', digest: 'a'.repeat(64) });
|
||||
const answer = new Promise((resolve, reject) => {
|
||||
const req = request(`${f.base}${ORG}/templates`, { method: 'POST', headers: { origin: f.base, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } }, res => {
|
||||
let text = ''; res.on('data', chunk => { text += chunk; }); res.on('end', () => resolve([res.statusCode, JSON.parse(text)]));
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.write(data.slice(0, 5));
|
||||
setTimeout(() => { f.signOut(); req.end(data.slice(5)); }, 150);
|
||||
});
|
||||
const [status, body] = await answer;
|
||||
assert.deepEqual([status, body.error], [401, 'sign-in-required']);
|
||||
assert.equal(f.calls.length, 0);
|
||||
});
|
||||
@@ -10,13 +10,12 @@ import { join } from 'node:path';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { systemTypesFake } from './helpers/system-types-fake.mjs';
|
||||
|
||||
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
|
||||
// Three organizations as sample 01 and 03 show them: two running buses and one stopped. P2: each running
|
||||
// organization's System types read comes from the installed modules; `send` adds the owner's writes.
|
||||
function workspaceOrgs({ failThreads = false, seen = null, send = false, types = {}, copies = {}, buses = {} } = {}) {
|
||||
// Three organizations as sample 01 and 03 show them: two running buses and one stopped. `send` adds the
|
||||
// owner's writes.
|
||||
function workspaceOrgs({ failThreads = false, seen = null, send = false, copies = {}, buses = {} } = {}) {
|
||||
const ORGS = [
|
||||
{ id: 'ddigital', label: 'Distinctly Digital', theme: 'rosewood', busHealthy: true },
|
||||
{ id: 'forge', label: 'Forge', theme: 'cobalt', busHealthy: true },
|
||||
@@ -30,8 +29,6 @@ function workspaceOrgs({ failThreads = false, seen = null, send = false, types =
|
||||
const AGENTS = { ddigital: [{ role: 'chief', holder_run: 'r1', state: 'waiting' }, { role: 'copywriter', holder_run: 'r2', state: 'working' }], forge: [] };
|
||||
const claim = (thread, holder_run) => ({ thread, holder_run, harness: 'claude', at: '2026-11-09T12:00:00.000Z' });
|
||||
const CLAIMS = { ddigital: [claim('t3', 'r1'), claim('t1', 'r2'), claim('t2', 'r3')], forge: [] };
|
||||
const TYPES = { ddigital: { enabled: ['coding', 'marketing'], projects: { 'spring-launch': ['coding'], 'brand-refresh': ['marketing'] } }, forge: { enabled: [], projects: { 'api-gateway': [] } }, ...types };
|
||||
const fakes = {};
|
||||
const FILES = { 'spring-launch': ['docs/north-star.md', 'docs/launch-plan.md', 'src/index.js'], 'brand-refresh': ['docs/brand-voice-guide.md'], 'api-gateway': [] };
|
||||
const instances = id => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {},
|
||||
instances: Object.fromEntries(Object.entries(INSTANCES[id]).map(([n, [definition, running]]) => [n, { definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running, alive: [] }])),
|
||||
@@ -45,10 +42,8 @@ function workspaceOrgs({ failThreads = false, seen = null, send = false, types =
|
||||
seen?.push(id);
|
||||
const org = ORGS.find(o => o.id === id); if (!org) return null;
|
||||
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
|
||||
fakes[id] ??= systemTypesFake(TYPES[id]);
|
||||
const st = await fakes[id];
|
||||
return {
|
||||
busHealthy: true, requestRead: st.requestRead, systemTypesWrite: send ? st.systemTypesWrite : null, ...(send ? { send: async () => ({}) } : {}),
|
||||
busHealthy: true, ...(send ? { send: async () => ({}) } : {}),
|
||||
reads: { business: async () => business(id), settings: async () => ({ release: '0.0.42', notifier: { binding: 'discord' }, launch: { limits: { total: 4 } } }),
|
||||
queue: async () => ({ rows: id === 'ddigital' ? [{ state: 'done' }, { state: 'in-progress' }, { state: 'queued' }] : [] }), busStatus: async () => ({}) },
|
||||
// `buses` hands an organization's instance read to a real booted bus instead.
|
||||
@@ -61,7 +56,7 @@ function workspaceOrgs({ failThreads = false, seen = null, send = false, types =
|
||||
}
|
||||
// No bus or setup work runs in these tests: every restart below is refused before the admin is used.
|
||||
const refusingAdmin = () => createOrgAdmin({ service: {}, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
const SETTINGS = ['Identity', 'Appearance', 'System types', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model proxy', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete'];
|
||||
const SETTINGS = ['Identity', 'Appearance', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model proxy', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete'];
|
||||
const TAGS = ['org file', 'override', 'system', 'root', 'not built', 'danger'];
|
||||
// Every page the Settings view has for the owner (bus.js settingsPages).
|
||||
const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-proxy', 'console', 'about'];
|
||||
@@ -138,8 +133,6 @@ test('organization dashboard renders every section from the per-organization rea
|
||||
assert.equal(head.avatar, 'DD'); assert.equal(head.title, 'Distinctly Digital');
|
||||
assert.match(head.meta, /Kind not recorded/); assert.match(head.meta, /id ddigital/); assert.match(head.meta, /Tracker: Vikunja/); assert.match(head.meta, /bus running, read \d/);
|
||||
assert.match(head.colour, /^#[0-9a-f]{6}$/i);
|
||||
// System types: the enabled modules by their own labels (P2).
|
||||
assert.match(await b.evaluate('document.querySelector(".ws-typechips").innerText'), /System types\s+Coding\s*Marketing\s+Each project picks from these/i);
|
||||
// Docs come from the project files reads: only documents, named by project.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-doc")].map(a => a.innerText.replace(/\\s+/g, " ").trim())'), ['North star Spring launch', 'Launch plan Spring launch', 'Brand voice guide Brand refresh']);
|
||||
// KPIs and metrics: one honest empty tile each, with no invented number.
|
||||
@@ -164,8 +157,6 @@ test('organization dashboard renders every section from the per-organization rea
|
||||
for (const s of settings) { assert.ok(s.icon, s.name); assert.ok(s.value, s.name); assert.ok(TAGS.includes(s.tag), `${s.name}: ${s.tag}`); }
|
||||
const by = Object.fromEntries(settings.map(s => [s.name, s]));
|
||||
assert.deepEqual([by['Members and invites'].tag, by['Members and invites'].href], ['not built', null]);
|
||||
assert.deepEqual([by['System types'].tag, by['System types'].value], ['org file', '2 of 5 installed enabled']);
|
||||
assert.equal(await b.evaluate('document.querySelector(\'[data-org-setting="System types"] button.go\').textContent'), 'Open');
|
||||
assert.deepEqual([by['Archive or delete'].tag, by['Archive or delete'].danger, by['Archive or delete'].href], ['danger', true, '#/settings/organizations']);
|
||||
assert.equal(by.Identity.value, 'Distinctly Digital · ddigital · kind not recorded');
|
||||
assert.equal(by['Task tracker'].value, 'Vikunja');
|
||||
@@ -185,8 +176,7 @@ test('organization dashboard empty states say so in one short line', async t =>
|
||||
await waitFor(b)('document.querySelector("[data-org-dashboard] [data-org-settings]")');
|
||||
const text = await b.evaluate('document.querySelector("[data-org-dashboard]").innerText');
|
||||
// Section labels are uppercased by CSS, so innerText carries the uppercase form.
|
||||
// The empty organization has no System types read, so it says unavailable, never that none exist.
|
||||
for (const line of [/System types\s+System types unavailable/i, /Docs\s+No docs yet/i, /No KPIs defined in the organization file/, /No metrics recorded yet/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/])
|
||||
for (const line of [/Docs\s+No docs yet/i, /No KPIs defined in the organization file/, /No metrics recorded yet/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/])
|
||||
assert.match(text, line);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-settings] > li").length'), SETTINGS.length);
|
||||
});
|
||||
@@ -546,7 +536,7 @@ test('agents grid takes a running copy, an unbound copy and a refused project fr
|
||||
const root = { state: 'ok', ...checkRootAgents(rootDoc, { rolesDir }) };
|
||||
const agentLevels = { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } };
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations, agentLevels, log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
|
||||
await b.viewport(1440, 900);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/agents`);
|
||||
await waitFor(b)('document.querySelectorAll(".ws-levels [data-org=ddigital] [data-copy-state]").length === 4');
|
||||
@@ -554,7 +544,8 @@ test('agents grid takes a running copy, an unbound copy and a refused project fr
|
||||
assert.deepEqual(pills, [['gate', 'instance', 'running'], ['researcher', 'unbound', "can't launch"], ['checker', 'instance', 'not running'], ['lint', 'refused', "can't launch"]]);
|
||||
const why = await b.evaluate('Object.fromEntries([...document.querySelectorAll(".ws-levels [data-org=ddigital] [data-copy-why]")].map(n => [n.dataset.copyWhy, n.innerText.trim()]))');
|
||||
assert.deepEqual(Object.keys(why), ['researcher', 'lint.web']);
|
||||
assert.equal(why.researcher, 'researcher: no binding in this organization for gitea');
|
||||
// CB5: the bus adds the binding's next step for a copy missing gitea, a bindable service.
|
||||
assert.equal(why.researcher, 'researcher: no binding in this organization for gitea. credentials.gitea needs an owner-approved binding.');
|
||||
assert.match(why['lint.web'], /^lint: project web refuses its agents: .*ghost/);
|
||||
const text = await b.evaluate('document.body.innerText');
|
||||
for (const value of [SECRET, dir]) assert.equal(text.includes(value), false, value);
|
||||
@@ -625,3 +616,52 @@ test('agents grid shows a running copy, an unbound copy and a refused project wi
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// #1873 CB5: a copy that needs a credential binding carries `binding` from its bus: the status code and
|
||||
// the owner's next step, copy-binding-status.mjs's fixed text. A booted copy whose binding is revoked
|
||||
// can't launch and says the next step; an unbound copy missing gitea adds the step after the services;
|
||||
// a copy whose role also needs a service a copy cannot bind says so, without asking for a gitea
|
||||
// binding; a ready binding launches as before with no reason line. The Console rebuilds each binding
|
||||
// from its status code, so text the bus put in `next` (a sentinel here) never reaches the page.
|
||||
test('agents grid shows a copy\'s binding status and next step, and a ready binding launches', async t => {
|
||||
const { checkRootAgents } = await import('../../organization/src/index.mjs');
|
||||
const { COPY_BINDING_STATUS } = await import('../../organization/src/copy-binding-status.mjs');
|
||||
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
|
||||
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {
|
||||
researcher: { definition: 'research' },
|
||||
reviewer: { definition: 'reviewer' },
|
||||
} }, { rolesDir }) };
|
||||
const DOCS = { ddigital: { roles: { chief: { definition: 'chief-of-staff' } }, projects: {} }, forge: { roles: { chief: { definition: 'chief-of-staff' } }, projects: {} } };
|
||||
const copy = (name, state, extra = {}) => ({ name, level: 'root', project: null, definition: name === 'reviewer' ? 'reviewer' : 'research', state, running: [], ...extra });
|
||||
const SENTINEL = 'cb5-bus-next-sentinel-4c19e2';
|
||||
const binding = (status) => ({ status, next: `${SENTINEL} ${status}`, extra: SENTINEL });
|
||||
const copies = {
|
||||
ddigital: { researcher: copy('researcher', 'instance', { bound: ['gitea'], binding: binding('credential-revoked') }),
|
||||
reviewer: copy('reviewer', 'unbound', { missing: ['gitea'], binding: binding('issue-required') }) },
|
||||
forge: { researcher: copy('researcher', 'instance', { bound: ['gitea'], running: ['r4'], binding: binding('ready') }),
|
||||
reviewer: copy('reviewer', 'unbound', { missing: ['gitea', 'vikunja'], binding: binding('copy-service-unbindable') }) },
|
||||
};
|
||||
const orgs = workspaceOrgs({ copies });
|
||||
const organizations = { ...orgs, members: async () => Object.entries(DOCS).map(([id, doc]) => ({ id, doc })) };
|
||||
const agentLevels = { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } };
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations, agentLevels, log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
|
||||
await b.viewport(1440, 900);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/agents`);
|
||||
await waitFor(b)('document.querySelectorAll(".ws-levels [data-org=ddigital] [data-copy-state], .ws-levels [data-org=forge] [data-copy-state]").length === 4');
|
||||
const pills = await b.evaluate('[...document.querySelectorAll(".ws-levels [data-org=ddigital], .ws-levels [data-org=forge]")].flatMap(c => [...c.querySelectorAll("[data-copy-state]")].map(p => [c.dataset.org, p.dataset.levelAgent, p.dataset.copyState, p.querySelector(".ws-dot").title]))');
|
||||
assert.deepEqual(pills, [
|
||||
['ddigital', 'researcher', 'instance', "can't launch"], ['ddigital', 'reviewer', 'unbound', "can't launch"],
|
||||
['forge', 'researcher', 'instance', 'running'], ['forge', 'reviewer', 'unbound', "can't launch"],
|
||||
]);
|
||||
const why = await b.evaluate('Object.fromEntries([...document.querySelectorAll(".ws-levels [data-org=ddigital], .ws-levels [data-org=forge]")].flatMap(c => [...c.querySelectorAll("[data-copy-why]")].map(n => [`${c.dataset.org}:${n.dataset.copyWhy}`, n.innerText.trim()])))');
|
||||
assert.deepEqual(why, {
|
||||
'ddigital:researcher': `researcher: ${COPY_BINDING_STATUS['credential-revoked']}`,
|
||||
'ddigital:reviewer': `reviewer: no binding in this organization for gitea. ${COPY_BINDING_STATUS['issue-required']}`,
|
||||
'forge:reviewer': `reviewer: no binding in this organization for gitea, vikunja. ${COPY_BINDING_STATUS['copy-service-unbindable']}`,
|
||||
});
|
||||
assert.equal((await b.evaluate('document.body.innerText')).includes(SENTINEL), false);
|
||||
const rows = await b.evaluate('Object.fromEntries([...document.querySelectorAll("[data-agents-available] tbody tr")].map(tr => [tr.cells[0].innerText.trim().split(/\\s/)[0], tr.cells[4].innerText.replace(/\\s+/g, " ").trim()]))');
|
||||
assert.equal(rows.researcher, `▲ can't launch ${COPY_BINDING_STATUS['credential-revoked']}`);
|
||||
assert.equal(rows.reviewer, `▲ can't launch no binding in this organization for gitea. ${COPY_BINDING_STATUS['issue-required']}`);
|
||||
});
|
||||
@@ -8,7 +8,6 @@ test('integrated project settings and conversation mounts use authorized context
|
||||
[`GET /api/chat/rooms/${ids.project}/messages?limit=100`]: {status:503,body:{error:'fixture-unavailable'}},
|
||||
'GET /api/project-files?project=fixture-repository': {status:503,body:{error:'fixture-unavailable'}},
|
||||
'GET /api/project-file?project=fixture-repository&path=spec%2Fnorth-star.md': {status:503,body:{error:'fixture-unavailable'}},
|
||||
[`GET /api/system-types/projects/${ids.project}`]: {status:503,body:{error:'fixture-unavailable'}},
|
||||
'/api/project-remotes/fixture-repository': { project: ids.repository, remote: null, revision: 'a'.repeat(64), firstSaveAllowed: true },
|
||||
};
|
||||
const { f, b, wait } = await w15Fixture(t, { scenario });
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user