Compare commits

...
9 Commits
Author SHA1 Message Date
jason.woltje 34dd331016 fix(packs): SP5 re-check, the inline pin digest is canonicalJson's for integer-like keys (#1873)
digestPrd rebuilds an object, so integer-like keys come first and the JSON
differs from canonicalJson, the digest the pack apply records. An inline
entry with such a key (a credential scope map group) refused as stale on
every raise. The broker now builds the canonical string itself, a local copy
of util.mjs canonicalJson, so the sandbox import closure is unchanged.
2026-11-12 19:05:33 -06:00
jason.woltje 808b2b7cbf fix(packs): SP5 review round, broker import closure, no-op spend, role.hire before the read, template-named steps (#1873)
The broker no longer imports organization util or definitions; the proposal
pin digest is digestPrd and the inline composition is built in place, so the
sandbox client import closure project-runtime.test.mjs pins is unchanged.
An agent apply the runtime skips (a repeat that adds nothing) never reaches
beforeWrite and spends no grant. A proposal raise checks role.hire before it
reads the packs list. An agent apply keeps a workflow step only for a pack
role the organization defines or one the pack pins to the template of that
name; an inline definition sharing a template's name is left out. Tests: a
repeat apply spends nothing, apply then raise end to end with the broker
booted from the file, a project pack, the template-name shadow, and a chief
without role.hire; the revision refusal is matched exactly.
2026-11-12 19:05:33 -06:00
jason.woltje 5ffe38e3b2 feat(packs): the chief applies a pack's non-definition half and raises hires from its proposals (#1873 SP5)
pack.preview, pack.apply, board.set and workflow.set accept an agent session whose role
lists organization.change (Jason 11-12 Q2): the check runs before the read, and the grant
is spent once after a write commits. A role without it gets decision-required. The packs
read lists packs for a within-role holder and spends nothing.

An agent apply never writes a definition. A definition a human apply would add is marked
not-written and its hire is pinned to the template or the inline entry. A workflow step
naming such a definition is left out and listed, and a workflow left with no steps is not
written. A definitions rename or a saved template refuses human-required, with the writer's
own guard behind both.

hire.raise takes {proposal: {pack, project?, hire}, route, reason?} from the chief. The broker
reads the recorded proposal, checks an inline pin's hash (starter-pack-proposal-stale) and
launch.noHire, and hands the pin to the hire service, which refuses a moved template or
definition as decision-stale or definition-rev-conflict.
2026-11-12 19:05:33 -06:00
jason.woltje 991eb8c332 fix(webui): SP6 review round, the writer's workflow name rule, no silent replace, preview redraw (#1873)
The workflow editor checks the writer's PLAN_NAME (lowercase letters, digits
and dashes, starting with a letter), so a name the bus would refuse no longer
reaches it with step guidance. A new workflow under a name its scope already
holds is refused on the page instead of replacing that workflow. A pack
preview the page cannot draw says so rather than leaving Preview disabled.
The browser test launches Chromium with --disable-extensions.
2026-11-12 18:40:34 -06:00
jason.woltje 504fcd9220 fix(webui): pack preview reads credential lines as {service, scope} objects (#1873 SP6)
The bus sends each hire's credential lines as {service, scope} (scope absent
when a definition names a service without scopes). The picker destructured
them as tuples, so a real preview threw and never rendered. The browser test
fixture now uses the producer's shape.
2026-11-12 18:31:21 -06:00
jason.woltje 154c2216f3 feat(webui): board labels, pack picker and workflow editor on the organization page (#1873 SP6)
The Tasks board takes the selected organization's board: its labels and column order over the five
fixed states, and its default layout unless the viewer saved one. The all-organizations view keeps
the fixed labels. The organization page gains the owner's starter pack picker (list, preview with
marks, flagged lines, credential lines and noHire marks, apply by digest) and a workflow list and
editor that marks a step role naming no current role. Every organization- or pack-supplied string
goes through esc or textContent.

The workspace read carries each organization's and project's board. GET /api/orgs/<id>/workflows
is the owner's read of the workflows, the role names a step may resolve to and the file revision.
packsServes pins HEAD and GET /api/board to the Board read, never the pack route.
2026-11-12 18:17:26 -06:00
jason.woltje 9a649abf85 fix(packs): SP4 re-check, the board route method split, human role reserved, distinct step roles (#1873)
- serve.mjs: only GET and HEAD /api/board stay the Board read; every
  other method goes to the pack route, so DELETE and PUT answer its 405
  again. The owner-only check moves inside packsHTTP after the method
  check, so OPTIONS on a root Console stays 405 as before SP4.
- runtime.mjs: a --as rename cannot target the definition name human,
  and a human step role never follows a rename. A step whose mapped
  roles collide refuses invalid-request at preview, not only at apply.
- The no-op apply skip also needs the same pack sha256, so a changed
  pack with nothing to add still records its entry.
- Tests: the --as refusals for human, a step role collision, a pack
  defining human, a changed saved pack recording its entry, board by
  PUT, a granted session refused owner-only on every pack route, and a
  Console without sign-in refused owner-only.
2026-11-12 17:17:19 -06:00
jason.woltje 1ba3288bec fix(packs): SP4 review round, --as collisions, step roles, the board route and repeat applies (#1873)
- An --as target that lands on another pack item's name refuses invalid-request
  (definitions and workflows); the preview no longer shows two adds for one path.
- A workflow step role naming one of the pack's definitions follows its --as rename,
  so an inline definition renamed at preview applies.
- GET /api/board stays the Board read; only POST /api/board is the pack board write.
- Tombstones key on pack id, origin and project: a saved template reusing a shipped
  id is another pack.
- An apply that adds nothing and proposes what the last apply proposed writes
  nothing, so retries do not fill the 256 packs entries.
- mosaic org pack list refuses inside an agent run like the other words.
- Tests pin coder-1's credential lines, skills.notEnabled and the member's
  unsuffixed pack.apply and board.set refusals; the CONSOLE_VERBS pins in two bus
  tests name the five pack verbs.
2026-11-12 17:03:56 -06:00
jason.woltje 079ced93f3 feat(packs): pack, board and workflow verbs, routes and CLI words (#1873 SP4)
Design section 8. The bus answers packs, pack.preview, pack.apply,
board.set and workflow.set to the organization's human, and their
.console forms to the owner's Console cap. The broker runs the section 3
merge, the plan digest (pack-plan-stale on a mismatch) and the held
credential check. The organization writer keeps packs, board and
workflows out of the generic write and refuses definition writes to
every actor name an agent carries, project agents included.

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

No files matched your search

+120 -1
View File
@@ -182,7 +182,9 @@ export const CONSOLE_VERBS = Object.freeze(['system-types.console', 'project.rem
// 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']);
'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']);
// 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',
@@ -208,6 +210,17 @@ export const DEFINITION_BUS_KEYS = Object.freeze({
'definition.edit': [['revision', 'rev', 'name', 'definition'], ['revision', 'rev', 'name', 'definition']],
'definition.remove': [['revision', 'rev', 'name'], ['revision', 'rev', 'name']],
});
// #1873 SP4: the starter-pack, board and workflow verbs, each with its [allowed, required] argument
// keys. The CLI calls the unsuffixed name as the owner's human cap, the Console the .console one.
// None is a tester verb: TESTER_ORGANIZATION_VERBS stays as it is.
const PACK_KEYS = Object.freeze({
'packs': [[], []],
'pack.preview': [['pack', 'project', 'as'], ['pack']],
'pack.apply': [['pack', 'project', 'as', 'digest'], ['pack', 'digest']],
'board.set': [['revision', 'board', 'project'], ['revision', 'board']],
'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]])));
// 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']);
@@ -6274,6 +6287,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);});
@@ -6281,6 +6297,52 @@ export class Broker {
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
if (request.verb === 'grants.scope' || request.verb === 'grants.scope.set')
return this.#grantScopeVerb(s, request.verb, structuredClone(args));
// #1873 SP4: the owner's starter packs, board and workflows. Only the organization's owner calls
// them: the human cap from the CLI, or the owner's console cap (a hire member's cap is refused
// above). The tester is refused before any argument check. A preview and an apply raise no
// decision; the hires a plan proposes skip any an open hire decision already names.
if (Object.hasOwn(PACK_BUS_KEYS, request.verb)) {
if (s.tester) fail('tester-refused');
const owner = this.#business(s.business).human;
// #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), 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);
}
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
// file lists organization.change. It takes the same keys, runs the same write path and
@@ -6629,6 +6691,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.
@@ -6885,6 +6995,15 @@ export class Broker {
};
return result?.then ? result.then(finish) : finish(result);
}
// #1873 SP4: a pack, board or workflow refusal passes by its code when it is one the plan's checks
// name; a file check (BusinessError) is invalid-request, anything else outcome-unknown.
#packFail(e) {
const code = e?.code ?? '';
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured'].includes(code)
|| /^(starter-pack|definition|organization)-[a-z-]+$/.test(code)) fail(code);
if (e?.name === 'BusinessError') fail('invalid-request');
throw new BusError('outcome-unknown');
}
// 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) {
+14
View File
@@ -204,6 +204,20 @@ group(
"R8: a pack's hash pin must match the current template",
"The template the pack pins has changed since the pack was written. Review the current template, then re-pin the pack to its new hash, or use a pack that already matches."
);
// #1873 SP4: apply writes exactly the plan the owner previewed. The digest binds the plan to the
// organization file's revision; any change in between refuses.
group(
"pack-plan-stale",
"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."
);
group(
"not-resolver",
"Role resolve right and decision route",
+258 -3
View File
@@ -1,5 +1,5 @@
import { autonomyHost, authorityHost } from './autonomy-host.mjs';
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
import { credentialLines, hireDecisions } from '../../organization/src/hire-decisions.mjs';
import { organizationPlugins } from '../../plugins/src/organization.mjs';
import { pluginService } from '../../plugins/src/tools.mjs';
import { readPluginLock } from '../../plugins/src/pinned.mjs';
@@ -40,7 +40,10 @@ import { ModelKeys, modelOrganization, stopModelRuns, MODEL_STOP_TIMEOUT_MS } fr
import { instanceSettings } from '../../organization/src/instance-settings.mjs';
import { organizationWriter, OrganizationError, setReplyLimits } from '../../organization/src/organization.mjs';
import { definitionVerbs, DEFINITION_BUS_VERBS } from '../../organization/src/definition-verbs.mjs';
import { ORG_PREFIX, orgDefinitionName } from '../../organization/src/definitions.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 { checkComposition } from '../../organization/src/composition.mjs';
import { validateBusinessDocument } from '../../organization/src/organization-config.mjs';
import { DEFINITION_HOLDS_CREDENTIAL, heldPath, scanDefinitions } from './definition-scan.mjs';
import { ROLE_RIGHTS } from '../../organization/src/org-rights.mjs';
import { getProjectRemote } from '../../organization/src/project-remotes.mjs';
@@ -52,7 +55,7 @@ import { copyRevoker as makeCopyRevoker, giteaCopyRemote } from './copy-revoke.m
import { readOrgEntrySync } from '../../organization/src/org-registry.mjs';
import { loadRole } from '../../organization/src/role.mjs';
import { resolveInstance } from '../../organization/src/resolve.mjs';
import { canonicalJson } from '../../organization/src/util.mjs';
import { canonicalJson, sha256 as textSha256 } from '../../organization/src/util.mjs';
import { selectModelProvider } from '../../plugins/src/model-provider-selection.mjs';
import { busOrganization } from './organization-context.mjs';
import { webService } from './web.mjs';
@@ -286,6 +289,247 @@ function modelRunInventory(dataRoot, bound, credentials) {
// #1873 CB4: how often the bus re-checks the copies holding a grant, and retries a pending revoke.
const COPY_SWEEP_MS = 60000;
// #1873 SP4: the human's pack, board and workflow ops (design section 3). preview reads the pack and
// the organization file and returns the plan with each item's mark, the lines each proposed hire
// would carry against the chief, the noHire marks and the skills this machine has not enabled, plus
// a digest of the plan and the file revision. apply rebuilds the plan, refuses pack-plan-stale when
// the digest differs and commits it in one applyPack. board.set and workflow.set are one-key plans.
// Nothing here reads a saved template but the caller's own (readSavedTemplate, account = actor), and
// a pack's origin comes from where it was found, never from the request.
const PACK_AS = /^(definitions|workflows)\.([a-z0-9][a-z0-9._-]{0,63})=([a-z0-9][a-z0-9._-]{0,63})$/;
const SAVED_PREFIX = 'saved:';
// Each op, and whether it writes.
const PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.apply': true, 'board.set': true, 'workflow.set': true });
const EMPTY_CHIEF = Object.freeze({ tools: [], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] });
function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean, configDir }) {
const bad = () => { throw new BusError('invalid-request'); };
const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v);
const scan = value => {
if (typeof value === 'string') assertClean(value);
else if (value !== null && typeof value === 'object') for (const [k, v] of Object.entries(value)) { assertClean(k); scan(v); }
};
const installed = async () => (await installedStarterPacks({ dataRoot, rolesDir })).packs;
async function loadPack(name, actor) {
if (typeof name !== 'string' || name.length > 128) bad();
if (name.startsWith(SAVED_PREFIX)) return readSavedTemplate({ configDir, account: actor, name: name.slice(SAVED_PREFIX.length), rolesDir });
const found = (await installed()).find(p => p.id === name);
if (!found) throw new BusError('starter-pack-not-found');
return found;
}
function renames(as) {
const out = { definitions: new Map(), workflows: new Map() };
if (as === undefined) return out;
if (!Array.isArray(as) || as.length > 32) bad();
for (const value of as) {
const m = typeof value === 'string' ? PACK_AS.exec(value) : null;
// `human` is the reserved step role: no rename may write a definition by that name.
if (!m || out[m[1]].has(m[2]) || [...out[m[1]].values()].includes(m[3]) || (m[1] === 'definitions' && m[3] === 'human')) bad();
out[m[1]].set(m[2], m[3]);
}
return out;
}
// The entry a pack definition writes: a template reference becomes the template's own entry, pinned
// by its hash (a moved hash refuses), and a full entry is copied as it is. Neither carries rev.
function entryOf(value) {
if (Object.hasOwn(value, 'template') && Object.hasOwn(value, 'sha256') && Object.keys(value).length === 2) {
const template = readTemplate(rolesDir, value.template);
if (template.sha256 !== value.sha256) throw new BusError('starter-pack-template-changed');
const { rev: _rev, ...entry } = entryFromTemplate(template);
return { entry, ref: { template: value.template, sha256: value.sha256 } };
}
return { entry: structuredClone(value), ref: null };
}
function chiefOf(doc, file) {
const loaded = validateBusinessDocument(doc, file, { rolesDir, dataRoot });
const chief = loaded.definitions[doc.roles?.[doc.launch?.by]?.definition];
if (!chief) return null;
return { ...chief, ...resolveInstance({ system, business: loaded, instance: doc.launch.by }).limits };
}
// Each earlier packs entry of this id and origin (and, for a project pack, this project) lists what
// it added; an item absent now that one of them added was removed on purpose, so it stays removed.
// 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;
const origin = found.origin;
let project = null;
if (pack.scope === 'org') { if (args.project !== undefined) bad(); }
else {
project = args.project;
const entry = typeof project === 'string' && Object.hasOwn(doc.projects ?? {}, project) ? doc.projects[project] : null;
if (!isObject(entry) || entry.kind === 'library') bad();
}
const as = renames(args.as);
for (const name of as.definitions.keys()) if (!Object.hasOwn(pack.definitions, name)) bad();
for (const name of as.workflows.keys()) if (!Object.hasOwn(pack.workflows, name)) bad();
// Two pack items of one kind never land on one name: a rename onto another item's own name
// would show both as add while the later one replaced the earlier in the plan.
for (const kind of ['definitions', 'workflows']) {
const targets = Object.keys(pack[kind]).map(name => as[kind].get(name) ?? name);
if (new Set(targets).size !== targets.length) bad();
}
scan(pack);
const gone = tombstones(doc, pack.id, origin, project);
const scope = project === null ? doc : doc.projects[project];
const prefix = project === null ? '' : `projects.${project}.`;
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.
const definitions = {};
const checked = {};
for (const [name, value] of Object.entries(pack.definitions)) {
const target = as.definitions.get(name) ?? name;
const { entry, ref } = entryOf(value);
const { composition, flagged } = checkComposition(compositionOf(entry), registry, chief ?? EMPTY_CHIEF, { assertClean });
checked[name] = { target, entry, ref, flagged: chief ? flagged : null, credentialLines: credentialLines(composition.credentials) };
const path = `definitions.${target}`;
const current = doc.definitions?.[target];
let mark;
if (current === undefined) mark = gone.has(path) ? 'removed' : 'add';
else mark = canonicalJson(compositionOf(current)) === canonicalJson(compositionOf(entry)) ? 'same' : 'kept';
const item = { item: 'definition', name, target, path, mark };
if (mark === 'kept') {
const before = compositionOf(current), after = compositionOf(entry);
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);
}
if (Object.keys(definitions).length) plan.definitions = definitions;
{
const path = `${prefix}board`;
let mark;
if (scope.board === undefined) mark = gone.has(path) ? 'removed' : 'add';
else mark = canonicalJson(scope.board) === canonicalJson(pack.board) ? 'same' : 'kept';
items.push({ item: 'board', path, mark });
if (mark === 'add') plan[path] = structuredClone(pack.board);
}
const workflows = {};
for (const [name, value] of Object.entries(pack.workflows)) {
const target = as.workflows.get(name) ?? name;
// The step ids are the pack's own; the organization's workflow keeps title, state and roles.
// A role naming one of this pack's definitions follows that definition's --as rename; the
// reserved `human` role never moves. A step whose mapped roles collide refuses here, not at apply.
const role = r => r !== 'human' && Object.hasOwn(pack.definitions, r) ? as.definitions.get(r) ?? r : r;
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 (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, ...(leftOut.length ? { leftOut } : {}) });
if (mark === 'add') workflows[target] = workflow;
}
if (Object.keys(workflows).length) plan[`${prefix}workflows`] = workflows;
// A proposal is filled when an instance by that name exists, or an open hire decision names it.
const instances = project === null ? doc.roles ?? {} : doc.projects[project].agents ?? {};
const openHires = context?.openHires ?? [];
const hires = [];
const proposedHires = [];
for (const hire of pack.hires) {
const d = checked[hire.definition];
const dropped = Object.hasOwn(instances, hire.name) || openHires.some(h => h.name === hire.name && (h.project ?? null) === project);
const pin = d.added ? { definition: d.target, rev: 1 } : d.ref ? { ...d.ref } : { inline: d.target, sha256: textSha256(canonicalJson(d.entry)) };
const marked = [d.target, hire.definition, d.ref?.template, d.entry.from?.template].some(n => n !== undefined && noHire.includes(n));
hires.push({ name: hire.name, definition: d.target, mark: dropped ? 'dropped' : 'propose', pin, flagged: d.flagged, credentialLines: d.credentialLines, noHire: marked });
if (!dropped) proposedHires.push({ name: hire.name, reason: hire.reason, pin, ...(Object.hasOwn(pin, 'inline') ? { entry: structuredClone(d.entry) } : {}) });
}
plan.packs = { id: pack.id, version: pack.version, sha256: textSha256(canonicalJson(pack)), origin, scope: pack.scope, project, proposedHires };
scan(plan);
const notEnabled = pack.skills.filter(name => { try { lstatSync(join(dataRoot, 'skills-enabled', name)); return false; } catch { return true; } });
const digest = textSha256(canonicalJson({ plan, revision }));
return {
pack: { id: pack.id, version: pack.version, label: pack.label, origin, scope: pack.scope }, project, revision,
items, hires, skills: { notEnabled }, chief: chief !== null, plan, digest,
};
}
// 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 };
};
const scoped = (args, key) => {
if (args.project === undefined) return key;
if (typeof args.project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.project)) bad();
return `projects.${args.project}.${key}`;
};
const revisionOf = args => { if (typeof args.revision !== 'string' || !/^[0-9a-f]{64}$/.test(args.revision)) bad(); return args.revision; };
return {
// Shipped and installed packs only: a saved template is its owner's, read by name.
packs: async () => ({ packs: (await installed()).map(({ id, origin, pack }) => ({ id, origin, pack })) }),
'pack.preview': (id, args, actor, context) => build(id, args, actor, context),
'pack.apply': async (id, args, actor, context) => {
if (typeof args.digest !== 'string') bad();
const preview = await build(id, args, actor, context);
if (preview.digest !== args.digest) throw new BusError('pack-plan-stale');
// An apply of the same pack (same sha256) that adds nothing and proposes what the last apply of
// it proposed writes nothing, so a retry loop does not fill the packs list to its cap. A changed
// pack still records its entry. The digest pins the revision.
const { plan } = preview;
const last = (writer.read(id).document.packs ?? []).filter(e => sameApply(e, plan.packs.id, plan.packs.origin, plan.packs.project)).at(-1);
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, {}, context), pack: preview.pack.id };
},
'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, {}, context);
},
'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, {}, context);
},
};
}
export async function startBroker({
dataRoot,
instanceRoot = null,
@@ -932,6 +1176,17 @@ export async function startBroker({
known.set(id, canonicalJson(next.projects));
return getProjectRemote(writer, id, args.project);
}
// #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 });
const out = ops[verb](id, args, actor, context);
if (!PACK_OPS[verb]) return out;
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'] ?? [];
if(verb==='limits')return withTokens(id,settings.read(id));
+3 -1
View File
@@ -90,7 +90,9 @@ function setup(t) {
// 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',
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.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']);
assert.ok(CONSOLE_VERBS.every(verb => verb.endsWith('.console')));
assert.equal(CONSOLE_VERBS.includes('decision.resolve'), false);
assert.ok(Object.isFrozen(CONSOLE_VERBS));
+384
View File
@@ -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));
});
+402
View File
@@ -0,0 +1,402 @@
// #1873 SP4: starter packs at the bus. The owner previews and applies a pack; the plan is the write.
// Preview writes nothing; apply writes only what preview marked `add` plus one packs entry, and
// raises no decision. board.set and workflow.set are one-key plans through the same writer.
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 { PACK_BUS_KEYS, TESTER_ORGANIZATION_VERBS } from '../src/broker.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';
const TOKEN = 'fixture-held-token-sp4-7d1f2b';
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 root = mkdtempSync(join(tmpdir(), 'packs-'));
const rolesDir = rolesCopy(root);
const doc = businessDoc(root, 'demo');
doc.plugins = { harness: ['pi'] };
mutate(doc);
writeJson(join(root, 'businesses/demo.json'), doc);
const other = businessDoc(join(root, 'b2'), 'other');
other.human = 'alex';
writeJson(join(root, 'businesses/other.json'), other);
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 },
other: { id: 'other', human: 'alex', arbiters: { technical: 'chief', delivery: 'chief' }, roles: { chief: roles.chief } },
};
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
// An installed plugin's directories are read-only; open them so the scratch tree can go.
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 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 file = () => JSON.parse(readFileSync(path, 'utf8'));
const revision = () => b.request(human, { verb: 'limits' }).revision;
// A pack installed on this machine (origin installed), as the plugin installer writes it.
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 });
};
// A pack an owner saved, under <configDir>/templates/<account>/<name>.json (origin saved).
const save = (account, name, pack) => {
const dir = join(root, 'templates', account);
mkdirSync(dir, { recursive: true, mode: 0o700 });
chmodSync(join(root, 'templates'), 0o700);
chmodSync(dir, 0o700);
writeFileSync(join(dir, `${name}.json`), JSON.stringify(pack), { mode: 0o600 });
};
const decisions = () => ['roles', 'recent'].map(list => bus.broker.request(human, { verb: 'decisions', args: { list } }));
return { bus, b, root, rolesDir, path, consoleOwner, human, call, file, revision, install, save, decisions };
}
// A pack built from the shipped coding pack, renamed and patched.
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('SP4 preview writes nothing; apply writes the add items and one packs entry, raises no decision, and a second apply is all same', async t => {
const { call, file, path, decisions, root, rolesDir } = await harness(t);
const before = readFileSync(path);
const decided = JSON.stringify(decisions());
const preview = await call('pack.preview.console', { pack: 'coding' });
assert.deepEqual(readFileSync(path), before);
assert.equal(preview.pack.origin, 'shipped');
assert.ok(preview.items.every(i => i.mark === 'add'), JSON.stringify(preview.items));
assert.deepEqual(preview.hires.map(h => [h.name, h.mark, h.noHire]), [['pm-1', 'propose', false], ['coder-1', 'propose', false], ['reviewer-1', 'propose', false]]);
// The chief is known, so every proposed hire lists its flagged and credential lines.
assert.equal(preview.chief, true);
for (const h of preview.hires) { assert.ok(Array.isArray(h.flagged)); assert.ok(Array.isArray(h.credentialLines)); }
// coder-1's credential lines name the services the coder template reaches.
const coderServices = JSON.parse(readFileSync(join(rolesDir, 'coder.json'), 'utf8')).credentials.map(c => c.service).sort();
assert.ok(coderServices.length > 0);
const lines = preview.hires.find(h => h.name === 'coder-1').credentialLines;
assert.ok(lines.length >= coderServices.length);
assert.deepEqual([...new Set(lines.map(l => l.service))].sort(), [...new Set(coderServices)]);
// On an empty data root every pack skill is not enabled; an enabled one drops out.
assert.deepEqual(preview.skills.notEnabled, codingPack().skills);
mkdirSync(join(root, 'data', 'skills-enabled', 'ms-sdlc'), { recursive: true });
assert.deepEqual((await call('pack.preview.console', { pack: 'coding' })).skills.notEnabled, codingPack().skills.filter(n => n !== 'ms-sdlc'));
assert.match(preview.digest, /^[0-9a-f]{64}$/);
const out = await call('pack.apply.console', { pack: 'coding', digest: preview.digest });
assert.equal(out.pack, 'coding');
const after = file();
assert.deepEqual(Object.keys(after.definitions).sort(), ['coder', 'cto', 'merge-gate', 'pm', 'reviewer', 'security-reviewer']);
assert.equal(after.board.layout, 'kanban');
// The organization's workflow drops the pack's step ids.
assert.deepEqual(after.workflows.change.steps[0], { title: 'Write the task', state: 'todo', roles: ['pm'] });
assert.ok(after.workflows.change.steps.every(s => !Object.hasOwn(s, 'id')));
assert.equal(after.packs.length, 1);
const entry = after.packs[0];
assert.equal(entry.id, 'coding');
assert.equal(entry.origin, 'shipped');
assert.ok(entry.added.includes('definitions.coder') && entry.added.includes('board') && entry.added.includes('workflows.change'));
assert.deepEqual(entry.proposedHires.find(h => h.name === 'coder-1').pin, { definition: 'coder', rev: 1 });
// No decision is raised: the owner hires from the proposals later.
assert.equal(JSON.stringify(decisions()), decided);
const again = await call('pack.preview.console', { pack: 'coding' });
assert.ok(again.items.every(i => i.mark === 'same'), JSON.stringify(again.items));
await call('pack.apply.console', { pack: 'coding', digest: again.digest });
assert.deepEqual(file().definitions, after.definitions);
assert.deepEqual(file().workflows, after.workflows);
// An apply that adds nothing and proposes what the last apply proposed writes nothing at all.
const settled = readFileSync(path);
const third = await call('pack.preview.console', { pack: 'coding' });
const out3 = await call('pack.apply.console', { pack: 'coding', digest: third.digest });
assert.deepEqual(out3.added, []);
assert.equal(out3.revision, third.revision);
assert.deepEqual(readFileSync(path), settled);
assert.equal(file().packs.length, 2);
});
test('SP4 a stale digest refuses pack-plan-stale and writes nothing', async t => {
const { call, path, revision } = await harness(t);
const preview = await call('pack.preview.console', { pack: 'coding' });
await call('workflow.set.console', { revision: revision(), name: 'intake', workflow: { description: 'Intake.', steps: [{ title: 'Take it', state: 'todo', roles: ['human'] }] } });
const before = readFileSync(path);
await assert.rejects(call('pack.apply.console', { pack: 'coding', digest: preview.digest }), /pack-plan-stale/);
await assert.rejects(call('pack.apply.console', { pack: 'coding', digest: 'f'.repeat(64) }), /pack-plan-stale/);
assert.deepEqual(readFileSync(path), before);
});
test('SP4 an edited definition is kept with its diff; a removed item stays removed; another pack naming it adds it', async t => {
const { call, human, file, revision, install, save } = await harness(t);
const first = await call('pack.preview.console', { pack: 'coding' });
await call('pack.apply.console', { pack: 'coding', digest: first.digest });
const coder = file().definitions.coder;
const { rev } = coder;
const definition = { role: coder.role, instructions: `${coder.instructions}Keep each change small.\n`, ...(coder.personality === undefined ? {} : { personality: coder.personality }) };
await call('definition.edit', { revision: revision(), rev, name: 'coder', definition }, human);
await call('definition.remove', { revision: revision(), rev: file().definitions.reviewer.rev, name: 'reviewer' }, human);
await call('board.set.console', { revision: revision(), board: null });
await call('workflow.set.console', { revision: revision(), name: 'change', workflow: null });
assert.equal(file().board, undefined);
assert.equal(file().workflows?.change, undefined);
const next = await call('pack.preview.console', { pack: 'coding' });
const m = marks(next);
assert.equal(m['definitions.coder'], 'kept');
assert.deepEqual(next.items.find(i => i.path === 'definitions.coder').diff.primitives, ['instructions']);
assert.equal(m['definitions.reviewer'], 'removed');
assert.equal(m.board, 'removed');
assert.equal(m['workflows.change'], 'removed');
assert.equal(m['definitions.pm'], 'same');
// The reviewer instance, its definition gone, pins the template the pack names.
assert.deepEqual(next.hires.find(h => h.name === 'reviewer-1').pin, { template: 'reviewer', sha256: codingPack().definitions.reviewer.sha256 });
const kept = file();
await call('pack.apply.console', { pack: 'coding', digest: next.digest });
assert.deepEqual(file().definitions, kept.definitions);
assert.equal(file().board, undefined);
assert.deepEqual(file().packs.at(-1).added, []);
// A different pack naming the same items adds them: a tombstone is per pack.
install(variant('teamkit'));
const other = await call('pack.preview.console', { pack: 'teamkit' });
assert.equal(other.pack.origin, 'installed');
const o = marks(other);
assert.equal(o['definitions.reviewer'], 'add');
assert.equal(o.board, 'add');
assert.equal(o['workflows.change'], 'add');
assert.equal(o['definitions.coder'], 'kept');
// A saved template reusing the shipped id is another pack: the shipped apply's removals don't bind it.
save('jason', 'mine', variant('coding'));
const mine = await call('pack.preview.console', { pack: 'saved:mine' });
assert.equal(mine.pack.origin, 'saved');
assert.equal(marks(mine)['definitions.reviewer'], 'add');
assert.equal(marks(mine).board, 'add');
});
test('SP4 --as renames a definition or workflow and pins the hire to the new name; a bad rename refuses', async t => {
const { call, file } = await harness(t);
const preview = await call('pack.preview.console', { pack: 'coding', as: ['definitions.coder=builder', 'workflows.change=ship'] });
const m = marks(preview);
assert.equal(m['definitions.builder'], 'add');
assert.equal(m['workflows.ship'], 'add');
assert.deepEqual(preview.hires.find(h => h.name === 'coder-1').pin, { definition: 'builder', rev: 1 });
await call('pack.apply.console', { pack: 'coding', as: ['definitions.coder=builder', 'workflows.change=ship'], digest: preview.digest });
assert.ok(file().definitions.builder);
assert.equal(file().definitions.coder, undefined);
assert.ok(file().workflows.ship);
// A rename onto another pack item's own name would show both as add while one replaced the other.
for (const as of [['definitions.nobody=x'], ['definitions.coder=a', 'definitions.coder=b'], ['definitions.coder=x', 'definitions.pm=x'], ['roles.coder=x'], 'definitions.coder=x', ['definitions.coder=reviewer'], ['definitions.coder=human'], ['definitions.merge-gate=human']])
await assert.rejects(call('pack.preview.console', { pack: 'coding', as }), /invalid-request/);
});
test('SP4 --as onto another workflow of the pack refuses; a renamed inline definition renames the workflow roles naming it', async t => {
const { call, file, install, rolesDir } = await harness(t);
install(variant('twoflow', p => { p.workflows.other = structuredClone(p.workflows.change); }));
await assert.rejects(call('pack.preview.console', { pack: 'twoflow', as: ['workflows.change=other'] }), /invalid-request/);
const { entryFromTemplate, readTemplate } = await import('../../organization/src/definitions.mjs');
const { rev: _rev, ...scribe } = entryFromTemplate(readTemplate(rolesDir, 'coder'));
install(variant('scribekit', p => {
p.definitions = { scribe };
p.hires = [];
p.workflows = { notes: { description: 'Notes.', steps: [{ id: 'write', title: 'Write it', state: 'todo', roles: ['scribe', 'human'] }] } };
}));
const as = ['definitions.scribe=writer'];
const preview = await call('pack.preview.console', { pack: 'scribekit', as });
assert.equal(marks(preview)['definitions.writer'], 'add');
assert.deepEqual(preview.plan.workflows.notes.steps[0].roles, ['writer', 'human']);
await call('pack.apply.console', { pack: 'scribekit', as, digest: preview.digest });
assert.ok(file().definitions.writer);
assert.equal(file().definitions.scribe, undefined);
assert.deepEqual(file().workflows.notes.steps[0].roles, ['writer', 'human']);
// A rename onto a role the same step already names refuses at preview, not only at apply.
install(variant('pairkit', p => {
p.definitions = { scribe };
p.hires = [];
p.workflows = { notes: { description: 'Notes.', steps: [{ id: 'write', title: 'Write it', state: 'todo', roles: ['scribe', 'pm'] }] } };
}));
await call('pack.preview.console', { pack: 'pairkit' });
await assert.rejects(call('pack.preview.console', { pack: 'pairkit', as: ['definitions.scribe=pm'] }), /invalid-request/);
// The reserved human step role never follows a rename, even when the pack defines a definition by that name.
install(variant('humankit', p => {
p.definitions = { human: scribe };
p.hires = [];
p.workflows = { signoff: { description: 'Sign-off.', steps: [{ id: 'sign', title: 'Sign it', state: 'todo', roles: ['human'] }] } };
}));
const renamed = await call('pack.preview.console', { pack: 'humankit', as: ['definitions.human=bot'] });
assert.deepEqual(renamed.plan.workflows.signoff.steps[0].roles, ['human']);
});
test('SP4 a changed pack with nothing to add still records its entry; an identical repeat writes nothing', async t => {
const { call, file, save } = await harness(t);
save('jason', 'mine', variant('mine'));
// The first apply pins the definitions it adds; the second pins the pack's template refs, so it
// records an entry too. From the second on, the proposals are settled.
for (let i = 0; i < 2; i++) {
const p = await call('pack.preview.console', { pack: 'saved:mine' });
await call('pack.apply.console', { pack: 'saved:mine', digest: p.digest });
}
assert.equal(file().packs.length, 2);
save('jason', 'mine', variant('mine', p => { p.version = '1.0.1'; p.description = 'A changed description.'; }));
const changed = await call('pack.preview.console', { pack: 'saved:mine' });
assert.ok(changed.items.every(i => i.mark === 'same'), JSON.stringify(changed.items));
await call('pack.apply.console', { pack: 'saved:mine', digest: changed.digest });
assert.equal(file().packs.length, 3);
assert.equal(file().packs.at(-1).version, '1.0.1');
assert.notEqual(file().packs.at(-1).sha256, file().packs[1].sha256);
const repeat = await call('pack.preview.console', { pack: 'saved:mine' });
const out = await call('pack.apply.console', { pack: 'saved:mine', digest: repeat.digest });
assert.deepEqual(out.added, []);
assert.equal(file().packs.length, 3);
});
test('SP4 an instance by the hire name drops the proposal; launch.noHire marks it', async t => {
const { call } = await harness(t, { mutate: doc => {
doc.roles['coder-1'] = { ...structuredClone(doc.roles.reviewer), definition: 'coder', tracker: { bot: 'bot-demo-coder-1', botId: 7 } };
doc.launch.noHire = ['pm'];
} });
const preview = await call('pack.preview.console', { pack: 'coding' });
const hires = Object.fromEntries(preview.hires.map(h => [h.name, h]));
assert.equal(hires['coder-1'].mark, 'dropped');
assert.equal(hires['pm-1'].noHire, true);
assert.equal(hires['reviewer-1'].noHire, false);
assert.deepEqual(preview.plan.packs.proposedHires.map(h => h.name), ['pm-1', 'reviewer-1']);
});
test('SP4 a held credential in a pack, a board or a workflow refuses credential-leak and is never echoed', async t => {
const { call, path, revision, save } = await harness(t);
save('jason', 'leaky', variant('leaky', p => { p.description = `Team notes ${TOKEN}`; }));
const before = readFileSync(path);
const leaks = [
() => call('pack.preview.console', { pack: 'saved:leaky' }),
() => call('pack.apply.console', { pack: 'saved:leaky', digest: 'a'.repeat(64) }),
() => call('board.set.console', { revision: revision(), board: { columns: codingPack().board.columns.map((c, i) => i ? c : { ...c, label: TOKEN }), layout: 'kanban' } }),
() => call('workflow.set.console', { revision: revision(), name: 'leak', workflow: { description: 'x', steps: [{ title: TOKEN, state: 'todo', roles: ['human'] }] } }),
];
for (const leak of leaks) {
await assert.rejects(leak(), e => { assert.match(e.message, /credential-leak/); assert.ok(!e.message.includes(TOKEN)); assert.ok(!JSON.stringify(e).includes(TOKEN)); return true; });
}
assert.deepEqual(readFileSync(path), before);
});
test('SP4 a template reference to a definition a hired agent may not hold refuses at preview', async t => {
const { call, install, rolesDir } = await harness(t);
const { templateHash } = await import('../../organization/src/definitions.mjs');
const cos = templateHash(rolesDir, 'chief-of-staff');
install(variant('chiefkit', p => { p.definitions.cos = { template: 'chief-of-staff', sha256: cos }; }));
await assert.rejects(call('pack.preview.console', { pack: 'chiefkit' }), /invalid-request/);
});
test('SP4 who may call: the owner only; the tester, a member, an agent and a console cap on the cli name refuse', async t => {
const { b, call, human, revision, path } = await harness(t);
// TESTER_ORGANIZATION_VERBS is unchanged: no pack, board or workflow verb.
assert.deepEqual(TESTER_ORGANIZATION_VERBS, ['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
const tester = b.bindTester({ business: 'demo' });
const before = readFileSync(path);
assert.throws(() => b.request(tester, { verb: 'board.set', args: { revision: revision(), board: null } }), /tester-refused/);
assert.throws(() => b.request(tester, { verb: 'workflow.set', args: { revision: revision(), name: 'x', workflow: null } }), /tester-refused/);
assert.throws(() => b.request(tester, { verb: 'pack.preview', args: { pack: 'coding' } }), /tester-refused/);
const member = b.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
for (const [verb, args] of [['pack.apply.console', { pack: 'coding', digest: 'a'.repeat(64) }], ['board.set.console', { revision: revision(), board: null }], ['workflow.set.console', { revision: revision(), name: 'x', workflow: null }], ['packs.console', {}],
['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' });
// 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/);
await assert.rejects(call('pack.preview.console', { pack: 'coding' }, human), /human-required/);
assert.deepEqual(readFileSync(path), before);
});
test('SP4 the request carries no origin, actor or unknown key; scope and argument checks refuse invalid-request', async t => {
const { call, revision, install } = await harness(t);
for (const args of [{ pack: 'coding', origin: 'shipped' }, { pack: 'coding', actor: 'mallory' }, {}, { pack: 7 }, { pack: 'coding', project: 'stack' }])
await assert.rejects(call('pack.preview.console', args), /invalid-request/);
await assert.rejects(call('pack.apply.console', { pack: 'coding' }), /invalid-request/);
await assert.rejects(call('pack.preview.console', { pack: 'nosuch' }), /starter-pack-not-found/);
await assert.rejects(call('board.set.console', { revision: 'nope', board: null }), /invalid-request/);
await assert.rejects(call('board.set.console', { revision: revision(), board: [] }), /invalid-request/);
await assert.rejects(call('workflow.set.console', { revision: revision(), name: 'x', workflow: 'y' }), /invalid-request/);
// A workflow step naming a role no definition, template or `human` resolves refuses.
await assert.rejects(call('workflow.set.console', { revision: revision(), name: 'x', workflow: { description: 'x', steps: [{ title: 'Do', state: 'todo', roles: ['nobody-at-all'] }] } }), /invalid-request/);
// A project pack needs a code project; an org pack takes none.
install(variant('projkit', p => { p.scope = 'project'; }));
await assert.rejects(call('pack.preview.console', { pack: 'projkit' }), /invalid-request/);
await assert.rejects(call('pack.preview.console', { pack: 'projkit', project: 'nosuch' }), /invalid-request/);
const preview = await call('pack.preview.console', { pack: 'projkit', project: 'stack' });
assert.equal(marks(preview)['projects.stack.board'], 'add');
assert.equal(marks(preview)['projects.stack.workflows.change'], 'add');
assert.equal(marks(preview)['definitions.coder'], 'add');
});
test('SP4 a saved template is read only from its own owner, and packs lists none', async t => {
const { b, call, save } = await harness(t);
save('jason', 'mine', variant('mine'));
const preview = await call('pack.preview.console', { pack: 'saved:mine' });
assert.equal(preview.pack.origin, 'saved');
const alex = b.bindHuman({ business: 'other', human: 'alex', via: 'cli', outsideAgent: true });
await assert.rejects(b.request(alex, { verb: 'pack.preview', args: { pack: 'saved:mine' } }), /starter-pack-not-found/);
const listed = await call('packs.console');
assert.ok(listed.packs.length >= 5);
assert.ok(listed.packs.every(p => p.origin !== 'saved' && p.id !== 'mine'));
for (const name of ['saved:../jason/mine', 'saved:', 'saved:a/b']) await assert.rejects(call('pack.preview.console', { pack: name }), /starter-pack-invalid|invalid-request/);
});
test('SP4 board.set changes only the board; workflow.set and remove change only that workflow', async t => {
const { call, file, revision } = await harness(t);
const before = file();
const board = structuredClone(codingPack().board);
await call('board.set.console', { revision: revision(), board });
const after = file();
assert.deepEqual(after.board, board);
delete after.board;
assert.deepEqual(after, before);
const flow = { description: 'One.', steps: [{ title: 'Do it', state: 'todo', roles: ['coder'] }] };
await call('workflow.set.console', { revision: revision(), name: 'one', workflow: flow });
await call('workflow.set.console', { revision: revision(), name: 'two', workflow: flow });
await call('workflow.set.console', { revision: revision(), name: 'one', workflow: null });
assert.deepEqual(file().workflows, { two: flow });
assert.deepEqual(file().board, board);
});
test('SP4 caps: at most 32 workflows and 256 packs entries', async t => {
const { call, file, revision, path } = await harness(t);
const flow = { description: 'x', steps: [{ title: 'Do it', state: 'todo', roles: ['human'] }] };
const doc = file();
doc.workflows = Object.fromEntries(Array.from({ length: 32 }, (_, i) => [`w${i}`, flow]));
writeFileSync(path, JSON.stringify(doc, null, 2) + '\n');
await assert.rejects(call('workflow.set.console', { revision: revision(), name: 'w32', workflow: flow }), /invalid-request/);
await call('workflow.set.console', { revision: revision(), name: 'w0', workflow: null });
const preview = await call('pack.preview.console', { pack: 'coding' });
await call('pack.apply.console', { pack: 'coding', digest: preview.digest });
const full = file();
full.packs = Array.from({ length: 256 }, () => structuredClone(full.packs[0]));
writeFileSync(path, JSON.stringify(full, null, 2) + '\n');
const again = await call('pack.preview.console', { pack: 'coding' });
await assert.rejects(call('pack.apply.console', { pack: 'coding', digest: again.digest }), /invalid-request/);
});
test('SP4 the broker knows each verb under both names', () => {
assert.deepEqual(Object.keys(PACK_BUS_KEYS).sort(), ['board.set', 'board.set.console', 'pack.apply', 'pack.apply.console', 'pack.preview', 'pack.preview.console', 'packs', 'packs.console', 'workflow.set', 'workflow.set.console']);
});
+3 -1
View File
@@ -91,7 +91,9 @@ const ask = (x, state, extra = {}) => x.call('pm', 'request.question', { request
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',
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.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']);
});
test('only the signed-in owner capability reaches the console verbs and it reaches nothing else', async t => {
+91 -4
View File
@@ -1,18 +1,23 @@
import { readFile, writeFile } from 'node:fs/promises';
import { configDir } from '../../organization/src/organization-config.mjs';
import { listOrgs, orgLock } from '../../organization/src/org-registry.mjs';
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 } from './config.mjs';
import { loadSystem, orgPaths, rolesDir } from './config.mjs';
import { CliError } from './errors.mjs';
import { busStart, busStopForDelete, copyRemoteFor } from './org-bus.mjs';
import { assertBuildStart, assertDevInstance } from './deployment.mjs';
import { consoleBusRestart } from './org-console.mjs';
import { refuseInsideAgent } from './transport.mjs';
import { busExit, humanTransport, refuseInsideAgent } from './transport.mjs';
import { definitionsCommand, DEFINITIONS_USAGE } from './org-definitions.mjs';
import { orgOwnerCommand, ORG_OWNER_USAGE, ORG_OWNER_VERBS } from './org-owner.mjs';
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) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
// 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]';
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';
@@ -28,6 +33,87 @@ function restoreBusCheck(system, env) {
try { assertBuildStart({ devOwner: true }); assertDevInstance(system, env); }
catch (e) { throw new CliError(`restore starts the bus as the local dev owner, and ${e.message}; restore with --no-bus, then start the bus with mosaic bus start`, 3); }
}
// Starter packs SP4: `mosaic org pack|board|workflow`. Every word is the owner's and goes through the
// organization's bus as its human, so it runs only from a human shell: the bus holds the credential
// store whose held-secret check each preview and write needs, and the open hire decisions a preview
// reads. A refusal arrives as its code; a FILE's text is never echoed.
async function packFile(file) {
try { return JSON.parse(await readFile(file, 'utf8')); }
catch (e) { throw new CliError(`cannot read ${file}: ${e instanceof SyntaxError ? 'not valid JSON' : errorCode(e)}`, 2); }
}
// deps.callFor or deps.transport stand in for the bus in tests; otherwise the call is callFor's in cli.mjs.
function packCall(id, io, deps) {
if (typeof deps.callFor === 'function') return deps.callFor({ positional: [id], flags: new Set(), values: { '--business': id } });
if (typeof deps.transport === 'function') return deps.transport(id);
return async (verb, args) => {
const dir = configDir(io.env);
const match = /^mosaic-([a-z][a-z0-9]{1,15})$/.exec(basename(dir));
if (!match) throw new CliError('organization commands require an instance config directory', 3);
const system = deps.system ?? loadSystem({ env: io.env, instance: match[1] });
const org = await resolveOrg({ configDir: dir, dataRoot: system.dataRoot, instance: match[1], env: io.env, system }, id);
if (org.state !== 'active') throw new CliError('organization is not active', 3);
return humanTransport({ socket: orgPaths(org.root).socket, business: id, env: io.env })(verb, args);
};
}
const PACK_REFUSALS = {
'pack-plan-stale': 'the organization or the pack changed since the preview; preview again and apply its digest',
'revision-conflict': 'the organization file changed while this ran; run it again',
'credential-leak': 'the request holds a credential the organization\'s bus holds; nothing was written',
'invalid-request': 'the bus refused the request: a bad argument, a project that is not a code project, or a pack that fails the composition check',
'human-required': 'only the organization\'s owner, from a human shell, may do this',
'starter-pack-not-found': 'no installed, shipped or saved pack has that name',
};
async function packsCommand(args, io, deps) {
const pos = [], values = {}, as = [];
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (['--project', '--digest', '--as'].includes(a)) {
if (!args[i + 1] || args[i + 1].startsWith('--') || (a !== '--as' && values[a] !== undefined)) throw new CliError(`${a} needs one value`, 4);
if (a === '--as') as.push(args[++i]); else values[a] = args[++i];
} else if (a.startsWith('--')) throw new CliError(`unknown option ${a}`, 4);
else pos.push(a);
}
const allowed = (...keys) => { for (const k of [...Object.keys(values), ...(as.length ? ['--as'] : [])]) if (!keys.includes(k)) throw new CliError(`unexpected ${k}`, 4); };
const project = values['--project'] === undefined ? {} : { project: values['--project'] };
const [word, sub, id, name, file] = pos;
// Every word is the human's: an agent run refuses before a file is read, a pack is loaded or the bus is called.
refuseAgentRun(io);
let verb, request, revised = false;
if (word === 'pack' && sub === 'list' && pos.length === 2) { allowed(); verb = 'packs'; request = {}; }
else if (word === 'pack' && ['preview', 'apply'].includes(sub) && pos.length === 4) {
allowed('--project', '--as', ...(sub === 'apply' ? ['--digest'] : []));
if (sub === 'apply' && !values['--digest']) throw new CliError('--digest is required: apply the digest a preview printed', 4);
verb = `pack.${sub}`;
request = { pack: name, ...project, ...(as.length ? { as } : {}), ...(sub === 'apply' ? { digest: values['--digest'] } : {}) };
} else if (word === 'board' && sub === 'set' && pos.length === 4) { allowed('--project'); verb = 'board.set'; revised = true; request = { board: await packFile(name), ...project }; }
else if (word === 'workflow' && sub === 'set' && pos.length === 5) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: await packFile(file), ...project }; }
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.
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) });
io.stdout.write(JSON.stringify({ packs: packs.map(({ id, origin, pack }) => ({ id, origin, pack })) }, null, 2) + '\n');
return;
}
const call = packCall(id, io, deps);
if (revised) {
const writer = deps.writer ?? organizationWriter({ dir: configDir(io.env), rolesDir: rolesDir(io.env) });
request = { revision: writer.read(id).revision, ...request };
}
let result;
try { result = await call(verb, request); }
catch (e) {
if (typeof e?.code !== 'string' || e.code === '' || e instanceof CliError) throw e;
const why = PACK_REFUSALS[e.code];
const error = new CliError(why ? `${e.code}: ${why}` : e.code, 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 {
@@ -35,6 +121,7 @@ export async function orgCommand(args, io, deps = {}) {
if (args[0] === 'definitions') return await definitionsCommand(args.slice(1), 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);
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]; };
+99
View File
@@ -0,0 +1,99 @@
// Starter packs SP4: `mosaic org pack|board|workflow`. Each word goes through the organization's bus as
// its human; pack apply writes the packs entry, and workflow remove takes out only that workflow.
import test from 'node:test';
import assert from 'node:assert/strict';
import { join } from 'node:path';
import { readFileSync, writeFileSync } from 'node:fs';
import { main } from '../src/cli.mjs';
import { ORG_USAGE, PACKS_USAGE } from '../src/org.mjs';
import { bootConfig, loadSystem } from '../src/config.mjs';
import { BusError } from '../../bus/src/broker.mjs';
import { startBroker } from '../../bus/src/runtime.mjs';
import { fixture, io, tmp } from './helpers.mjs';
const FLOW = (title) => ({ description: `${title}.`, steps: [{ title, state: 'todo', roles: ['human'] }] });
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 = [];
// The human transport's shape: a bus refusal arrives as its code.
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 })); }
catch (e) { if (!(e instanceof BusError)) throw e; throw Object.assign(new Error(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 doc = () => JSON.parse(readFileSync(file, 'utf8'));
return { root, f, file, calls, run, doc };
}
test('SP4 mosaic org pack: list reads the shipped packs, preview writes nothing, apply with its digest writes the packs entry', async (t) => {
const s = await setup(t);
assert.ok(ORG_USAGE.includes(PACKS_USAGE.slice('mosaic org '.length)));
const listed = await s.run(['pack', 'list']);
assert.ok(listed.packs.some((p) => p.id === 'coding' && p.origin === 'shipped'));
assert.deepEqual(s.calls, [], 'pack list reads the data root; it asks no bus');
const before = readFileSync(s.file);
const preview = await s.run(['pack', 'preview', 'acme', 'coding']);
assert.match(preview.digest, /^[0-9a-f]{64}$/);
assert.deepEqual(readFileSync(s.file), before, 'preview writes nothing');
await assert.rejects(s.run(['pack', 'apply', 'acme', 'coding']), (e) => e.exitCode === 4 && /--digest is required/.test(e.message));
await assert.rejects(s.run(['pack', 'apply', 'acme', 'coding', '--digest', '0'.repeat(64)]), (e) => e.code === 'pack-plan-stale' && /preview again/.test(e.message));
assert.deepEqual(readFileSync(s.file), before);
const applied = await s.run(['pack', 'apply', 'acme', 'coding', '--digest', preview.digest]);
assert.equal(applied.pack, 'coding');
const packs = s.doc().packs;
assert.equal(packs.length, 1);
assert.equal(packs[0].id, 'coding');
assert.equal(packs[0].origin, 'shipped');
assert.deepEqual(s.calls.map(([verb]) => verb), ['pack.preview', 'pack.apply', 'pack.apply']);
assert.deepEqual(s.calls[2][1], ['digest', 'pack']);
});
test('SP4 mosaic org workflow remove takes out only that workflow; board set changes only the board', async (t) => {
const s = await setup(t);
const spec = join(s.root, 'flow.json');
for (const name of ['one', 'two']) {
writeFileSync(spec, JSON.stringify(FLOW(name)));
await s.run(['workflow', 'set', 'acme', name, spec]);
}
writeFileSync(spec, JSON.stringify({ columns: [{ state: 'todo', label: 'Backlog' }, { state: 'in-progress', label: 'Building' }, { state: 'in-review', label: 'Review' }, { state: 'blocked', label: 'Blocked' }, { state: 'done', label: 'Merged' }], layout: 'kanban' }));
await s.run(['board', 'set', 'acme', spec]);
const before = s.doc();
assert.deepEqual(Object.keys(before.workflows).sort(), ['one', 'two']);
await s.run(['workflow', 'remove', 'acme', 'one']);
const after = s.doc();
assert.deepEqual(after.workflows, { two: before.workflows.two });
const { workflows: _a, ...restBefore } = before;
const { workflows: _b, ...restAfter } = after;
assert.deepEqual(restAfter, restBefore, 'nothing but the one workflow changed');
assert.deepEqual(s.calls.at(-1), ['workflow.set', ['name', 'revision', 'workflow']]);
// A file that is not JSON is named without its text; an unknown word prints the usage.
writeFileSync(spec, '{"title": fixture-not-json');
await assert.rejects(s.run(['workflow', 'set', 'acme', 'three', spec]), (e) => e.exitCode === 2 && !e.message.includes('fixture-not-json'));
await assert.rejects(s.run(['workflow', 'rename', 'acme', 'two']), (e) => e.exitCode === 4 && e.message === PACKS_USAGE);
});
test('SP4 an agent shell refuses every pack, board and workflow word, pack list too, before it reads a file or calls the bus', async (t) => {
const s = await setup(t);
const agent = { ...s.f.env, MOSAIC_RUN_ID: 'run-1' };
const spec = join(s.root, 'flow.json');
writeFileSync(spec, JSON.stringify(FLOW('one')));
const before = readFileSync(s.file);
for (const args of [['pack', 'list'], ['pack', 'preview', 'acme', 'coding'], ['pack', 'apply', 'acme', 'coding', '--digest', 'a'.repeat(64)], ['board', 'set', 'acme', spec], ['workflow', 'set', 'acme', 'one', spec], ['workflow', 'remove', 'acme', 'one']]) {
await assert.rejects(s.run(args, agent), (e) => e.exitCode === 3 && /human shell/.test(e.message), args.join(' '));
}
assert.deepEqual(s.calls, []);
assert.deepEqual(readFileSync(s.file), before);
});
+12
View File
@@ -136,6 +136,18 @@ export function instancesNaming(document, name) {
return users.sort();
}
// SP4: every actor name an agent of the organization can carry: a root instance as `n` and
// `<definition>.n`, a project agent as `n`, `n.<project>` and `<definition>.n.<project>`. A write
// only a human makes refuses any of them.
export function agentActors(document) {
const out = [];
for (const [n, role] of Object.entries(document?.roles ?? {})) out.push(n, `${role?.definition}.${n}`);
for (const [project, p] of Object.entries(document?.projects ?? {})) {
for (const [n, entry] of Object.entries(p?.agents ?? {})) out.push(n, `${n}.${project}`, `${entry?.definition}.${n}.${project}`);
}
return out;
}
// ---- Templates ----
function frame(...parts) {
+7
View File
@@ -90,6 +90,13 @@ export const VERB_RIGHTS = record({
'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
// the owner's alone (null): a pack copies roles, and nothing else writes board or workflows.
'packs.console': 'board.read',
'pack.preview.console': null,
'pack.apply.console': null,
'board.set.console': null,
'workflow.set.console': null,
});
function refuse(code) {
@@ -37,6 +37,8 @@ const TOP_KEYS = ["businessVersion", "id", "human", "arbiters", "projects", "var
const STORE_STATES = Object.freeze(["todo", "in-progress", "in-review", "blocked", "done"]);
const BOARD_LAYOUTS = Object.freeze(["kanban", "list"]);
const PACK_ORIGINS = Object.freeze(["shipped", "installed", "saved"]);
export const PACKS_MAX = 256;
export const WORKFLOWS_MAX = 32;
const PACK_KEYS = Object.freeze(["id", "version", "sha256", "origin", "scope", "project", "at", "by", "added", "proposedHires"]);
const HEX64 = /^[0-9a-f]{64}$/;
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
@@ -75,6 +77,8 @@ export function checkBoard(board, where) {
// must not fail the whole organization. applyPack resolves the roles of the workflows it writes.
export function checkWorkflows(workflows, where) {
requireObject(workflows, where);
// SP4: at most 32 per scope. A pack names a handful; the cap bounds what one apply can grow.
if (Object.keys(workflows).length > WORKFLOWS_MAX) refuse(`${where} must hold at most ${WORKFLOWS_MAX} workflows`);
const out = {};
Object.entries(workflows).forEach(([name, workflow], n) => {
if (!isKindName(name)) refuse(`${where} key ${n + 1} must be a workflow name matching ${KIND_NAME}, at most 64 characters`);
@@ -126,6 +130,8 @@ function checkPin(pin, where) {
// checked against today's projects, and its proposals are pins, not hires.
export function checkPacks(packs, where) {
if (!Array.isArray(packs)) refuse(`${where} must be a list`);
// SP4: at most 256 entries. Every apply appends one, so the list grows; the cap bounds the file.
if (packs.length > PACKS_MAX) refuse(`${where} must hold at most ${PACKS_MAX} entries`);
return packs.map((entry, i) => {
const at = `${where}[${i}]`;
requireObject(entry, at);
+8 -4
View File
@@ -16,7 +16,7 @@ import { REPO_BOUND, projectBindings, repoBoundMessage } from "./repo-remote.mjs
import { orgIncarnation, withRegistryWriter } from "./org-registry.mjs";
import { REMOTE_OUTCOMES, REVOKE_CAUSES, allGranted, bindingText, definitionPin, samePin } from "./copy-bindings.mjs";
import { entryForm, projectAgentProblem, rootForProjectCheck } from "./agent-levels-write.mjs";
import { checkDefinition, checkDefinitionName, instancesNaming, readTemplate } from "./definitions.mjs";
import { agentActors, checkDefinition, checkDefinitionName, instancesNaming, readTemplate } from "./definitions.mjs";
export class OrganizationError extends Error {
constructor(code, message = code) {
@@ -390,8 +390,12 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
const definitionsProtected = (old, document) => {
if (canonicalJson(document?.definitions ?? {}) !== canonicalJson(old.definitions ?? {})) fail("organization-definitions-protected");
};
// SP4: packs, board and workflows change only through applyPack (project keys are under projects).
const packKeysProtected = (old, document) => {
for (const key of ["packs", "board", "workflows"]) if (canonicalJson(document?.[key] ?? null) !== canonicalJson(old[key] ?? null)) fail("organization-packs-protected");
};
function write(id, document, options) {
return commit(id, document, { ...options, capability: null, incarnation: undefined, guard: (old, next) => { projectsProtected(old, next); definitionsProtected(old, next); } });
return commit(id, document, { ...options, capability: null, incarnation: undefined, guard: (old, next) => { projectsProtected(old, next); definitionsProtected(old, next); packKeysProtected(old, next); } });
}
// #1873 T1: the only writer of `definitions`. `next(current)` returns the new entry without its
@@ -405,7 +409,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
checkDefinitionName(name, "definition name");
const logged = { ...detail, definition: name, rev: null };
const guard = (old, document) => {
const agents = Object.entries(old.roles ?? {}).flatMap(([n, role]) => [n, `${role?.definition}.${n}`]);
const agents = agentActors(old);
if (actor === "tester" || agents.includes(actor) || (old.retired ?? []).includes(actor)) fail("human-required");
const { definitions: a = {}, ...restOld } = old;
const { definitions: b = {}, ...restNew } = document ?? {};
@@ -501,7 +505,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
const at = new Date().toISOString();
const logged = { ...detail, verb: pack ? "pack.apply" : "organization.layout", pack: pack ? pack.id : null, added: null };
const build = (old) => {
const agents = Object.entries(old.roles ?? {}).flatMap(([n, role]) => [n, `${role?.definition}.${n}`]);
const agents = agentActors(old);
const agent = actor === "tester" || agents.includes(actor) || (old.retired ?? []).includes(actor);
if (agent && (Object.hasOwn(plan, "definitions") || pack?.origin === "saved")) fail("human-required");
const next = structuredClone(old);
@@ -82,6 +82,13 @@ const VERBS = {
'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
// the owner's alone (null): a pack copies roles, and nothing else writes board or workflows.
'packs.console': 'board.read',
'pack.preview.console': null,
'pack.apply.console': null,
'board.set.console': null,
'workflow.set.console': null,
};
test('M1/R1 the eleven rights pin the grantable flags, including compulsory org.view', () => {
@@ -0,0 +1,84 @@
// Starter packs SP4: the writer's fences for the pack keys. The generic write never changes packs,
// board or workflows (only applyPack does), and every actor name an agent carries, a project agent's
// included, is refused a write of definitions.
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { organizationWriter } from "../src/organization.mjs";
import { agentActors } from "../src/definitions.mjs";
import { PACKS_MAX, WORKFLOWS_MAX, checkPacks, checkWorkflows } from "../src/organization-config.mjs";
import { businessDoc, rolesCopy, tmp, writeJson } from "./helpers.mjs";
const assertClean = () => {};
const PLAIN = { role: { tools: ["read"], network: "none", authority: { withinRole: [], crossRole: [] }, credentials: [] }, instructions: "Read and report.\n" };
const BOARD = {
columns: [
{ state: "todo", label: "Backlog" }, { state: "in-progress", label: "Building" },
{ state: "in-review", label: "Review" }, { state: "blocked", label: "Blocked" }, { state: "done", label: "Merged" },
],
layout: "kanban",
};
const PACK = { id: "coding", version: "1.0.0", sha256: "a".repeat(64), origin: "shipped", scope: "org", project: null, proposedHires: [] };
const FLOW = { description: "One.", steps: [{ title: "Do it", state: "todo", roles: ["human"] }] };
function fixture(t) {
const root = tmp();
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
const rolesDir = rolesCopy(root);
const file = writeJson(join(dir, "businesses/acme.json"), businessDoc(root));
return { file, writer: organizationWriter({ dir, rolesDir }) };
}
const rev = (f) => f.writer.read("acme").revision;
const doc = (f) => JSON.parse(readFileSync(f.file, "utf8"));
test("SP4 the generic write refuses any change to packs, board or workflows", (t) => {
const f = fixture(t);
const before = readFileSync(f.file, "utf8");
for (const [key, value] of [["board", BOARD], ["workflows", { one: FLOW }], ["packs", []]]) {
const next = { ...doc(f), [key]: value };
assert.throws(() => f.writer.write("acme", next, { revision: rev(f), actor: "jason" }), { code: "organization-packs-protected" }, key);
}
assert.equal(readFileSync(f.file, "utf8"), before);
// Once applyPack wrote them, the generic write may carry them unchanged, but not remove them.
f.writer.applyPack("acme", { board: BOARD, workflows: { one: FLOW } }, { revision: rev(f), actor: "jason", assertClean });
const kept = doc(f);
kept.vars = { ...kept.vars, "tracker.pollSeconds": 90 };
f.writer.write("acme", kept, { revision: rev(f), actor: "jason" });
assert.equal(doc(f).vars["tracker.pollSeconds"], 90);
const { board: _board, ...dropped } = doc(f);
assert.throws(() => f.writer.write("acme", dropped, { revision: rev(f), actor: "jason" }), { code: "organization-packs-protected" });
});
test("SP4 agentActors names root instances and project agents in every form", () => {
const document = {
roles: { coder: { definition: "coder" }, chief: { definition: "chief-of-staff" } },
projects: { stack: { agents: { checker: { definition: "fact-checker" } } }, docs: {} },
};
assert.deepEqual(agentActors(document).sort(), ["checker", "checker.stack", "chief", "chief-of-staff.chief", "coder", "coder.coder", "fact-checker.checker.stack"].sort());
assert.deepEqual(agentActors(null), []);
});
test("SP4 a project agent's actor name refuses a definition write through setDefinition and applyPack", (t) => {
const f = fixture(t);
let { revision } = f.writer.read("acme");
({ revision } = f.writer.setProjectAgent("acme", { revision, project: "stack", name: "checker", entry: { definition: "fact-checker" } }, "jason"));
const before = readFileSync(f.file, "utf8");
for (const actor of ["checker", "checker.stack", "fact-checker.checker.stack"]) {
assert.throws(() => f.writer.setDefinition("acme", "scout", () => PLAIN, { revision, actor, assertClean }), { code: "human-required" }, actor);
assert.throws(() => f.writer.applyPack("acme", { definitions: { scout: PLAIN }, packs: PACK }, { revision, actor, assertClean }), { code: "human-required" }, actor);
}
assert.equal(readFileSync(f.file, "utf8"), before);
f.writer.setDefinition("acme", "scout", () => PLAIN, { revision, actor: "jason", assertClean });
assert.ok(doc(f).definitions.scout);
});
test("SP4 caps: at most 32 workflows in a scope and 256 packs entries", () => {
const flows = (n) => Object.fromEntries(Array.from({ length: n }, (_, i) => [`w${i}`, FLOW]));
assert.equal(WORKFLOWS_MAX, 32);
assert.equal(PACKS_MAX, 256);
assert.equal(Object.keys(checkWorkflows(flows(32), "workflows")).length, 32);
assert.throws(() => checkWorkflows(flows(33), "workflows"), /at most 32 workflows/);
assert.throws(() => checkPacks(Array.from({ length: 257 }, () => ({})), "packs"), /at most 256 entries/);
});
+9
View File
@@ -7,6 +7,7 @@ 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 { autonomyCaller } from './autonomy-http.mjs';
import { consoleAccess } from './access.mjs';
import { accessContextFor } from '../../cli/src/access.mjs';
@@ -20,6 +21,8 @@ import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
import { showOrg } from '../../organization/src/org-service.mjs';
import { configDir } from '../../organization/src/organization-config.mjs';
import { loadRootAgents } from '../../organization/src/agent-levels.mjs';
import { organizationWriter } from '../../organization/src/organization.mjs';
import { templateHashes } from '../../organization/src/definitions.mjs';
import { consoleReads, redactor } from './reads.mjs';
import { createDevOwner } from './dev-owner.mjs';
import { devOwnerInstance, devLanOptions } from '../../cli/src/dev-local-owner.mjs';
@@ -195,6 +198,12 @@ try {
// 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.
autonomyWrite: session.user === undefined && sendOn ? autonomyCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
// 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 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,
reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }),
};
},
+160
View File
@@ -0,0 +1,160 @@
// Starter packs SP4 (#1873, design section 8): the owner's pack, board and workflow routes on a
// selected organization. Owner Console transports only; no caller-supplied business, actor, subject
// or origin reaches the bus.
//
// GET /api/orgs/<id>/packs {packs, writable}: packs.console, the shipped and installed
// packs (never a saved template). /api/packs on a root Console.
// POST /api/orgs/<id>/packs/preview {pack, project?, as?}: pack.preview.console. Writes nothing.
// POST /api/orgs/<id>/packs/apply {pack, digest, project?, as?}: pack.apply.console
// POST /api/orgs/<id>/board {revision, board, project?}: board.set.console (board null removes it)
// POST /api/orgs/<id>/workflows/<name> {revision, workflow, project?}: workflow.set.console
// DELETE /api/orgs/<id>/workflows/<name> {revision, project?}: workflow.set.console with workflow null
// GET /api/orgs/<id>/workflows {workflows, projects, roles, revision, writable} (SP6): the org's and
// each code project's workflows, the role names a step may resolve to
// now (org definitions and V2 templates; `human` always does), and the
// file revision a workflow write sends back
//
// `read` is the owner's Console call (consoleCall), used for the two verbs that write nothing. `write`
// is the owner's Console call fenced to the three write verbs (packsCaller), present only for the
// owner's own session under --send. The broker answers every .console verb to the business human's
// console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows`
// (SP6) is the owner's read of the organization file as the writer reads it ({document, revision,
// templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it.
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply))?|board|workflows(?:\/([^/]+))?)$/;
// Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task
// board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405).
// serve.mjs dispatches on this, so the HEAD pin in packs-http.test.mjs tests the predicate it uses.
export const packsServes = (path, method) => PACKS_ROUTE.test(path) && !(path === '/api/board' && (method === 'GET' || method === 'HEAD'));
export const PACK_WRITE_VERBS = Object.freeze(['pack.apply.console', 'board.set.console', 'workflow.set.console']);
export const packsCaller = call => async (verb, args, options) => {
if (!PACK_WRITE_VERBS.includes(verb)) throw new Error(`the pack writer does not call ${verb}`);
return call(verb, args, options);
};
// A pack id, project id or workflow name: the bus's own name rule (vocabulary KIND_NAME, PACK_AS).
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const SAVED = /^saved:[a-z0-9][a-z0-9._-]{0,63}$/;
const REVISION = /^[a-f0-9]{64}$/;
// A board or workflow body stays small; the organization config caps both (WORKFLOWS_MAX, board columns).
const LIMIT = 65536;
const codes = {
'invalid-request': 400, 'credential-leak': 400, 'starter-pack-invalid': 400, 'definition-invalid': 400,
'starter-pack-not-found': 404, 'project-not-found': 404,
'pack-plan-stale': 409, 'revision-conflict': 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 packsHTTP(req, res, { path, owner, read, write, workflows = null, 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 = PACKS_ROUTE.exec(path);
const step = match?.[1] ?? null;
let name = null;
if (match?.[2] !== undefined) {
try { name = decodeURIComponent(match[2]); } catch { return refuse(400, 'invalid-request'); }
if (!NAME.test(name)) return refuse(400, 'invalid-request');
}
const list = path === '/api/packs', flows = path === '/api/workflows';
const allowed = list || flows ? ['GET'] : name !== null ? ['POST', 'DELETE'] : ['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 (flows ? !workflows : !read) return refuse(503, 'not-configured');
const writes = !list && !flows && step !== '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');
if (flows) return workflowsRead(res, { workflows, live, session, writable: Boolean(write) });
let verb, args = {};
if (list) verb = 'packs.console';
else if (step !== null) {
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], ['project', 'as']);
if (value === 'too-large') return refuse(413, 'invalid-request');
if (!value || typeof value.pack !== 'string' || !(NAME.test(value.pack) || SAVED.test(value.pack))
|| (step === 'apply' && (typeof value.digest !== 'string' || !REVISION.test(value.digest)))
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project)))
|| (value.as !== undefined && (!Array.isArray(value.as) || value.as.length > 32 || value.as.some(a => typeof a !== 'string' || a.length > 200))))
return refuse(400, 'invalid-request');
verb = `pack.${step}.console`;
args = value;
} else {
const value = await body(req, name === null ? ['revision', 'board'] : req.method === 'DELETE' ? ['revision'] : ['revision', 'workflow'], ['project']);
if (value === 'too-large') return refuse(413, 'invalid-request');
if (!value || typeof value.revision !== 'string' || !REVISION.test(value.revision)
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project))))
return refuse(400, 'invalid-request');
if (name === null) {
if (value.board !== null && !plain(value.board)) return refuse(400, 'invalid-request');
verb = 'board.set.console';
args = value;
} else {
if (req.method === 'POST' && !plain(value.workflow)) return refuse(400, 'invalid-request');
verb = 'workflow.set.console';
args = { revision: value.revision, name, workflow: req.method === 'DELETE' ? null : value.workflow, ...(value.project === undefined ? {} : { project: value.project }) };
}
}
// 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.packs)) return refuse(503, 'outcome-unknown');
return json(res, 200, { packs: result.packs, writable: Boolean(write) });
}
if (step === 'preview') {
if (!REVISION.test(result.digest ?? '')) return refuse(503, 'outcome-unknown');
return json(res, 200, result);
}
// A write admitted may already have committed: its receipt is returned even if the session ended
// meanwhile, never reported as not done.
if (!REVISION.test(result.revision ?? '')) return refuse(503, 'outcome-unknown');
return json(res, 200, { revision: result.revision, added: Array.isArray(result.added) ? result.added : [], ...(step === 'apply' ? { pack: result.pack } : {}) });
}
// SP6: the workflow list and editor's read. Only workflows, the names a step role may resolve to and the
// revision leave; nothing else of the organization file does. A workflow stays as the file holds it, so a
// step naming a role that no longer resolves is shown as written and the page marks it.
async function workflowsRead(res, { workflows, live, session, writable }) {
const refuse = (status, error) => json(res, status, { error });
let current;
try { current = await workflows(); } catch { return refuse(503, 'org-unavailable'); }
const doc = current?.document;
if (!plain(doc) || !REVISION.test(current.revision ?? '') || !Array.isArray(current.templates)) return refuse(503, 'outcome-unknown');
// A sign-out while the file was read shows nothing.
if (live() !== session) return refuse(401, 'sign-in-required');
const flowsOf = scope => (plain(scope?.workflows) ? scope.workflows : {});
const projects = {};
for (const [id, entry] of Object.entries(plain(doc.projects) ? doc.projects : {})) {
if (plain(entry) && entry.kind !== 'library') projects[id] = flowsOf(entry);
}
const roles = {
definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(),
templates: current.templates.filter(n => typeof n === 'string').sort(),
};
return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable });
}
+1 -1
View File
@@ -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><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="/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>
<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>
+15
View File
@@ -0,0 +1,15 @@
[data-packs],[data-workflows]{margin-top:16px}
:is(.pack-list,.pack-hires,.wf-list){list-style:none;margin:8px 0;padding:0}
:is(.pack-row,.pack-hire,.wf-item){border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere}
.pack-preview{border:1px solid var(--border);border-radius:var(--r);padding:12px;margin:12px 0;overflow-wrap:anywhere}
.pack-preview .ws-tbl{overflow-x:auto}
.pack-nohire,.wf-missing,.wf-note{color:var(--danger)}
.wf-missing{font-size:.9em}
.wf-steps{margin:6px 0;padding-left:22px}.wf-steps li{margin:4px 0}
.wf-editor{display:grid;gap:12px;margin:12px 0}
.wf-step{border:1px solid var(--border);border-radius:var(--r);padding:12px;display:grid;gap:10px;min-width:0}
:is(.wf-editor,[data-packs]) label{display:flex;flex-direction:column;gap:6px;min-width:0}
:is(.wf-editor,[data-packs]) :is(select,input,textarea){width:100%;box-sizing:border-box;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit}
:is([data-packs],[data-workflows]) .btn{min-height:44px;margin:4px 8px 4px 0}
:is([data-packs],[data-workflows]) :is(button,select,input,textarea):focus-visible{outline:2px solid var(--focus);outline-offset:2px}
:is([data-packs],[data-workflows]) [role=status]{overflow-wrap:anywhere}
+132
View File
@@ -0,0 +1,132 @@
// Starter packs SP6 (#1873, design section 8): the owner's pack picker on an organization's page.
// It lists the shipped and installed packs (GET /api/orgs/<id>/packs), previews one through
// pack.preview (POST .../packs/preview, writes nothing) and applies the previewed plan by its digest
// (POST .../packs/apply). The bus builds the plan, the marks, the flagged and credential lines and the
// noHire marks; this page only shows them. Every pack- or organization-supplied string goes through esc.
(() => {
'use strict';
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const base = org => `/api/orgs/${encodeURIComponent(org)}`;
const states = new Map();
const guidance = {
'pack-plan-stale': 'The organization or the pack changed since this preview. Preview again before applying.',
'revision-conflict': 'The organization changed. Preview again before applying.',
'organization-busy': 'The organization is busy with another write. Try again shortly.',
'starter-pack-not-found': 'This pack is no longer installed. Reload the page.',
'starter-pack-template-changed': 'A role template this pack pins has changed. The pack needs a new version.',
'starter-pack-invalid': 'This pack does not pass its checks against the organization.',
'definition-invalid': 'A role in this pack does not pass the organization checks.',
'project-not-found': 'That project is not in the organization file.',
'credential-leak': 'The pack carries a value the credential store holds. It cannot be applied.',
'read-only': 'This Console was started without send. Packs can be previewed, not applied.',
'owner-only': 'Only the owner can use starter packs.',
'sign-in-required': 'Sign in again to use starter packs.',
'cross-origin': 'The request did not come from this Console.',
'not-configured': 'This Console has no bus connection for packs.',
'no-bus-host': 'The organization bus is not running.',
'invalid-request': 'The bus refused the request as malformed.',
};
const MARKS = {
add: 'will be added',
same: 'already the same',
kept: 'kept: the organization has its own version',
removed: 'stays removed: you removed it after an earlier apply',
};
async function call(url, body) {
const r = await fetch(url, body === undefined ? { cache: 'no-store' } : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
let value = null;
try { value = await r.json(); } catch { value = null; }
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
return value;
}
async function load(org) {
const s = { packs: null, writable: false, error: null, projects: null, preview: null, status: '' };
try {
const value = await call(`${base(org)}/packs`);
s.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
s.writable = value?.writable === true;
} catch (error) { s.error = error.message; }
// A project pack needs a code project. The workflow read lists them; when it fails, a project pack
// says so instead of guessing.
if (s.packs?.some(p => p.pack.scope === 'project')) {
try { const w = await call(`${base(org)}/workflows`); s.projects = w && typeof w.projects === 'object' ? Object.keys(w.projects).sort() : null; } catch { s.projects = null; }
}
states.set(org, s);
}
const markText = m => MARKS[m] ?? m;
function itemRow(item) {
const what = item.item === 'board' ? 'Board' : item.item === 'definition' ? 'Role' : item.item === 'workflow' ? 'Workflow' : item.item;
const name = item.item === 'board' ? '' : item.target !== item.name ? `${esc(item.target)} <span class="muted">from ${esc(item.name)}</span>` : esc(item.target);
const diff = item.diff?.primitives?.length ? `<span class="muted"> differs in ${item.diff.primitives.map(esc).join(', ')}</span>` : '';
return `<tr data-pack-item="${esc(item.path)}"><td>${esc(what)}</td><td>${name}</td><td><code>${esc(item.path)}</code></td><td data-pack-mark="${esc(item.mark)}">${esc(markText(item.mark))}${diff}</td></tr>`;
}
function hireBlock(h) {
const flagged = h.flagged === null
? '<p class="note" data-pack-noflag>No chief to compare against: every line will need the owner.</p>'
: Array.isArray(h.flagged) && h.flagged.length
? `<p>Flagged lines, which only the owner approves:</p><ul data-pack-flagged>${h.flagged.map(l => `<li><code>${esc(l.field)}</code> ${esc(l.value)} <span class="muted">${(l.reasons || []).map(r => r === 'above-chief' ? 'above the chief' : r === 'resolve-right' ? 'a resolve right' : r).map(esc).join(', ')}</span></li>`).join('')}</ul>`
: '<p class="note">No flagged lines.</p>';
const creds = Array.isArray(h.credentialLines) && h.credentialLines.length
? `<p>Credential lines:</p><ul data-pack-credentials>${h.credentialLines.map(l => `<li><code>${esc(l?.service)}</code>${l?.scope === undefined ? '' : ` ${esc(l.scope)}`}</li>`).join('')}</ul>`
: '<p class="note">No credential lines.</p>';
const mark = h.mark === 'dropped' ? 'Not proposed: an agent or open hire decision already has this name.' : 'Recorded on apply for the chief to raise as a hire decision.';
const noHire = h.noHire ? '<p class="pack-nohire" data-pack-nohire>On this organization\'s no-hire list: the decision will say so.</p>' : '';
return `<li class="pack-hire" data-pack-hire="${esc(h.name)}"><strong>${esc(h.name)}</strong> <span class="muted">role ${esc(h.definition)}</span><p>${esc(mark)}</p>${noHire}${flagged}${creds}</li>`;
}
function previewBlock(s) {
const p = s.preview;
if (!p) return '';
const v = p.value;
const items = Array.isArray(v.items) && v.items.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Item</th><th scope="col">Name</th><th scope="col">Path</th><th scope="col">Plan</th></tr></thead><tbody>${v.items.map(itemRow).join('')}</tbody></table></div>` : '<p class="note">The pack has no items.</p>';
const hires = Array.isArray(v.hires) && v.hires.length ? `<h4>Hires</h4><ul class="pack-hires">${v.hires.map(hireBlock).join('')}</ul>` : '<p class="note">The pack proposes no hires.</p>';
const skills = v.skills?.notEnabled?.length ? `<p data-pack-skills>Skills this machine has not enabled: ${v.skills.notEnabled.map(n => `<code>${esc(n)}</code>`).join(', ')}</p>` : '';
const chief = v.chief === false ? '<p class="note">The organization has no chief, so no line is compared against one.</p>' : '';
const apply = s.writable ? `<button class="btn" type="button" data-pack-apply>Apply this plan</button>` : '<p class="note">This Console was started without send. Packs can be previewed, not applied.</p>';
return `<div class="pack-preview" data-pack-preview="${esc(p.pack)}"><h4>Preview: ${esc(v.pack?.label ?? p.pack)}${v.project ? ` <span class="muted">for project ${esc(v.project)}</span>` : ''}</h4>${items}${hires}${skills}${chief}${apply}</div>`;
}
function packRow(org, s, entry) {
const pack = entry.pack;
const project = pack.scope === 'project'
? s.projects === null ? '<p class="note">The project list could not be read.</p>' : s.projects.length
? `<label>Project<select data-pack-project>${s.projects.map(id => `<option value="${esc(id)}">${esc(id)}</option>`).join('')}</select></label>`
: '<p class="note">No code project to apply this pack to.</p>'
: '';
const canPreview = pack.scope !== 'project' || (s.projects && s.projects.length);
return `<li class="pack-row" data-pack="${esc(entry.id)}"><strong>${esc(pack.label ?? entry.id)}</strong> <span class="muted"><code>${esc(entry.id)}</code> ${esc(pack.version)} · ${esc(entry.origin)} · ${pack.scope === 'project' ? 'project pack' : 'organization pack'}</span>
<p>${esc(pack.description)}</p>${project}${canPreview ? '<button class="btn" type="button" data-pack-preview-button>Preview</button>' : ''}</li>`;
}
function section(org) {
const s = states.get(org);
if (!s || s.error) return `<section class="panel" data-packs data-packs-org="${esc(org)}"><h3>Starter packs</h3><p>${esc(s?.error ?? 'Starter packs could not be read.')}</p></section>`;
const list = s.packs.length ? `<ul class="pack-list">${s.packs.map(e => packRow(org, s, e)).join('')}</ul>` : '<p class="note">No starter packs are installed.</p>';
return `<section class="panel" data-packs data-packs-org="${esc(org)}"><h3>Starter packs</h3><p>A pack adds roles, a board and workflows to the organization. Preview shows what it would change; apply adds only what is missing, and a hire it proposes is only raised by the chief, as a decision.</p>${list}${previewBlock(s)}<p role="status" data-packs-status>${esc(s.status)}</p></section>`;
}
function redraw(org) {
const el = [...document.querySelectorAll('[data-packs-org]')].find(n => n.dataset.packsOrg === org);
if (el) el.outerHTML = section(org);
}
document.addEventListener('click', async e => {
const button = e.target.closest('[data-pack-preview-button],[data-pack-apply]');
if (!button) return;
const root = button.closest('[data-packs-org]'), org = root?.dataset.packsOrg, s = states.get(org);
if (!s) return;
button.disabled = true;
try {
if (button.hasAttribute('data-pack-preview-button')) {
const row = button.closest('[data-pack]'), pack = row.dataset.pack, project = row.querySelector('[data-pack-project]')?.value;
const body = { pack, ...(project ? { project } : {}) };
s.preview = { pack, project: project ?? null, value: await call(`${base(org)}/packs/preview`, body) };
s.status = '';
} else {
const p = s.preview;
const r = await call(`${base(org)}/packs/apply`, { pack: p.pack, digest: p.value.digest, ...(p.project ? { project: p.project } : {}) });
const added = Array.isArray(r.added) && r.added.length ? r.added.join(', ') : 'nothing new';
s.preview = null;
s.status = `Applied. Added ${added}. Proposed hires are recorded for the chief to raise as decisions.`;
}
} catch (error) { s.status = error.message; }
// A preview the page cannot draw says so, instead of leaving the button disabled with nothing shown.
try { redraw(org); } catch { s.preview = null; s.status = 'The preview could not be shown.'; redraw(org); }
});
window.MosaicPacks = { load, section };
})();
+33 -10
View File
@@ -20,6 +20,13 @@
const save = (key, value) => { try { localStorage.setItem(key, value); } catch {} };
const STATES = [['todo', 'To do'], ['in-progress', 'In progress'], ['in-review', 'Review'], ['blocked', 'Blocked'], ['done', 'Done']];
const STATE_LABEL = Object.fromEntries(STATES);
// Starter packs SP6 (#1873): an organization's or project's board style relabels, reorders and sets
// the default layout over the five fixed states (Jason 11-12 Q3); the states themselves never change.
// It applies only while the view is narrowed to one organization or project, so the all-orgs view
// keeps the fixed labels. A board that is not exactly that shape is ignored, never half applied.
const boardOk = b => Boolean(b) && typeof b === 'object' && Array.isArray(b.columns) && b.columns.length === STATES.length
&& b.columns.every(c => c && typeof c === 'object' && Object.hasOwn(STATE_LABEL, c.state) && typeof c.label === 'string' && c.label.trim() !== '' && c.label.length <= 32)
&& new Set(b.columns.map(c => c.state)).size === STATES.length && (b.layout === 'kanban' || b.layout === 'list');
const UNREAD = 'unread';
const REQUIREMENT = '^REQ-[A-Z]+-[1-9][0-9]*$';
const ORG_STATE = { down: ['s-offline', '○', 'bus down'], timeout: ['s-waiting', '◐', 'no answer in time'], invalid: ['s-error', '▲', 'invalid answer'], starting: ['s-waiting', '◐', 'starting'] };
@@ -28,8 +35,24 @@
// The layout is remembered per viewer and per width: a phone opens on List until its viewer picks
// Kanban, a wide screen on Kanban until its viewer picks List.
const layouts = (() => { try { const v = JSON.parse(load(LAYOUT) || '{}'); return v && typeof v === 'object' ? v : {}; } catch { return {}; } })();
const layoutNow = () => { const v = layouts[phone() ? 'phone' : 'wide']; return v === 'kanban' || v === 'list' ? v : phone() ? 'list' : 'kanban'; };
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '' };
// The board style in force: the filtered project's when it has one, else the one organization's the
// view is narrowed to (by the org chip or by a project of that org), else none.
function activeBoard() {
if (!snap) return null;
const m = /^([^:]+):(.+)$/.exec(filter.project);
const org = filter.org || (m ? m[1] : '');
if (!org) return null;
const project = m && m[1] === org ? snap.projects.find(p => p.org === org && p.id === m[2]) : null;
if (boardOk(project?.board)) return project.board;
const o = snap.orgs.find(x => x.id === org);
return boardOk(o?.board) ? o.board : null;
}
// The five states as [state, label] in the board's order, or the fixed ones.
const states = () => { const b = activeBoard(); return b ? b.columns.map(c => [c.state, c.label]) : STATES; };
const stateLabel = s => states().find(([v]) => v === s)?.[1];
// The viewer's saved choice for this width wins; then the board's layout; then the width's default.
const layoutNow = () => { const v = layouts[phone() ? 'phone' : 'wide']; return v === 'kanban' || v === 'list' ? v : activeBoard()?.layout ?? (phone() ? 'list' : 'kanban'); };
// `opened` is the task as the edit dialog showed it: Save diffs against it and sends its digest, so a
// poll that reads a newer task while the dialog is open turns a stale save into a task-conflict.
let snap = null, canWrite = false, notice = null, dragging = null, dragEnded = null, opened = null;
@@ -120,7 +143,7 @@
const roles = [...new Set(scope.flatMap(o => o.roles).concat(snap.tasks.filter(t => !filter.org || t.org === filter.org).flatMap(t => t.assignees)))].sort();
if (filter.assignee && filter.assignee !== '-' && !roles.includes(filter.assignee)) roles.push(filter.assignee);
const assigneeOpts = opt('', 'Anyone', filter.assignee) + opt('-', 'Nobody', filter.assignee) + roles.map(r => opt(r, r, filter.assignee)).join('');
const stateOpts = opt('', 'Any', filter.state) + STATES.map(([v, l]) => opt(v, l, filter.state)).join('') + (snap.tasks.some(t => stateOf(t) === UNREAD) ? opt(UNREAD, 'State not read', filter.state) : '');
const stateOpts = opt('', 'Any', filter.state) + states().map(([v, l]) => opt(v, l, filter.state)).join('') + (snap.tasks.some(t => stateOf(t) === UNREAD) ? opt(UNREAD, 'State not read', filter.state) : '');
const labels = [...new Set(snap.tasks.flatMap(t => t.labels.map(String)))].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
const labelSel = labels.length ? select('label', 'Label', opt('', 'Any', filter.label) + labels.map(l => opt(l, l, filter.label)).join(''), 'tb-label') : '';
return `<div class="tb-toolbar">
@@ -144,7 +167,7 @@
</article>`;
}
function kanban(rows) {
const cols = STATES.concat(rows.some(t => stateOf(t) === UNREAD) ? [[UNREAD, 'State not read']] : []);
const cols = states().concat(rows.some(t => stateOf(t) === UNREAD) ? [[UNREAD, 'State not read']] : []);
return `<div class="tb-board" style="--tb-cols:${cols.length}" data-tb-kanban>${cols.map(([v, l]) => {
const inCol = rows.filter(t => stateOf(t) === v), orgs = [...new Set(inCol.map(t => t.org))];
const drop = v !== UNREAD ? ` data-tb-col="${v}"` : '';
@@ -152,12 +175,12 @@
${v === UNREAD ? '<p class="tb-colnote">Vikunja does not tell the bus which bucket an open task is in.</p>' : ''}${inCol.map(card).join('') || '<p class="tb-empty">No tasks</p>'}</section>`;
}).join('')}</div>`;
}
const order = t => { const i = STATES.findIndex(([v]) => v === t.state); return i < 0 ? STATES.length : i; };
function list(rows) {
const cols = states(), order = t => { const i = cols.findIndex(([v]) => v === t.state); return i < 0 ? cols.length : i; };
const sorted = [...rows].sort((a, b) => order(a) - order(b) || a.org.localeCompare(b.org) || a.ref.localeCompare(b.ref, undefined, { numeric: true }));
const stateCell = t => {
if (!taskWritable(t)) return esc(STATE_LABEL[t.state] || 'Not read');
return `<select class="tb-move" data-tb-move="${esc(key(t))}" data-focus-key="move:${esc(key(t))}" aria-label="${esc(`State of ${shortId(t.ref)}, ${t.title || 'Untitled'}`)}">${STATES.map(([v, l]) => opt(v, l, t.state)).join('')}</select>`;
if (!taskWritable(t)) return esc(stateLabel(t.state) || 'Not read');
return `<select class="tb-move" data-tb-move="${esc(key(t))}" data-focus-key="move:${esc(key(t))}" aria-label="${esc(`State of ${shortId(t.ref)}, ${t.title || 'Untitled'}`)}">${cols.map(([v, l]) => opt(v, l, t.state)).join('')}</select>`;
};
return `<div class="ws-tbl tb-list" data-tb-list><table><thead><tr><th scope="col">Org</th><th scope="col">Id</th><th scope="col">Task</th><th scope="col" class="hide-m">Project</th><th scope="col">State</th><th scope="col" class="hide-m">Assignee</th><th scope="col" class="hide-m">Priority</th><th scope="col" class="hide-m">Due</th></tr></thead><tbody>
${sorted.map(t => `<tr class="tb-row ws-o${t.state === 'done' ? ' dim' : ''}" style="${colours(t.org)}" data-tb-task="${esc(key(t))}" data-org="${esc(t.org)}">
@@ -280,9 +303,9 @@
async function move(k, state) {
const t = find(k);
if (!t || !taskWritable(t) || t.state === state) return;
notice = { text: `Moving ${shortId(t.ref)} to ${STATE_LABEL[state]}…` }; paint();
notice = { text: `Moving ${shortId(t.ref)} to ${stateLabel(state)}…` }; paint();
const r = await write({ op: 'edit', org: t.org, task_ref: t.ref, expect: t.digest, state });
notice = r.ok ? { text: `${shortId(t.ref)} moved to ${STATE_LABEL[state]} in ${orgOf(t.org).label}.` } : { error: true, text: r.unknown ? `${shortId(t.ref)}: ${r.message}` : `${shortId(t.ref)} was not moved. ${r.message}` };
notice = r.ok ? { text: `${shortId(t.ref)} moved to ${stateLabel(state)} in ${orgOf(t.org).label}.` } : { error: true, text: r.unknown ? `${shortId(t.ref)}: ${r.message}` : `${shortId(t.ref)} was not moved. ${r.message}` };
try { await reload(); } catch {}
paint();
}
@@ -303,7 +326,7 @@
? `<fieldset class="tb-roles"><legend>Assignees</legend>${roles.map(r => `<label><input type="checkbox" name="assignees" value="${esc(r)}"${picked.includes(r) ? ' checked' : ''}>${esc(r)}</label>`).join('')}</fieldset>`
: '<p class="tb-field-note">Assignees: this organization reports no roles.</p>');
const prioSelect = p => `<label>Priority<select name="priority">${[0, 1, 2, 3, 4, 5].map(n => `<option value="${n}"${n === (p ?? 0) ? ' selected' : ''}>${n ? `P${n}` : 'None'}</option>`).join('')}</select></label>`;
const stateSelect = s => `<label>State<select name="state">${STATES.map(([v, l]) => `<option value="${v}"${v === s ? ' selected' : ''}>${l}</option>`).join('')}</select></label>`;
const stateSelect = s => `<label>State<select name="state">${states().map(([v, l]) => `<option value="${esc(v)}"${v === s ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`;
function projectOptions(org, current) {
return `<option value="">No project</option>${snap.projects.filter(p => p.org === org).map(p => `<option value="${esc(p.id)}"${p.id === current ? ' selected' : ''}>${esc(p.name || p.key || p.id)}</option>`).join('')}`;
}
@@ -329,7 +352,7 @@
const facts = `<p class="tb-facts">${av(t.org, 'xs')}${esc(o.label)} · <span class="mono">${esc(shortId(t.ref))}</span> ${trk(t.tracker)}${t.requirement ? ` · <span class="mono">${esc(t.requirement)}</span>` : ''}${projectName(t) ? ` · ${esc(projectName(t))}` : ''}</p>`;
if (!w) {
return `<div class="tb-form" data-tb-form="view"><h2 id="tb-dialog-h">${title(t)}</h2>${facts}
<dl class="tb-dl"><dt>State</dt><dd>${esc(STATE_LABEL[t.state] || 'Not read')}</dd><dt>Assignees</dt><dd>${t.assignees.length ? esc(t.assignees.join(', ')) : 'nobody'}</dd><dt>Priority</dt><dd>${prio(t) || 'none'}</dd><dt>Due</dt><dd>${due(t) || 'none'}</dd></dl>
<dl class="tb-dl"><dt>State</dt><dd>${esc(stateLabel(t.state) || 'Not read')}</dd><dt>Assignees</dt><dd>${t.assignees.length ? esc(t.assignees.join(', ')) : 'nobody'}</dd><dt>Priority</dt><dd>${prio(t) || 'none'}</dd><dt>Due</dt><dd>${due(t) || 'none'}</dd></dl>
<p class="tb-field-note">${esc(why)}</p>
${refusal ? `<p id="tb-dialog-status" class="tb-form-status" role="status" data-tb-form-status>${esc(refusal)}</p>` : ''}
<div class="tb-actions"><button type="button" class="ws-btn" data-tb-cancel>Close</button></div></div>`;
+186
View File
@@ -0,0 +1,186 @@
// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an
// organization's page. GET /api/orgs/<id>/workflows reads the org's and each code project's workflows
// with the file revision; a save is POST .../workflows/<name> {revision, workflow, project?} and a delete
// DELETE .../workflows/<name> {revision, project?} (workflow.set.console). The bus checks the shape; this
// page marks a step role that resolves to no org definition or role template (and is not `human`) as
// naming no current role. Every organization-supplied string goes through esc.
(() => {
'use strict';
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const base = org => `/api/orgs/${encodeURIComponent(org)}`;
const STATES = [['todo', 'To do'], ['in-progress', 'In progress'], ['in-review', 'Review'], ['blocked', 'Blocked'], ['done', 'Done']];
const STATE_LABEL = Object.fromEntries(STATES);
// The writer's workflow name rule (organization.mjs PLAN_NAME); a name it would refuse is refused here first.
const NAME = /^[a-z][a-z0-9-]{0,63}$/;
const NAME_RULE = 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.';
const MISSING = 'names no current role';
const states = new Map();
const guidance = {
'revision-conflict': 'The organization changed since this page read it. Reload the page before saving.',
'organization-busy': 'The organization is busy with another write. Try again shortly.',
'invalid-request': 'The bus refused the workflow. Check each step has a title, a state and one to eight distinct roles.',
'project-not-found': 'That project is not in the organization file.',
'credential-leak': 'The workflow carries a value the credential store holds.',
'read-only': 'This Console was started without send. Workflows can be read, not changed.',
'owner-only': 'Only the owner can read and change workflows.',
'sign-in-required': 'Sign in again to read workflows.',
'cross-origin': 'The request did not come from this Console.',
'not-configured': 'This Console cannot read the organization file.',
'org-unavailable': 'The organization file could not be read.',
'no-bus-host': 'The organization bus is not running.',
};
async function call(url, method, body) {
const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
let value = null;
try { value = await r.json(); } catch { value = null; }
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
return value;
}
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
async function read(org, s) {
const value = await call(`${base(org)}/workflows`, 'GET');
if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.');
s.data = value;
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
}
async function load(org) {
const s = { data: null, known: new Set(), error: null, editing: null, confirm: null, status: '' };
try { await read(org, s); } catch (error) { s.error = error.message; }
states.set(org, s);
}
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
const roleChip = (s, role) => s.known.has(role)
? `<code>${esc(role)}</code>`
: `<code>${esc(role)}</code> <span class="wf-missing" data-wf-missing>${MISSING}</span>`;
function stepItem(s, step) {
const roles = Array.isArray(step?.roles) ? step.roles : [];
return `<li data-wf-step><span>${esc(step?.title)}</span> <span class="muted">${esc(STATE_LABEL[step?.state] ?? step?.state)}</span> <span class="wf-roles">${roles.map(r => roleChip(s, r)).join(', ')}</span></li>`;
}
function workflowItem(org, s, scope, name, w) {
const steps = Array.isArray(w?.steps) ? w.steps : [];
const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name;
const actions = !s.data.writable ? '' : confirm
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes>Delete</button> <button class="btn" type="button" data-wf-delete-no>Keep</button></p>`
: `<p><button class="btn" type="button" data-wf-edit>Edit</button> <button class="btn" type="button" data-wf-delete>Delete</button></p>`;
return `<li class="wf-item" data-wf="${esc(name)}" data-wf-scope="${esc(scope)}"><strong data-wf-title>${esc(w?.title || name)}</strong> <span class="muted"><code>${esc(name)}</code></span>
${w?.description ? `<p>${esc(w.description)}</p>` : ''}<ol class="wf-steps">${steps.map(st => stepItem(s, st)).join('')}</ol>${actions}</li>`;
}
function stepRow(s, step, i) {
const roles = step.roles.split(',').map(r => r.trim()).filter(Boolean);
const missing = roles.filter(r => !s.known.has(r));
return `<fieldset class="wf-step" data-wf-edit-step="${i}"><legend>Step ${i + 1}</legend>
<label>Title<input name="title" maxlength="120" value="${esc(step.title)}" autocomplete="off"></label>
<label>State<select name="state">${STATES.map(([v, l]) => `<option value="${v}"${step.state === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
<label>Roles, separated by commas<input name="roles" value="${esc(step.roles)}" autocomplete="off"></label>
<p class="wf-note" data-wf-step-missing>${missing.length ? `${missing.map(r => `<code>${esc(r)}</code>`).join(', ')} ${MISSING}` : ''}</p>
<button class="btn" type="button" data-wf-step-remove>Remove step</button></fieldset>`;
}
function editor(s) {
const e = s.editing;
if (!e) return '';
const scopeField = e.isNew
? `<label>Where<select name="scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${e.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label><label>Name<input name="name" maxlength="64" value="${esc(e.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes"></label>`
: `<p>${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, <code>${esc(e.name)}</code></p>`;
return `<form class="wf-editor" data-wf-editor><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
<label>Title<input name="title" maxlength="120" value="${esc(e.draft.title)}" autocomplete="off"></label>
<label>Description<textarea name="description" maxlength="1000" rows="2">${esc(e.draft.description)}</textarea></label>
${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}
<p><button class="btn" type="button" data-wf-step-add>Add step</button> <button class="btn" type="submit">Save workflow</button> <button class="btn" type="button" data-wf-cancel>Cancel</button></p>
<p class="note">Roles name an organization role, a role template, or <code>human</code>.</p></form>`;
}
function section(org) {
const s = states.get(org);
if (!s || s.error) return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>${esc(s?.error ?? 'Workflows could not be read.')}</p></section>`;
const lists = scopes(s).map(([scope, label, flows]) => {
const names = Object.keys(flows || {}).sort();
return `<div class="wf-scope" data-wf-scope-list="${esc(scope)}"><h4>${esc(label)}</h4>${names.length ? `<ul class="wf-list">${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}</ul>` : '<p class="note">No workflows.</p>'}</div>`;
}).join('');
const add = s.data.writable ? (s.editing ? '' : '<p><button class="btn" type="button" data-wf-new>New workflow</button></p>') : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
}
function redraw(org) {
const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org);
if (el) el.outerHTML = section(org);
}
// The editor's current values back into the draft, so adding or removing a step keeps what was typed.
function capture(root, s) {
const form = root.querySelector('[data-wf-editor]');
if (!form || !s.editing) return;
const e = s.editing;
if (e.isNew) { e.scope = form.elements.scope?.value ?? e.scope; e.name = form.elements.name?.value ?? e.name; }
e.draft.title = form.querySelector(':scope > label > input[name="title"]').value;
e.draft.description = form.elements.description.value;
e.draft.steps = [...form.querySelectorAll('[data-wf-edit-step]')].map(f => ({ title: f.querySelector('[name="title"]').value, state: f.querySelector('[name="state"]').value, roles: f.querySelector('[name="roles"]').value }));
}
const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
const target = (s, scope) => scope ? { project: scope } : {};
async function reload(org, s, status) {
try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; }
}
document.addEventListener('click', async ev => {
const button = ev.target.closest('[data-wf-new],[data-wf-edit],[data-wf-cancel],[data-wf-step-add],[data-wf-step-remove],[data-wf-delete],[data-wf-delete-yes],[data-wf-delete-no]');
if (!button) return;
const root = button.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
if (!s?.data) return;
const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf;
if (button.hasAttribute('data-wf-new')) {
s.editing = { isNew: true, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
} else if (button.hasAttribute('data-wf-edit')) {
const w = flowsIn(s, scope)?.[name];
s.editing = { isNew: false, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
} else if (button.hasAttribute('data-wf-cancel')) {
s.editing = null;
} else if (button.hasAttribute('data-wf-step-add')) {
capture(root, s); s.editing.draft.steps.push({ title: '', state: 'todo', roles: '' });
} else if (button.hasAttribute('data-wf-step-remove')) {
capture(root, s); s.editing.draft.steps.splice(Number(button.closest('[data-wf-edit-step]').dataset.wfEditStep), 1);
} else if (button.hasAttribute('data-wf-delete')) {
s.confirm = { scope, name };
} else if (button.hasAttribute('data-wf-delete-no')) {
s.confirm = null;
} else if (button.hasAttribute('data-wf-delete-yes')) {
button.disabled = true;
try {
await call(`${base(org)}/workflows/${encodeURIComponent(name)}`, 'DELETE', { revision: s.data.revision, ...target(s, scope) });
s.confirm = null;
await reload(org, s, `Deleted ${name}.`);
} catch (error) { s.status = error.message; }
}
redraw(org);
});
document.addEventListener('input', ev => {
const field = ev.target.closest('[data-wf-edit-step] [name="roles"]');
if (!field) return;
const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg);
if (!s) return;
const missing = field.value.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r));
// textContent and created nodes only: a typed name never becomes markup.
const note = field.closest('[data-wf-edit-step]').querySelector('[data-wf-step-missing]');
note.textContent = missing.length ? `${missing.join(', ')} ${MISSING}` : '';
});
document.addEventListener('submit', async ev => {
if (!ev.target.matches('[data-wf-editor]')) return;
ev.preventDefault();
const root = ev.target.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
if (!s?.editing) return;
capture(root, s);
const e = s.editing;
if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; }
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; }
const workflow = {
...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}),
...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}),
steps: e.draft.steps.map(st => ({ title: st.title.trim(), state: st.state, roles: st.roles.split(',').map(r => r.trim()).filter(Boolean) })),
};
const button = ev.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: s.data.revision, workflow, ...target(s, e.scope) });
s.editing = null;
await reload(org, s, `Saved ${e.name}.`);
} catch (error) { s.status = error.message; }
redraw(org);
});
window.MosaicWorkflows = { load, section };
})();
+3 -1
View File
@@ -207,7 +207,7 @@
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)]);
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 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));
@@ -269,6 +269,8 @@
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null, types })}
${types ? types.section(id, { pane, idPrefix: opts.idPrefix || '' }) : ''}
${window.MosaicAutonomy?.section(id)??''}
${window.MosaicPacks?.section(id) ?? ''}
${window.MosaicWorkflows?.section(id) ?? ''}
</section>
</div>
</article>`;
+22 -8
View File
@@ -21,6 +21,7 @@ import { DECISION_ROUTE, decisionHTTP, decisionRefuse, createConfirmations } fro
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 { orgAdminHTTP, defaultOrgAdmin } from './org-admin.mjs';
import { consoleRestartHTTP } from './console-restart-http.mjs';
import { workspaceHTTP } from './workspace-read.mjs';
@@ -82,6 +83,9 @@ const files = new Map([
// 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']]),
@@ -523,7 +527,9 @@ const AGENT_ROUTES = {
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);
|| 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);
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.
@@ -860,7 +866,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;
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;
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
@@ -930,7 +936,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), systemTypesPath = SYSTEM_TYPES_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);
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;
@@ -942,7 +950,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) return json(res, 401, { error: 'sign-in-required' });
if (remotePath || systemTypesPath || autonomyPath || packsPath) 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();
@@ -955,7 +963,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 = upstream = null;
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;
}
if (session?.user !== undefined && !session.rootOwner && !instanceAction) {
// #1873: proxy setup answers a grant holder the way the bus answers an agent.
@@ -963,7 +971,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;
reads = null; upstream = null; libraryStatus = null; libraryRevert = null; files = USER_FILES; granted = true; proxyCall = null; systemTypesWrite = null; packsWrite = null; workflowsRead = null;
chatGrants = sso.chatGrants?.(session) ?? [];
}
}
@@ -994,7 +1002,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, upstream = null } = selected);
processing = null, decisionWrite = null, requestRead = null, requestWrite = null, systemTypesWrite = null, autonomyWrite = null, packsWrite = null, workflowsRead = 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.
@@ -1070,7 +1078,13 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
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 });
}
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/system-types.js', '/system-types.css'].includes(path)) return json(res, 403, { error: 'owner-only' });
// 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' });
// 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 });
+6 -2
View File
@@ -137,9 +137,12 @@ function median(values) {
// One org's bus state and reads. Never throws: every failure becomes the org's state.
async function readOrg(member, needs, { timeoutMs, now, ctx }) {
const started = now();
const head = { org: member.id, label: member.id, theme: member.doc?.appearance?.theme ?? null, tracker: member.doc?.tracker ? 'vikunja' : 'built-in', roles: Object.keys(member.doc?.roles ?? {}).sort() };
const head = { org: member.id, label: member.id, theme: member.doc?.appearance?.theme ?? null, tracker: member.doc?.tracker ? 'vikunja' : 'built-in', roles: Object.keys(member.doc?.roles ?? {}).sort(),
// Starter packs SP6 (#1873): the org's board style (labels, order and a default layout over the five
// fixed states), as the organization file holds it; the tasks page applies it only to a one-org view.
board: member.doc?.board ?? null };
const finish = (state, extra = {}) => ({ ...head, state, at: iso(now()), readMs: now() - started, ...extra });
if (member.invalid) return { org: { ...head, roles: [], state: 'invalid', at: iso(now()), readMs: 0, reason: member.reason } };
if (member.invalid) return { org: { ...head, roles: [], board: null, state: 'invalid', at: iso(now()), readMs: 0, reason: member.reason } };
const limit = deadline(timeoutMs);
const bound = { signal: limit.signal, deadline: limit.deadline };
const invalid = () => ({ org: finish('invalid', { error: 'invalid-response' }) });
@@ -278,6 +281,7 @@ function orgRows(org, data, doc, nowMs) {
org: id, id: p.id, key: p.repo ?? null, name: p.name ?? null, status: p.archived ? 'archived' : 'active',
state: counts.working ? 'working' : counts.waiting || needs.length ? 'waiting' : counts.idle ? 'idle' : 'none',
git: entry ? (entry.git?.mode ?? (entry.remote ? 'remote' : null)) : null,
board: entry?.board ?? null,
sessions: counts, openTasks: open.length, needsYou: needs.length,
lastActivity: latest([p.at, ...tasks.filter(t => t.project?.id === p.id).map(t => t.changedAt), ...needs.map(d => d.at), ...ps.map(s => s.claimedAt)]),
};
+1 -1
View File
@@ -19,7 +19,7 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t
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', '/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.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']);
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);
+374
View File
@@ -0,0 +1,374 @@
// Starter packs SP4 (#1873): the owner's pack, board and workflow routes on a selected organization,
// end to end. An ephemeral organization with the real runtime writer 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 { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { createServer, 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 { organizationWriter } from '../../organization/src/organization.mjs';
import { templateHashes } from '../../organization/src/definitions.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 { PACK_WRITE_VERBS, packsCaller, packsServes } from '../src/packs-http.mjs';
import { close } from './fixture.mjs';
const FLOW = (title) => ({ description: `${title}.`, steps: [{ title, state: 'todo', roles: ['human'] }] });
const BOARD = { columns: [{ state: 'todo', label: 'Backlog' }, { state: 'in-progress', label: 'Building' }, { state: 'in-review', label: 'Review' }, { state: 'blocked', label: 'Blocked' }, { state: 'done', label: 'Merged' }], layout: 'kanban' };
async function fixture(t, { send = true, workflows = true } = {}) {
const undo = []; t.after(async () => { for (const step of undo.reverse()) await step(); });
const root = mkdtempSync(join(tmpdir(), 'pk-'));
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 = [];
// SP6: the owner's workflow read, as cli.mjs builds it: the writer's read of the file and the V2 template names.
const flowReads = [];
let flowFails = false;
const workflowsRead = () => { flowReads.push(1); if (flowFails) throw new Error('unreadable'); return { ...organizationWriter({ dir: root, rolesDir }).read('demo'), templates: templateHashes(rolesDir).map(x => x.template) }; };
// A stand-in Board upstream: it counts what reaches it, so a test can tell the Board read from the pack route.
const boardHits = [];
const board = createServer((req, res) => { boardHits.push([req.method, req.url]); res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ from: 'board' })); });
await new Promise(resolve => board.listen(0, '127.0.0.1', resolve));
undo.push(() => close(board));
const upstream = `http://127.0.0.1:${board.address().port}`;
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 packsWrite = packsCaller(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, packsWrite: send ? packsWrite : null, workflowsRead: typeof workflows === 'function' ? workflows : workflows ? workflowsRead : null, upstream,
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 onDisk = () => JSON.parse(readFileSync(file, 'utf8'));
return { base, file, root, calls, onDisk, flowReads, boardHits, failFlows: () => { flowFails = true; }, 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('SP4 the owner lists the packs, previews one (nothing written) and applies it with its digest', async t => {
const f = await fixture(t);
const [listed, list] = await call(f, `${ORG}/packs`);
assert.equal(listed, 200, JSON.stringify(list));
assert.equal(list.writable, true);
assert.ok(list.packs.some(p => p.id === 'coding' && p.origin === 'shipped'));
const before = readFileSync(f.file);
const [previewed, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
assert.equal(previewed, 200, JSON.stringify(preview));
assert.match(preview.digest, /^[a-f0-9]{64}$/);
assert.deepEqual(readFileSync(f.file), before, 'preview writes nothing');
const [stale, staleBody] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: '0'.repeat(64) });
assert.deepEqual([stale, staleBody.error], [409, 'pack-plan-stale']);
assert.deepEqual(readFileSync(f.file), before);
const [applied, receipt] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
assert.equal(applied, 200, JSON.stringify(receipt));
assert.equal(receipt.pack, 'coding');
assert.match(receipt.revision, /^[a-f0-9]{64}$/);
assert.deepEqual(f.onDisk().packs.map(p => [p.id, p.origin]), [['coding', 'shipped']]);
// The two reads go over the read call; only apply over the fenced writer, and only the .console verbs.
assert.deepEqual(f.calls.map(c => [c[0], c[1]]), [['read', 'packs.console'], ['read', 'pack.preview.console'], ['write', 'pack.apply.console'], ['write', 'pack.apply.console']]);
});
test('SP4 DELETE of a workflow removes only that workflow; board POST changes only the board', async t => {
const f = await fixture(t);
const rev = async () => (await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' }))[1].revision;
for (const name of ['one', 'two']) {
const [status, body] = await call(f, `${ORG}/workflows/${name}`, 'POST', { revision: await rev(), workflow: FLOW(name) });
assert.equal(status, 200, JSON.stringify(body));
}
const [boarded, boardBody] = await call(f, `${ORG}/board`, 'POST', { revision: await rev(), board: BOARD });
assert.equal(boarded, 200, JSON.stringify(boardBody));
const before = f.onDisk();
assert.deepEqual(Object.keys(before.workflows).sort(), ['one', 'two']);
assert.deepEqual(before.board, BOARD);
const [removed, receipt] = await call(f, `${ORG}/workflows/one`, 'DELETE', { revision: await rev() });
assert.equal(removed, 200, JSON.stringify(receipt));
const after = f.onDisk();
assert.deepEqual(after.workflows, { two: before.workflows.two });
const { workflows: _a, ...restBefore } = before;
const { workflows: _b, ...restAfter } = after;
assert.deepEqual(restAfter, restBefore, 'nothing but the one workflow changed');
assert.deepEqual(f.calls.at(-1), ['write', 'workflow.set.console', ['name', 'revision', 'workflow']]);
// A stale revision is refused and writes nothing.
const [stale, staleBody] = await call(f, `${ORG}/workflows/two`, 'DELETE', { revision: receipt.revision.replace(/^./, c => c === 'a' ? 'b' : 'a') });
assert.deepEqual([stale, staleBody.error], [409, 'revision-conflict']);
assert.deepEqual(f.onDisk(), after);
});
test('SP4 the admission checks refuse before any bus call; a read-only Console still lists and previews', async t => {
const f = await fixture(t);
const revisionNow = (await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' }))[1].revision;
const asked = f.calls.length;
for (const [label, path, method, body, headers, expected] of [
['business field', `${ORG}/packs/preview`, 'POST', { pack: 'coding', business: 'other' }, {}, [400, 'invalid-request']],
['origin field', `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: 'a'.repeat(64), origin: 'shipped' }, {}, [400, 'invalid-request']],
['apply without digest', `${ORG}/packs/apply`, 'POST', { pack: 'coding' }, {}, [400, 'invalid-request']],
['bad pack name', `${ORG}/packs/preview`, 'POST', { pack: '../x' }, {}, [400, 'invalid-request']],
['bad workflow name', `${ORG}/workflows/Bad%20Name`, 'POST', { revision: revisionNow, workflow: FLOW('x') }, {}, [400, 'invalid-request']],
['workflow not an object', `${ORG}/workflows/three`, 'POST', { revision: revisionNow, workflow: 'x' }, {}, [400, 'invalid-request']],
['delete with a workflow', `${ORG}/workflows/three`, 'DELETE', { revision: revisionNow, workflow: FLOW('x') }, {}, [400, 'invalid-request']],
['no revision', `${ORG}/board`, 'POST', { board: BOARD }, {}, [400, 'invalid-request']],
['not JSON', `${ORG}/board`, 'POST', '{', {}, [400, 'invalid-request']],
['too large', `${ORG}/board`, 'POST', JSON.stringify({ revision: revisionNow, board: { pad: 'x'.repeat(70000) } }), {}, [413, 'invalid-request']],
['form post', `${ORG}/board`, 'POST', { revision: revisionNow, board: BOARD }, { 'content-type': 'text/plain' }, [400, 'invalid-request']],
['cross site', `${ORG}/board`, 'POST', { revision: revisionNow, board: BOARD }, { 'sec-fetch-site': 'cross-site' }, [403, 'cross-origin']],
['preview by GET', `${ORG}/packs/preview`, 'GET', undefined, {}, [405, 'method-not-allowed']],
['board by DELETE', `${ORG}/board`, 'DELETE', { revision: revisionNow }, {}, [405, 'method-not-allowed']],
['board by PUT', `${ORG}/board`, 'PUT', { revision: revisionNow }, {}, [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, asked, 'no refused request reached the bus');
// The bus's own refusals arrive as their codes: an unknown pack, and a workflow naming no role.
assert.deepEqual((await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'no-such-pack' })).map((x, i) => i ? x.error : x), [404, 'starter-pack-not-found']);
const [badRole, badRoleBody] = await call(f, `${ORG}/workflows/three`, 'POST', { revision: revisionNow, workflow: { description: 'x.', steps: [{ title: 'x', state: 'todo', roles: ['ghost'] }] } });
assert.deepEqual([badRole, badRoleBody.error], [400, 'invalid-request']);
// The fenced writer calls nothing but the three write verbs.
assert.deepEqual(PACK_WRITE_VERBS, ['pack.apply.console', 'board.set.console', 'workflow.set.console']);
await assert.rejects(packsCaller(async () => ({}))('packs.console', {}, {}), /does not call packs\.console/);
f.signOut();
assert.deepEqual((await call(f, `${ORG}/packs`))[0], 401);
});
test('SP4 without --send the writes are read-only; the list and preview still answer', async t => {
const f = await fixture(t, { send: false });
const [listed, list] = await call(f, `${ORG}/packs`);
assert.equal(listed, 200, JSON.stringify(list));
assert.equal(list.writable, false);
const [previewed, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
assert.equal(previewed, 200, JSON.stringify(preview));
const before = readFileSync(f.file);
for (const [path, method, body] of [[`${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest }], [`${ORG}/board`, 'POST', { revision: preview.revision, board: BOARD }], [`${ORG}/workflows/one`, 'DELETE', { revision: preview.revision }]]) {
const [status, result] = await call(f, path, method, body);
assert.deepEqual([status, result.error], [403, 'read-only'], `${method} ${path}`);
}
assert.deepEqual(readFileSync(f.file), before);
});
test('SP4 a session that is not the root owner reaches no pack route', async t => {
const f = await fixture(t);
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
const asked = f.calls.length;
const before = readFileSync(f.file);
f.revokeOwner();
for (const [path, method, body] of [[`${ORG}/packs`, 'GET'], [`${ORG}/packs/preview`, 'POST', { pack: 'coding' }], [`${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest }], [`${ORG}/workflows/one`, 'POST', { revision: preview.revision, workflow: FLOW('one') }], [`${ORG}/board`, 'POST', { revision: preview.revision, board: BOARD }]]) {
// revokeOwner leaves a granted user's session: the route refuses it owner-only, POST /api/board included.
const [status, result] = await call(f, path, method, body);
assert.deepEqual([status, result.error], [403, 'owner-only'], `${method} ${path}`);
}
assert.equal(f.calls.length, asked, 'nothing reached the bus');
assert.deepEqual(readFileSync(f.file), before);
});
test('SP4 a sign-out while the body is still arriving dispatches nothing', async t => {
const f = await fixture(t);
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
const asked = f.calls.length;
const before = readFileSync(f.file);
const data = JSON.stringify({ pack: 'coding', digest: preview.digest });
const answer = new Promise((resolve, reject) => {
const req = request(`${f.base}${ORG}/packs/apply`, { 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, asked);
assert.deepEqual(readFileSync(f.file), before);
});
test('SP4 a Console without sign-in serves no pack route; a method the route never serves stays 405', async t => {
const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', log: () => {} });
t.after(() => close(web));
const f = { base: `http://127.0.0.1:${web.address().port}` };
for (const [path, method, body] of [['/api/packs', 'GET'], ['/api/packs/preview', 'POST', { pack: 'coding' }], ['/api/board', 'POST', { revision: '0'.repeat(64), board: BOARD }]]) {
const [status, result] = await call(f, path, method, body);
assert.deepEqual([status, result.error], [403, 'owner-only'], `${method} ${path}`);
}
for (const method of ['OPTIONS', 'PUT', 'DELETE']) assert.equal((await call(f, '/api/board', method))[0], 405, method);
});
// SP6: a HEAD carries no body, so it reports only the status.
function head(f, path) {
return new Promise((resolve, reject) => {
const req = request(f.base + path, { method: 'HEAD' }, res => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
req.on('error', reject); req.setTimeout(10000, () => req.destroy(new Error('fixture request timed out'))); req.end();
});
}
test('SP6 GET /workflows returns the org and code-project workflows, the role names and the file revision a save takes', async t => {
const f = await fixture(t);
// One workflow per scope, written straight into the file. The step role `ghost` names no definition or
// template: the load checks only the shape of a role name, so the file holds it and the read shows it as written.
const doc = f.onDisk();
doc.definitions = { triage: { rev: 1, role: { tools: ['read'], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] }, instructions: 'Sort new work.' } };
doc.workflows = { intake: { title: 'Intake <img src=x onerror=window.pwn=1>', description: 'New work.', steps: [{ title: 'Sort', state: 'todo', roles: ['triage', 'human'] }, { title: 'Hand off', state: 'in-progress', roles: ['ghost'] }] } };
doc.projects.stack.workflows = { ship: { steps: [{ title: 'Build', state: 'in-progress', roles: ['coder'] }] } };
writeFileSync(f.file, `${JSON.stringify(doc, null, 2)}\n`);
const [status, body] = await call(f, `${ORG}/workflows`);
assert.equal(status, 200, JSON.stringify(body));
assert.deepEqual(Object.keys(body).sort(), ['projects', 'revision', 'roles', 'workflows', 'writable']);
assert.deepEqual(body.workflows, doc.workflows);
assert.deepEqual(body.projects, Object.fromEntries(Object.entries(doc.projects).map(([id, p]) => [id, p.workflows ?? {}])));
assert.deepEqual(body.projects.stack, doc.projects.stack.workflows);
assert.deepEqual(body.roles.definitions, ['triage']);
assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).sort());
assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost'));
assert.equal(body.revision, createHash('sha256').update(readFileSync(f.file)).digest('hex'), 'the revision is the writer\'s: the hash of the file bytes');
assert.equal(body.writable, true);
assert.equal(JSON.stringify(body).includes(f.root), false, 'no host path leaves');
// The revision is the one a save sends back.
const [saved, receipt] = await call(f, `${ORG}/workflows/review`, 'POST', { revision: body.revision, workflow: FLOW('Check') });
assert.equal(saved, 200, JSON.stringify(receipt));
const [, again] = await call(f, `${ORG}/workflows`);
assert.equal(again.revision, receipt.revision);
assert.deepEqual(Object.keys(again.workflows).sort(), ['intake', 'review']);
// A project save and delete through the same revision chain.
const [projectSaved, projectReceipt] = await call(f, `${ORG}/workflows/review`, 'POST', { revision: again.revision, workflow: FLOW('Check'), project: 'stack' });
assert.equal(projectSaved, 200, JSON.stringify(projectReceipt));
const [deleted] = await call(f, `${ORG}/workflows/review`, 'DELETE', { revision: projectReceipt.revision, project: 'stack' });
assert.equal(deleted, 200);
assert.deepEqual(Object.keys((await call(f, `${ORG}/workflows`))[1].projects.stack).sort(), ['ship']);
});
test('SP6 GET /workflows leaves out a library project and answers outcome-unknown for a read it cannot trust', async t => {
const REV = 'a'.repeat(64);
const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7] };
const f = await fixture(t, { workflows: () => read });
const [status, body] = await call(f, `${ORG}/workflows`);
assert.equal(status, 200, JSON.stringify(body));
assert.deepEqual(body, { workflows: {}, projects: { code: { w: FLOW('W') }, bare: {} }, roles: { definitions: [], templates: ['coder'] }, revision: REV, writable: true });
for (const bad of [{ ...read, revision: 'stale' }, { ...read, templates: null }, { ...read, document: [] }, null]) {
const g = await fixture(t, { workflows: () => bad });
assert.deepEqual((await call(g, `${ORG}/workflows`)).map((x, i) => i ? x.error : x), [503, 'outcome-unknown'], JSON.stringify(bad));
}
});
test('SP6 GET /workflows is the owner\'s: non-owner, sign-out, no reader, an unreadable file, a write method and a cross-site read', async t => {
const f = await fixture(t);
const before = readFileSync(f.file);
assert.deepEqual((await call(f, `${ORG}/workflows`, 'POST', { revision: '0'.repeat(64) })).map((x, i) => i ? x.error : x), [405, 'method-not-allowed']);
assert.deepEqual((await call(f, `${ORG}/workflows`, 'DELETE', { revision: '0'.repeat(64) })).map((x, i) => i ? x.error : x), [405, 'method-not-allowed']);
assert.deepEqual((await call(f, `${ORG}/workflows`, 'GET', undefined, { 'sec-fetch-site': 'cross-site' })).map((x, i) => i ? x.error : x), [403, 'cross-origin']);
assert.equal(f.flowReads.length, 0, 'no refused request read the file');
f.failFlows();
assert.deepEqual((await call(f, `${ORG}/workflows`)).map((x, i) => i ? x.error : x), [503, 'org-unavailable']);
const reads = f.flowReads.length;
f.revokeOwner();
assert.deepEqual((await call(f, `${ORG}/workflows`)).map((x, i) => i ? x.error : x), [403, 'owner-only']);
assert.equal(f.flowReads.length, reads, 'a non-owner reads nothing');
assert.deepEqual(readFileSync(f.file), before);
const g = await fixture(t, { workflows: false });
assert.deepEqual((await call(g, `${ORG}/workflows`)).map((x, i) => i ? x.error : x), [503, 'not-configured']);
g.signOut();
assert.deepEqual((await call(g, `${ORG}/workflows`)).map((x, i) => i ? x.error : x), [401, 'sign-in-required']);
const h = await fixture(t, { send: false });
const [status, body] = await call(h, `${ORG}/workflows`);
assert.equal(status, 200, JSON.stringify(body));
assert.equal(body.writable, false, 'a Console without send reads workflows but cannot save them');
});
test('SP6 HEAD /api/board: serve sends GET and HEAD to the Board read, never the pack route', async t => {
// The predicate serve.mjs dispatches on (`packsPath = packsServes(path, req.method)`).
for (const method of ['GET', 'HEAD']) assert.equal(packsServes('/api/board', method), false, method);
for (const method of ['POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']) assert.equal(packsServes('/api/board', method), true, method);
assert.equal(packsServes('/api/workflows', 'HEAD'), true, 'only /api/board is carved out');
assert.equal(packsServes('/api/packs', 'HEAD'), true);
// On an organization: GET /api/orgs/<id>/board reaches the organization's Board upstream; HEAD is the Board
// read's own 405 (it serves GET only) and nothing reaches the upstream or the pack route's bus.
const f = await fixture(t);
const [got, board] = await call(f, `${ORG}/board`);
assert.deepEqual([got, board], [200, { from: 'board' }]);
assert.deepEqual(f.boardHits, [['GET', '/api/board']]);
const asked = f.calls.length;
assert.equal(await head(f, `${ORG}/board`), 405);
assert.deepEqual(f.boardHits, [['GET', '/api/board']], 'the HEAD reached no upstream');
assert.equal(f.calls.length, asked, 'the HEAD reached no bus');
// POST stays the pack route's: a board write with a stale revision is the bus's revision-conflict.
const [posted, postBody] = await call(f, `${ORG}/board`, 'POST', { revision: '0'.repeat(64), board: BOARD });
assert.deepEqual([posted, postBody.error], [409, 'revision-conflict']);
assert.deepEqual(f.calls.at(-1), ['write', 'board.set.console', ['board', 'revision']]);
// On a root Console: GET /api/board is the Board read through its upstream, HEAD its 405, POST the pack route's owner-only.
const hits = [];
const upstream = createServer((req, res) => { hits.push(req.method); res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"from":"root-board"}'); });
await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve));
t.after(() => close(upstream));
const web = await startServer({ port: 0, board: `http://127.0.0.1:${upstream.address().port}`, log: () => {} });
t.after(() => close(web));
const r = { base: `http://127.0.0.1:${web.address().port}` };
assert.deepEqual(await call(r, '/api/board'), [200, { from: 'root-board' }]);
assert.equal(await head(r, '/api/board'), 405);
assert.deepEqual(hits, ['GET']);
assert.deepEqual((await call(r, '/api/board', 'POST', { revision: '0'.repeat(64), board: BOARD })).map((x, i) => i ? x.error : x), [403, 'owner-only']);
});
test('SP6 the pack picker and workflow files are the owner\'s: the tester listener gets 403, the owner 200', async t => {
const { createDevOwner } = await import('../src/dev-owner.mjs');
const organizations = { list: async () => [], resolve: async () => null };
const root = mkdtempSync(join(tmpdir(), 'pkt-')), 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 => new Promise((resolve, reject) => {
const req = request({ socketPath: socket, path, headers: { host: 'mosaic-tester.invalid' } }, res => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
req.on('error', reject); req.end();
});
const owner = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations, log: () => {} });
t.after(() => close(owner));
for (const [path, type] of [['/packs.js', /javascript/], ['/workflows.js', /javascript/], ['/packs.css', /css/]]) {
assert.equal(await viaTester(path), 403, path);
const res = await fetch(`http://127.0.0.1:${owner.address().port}${path}`);
assert.equal(res.status, 200, path);
assert.match(res.headers.get('content-type'), type, path);
assert.ok((await res.text()).length > 100, path);
}
});
@@ -0,0 +1,210 @@
// Starter packs SP6 (#1873): the owner's pack picker and workflow editor on an organization's page,
// driven in Chromium against stand-in pack verbs and a stand-in workflow read. It checks what the page
// shows from what the bus returns: the preview's marks, flagged lines, credential lines and noHire mark;
// a step role that no longer resolves; an organization-supplied title or label rendered as text; and
// the save and delete requests the editor sends.
import test from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const XSS = '<img src=x onerror=window.__sp6pwn=1>';
const waitFor = (b, expression, what) => 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(what)}+': '+document.body.innerText.slice(0,2000))})()`);
const REV = n => String(n).repeat(64);
const PACKS = [
{ id: 'software-team', origin: 'shipped', pack: { label: `Software team ${XSS}`, description: 'Roles, a board and a review workflow.', version: '1.0.0', scope: 'organization' } },
{ id: 'web-project', origin: 'installed', pack: { label: 'Web project', description: 'A project board.', version: '0.2.0', scope: 'project' } },
];
const PREVIEW = {
pack: { id: 'software-team', version: '1.0.0', label: `Software team ${XSS}`, origin: 'shipped', scope: 'organization' },
project: null, revision: REV('c'),
items: [
{ item: 'board', name: 'board', target: 'board', path: 'board', mark: 'add' },
{ item: 'definition', name: 'reviewer', target: 'reviewer', path: 'definitions.reviewer', mark: 'kept', diff: { primitives: ['tools', 'instructions'] } },
{ item: 'workflow', name: 'review', target: 'review', path: 'workflows.review', mark: 'same' },
{ item: 'workflow', name: 'ship', target: 'ship', path: 'workflows.ship', mark: 'removed' },
],
hires: [
{ name: 'lead-reviewer', definition: 'org:reviewer', mark: 'propose', pin: null, flagged: [{ field: 'authority.withinRole', value: 'decision.resolve.technical', reasons: ['above-chief', 'resolve-right'] }], credentialLines: [{ service: 'gitea', scope: 'repo:write' }, { service: 'matrix' }], noHire: true },
{ name: 'builder', definition: 'coder', mark: 'dropped', pin: null, flagged: null, credentialLines: [], noHire: false },
],
skills: { notEnabled: ['lint-fix'] }, chief: true, plan: {}, digest: REV('d'),
};
async function fixture(t, { send = true } = {}) {
const verbs = [];
let flows = {
revision: REV('a'),
document: {
workflows: {
intake: { title: `Intake ${XSS}`, description: `Sort ${XSS}`, steps: [{ title: `Sort ${XSS}`, state: 'todo', roles: ['triage', 'human'] }, { title: 'Hand off', state: 'in-progress', roles: ['ghost'] }] },
},
projects: { site: { workflows: { ship: { steps: [{ title: 'Build', state: 'in-progress', roles: ['coder'] }] } } } },
definitions: { triage: {} },
},
templates: ['coder', 'reviewer'],
};
const read = async (verb, args) => {
verbs.push([verb, args]);
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) => {
verbs.push([verb, args]);
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' } };
if (verb === 'workflow.set.console') {
assert.equal(args.revision, flows.revision);
const doc = structuredClone(flows.document);
const scope = args.project ? doc.projects[args.project] : doc;
scope.workflows ??= {};
if (args.workflow === null) delete scope.workflows[args.name]; else scope.workflows[args.name] = args.workflow;
flows = { ...flows, revision: REV(flows.revision[0] === 'a' ? 'b' : '9'), document: doc };
return { revision: flows.revision, added: [] };
}
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
const server = await startServer({
port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {},
organizations: {
list: async () => [{ id: 'acme', label: 'Acme', busHealthy: true }],
resolve: async () => ({
busHealthy: true, decisionWrite: async () => ({}), requestRead: read, requestWrite: read, packsWrite: send ? write : null,
workflowsRead: async () => structuredClone(flows), send: send ? async () => ({}) : null,
reads: { business: async () => ({ business: { id: 'acme', projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
chat: { projects: async () => [], threads: async () => [] },
}),
},
});
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/acme/organization`);
return { b, verbs, flows: () => flows };
}
test('SP6 pack picker: list, preview with marks, flagged, credential and noHire lines, apply by digest; pack text stays text', { timeout: 60000 }, async t => {
const { b, verbs } = await fixture(t);
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
assert.equal(await b.evaluate(`document.querySelector('[data-pack="software-team"] strong').textContent`), `Software team ${XSS}`);
// The project pack offers the code projects the workflow read lists.
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack="web-project"] [data-pack-project] option')].map(o=>o.value)`), ['site']);
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-preview]')`, 'preview');
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-item]')].map(r=>[r.dataset.packItem,r.querySelector('[data-pack-mark]').dataset.packMark,r.querySelector('[data-pack-mark]').textContent])`), [
['board', 'add', 'will be added'],
['definitions.reviewer', 'kept', 'kept: the organization has its own version differs in tools, instructions'],
['workflows.review', 'same', 'already the same'],
['workflows.ship', 'removed', 'stays removed: you removed it after an earlier apply'],
]);
const lead = '[data-pack-hire="lead-reviewer"]';
assert.match(await b.evaluate(`document.querySelector('${lead} [data-pack-flagged]').textContent`), /authority\.withinRole decision\.resolve\.technical above the chief, a resolve right/);
// The bus sends each credential line as {service, scope} (hire-decisions credentialLines); scope is absent
// when the definition names a service without scopes.
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('${lead} [data-pack-credentials] li')].map(l=>l.textContent)`), ['gitea repo:write', 'matrix']);
assert.match(await b.evaluate(`document.querySelector('${lead} [data-pack-nohire]').textContent`), /no-hire list/);
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire="builder"] [data-pack-nohire]')`), null);
assert.ok(await b.evaluate(`document.querySelector('[data-pack-hire="builder"] [data-pack-noflag]')!==null`));
assert.match(await b.evaluate(`document.querySelector('[data-pack-hire="builder"]').textContent`), /Not proposed/);
assert.match(await b.evaluate(`document.querySelector('[data-pack-skills]').textContent`), /lint-fix/);
assert.equal(await b.evaluate(`document.querySelectorAll('[data-packs] img').length`), 0, 'a pack label never becomes markup');
assert.equal(await b.evaluate(`window.__sp6pwn===undefined`), true);
assert.equal(verbs.filter(([v]) => v.startsWith('pack.apply')).length, 0, 'preview writes nothing');
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]').textContent)`, 'apply status');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board, definitions.reviewer. Proposed hires are recorded for the chief to raise as decisions.');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.apply.console').map(([, a]) => a), [{ pack: 'software-team', digest: REV('d') }]);
assert.equal(await b.evaluate(`document.querySelector('[data-pack-preview]')`), null);
// A project pack previews against the chosen project.
await b.evaluate(`document.querySelector('[data-pack="web-project"] [data-pack-preview-button]').click();true`);
await waitFor(b, `/for project site/.test(document.querySelector('[data-pack-preview] h4')?.textContent??'')`, 'project preview');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.preview.console').at(-1)[1], { pack: 'web-project', project: 'site' });
});
test('SP6 pack picker without send previews but offers no apply', { timeout: 60000 }, async t => {
const { b } = await fixture(t, { send: false });
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-preview]')`, 'preview');
assert.equal(await b.evaluate(`document.querySelector('[data-pack-apply]')`), null);
assert.match(await b.evaluate(`document.querySelector('[data-pack-preview]').textContent`), /started without send/);
assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit],[data-wf-new]')`), null, 'no workflow change controls without send');
});
test('SP6 workflows: list by scope, a step naming no current role, titles as text, edit, new and delete', { timeout: 60000 }, async t => {
const { b, verbs, flows } = await fixture(t);
await waitFor(b, `document.querySelector('[data-wf="intake"]')`, 'workflow list');
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wf-scope-list]')].map(n=>n.dataset.wfScopeList)`), ['', 'site']);
assert.equal(await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-title]').textContent`), `Intake ${XSS}`);
assert.equal(await b.evaluate(`document.querySelectorAll('[data-workflows] img').length`), 0, 'a workflow title never becomes markup');
assert.equal(await b.evaluate(`window.__sp6pwn===undefined`), true);
// triage (an org definition), human and coder (a template) resolve; ghost names no current role.
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wf="intake"] [data-wf-step]')].map(s=>s.querySelectorAll('[data-wf-missing]').length)`), [0, 1]);
assert.match(await b.evaluate(`document.querySelectorAll('[data-wf="intake"] [data-wf-step]')[1].textContent`), /ghost names no current role/);
assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf="ship"] [data-wf-missing]').length`), 0);
// Edit: the ghost step shows the mark in the editor; fixing the role clears it; save sends the revision.
await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`);
await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor');
assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), 'ghost names no current role');
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), `Intake ${XSS}`);
await b.evaluate(`{const r=document.querySelector('[data-wf-edit-step="1"] [name=roles]');r.value='reviewer, <b>x</b>';r.dispatchEvent(new Event('input',{bubbles:true}))}true`);
assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), '<b>x</b> names no current role');
assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf-edit-step="1"] b').length`), 0);
await b.evaluate(`{const r=document.querySelector('[data-wf-edit-step="1"] [name=roles]');r.value='reviewer';r.dispatchEvent(new Event('input',{bubbles:true}))}true`);
assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), '');
await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value='Intake';document.querySelector('[data-wf-editor]').requestSubmit();true`);
await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Saved intake.'`, 'save status');
const saved = verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1];
assert.deepEqual(saved, { revision: REV('a'), name: 'intake', workflow: { title: 'Intake', description: `Sort ${XSS}`, steps: [{ title: `Sort ${XSS}`, state: 'todo', roles: ['triage', 'human'] }, { title: 'Hand off', state: 'in-progress', roles: ['reviewer'] }] } });
assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf="intake"] [data-wf-missing]').length`), 0, 'the re-read shows the fixed step');
// New, in the project scope: a bad name is refused on the page and sends nothing.
const sets = () => verbs.filter(([v]) => v === 'workflow.set.console').length;
const before = sets();
await b.evaluate(`document.querySelector('[data-wf-new]').click();true`);
await waitFor(b, `document.querySelector('[data-wf-editor] select[name=scope]')`, 'new editor');
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.scope.value='site';f.elements.name.value='Bad Name';f.querySelector('[data-wf-edit-step="0"] [name=title]').value='Plan';f.querySelector('[data-wf-edit-step="0"] [name=roles]').value='human';f.requestSubmit()}true`);
await waitFor(b, `/lowercase/.test(document.querySelector('[data-workflows-status]').textContent)`, 'name refusal');
assert.equal(sets(), before);
// The writer's name rule (PLAN_NAME): no underscore, dot or leading digit. Each is refused here, not at the bus.
for (const bad of ['release_1', 'v2.ship', '2nd-review']) {
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value=${JSON.stringify(bad)};f.requestSubmit()}true`);
assert.equal(await b.evaluate(`document.querySelector('[data-workflows-status]').textContent`), 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.', bad);
assert.equal(sets(), before, `${bad} sends nothing`);
}
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=name]').placeholder`), 'lowercase letters, digits, dashes');
// A new workflow under a name the scope already holds would replace it: refused, nothing sent.
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value='ship';f.requestSubmit()}true`);
assert.equal(await b.evaluate(`document.querySelector('[data-workflows-status]').textContent`), 'A workflow named ship already exists here. Edit it instead.');
assert.equal(sets(), before, 'an existing name sends nothing');
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] select[name=scope]').value`), 'site', 'the editor keeps the chosen scope');
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value='plan';f.requestSubmit()}true`);
await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Saved plan.'`, 'new save');
assert.deepEqual(verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1], { revision: REV('b'), name: 'plan', workflow: { steps: [{ title: 'Plan', state: 'todo', roles: ['human'] }] }, project: 'site' });
assert.ok(await b.evaluate(`document.querySelector('[data-wf-scope-list="site"] [data-wf="plan"]')!==null`));
// Delete asks first; Keep sends nothing; Delete sends the project and the revision.
const del = `[data-wf-scope-list="site"] [data-wf="ship"]`;
await b.evaluate(`document.querySelector('${del} [data-wf-delete]').click();true`);
await waitFor(b, `document.querySelector('${del} [data-wf-delete-no]')`, 'delete confirm');
await b.evaluate(`document.querySelector('${del} [data-wf-delete-no]').click();true`);
await waitFor(b, `document.querySelector('${del} [data-wf-delete]')`, 'kept');
const n = sets();
await b.evaluate(`document.querySelector('${del} [data-wf-delete]').click();true`);
await waitFor(b, `document.querySelector('${del} [data-wf-delete-yes]')`, 'delete confirm again');
assert.equal(sets(), n);
const rev = flows().revision;
await b.evaluate(`document.querySelector('${del} [data-wf-delete-yes]').click();true`);
await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Deleted ship.'`, 'delete status');
assert.deepEqual(verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1], { revision: rev, name: 'ship', workflow: null, project: 'site' });
assert.equal(await b.evaluate(`document.querySelector('${del}')`), null);
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true);
});
@@ -0,0 +1,183 @@
// Starter packs SP6 (#1873): board styles on the task board, in a real browser. A board style
// relabels, reorders and sets the default layout over the five fixed states (Jason 11-12 Q3), and
// only while the view is narrowed to one organization or project; the all-orgs view keeps the fixed
// labels. Every bus is a fake in this file.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.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)})})()`);
const D = n => String(n).repeat(64);
const FIXED = ['To do', 'In progress', 'Review', 'Blocked', 'Done'];
// forge's board: a support desk's words, done first, list by default.
const FORGE_BOARD = { columns: [
{ state: 'done', label: 'Solved' }, { state: 'todo', label: 'New ticket' }, { state: 'in-progress', label: 'With an agent' },
{ state: 'in-review', label: 'Awaiting customer' }, { state: 'blocked', label: 'On hold' },
], layout: 'list' };
// forge's billing project has a board of its own, which wins over the org's for that project.
const BILLING_BOARD = { columns: [
{ state: 'todo', label: 'Draft' }, { state: 'in-progress', label: 'Invoicing' }, { state: 'in-review', label: 'Checked' },
{ state: 'blocked', label: 'Disputed' }, { state: 'done', label: 'Paid' },
], layout: 'kanban' };
const XSS = '<img src=x onerror=window.pwn=1>';
function orgs({ forgeBoard = FORGE_BOARD, billingBoard = BILLING_BOARD } = {}) {
const ORGS = [
{ id: 'ddigital', label: 'Distinctly Digital', theme: 'rosewood', busHealthy: true },
{ id: 'forge', label: 'Forge', theme: 'cobalt', busHealthy: true },
];
const DOCS = {
ddigital: { appearance: { theme: 'rosewood' }, roles: { editor: {} } },
forge: { appearance: { theme: 'cobalt' }, roles: { coder: {} }, ...(forgeBoard ? { board: forgeBoard } : {}),
projects: { gateway: { root: 'code/gateway', repo: 'gateway' }, billing: { root: 'code/billing', repo: 'billing', ...(billingBoard ? { board: billingBoard } : {}) } } },
};
const PROJECTS = {
ddigital: [{ id: 'spring-launch', repo: 'spring', name: 'Spring launch', at: '2026-11-09T10:00:00.000Z' }],
forge: [{ id: 'api-gateway', repo: 'gateway', name: 'API gateway', at: '2026-11-09T10:00:00.000Z' }, { id: 'billing', repo: 'billing', name: 'Billing', at: '2026-11-08T10:00:00.000Z' }],
};
const STORE = {
forge: [
{ n: 41, title: 'Rate limit the public API', state: 'todo', group: 'api-gateway' },
{ n: 42, title: 'Invoice export', state: 'in-progress', group: 'billing' },
{ n: 43, title: 'Retire the v1 gateway', state: 'done', group: 'api-gateway' },
],
ddigital: [{ n: 7, title: 'Launch email', state: 'in-review', group: 'spring-launch' }],
};
const tasks = id => STORE[id].map(t => ({ source: 'store', task_ref: `task:${t.n}`, at: '2026-11-09T12:00:00.000Z', priority: 0, digest: D(t.n % 10), requirement: 'REQ-API-1',
fields: { title: t.title, state: t.state, group: t.group, assignees: [], due_date: null } }));
const options = id => ({
bus: { inbox: async () => [], agents: async () => [], 'thread.claims': async () => [], tasks: async () => tasks(id), messages: async () => ({ messages: [], unread: 0 }) },
chat: { projects: async () => PROJECTS[id], threads: async () => [] },
});
const healthy = async () => ({ healthy: true, pid: 4242, boot: null });
return {
list: async () => ORGS,
members: async () => ORGS.map(o => ({ id: o.id, doc: DOCS[o.id], status: healthy, options: () => options(o.id) })),
resolve: async id => {
if (!ORGS.some(o => o.id === id)) return null;
return { busHealthy: true, reads: { business: async () => ({ business: { id, projects: PROJECTS[id].map(p => p.id) } }) }, ...options(id), taskWrite: async (verb, args) => ({ task_ref: args.task_ref, digest: D(9) }) };
},
};
}
async function open(t, fixture = orgs()) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture, send: async () => ({}), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
await b.viewport(1440, 900);
const url = `http://127.0.0.1:${server.address().port}/#/orgs/forge/tasks`;
await b.navigate(url);
const wait = waitFor(b);
await wait('document.querySelector("[data-tasks-board] [data-tb-tracker=forge]")');
return { b, wait, url };
}
const heads = b => b.evaluate('[...document.querySelectorAll("[data-tasks-board] .tb-col h3")].map(h => h.textContent)');
const layout = b => b.evaluate('document.querySelector("[data-tasks-board]").dataset.layout');
const pick = (b, wait, org) => b.evaluate(`document.querySelector("[data-tb-org='${org}']").click()`)
.then(() => wait(`document.querySelector("[data-tb-org='${org}']").getAttribute("aria-pressed") === "true"`));
const project = async (b, wait, value, count) => {
await b.evaluate(`(() => { const s = document.querySelector("[data-tb-filter=project]"); s.value = ${JSON.stringify(value)}; s.dispatchEvent(new Event("change", { bubbles: true })); })()`);
await wait(`document.querySelectorAll("[data-tasks-board] [data-tb-task]").length === ${count}`);
};
// The red-before test: on BASE the view filtered to forge showed the fixed labels.
test('a view filtered to an organization with a board shows its labels', async t => {
const { b, wait } = await open(t, orgs({ forgeBoard: { ...FORGE_BOARD, layout: 'kanban' } }));
assert.deepEqual(await heads(b), FIXED);
await pick(b, wait, 'forge');
assert.deepEqual(await heads(b), ['Solved', 'New ticket', 'With an agent', 'Awaiting customer', 'On hold']);
});
test('a filtered view uses the board\'s labels and order in the list, the filters and the dialog', async t => {
const { b, wait } = await open(t);
await pick(b, wait, 'forge');
// forge's board says list; no viewer choice is saved, so the board's layout is the default.
assert.equal(await layout(b), 'list');
// The list orders rows by the board's columns (Solved first) and labels each state cell with its label.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-tb-list] tbody tr")].map(r => r.dataset.tbTask)'), ['forge|task:43', 'forge|task:41', 'forge|task:42']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-tb-list] select.tb-move")].map(s => s.selectedOptions[0].textContent)'), ['Solved', 'New ticket', 'With an agent']);
assert.deepEqual(await b.evaluate('[...document.querySelector("[data-tb-list] select.tb-move").options].map(o => [o.value, o.textContent])'),
[['done', 'Solved'], ['todo', 'New ticket'], ['in-progress', 'With an agent'], ['in-review', 'Awaiting customer'], ['blocked', 'On hold']]);
// The state filter speaks the board's words too; its values stay the five fixed states.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-tb-filter=state] option")].map(o => [o.value, o.textContent])'),
[['', 'Any'], ['done', 'Solved'], ['todo', 'New ticket'], ['in-progress', 'With an agent'], ['in-review', 'Awaiting customer'], ['blocked', 'On hold']]);
// In Kanban the columns are the board's labels, in the board's order.
await b.evaluate('document.querySelector("[data-tb-layout=kanban]").click()');
await wait('document.querySelector("[data-tasks-board]").dataset.layout === "kanban"');
assert.deepEqual(await heads(b), ['Solved', 'New ticket', 'With an agent', 'Awaiting customer', 'On hold']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-tb-kanban] [data-tb-col]")].map(c => c.dataset.tbCol)'), ['done', 'todo', 'in-progress', 'in-review', 'blocked']);
// The edit dialog's state picker uses the same labels.
await b.evaluate('document.querySelector("[data-tb-open=\'forge|task:41\']").click()');
await wait('document.querySelector("#tb-dialog[open] select[name=state]")');
assert.deepEqual(await b.evaluate('[...document.querySelector("#tb-dialog select[name=state]").options].map(o => o.textContent)'), ['Solved', 'New ticket', 'With an agent', 'Awaiting customer', 'On hold']);
assert.equal(await b.evaluate('document.querySelector("#tb-dialog select[name=state]").value'), 'todo');
});
test('a project filter uses the project\'s board, and the org\'s when the project has none', async t => {
const { b, wait } = await open(t);
await b.evaluate('document.querySelector("[data-tb-layout=kanban]").click()');
await wait('document.querySelector("[data-tasks-board]").dataset.layout === "kanban"');
await project(b, wait, 'forge:billing', 1);
assert.deepEqual(await heads(b), ['Draft', 'Invoicing', 'Checked', 'Disputed', 'Paid']);
await project(b, wait, 'forge:api-gateway', 2);
assert.deepEqual(await heads(b), ['Solved', 'New ticket', 'With an agent', 'Awaiting customer', 'On hold']);
// ddigital holds no board: its project keeps the fixed labels.
await project(b, wait, 'ddigital:spring-launch', 1);
assert.deepEqual(await heads(b), FIXED);
});
test('the all-orgs view keeps today\'s labels, and so does an org without a board', async t => {
const { b, wait } = await open(t);
assert.equal(await b.evaluate('document.querySelector("[data-tb-org=\'\']").getAttribute("aria-pressed")'), 'true');
assert.equal(await layout(b), 'kanban');
assert.deepEqual(await heads(b), FIXED);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-tb-filter=state] option")].map(o => o.textContent)'), ['Any', ...FIXED]);
await pick(b, wait, 'ddigital');
assert.deepEqual(await heads(b), FIXED);
// Back to every organization after a narrowed view: the fixed labels return.
await pick(b, wait, 'forge');
await pick(b, wait, '');
assert.equal(await layout(b), 'kanban');
assert.deepEqual(await heads(b), FIXED);
});
test('a saved viewer layout wins over the board\'s default', async t => {
const { b, wait, url } = await open(t);
await pick(b, wait, 'forge');
assert.equal(await layout(b), 'list');
// The viewer picks Kanban, which is saved for this width; after a reload it still wins over forge's list.
await b.evaluate('document.querySelector("[data-tb-layout=kanban]").click()');
await wait('document.querySelector("[data-tasks-board]").dataset.layout === "kanban"');
assert.match(await b.evaluate('localStorage.getItem("mosaic-tasks-layout-v1")'), /"wide":"kanban"/);
await b.navigate(url.replace('/#', '/?reload=1#'));
await wait('document.querySelector("[data-tasks-board] [data-tb-tracker=forge]")');
await pick(b, wait, 'forge');
assert.equal(await layout(b), 'kanban');
assert.deepEqual(await heads(b), ['Solved', 'New ticket', 'With an agent', 'Awaiting customer', 'On hold']);
});
test('a board label holding markup renders as text', async t => {
const board = { columns: [{ state: 'todo', label: XSS }, ...FORGE_BOARD.columns.filter(c => c.state !== 'todo')], layout: 'kanban' };
const { b, wait } = await open(t, orgs({ forgeBoard: board }));
await pick(b, wait, 'forge');
assert.deepEqual((await heads(b)).slice(0, 2), [XSS, 'Solved']);
assert.equal(await b.evaluate('document.querySelector("[data-tb-col=todo]").getAttribute("aria-label")'), XSS);
assert.ok((await b.evaluate('[...document.querySelectorAll("[data-tb-filter=state] option")].map(o => o.textContent)')).includes(XSS));
await b.evaluate('document.querySelector("[data-tb-open=\'forge|task:41\']").click()');
await wait('document.querySelector("#tb-dialog[open] select[name=state]")');
assert.ok((await b.evaluate('[...document.querySelector("#tb-dialog select[name=state]").options].map(o => o.textContent)')).includes(XSS));
assert.equal(await b.evaluate('document.querySelectorAll("img[src=x]").length'), 0);
await new Promise(r => setTimeout(r, 200));
assert.equal(await b.evaluate('window.pwn === undefined'), true);
});
test('a board that is not exactly the five states is ignored, never half applied', async t => {
const broken = { columns: FORGE_BOARD.columns.slice(0, 4), layout: 'list' };
const { b, wait } = await open(t, orgs({ forgeBoard: broken, billingBoard: null }));
await pick(b, wait, 'forge');
assert.equal(await layout(b), 'kanban');
assert.deepEqual(await heads(b), FIXED);
});
+11 -1
View File
@@ -71,7 +71,7 @@ test('merge: every item from two buses carries its org, and the snapshot names b
// Archived projects are hidden by default; the default sort is newest activity first.
assert.deepEqual(body.projects.map(p => `${p.org}/${p.key}`), ['acme/site', 'beta/shop']);
const site = body.projects[0];
assert.deepEqual({ ...site }, { org: 'acme', id: 'p-site', key: 'site', name: 'Website', status: 'active', state: 'working', git: null,
assert.deepEqual({ ...site }, { org: 'acme', id: 'p-site', key: 'site', name: 'Website', status: 'active', state: 'working', git: null, board: null,
sessions: { working: 1, waiting: 1, idle: 0 }, openTasks: 1, needsYou: 1, lastActivity: '2026-11-09T12:00:00.000Z' });
const role = body.sessions.find(s => s.kind === 'role'), thread = body.sessions.find(s => s.kind === 'thread');
assert.equal(role.org, 'acme'); assert.equal(role.role, 'coder'); assert.equal(role.state, 'waiting'); assert.equal(role.inputNeeded, 1);
@@ -87,6 +87,16 @@ test('merge: every item from two buses carries its org, and the snapshot names b
assert.deepEqual(body.metrics.totals, { needsYou: 1, oldestNeedsYouAt: '2026-11-09T12:00:00.000Z', sessions: { working: 0, waiting: 1, idle: 0, live: 1 }, openTasks: 2, doneThisWeek: 1, projects: { active: 2, archived: 1 } });
});
test('SP6 board: the org head carries its board, each project row its project board, an invalid org none', async () => {
const ORG_BOARD = { columns: [{ state: 'done', label: 'Solved' }, { state: 'todo', label: 'New' }, { state: 'in-progress', label: 'Working' }, { state: 'in-review', label: 'Waiting' }, { state: 'blocked', label: 'On hold' }], layout: 'list' };
const SITE_BOARD = { columns: [{ state: 'todo', label: 'Draft' }, { state: 'in-progress', label: 'Editing' }, { state: 'in-review', label: 'Proof' }, { state: 'blocked', label: 'Held' }, { state: 'done', label: 'Live' }], layout: 'kanban' };
const doc = { ...ACME_DOC, board: ORG_BOARD, projects: { site: { root: '/x', board: SITE_BOARD }, old: { root: '/y' } } };
const broken = { id: 'gamma', invalid: true, reason: 'organization file is invalid', doc: { board: ORG_BOARD } };
const body = await readWorkspace({ organizations: organizationsOf(member('acme', ACME, { doc }), member('beta', BETA), broken), session: principal, now });
assert.deepEqual(body.orgs.map(o => [o.org, o.board]), [['acme', ORG_BOARD], ['beta', null], ['gamma', null]]);
assert.deepEqual(body.projects.map(p => [`${p.org}/${p.key}`, p.board]).sort(), [['acme/site', SITE_BOARD], ['beta/shop', null]]);
});
test('sections: only the asked sections are read and returned', async () => {
const asked = [];
const tracked = member('acme', ACME, { over: Object.fromEntries(['inbox', 'agents', 'claims', 'threads', 'tasks', 'projects', 'usage', 'limits', 'decisions'].map(n => [n, () => { asked.push(n); return Promise.resolve(ACME[n] ?? (['usage', 'limits'].includes(n) ? {} : [])); }])) });