Compare commits
14
Commits
f6w
..
sp2-polish
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1b01329bc | ||
|
|
c7aecbffa9 | ||
|
|
bb2f79f3d9 | ||
|
|
e24e7e93a2 | ||
|
|
387f73a7a4 | ||
|
|
61371adb10 | ||
|
|
b913f0f4c8 | ||
|
|
bfd2cc5e79 | ||
|
|
3e53af3941 | ||
|
|
359b3299b4 | ||
|
|
65f7288cea | ||
|
|
211b32ef1a | ||
|
|
163972e08e | ||
|
|
23e504f331 |
No files matched your search
@@ -346,8 +346,12 @@ For local development on a named instance only, `mosaic bus start BUSINESS --dev
|
||||
|
||||
The hire form and the autonomy panel from a terminal (E2, #1873, P1-3). `mosaic org role-templates|hire|fire|change ORG` and `mosaic org autonomy ORG [set|review]` send the page's own request to the running Console's org route (`/api/orgs/ORG/decisions/hire/templates|start`, `/api/orgs/ORG/autonomy[/review]`), as `org reload` does, so the Console applies the same owner, `--send`, origin, body and live-session checks and the same bus verbs run (`hire.templates.console`, `hire.start.console`, `autonomy.get.console`, `autonomy.set.console`, `autonomy.review.console`). `hire` and `change` read the templates first and send the chosen template's name and sha256, as the form does. `autonomy set` needs the 64-hex `--revision` from `mosaic org autonomy ORG` and sends every setting the panel sends, with only the named ones changed; a stale revision is refused `revision-conflict`; an empty `--authority-resolver ""` clears the resolver, as emptying the panel's field does. These verbs need a named instance (`MOSAIC_CONFIG` set to `~/.config/mosaic-NAME/config.json`) whose Console runs with `--dev-local-owner`; the default instance is refused with exit 3. A Console refusal exits 3 with the Console's code and message; `outcome-unknown` exits 1; an unknown template exits 2. Every one of these verbs, reads included, refuses inside an agent run. `mosaic tasks create|edit|archive` are the task board's three writes: the arguments pass the board's own check (`workspace-tasks.mjs parseTaskWrite`) and go to the bus as the person (`tasks.create|edit|archive`, human transport), so the bus runs its human, field, digest and archive checks. A stale `--expect` is refused `task-conflict`; read the digest with `mosaic tasks --json`.
|
||||
|
||||
Starter packs (#1873): `mosaic org pack list`, `mosaic org pack preview ID PACK [--project P]`, `mosaic org pack apply ID PACK --digest D [--project P]` and `mosaic org pack hire ID PACK [--project P]` call the bus as the organization's human (`packs`, `pack.preview`, `pack.apply`, `pack.hire`). Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's apply is the hire decision. After the pack commits, the same act hires each proposed agent through the hire-decisions path and the receipt's `hires` lists `{name, state, decision | code}` per proposal (`hired`, `exists`, `open`, `awaiting-owner`, `refused`); a `hired` or `awaiting-owner` line adds `routeFrom: 'chief' | 'assistant'`. The owner's apply approves the flagged and credential lines; a credential line is approved but not bound, so the agent's launch refuses `credential-unbound` until its services are bound. The bus verb `pack.hire.console` also takes a member's console cap with `org.hire`: it hires only the proposals with no flagged or credential line, and the rest wait for the owner in the inbox. No member surface calls it yet: the WebUI packs routes and the CLI `pack` words are the owner's. An owner's pack hire also replaces and approves a hire this pack's own member hire left in the inbox; the old decision is withdrawn only after the new hire applies. Two pack hires on one organization at once: the second refuses `organization-busy`; an apply whose hire loop did not run still answers the apply's receipt with `hireError` and no hires. An agent's apply hires nothing. `pack hire` reruns the loop on a pack already applied and hires none twice; it refuses `pack-not-applied` when the pack has no packs entry, and a hire runs as the chief of staff's harness and model, else the organization assistant's (the instance whose definition is `assistant`), and a proposal refuses `pack-hire-route-missing` only when neither has both. All pack words refuse inside an agent run (exit 3). The WebUI pack card's "Hire the N proposed agents" is `POST /api/orgs/<id>/packs/hire`. Details: `packages/cli/README.md`, `packages/bus/README.md` and `packages/webui/README.md`, "Starter pack hires"; design: `docs/plans/2026-11-12_starter-packs-design.md` section 3.
|
||||
|
||||
The bus and Console lifecycle verbs refuse inside an agent run (agent-guard, #1873): `mosaic bus start`, `bus stop`, `bus restart` and `bus recover`, and `mosaic console start`, `console stop` and `console restart`, and `mosaic org archive` and `org delete`, which stop the organization's bus, and `mosaic org restore`, which starts it (`org restore --no-bus` starts nothing and is not refused), and `mosaic org role-templates`, `hire`, `fire`, `change` and `autonomy` (E2). Each exits 3 with `refused: this runs only from a human shell, outside any agent run (found MARKER in the environment)` before it reads anything. It checks the environment it is given and its own process environment, so a sanitized environment does not hide a marker. A usage error (a missing or extra argument, `--pm` with `--no-launch`, or a bad `--dev-insecure-bind`/`--dev-allow-host`) still comes first (exit 4). `mosaic bus status` and `mosaic console status` stay open to agents. The Console's Restart bus and Restart Console controls keep working: the Console starts its bus host with its own environment, which carries no marker, and Restart Console relaunches the Console under its supervisor without going through the CLI. The markers are the ones `packages/cli/src/transport.mjs` lists. The check is cooperative: a process that drops the markers from its environment is not stopped by it.
|
||||
|
||||
Refusal lines (E2E6, #1873). A refusal that has a next step prints it on a second line, `mosaic: next: ...`, after the unchanged message, so callers that match the message keep working. `mosaic bus status`, `start`, `stop` and `restart` on a stale bus host lock exit 3 with `mosaic: stale bus host lock ...` and `mosaic: next: if the bus host died, clear it with mosaic bus recover ORG; recover refuses while the host still runs`. A human-transport verb whose bus is not running (no socket, or the connect refused before anything was sent) exits 3 with `bus-not-running: the bus for ORG is not running, so the request was not sent` and a next line naming `mosaic bus start ORG` and `mosaic bus recover ORG`; `outcome-unknown` (exit 1) stays for a request that left and got no answer. `mosaic org definitions` with an unknown organization, an unknown or malformed name, or a bad id prints one refusal line (exit 3; `unknown-organization` only when the organization file itself is missing, `definitions-unreadable` when `templates` cannot read the roles directory) or, for a bad id, the usage (exit 4), with no stack trace and no host path. Pack, board and workflow refusals carry their next step as `template save` does. `mosaic console start` and `console stop` clear a `console/start.lock` whose named supervisor (pid and start time) is gone, once, with a `cleared a console start lock left by process PID, which is gone` warning; a lock whose holder still runs, or that names no holder, refuses and stays. A start or stop releasing its lock marks it released through its own descriptor and removes the path only while it is still that file, so a lock put back after its release is cleared the same way, with a `cleared a console start lock its holder had released` warning. An `autonomy-precondition` refusal from the bus carries the check that failed (owner notices off, no tested reverse, a resolver without the right, no `review.verdict` holder, no enforced budget, out of the loop only from near the loop, the trail review or near-loop decision missing); the human-transport child writes only the code, so a terminal `org autonomy set` shows the Console's message. `mosaic org template save` writes free text verbatim: it never rewrites prose, and the preview lists every field that mentions the organization id, a project id, an agent name or the owner's account, with the names it mentions, for the owner to edit before sharing. Saving under a name already saved for the account refuses `template-exists` (exit 2, nothing written) with a next line to save under another name or list the saved ones with `mosaic org template list ORG`.
|
||||
|
||||
The instance processing switch is separate from per-business launches off/on.
|
||||
`mosaic halt` durably stops managed processing across every business in the
|
||||
selected configuration's data root. The bus stays up for reads and human
|
||||
|
||||
@@ -374,6 +374,48 @@ exactly as if a person had made them by hand. The steps:
|
||||
`projects.<p>.agents`; those entries refuse instance credential material
|
||||
(`BOUND_KEYS`, `agent-levels.mjs:21`).
|
||||
|
||||
**2026-11-14 change (#1873, lane pd).** Jason's ruling: "Damnit. If I
|
||||
choose a starter pack and apply it, that is a decision!" This replaces
|
||||
"Apply never hires" above for a person's apply. The `packs` entry and the
|
||||
proposals stay as written; what changes is who acts on them:
|
||||
- A person's apply (`pack.apply.console` from the WebUI, `pack.apply` from
|
||||
the CLI) is the hire decision. In the same act, after the pack's commit,
|
||||
the broker raises one hire decision per proposal through the
|
||||
hire-decisions path and resolves it, leaving the evidence an inbox
|
||||
approval leaves: the decision row, its resolved event, `human.input`,
|
||||
`hire.consume`, the `hire.apply` event and `action.allowed pack.hire`.
|
||||
The hired entry carries `hireDecision`.
|
||||
- Invariant 7 still decides each line. The owner's apply approves the
|
||||
flagged and credential lines. A member with `org.hire` hires only the
|
||||
proposals with neither a flagged nor a credential line; each of the
|
||||
others is raised as an open decision that waits for the owner in the
|
||||
inbox (`awaiting-owner`). The owner's later pack hire withdraws such a
|
||||
decision and hires the agent itself. An
|
||||
agent apply hires nothing: the hire stays a proposal for the chief, and
|
||||
a hire verb from an agent is refused `human-required`.
|
||||
- Credentials take the smallest rule. The hire writes the entry with no
|
||||
credential material, so its services show `unbound` and a launch is
|
||||
refused `credential-unbound` until someone binds them. The owner's
|
||||
approval covers the credential lines; it binds nothing and reads no
|
||||
secret.
|
||||
- The route is the chief of staff's resolved harness and model. With
|
||||
none, that proposal is refused `pack-hire-route-missing` and stays open.
|
||||
Note 2026-11-14 (lead ruling, lane pr2): the route is the chief's, else
|
||||
the organization assistant's (the instance whose definition is
|
||||
`assistant`; the one named `assistant` when there are several, else the
|
||||
first in key order), and the refusal applies only when neither resolves
|
||||
a harness and a model. Hire lines carry `routeFrom`.
|
||||
- `pack.hire` / `pack.hire.console` (`mosaic org pack hire ID PACK
|
||||
[--project P]`, `POST /api/orgs/<id>/packs/hire`) runs the same loop on
|
||||
a pack already applied, refused `pack-not-applied` otherwise. A proposal
|
||||
whose instance exists is `exists`, and one with an open decision is
|
||||
`open` or `awaiting-owner`, so neither a re-apply nor `pack hire` ever
|
||||
hires twice. A project pack hires into `projects.<p>.agents`.
|
||||
- Each hire line in the receipt is `{name, state, decision | code}` with
|
||||
state `hired`, `exists`, `open`, `awaiting-owner` or `refused`. The
|
||||
packs read adds `hired` and `open` (with each proposal's reason) to each
|
||||
applied entry, and the instances read names the pack an agent came from.
|
||||
|
||||
### The surface
|
||||
|
||||
| Layer | Name |
|
||||
|
||||
@@ -1135,3 +1135,40 @@ Each write records `human.input`. A task read returns a `digest` that can be sup
|
||||
`task-conflict`. Existing assignees may remain after a role is removed, but new assignees
|
||||
must be current roles. Automatic tail placement and an explicitly occupied position refuse
|
||||
`task-position-full` when there is no room; no task row is written.
|
||||
|
||||
## Starter pack hires (ruling 2026-11-14, #1873)
|
||||
|
||||
"If I choose a starter pack and apply it, that is a decision!" A person's
|
||||
`pack.apply` (the organization's human, outside any run) or `pack.apply.console`
|
||||
hires the proposals of the packs entry it wrote, once the apply has committed.
|
||||
An agent's `pack.apply` hires nothing. `pack.hire` (the owner's human session)
|
||||
and `pack.hire.console` (the owner's or a member's console cap, needing
|
||||
`org.hire`) run the same loop on a pack already applied; with no packs entry they
|
||||
refuse `pack-not-applied`.
|
||||
|
||||
Each proposal goes through `#raiseHire` and `hire.resolve.console`, the path an
|
||||
inbox approval takes: the decision row, its resolved event, `human.input`,
|
||||
`hire.consume`, the hire's commit and `hire.apply` event, plus
|
||||
`action.allowed {operation: 'pack.hire', pack, version, origin, project, hire,
|
||||
decision}`. The route is the chief of staff's resolved harness and model (the
|
||||
`launch.by` instance), else the organization assistant's: the instance whose
|
||||
definition is `assistant`, the one named `assistant` when there are several,
|
||||
else the first in key order. Thinking is carried when set. With neither the
|
||||
proposal refuses `pack-hire-route-missing`. A `hired` or `awaiting-owner` line
|
||||
carries `routeFrom: 'chief' | 'assistant'`. The entry is written with
|
||||
no credential material, so a credential line leaves its services `unbound`.
|
||||
A proposal whose instance exists is `exists`; one an open hire decision names is
|
||||
`open`, so nothing is hired twice. The owner approves every line, and replaces
|
||||
an open decision an earlier hire of the same pack left for the owner: the new
|
||||
hire is raised and applied first, and the old decision is withdrawn only once it
|
||||
has applied, so a replacement that refuses leaves the old one in the inbox. A member's flagged or credentialed hires are raised after
|
||||
the others, left open for the owner's inbox (`awaiting-owner`). A hire that
|
||||
refuses records `action.allowed {operation: 'pack.hire.refused', code}` and the
|
||||
loop goes on. The `packs` read adds `hired` and `open` to each applied entry,
|
||||
and the `instances` read adds `pack: {id, origin, project}` to each instance a
|
||||
pack hire created. An `awaiting-owner` line this pack's own hire raised carries
|
||||
`fromPack: true` (the owner's pack hire would replace it). One pack hire loop
|
||||
runs per business at a time; a second refuses `organization-busy`. An apply
|
||||
whose hire loop throws after the apply committed still answers the apply's
|
||||
receipt, with no hires and the loop's code as `hireError`. No member surface
|
||||
calls `pack.hire.console` yet; the Console's packs routes are the owner's.
|
||||
+240
-54
@@ -178,7 +178,7 @@ export const USER_VERBS = Object.freeze(['project.list', 'thread.create', 'threa
|
||||
'thread.share', 'thread.unshare', 'thread.shares']);
|
||||
// Row 252 (#1753, design sections 2-3): the only verbs a Console owner cap reaches. Every other verb
|
||||
// refuses it human-required before its own checks, and these refuse every other cap.
|
||||
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
// Task 3 (#1839): and the owner's intake controls. The reads and writes are the same lifecycle methods the PM's
|
||||
// unsuffixed verbs reach, with the owner's verified (provider, iss, sub) as the only caller; the PM-only
|
||||
// request.question and the PM's own reads keep their unsuffixed names and refuse a console cap.
|
||||
@@ -233,7 +233,7 @@ const TEMPLATE_KEYS = Object.freeze({
|
||||
export const TEMPLATE_BUS_KEYS = Object.freeze(Object.fromEntries(Object.entries(TEMPLATE_KEYS).flatMap(([verb, k]) => [[verb, k], [`${verb}.console`, k]])));
|
||||
// The codes a template refusal keeps, each with its reason: a field path or a checked name, never a
|
||||
// value from the organization file and never a host path.
|
||||
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
|
||||
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'template-exists', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
|
||||
// Row 175: the organization verbs a tester may call. Its writes run every check the human's do
|
||||
// and log actor `tester`; row 176 adds routes reads; limits.set, organization.set and organization.revision refuse it.
|
||||
export const TESTER_ORGANIZATION_VERBS = Object.freeze(['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
|
||||
@@ -289,9 +289,12 @@ export class BusError extends Error {
|
||||
if (reason !== undefined) this.reason = reason;
|
||||
}
|
||||
}
|
||||
const fail = (code) => {
|
||||
throw new BusError(code);
|
||||
// E2E6 fix 7: a refusal may carry a reason, static text that names which check failed; it never
|
||||
// quotes an argument or file bytes.
|
||||
const fail = (code, reason) => {
|
||||
throw new BusError(code, reason);
|
||||
};
|
||||
const BUDGET_UNCOVERED = 'no enforced budget covers new agents; authority away from the loop needs one';
|
||||
const object = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
// #1873 CB5: a copy binding proposal leaves the bus only as its copy and its change. The copy id,
|
||||
// incarnation, definition pin, services, grant ids and slots stay in the raise event, which the
|
||||
@@ -636,6 +639,9 @@ export class Broker {
|
||||
#builtinBinding;
|
||||
#organization;
|
||||
#hires;
|
||||
// Businesses with a pack hire loop running: a second loop on the same business refuses
|
||||
// organization-busy rather than raising a second decision for the same agent.
|
||||
#packHiring = new Set();
|
||||
#autonomyHost;
|
||||
#pluginService;
|
||||
#credentialVerbs;
|
||||
@@ -6262,16 +6268,16 @@ export class Broker {
|
||||
if (CREDENTIAL_VERBS.includes(request.verb)) return this.#requestCredential(s, request.verb, structuredClone(args));
|
||||
if(['autonomy.get.console','autonomy.set.console','autonomy.review.console','decision.reverse.console'].includes(request.verb)) {
|
||||
this.#autonomyOwner(s);
|
||||
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
|
||||
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
}
|
||||
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console'].includes(request.verb)) fail('human-required');
|
||||
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console','pack.hire.console'].includes(request.verb)) fail('human-required');
|
||||
if(request.verb==='decision.resolve' && !s.human) {
|
||||
if(s.tester)fail('tester-refused');
|
||||
keys(args,['id','choice','note'],['id','choice']);identifier(args.id);
|
||||
}
|
||||
if(request.verb==='decision.resolve' && !s.human && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action)) {
|
||||
const d=this.#decision(s,args.id);
|
||||
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
|
||||
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
}
|
||||
if(request.verb==='hire.templates.console') {
|
||||
keys(args,[]);const caller=this.#hireCaller(s);
|
||||
@@ -6285,14 +6291,32 @@ export class Broker {
|
||||
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);});
|
||||
return Promise.resolve().then(()=>{const r=this.#proposalHire(s,args);return this.#raiseHire(s,r.input,false,{pack:r.pack});}).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),request);});
|
||||
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),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);});
|
||||
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',e instanceof BusError?e.reason:undefined),request);});
|
||||
if (['hire.preview.console','hire.resolve.console'].includes(request.verb))
|
||||
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
|
||||
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
if (request.verb === 'grants.scope' || request.verb === 'grants.scope.set')
|
||||
return this.#grantScopeVerb(s, request.verb, structuredClone(args));
|
||||
// Ruling 2026-11-14: hire a pack's proposed agents after the apply that recorded them, through
|
||||
// the same loop a person's apply runs. pack.hire is the owner's CLI human cap; pack.hire.console
|
||||
// the owner's or a member's console cap. An agent and the tester never get here.
|
||||
if (request.verb === 'pack.hire' || request.verb === 'pack.hire.console') {
|
||||
if (s.tester) fail('tester-refused');
|
||||
if ((request.verb === 'pack.hire.console') !== !!s.console) fail('human-required');
|
||||
keys(args, ['pack', 'project'], ['pack']);
|
||||
if (typeof args.pack !== 'string' || !/^(saved:)?[a-z0-9][a-z0-9._-]{0,63}$/.test(args.pack)) fail('invalid-request');
|
||||
if (Object.hasOwn(args, 'project') && (typeof args.project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.project))) fail('invalid-request');
|
||||
const callerOf = () => this.#packHireCaller(s);
|
||||
if (!callerOf().rights.includes('org.hire')) fail('right-required');
|
||||
return Promise.resolve().then(async () => {
|
||||
const state = this.#organization ? this.#organization(s.business, 'pack.state', { pack: args.pack, project: args.project ?? null }, s.human, {}) : null;
|
||||
if (!state?.entry) fail('pack-not-applied');
|
||||
const out = await this.#packHires(s, callerOf, { pack: args.pack, project: args.project ?? null });
|
||||
this.#secretCheck(out); return { pack: state.entry.id, ...out };
|
||||
}).catch(e => { if (e instanceof BusError) throw this.#refused(s, e, request); this.#packFail(e); });
|
||||
}
|
||||
// #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
|
||||
@@ -6337,6 +6361,20 @@ export class Broker {
|
||||
if (spends && wrote) this.#store.transaction(() => this.#consumeAuthority(s, 'organization.change'));
|
||||
this.#secretCheck(value); return value;
|
||||
};
|
||||
// Ruling 2026-11-14: a person's apply is the hire decision. Once the apply has committed, the
|
||||
// same call hires the proposals (#packHires); an agent's apply never hires.
|
||||
// The apply has committed by then, so a hire loop that throws (organization-busy, a store error)
|
||||
// still returns the apply's receipt, with no hires and the loop's code as hireError.
|
||||
if (verb === 'pack.apply' && !agent) {
|
||||
const hired = async (value) => {
|
||||
let out;
|
||||
try { out = await this.#packHires(s, () => this.#packHireCaller(s), { pack: args.pack, project: args.project ?? null }); }
|
||||
catch (e) { out = { hires: [], hireError: e instanceof BusError && typeof e.code === 'string' ? e.code : 'outcome-unknown' }; }
|
||||
return done({ ...value, ...out });
|
||||
};
|
||||
return Promise.resolve(result).then(value => value, packFail).then(hired);
|
||||
}
|
||||
if (verb === 'packs') return Promise.resolve(result).then(value => done(this.#packsEnrich(s.business, value)), packFail);
|
||||
return result?.then ? result.then(done, packFail) : done(result);
|
||||
}
|
||||
// #1873 SP8: saving a template. Only the organization's owner: the human cap from the CLI or the
|
||||
@@ -6458,6 +6496,12 @@ export class Broker {
|
||||
entry.running = this.#running(s.business, name);
|
||||
entry.alive = this.#aliveAfterFire(s.business, name);
|
||||
}
|
||||
// Ruling 2026-11-14: each instance a pack hire created names the pack, from its pack.hire event.
|
||||
if (request.verb === "instances" && result?.instances && typeof result.instances === "object") {
|
||||
const from = this.#packHireOrigins(s.business);
|
||||
for (const entry of Object.values(result.instances))
|
||||
if (typeof entry.hireDecision === 'string' && from.has(entry.hireDecision)) entry.pack = from.get(entry.hireDecision);
|
||||
}
|
||||
// #1873 A3: the copies this bus booted with, and each one's running runs. The file's own
|
||||
// instances above carry no copy; a copy carries its state, missing service names or reason.
|
||||
if (request.verb === "instances" && result?.instances && typeof result.instances === "object" && this.#business(s.business).copies)
|
||||
@@ -6628,7 +6672,7 @@ export class Broker {
|
||||
if(!this.#autonomyHost?.get || !this.#autonomyHost?.set)fail('not-configured');
|
||||
const old=await this.#autonomyHost.get(s.business),b=this.#business(s.business);
|
||||
if(a.revision!==old.revision)fail('revision-conflict');
|
||||
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition');
|
||||
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition','owner notices are off; a class near the loop needs them on');
|
||||
for(const cls of AUTONOMY_CLASSES) {
|
||||
const before=decisionAutonomy(cls,old.autonomy),after=decisionAutonomy(cls,a.autonomy);
|
||||
// Pulling back is unconditional. Only a move away from the loop has prerequisites.
|
||||
@@ -6637,22 +6681,24 @@ export class Broker {
|
||||
if(cls==='policy')continue;
|
||||
if(cls==='authority' && after==='out of the loop' && before!==after)fail('authority-limits-unavailable');
|
||||
if(['in the loop','near the loop','out of the loop'].indexOf(after)<=['in the loop','near the loop','out of the loop'].indexOf(before))continue;
|
||||
if(a.autonomy.notices!==true || !this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition');
|
||||
if(a.autonomy.notices!==true)fail('autonomy-precondition',`owner notices are off; moving ${cls} away from the loop needs them on`);
|
||||
if(!this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition',`${cls} has no tested reverse in this organization, so it stays in the loop`);
|
||||
const resolvers=cls==='authority'?[a.autonomy.authorityResolver]:cls==='merge'?[b.arbiters.technical]:cls==='policy'?[b.arbiters.delivery]:Object.values(b.arbiters);
|
||||
for(const name of resolvers) {
|
||||
const role=b.roles[name],right=cls==='authority'?'decision.resolve.authority':`decision.resolve.${cls==='merge'?'technical':cls==='policy'?'delivery':name===b.arbiters.technical?'technical':'delivery'}`;
|
||||
if(!role?.authority?.withinRole.includes(right) || (cls==='authority' && name===b.launch?.by))fail('autonomy-precondition');
|
||||
if(!role?.authority?.withinRole.includes(right))fail('autonomy-precondition',cls==='authority'?'the authority resolver is not a role with decision.resolve.authority':`the ${cls} resolver is not a role with ${right}`);
|
||||
if(cls==='authority' && name===b.launch?.by)fail('autonomy-precondition','the authority resolver is the role that launches agents; name a separate resolver');
|
||||
}
|
||||
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition');
|
||||
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition');
|
||||
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition',`no role holds review.verdict, which ${cls} away from the loop needs`);
|
||||
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(after==='out of the loop') {
|
||||
if(before!=='near the loop')fail('autonomy-precondition');
|
||||
if(before!=='near the loop')fail('autonomy-precondition',`${cls} moves out of the loop only from near the loop`);
|
||||
const review=this.#store.get("SELECT seq,body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.review' AND json_extract(body,'$.decisionClass')=? ORDER BY seq DESC LIMIT 1",s.business,cls);
|
||||
const latest=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.set' ORDER BY seq DESC LIMIT 1",s.business);
|
||||
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition');
|
||||
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition',`${cls} needs your review of its trail since the last autonomy change`);
|
||||
const notice=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.notice' AND json_extract(body,'$.decisionClass')=? AND seq>? ORDER BY seq DESC LIMIT 1",s.business,cls,latest?.seq??0);
|
||||
const reversal=this.#store.get("SELECT max(e.seq) seq FROM events e WHERE e.business=? AND e.kind='action.allowed' AND json_extract(e.body,'$.operation') LIKE 'autonomy.reverse%' AND EXISTS(SELECT 1 FROM events n WHERE n.business=e.business AND n.kind='action.allowed' AND json_extract(n.body,'$.operation')='autonomy.notice' AND json_extract(n.body,'$.decisionClass')=? AND json_extract(n.body,'$.decision')=json_extract(e.body,'$.decision'))",s.business,cls);
|
||||
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition');
|
||||
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition',`${cls} needs a near-loop decision since the last autonomy change, and your trail review after it`);
|
||||
}
|
||||
}
|
||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'autonomy.set.requested',autonomy:a.autonomy,subject:s.console},null));
|
||||
@@ -6736,28 +6782,159 @@ export class Broker {
|
||||
.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 role = this.#pinRole(b.launch?.noHire ?? [], hire);
|
||||
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 };
|
||||
return { input: { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason },
|
||||
pack: { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project } };
|
||||
}
|
||||
async #raiseHire(s, input, immediate) {
|
||||
// A recorded proposal's pin as a hire request's role (SP5's chief raise and a person's pack hire).
|
||||
#pinRole(noHire, hire) {
|
||||
const pin = hire?.pin;
|
||||
if (!object(pin)) fail('invalid-request');
|
||||
if (!Object.hasOwn(pin, 'inline')) return structuredClone(pin);
|
||||
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 && noHire.includes(from)) fail('definition-not-hireable');
|
||||
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
|
||||
return { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
|
||||
}
|
||||
// Ruling 2026-11-14: a person's pack apply is the hire decision. The person who may hire from a
|
||||
// pack: the owner's console cap, the owner's CLI human cap (outside any run), or a member's console
|
||||
// cap with org.hire. Anyone else is refused human-required; the tester tester-refused.
|
||||
#packHireCaller(s) {
|
||||
if (s.tester) fail('tester-refused');
|
||||
if (s.console) return this.#hireCaller(s);
|
||||
this.#human(s);
|
||||
if (s.human !== this.#business(s.business).human) fail('human-required');
|
||||
return { actor: s.human, agent: false, rights: ['org.hire'], owner: true, instanceOwner: false, subject: null, via: 'cli' };
|
||||
}
|
||||
#openHireDecisions(business) {
|
||||
return 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`, business)
|
||||
.map(({ id }) => ({ id, hire: this.#raised(business, id)?.hire })).filter(x => object(x.hire));
|
||||
}
|
||||
// decision id -> {id, origin, project} of the pack whose hire raised it.
|
||||
#packHireOrigins(business) {
|
||||
return new Map(this.#packHireEvents(business).filter(e => e.operation === 'pack.hire' && typeof e.decision === 'string')
|
||||
.map(e => [e.decision, { id: e.pack, origin: e.origin ?? null, project: e.project ?? null }]));
|
||||
}
|
||||
// Ruling 2026-11-14: the packs read gains, per applied entry, the agents its hires created
|
||||
// (launched, for the organization level) and each proposal still open: awaiting-owner with its
|
||||
// decision, refused with the last refusal code, or proposed. Each carries the pack's reason.
|
||||
#packsEnrich(business, value) {
|
||||
if (!Array.isArray(value?.applied)) return value;
|
||||
const events = this.#packHireEvents(business), agents = value.agents ?? { org: {}, projects: {} };
|
||||
const open = new Map(this.#openHireDecisions(business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
|
||||
const raisedBy = new Map(events.filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
|
||||
for (const a of value.applied) {
|
||||
const level = a.project === null ? agents.org ?? {} : agents.projects?.[a.project] ?? {};
|
||||
const mine = e => e.pack === a.id && (e.origin ?? null) === (a.origin ?? null) && (e.project ?? null) === (a.project ?? null);
|
||||
// Hired: every live instance at the entry's level a hire of this pack created, whichever entry
|
||||
// proposed it (a re-apply records an entry that proposes nothing new).
|
||||
a.hired = Object.entries(level).filter(([, inst]) => inst.launched && inst.hireDecision && raisedBy.has(inst.hireDecision) && mine(raisedBy.get(inst.hireDecision))).map(([name]) => name);
|
||||
a.open = [];
|
||||
for (const h of a.proposedHires) {
|
||||
if (Object.hasOwn(level, h.name)) continue;
|
||||
const decision = open.get(JSON.stringify([h.name, a.project ?? null]));
|
||||
// fromPack: this pack's own hire raised it, so the owner's pack hire replaces and approves it.
|
||||
if (decision) { a.open.push({ name: h.name, reason: h.reason, state: 'awaiting-owner', decision, ...(raisedBy.has(decision) && mine(raisedBy.get(decision)) ? { fromPack: true } : {}) }); continue; }
|
||||
const last = events.filter(e => mine(e) && e.hire === h.name).at(-1);
|
||||
if (last?.operation === 'pack.hire.refused') a.open.push({ name: h.name, reason: h.reason, state: 'refused', code: last.code });
|
||||
else a.open.push({ name: h.name, reason: h.reason, state: 'proposed' });
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
#packHireEvents(business) {
|
||||
return this.#store.all(`SELECT body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation') IN ('pack.hire','pack.hire.refused') ORDER BY seq`, business)
|
||||
.map(r => JSON.parse(r.body));
|
||||
}
|
||||
// One pass over the latest packs entry of `pack` (and project): each proposed hire is raised and
|
||||
// approved in the same act through #raiseHire and #hireConsole, the path an inbox approval takes, so
|
||||
// each agent leaves the same decision record. A hire whose instance exists, or that an open hire
|
||||
// decision already names, is skipped, so a re-apply hires nothing twice. The owner approves every
|
||||
// line. A member approves only the unflagged hires; each flagged or credentialed one is recorded
|
||||
// after them, pinned to the final revision, as an open decision for the owner's inbox. A hire that
|
||||
// refuses records action.allowed pack.hire.refused with its code, and the loop goes on.
|
||||
async #packHires(s, callerOf, { pack, project = null }) {
|
||||
if (!this.#organization || !this.#hires) fail('not-configured');
|
||||
if (this.#packHiring.has(s.business)) fail('organization-busy');
|
||||
this.#packHiring.add(s.business);
|
||||
try { return await this.#packHireLoop(s, callerOf, { pack, project }); }
|
||||
finally { this.#packHiring.delete(s.business); }
|
||||
}
|
||||
async #packHireLoop(s, callerOf, { pack, project }) {
|
||||
const caller = callerOf();
|
||||
const read = () => this.#organization(s.business, 'pack.state', { pack, project }, caller.actor, {});
|
||||
const state = read();
|
||||
if (!state?.entry) return { hires: [] };
|
||||
const entry = state.entry, provenance = { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project };
|
||||
const out = [], deferred = [];
|
||||
const refused = (name, e) => {
|
||||
const code = e?.code ?? 'outcome-unknown';
|
||||
this.#store.transaction(() => this.#event(s, 'action.allowed', { operation: 'pack.hire.refused', pack: entry.id, origin: entry.origin ?? null, project, hire: name, code }, null));
|
||||
out.push({ name, state: 'refused', code });
|
||||
};
|
||||
const open = new Map(this.#openHireDecisions(s.business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
|
||||
const raisedBy = new Map(this.#packHireEvents(s.business).filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
|
||||
for (const hire of (Array.isArray(entry.proposedHires) ? entry.proposedHires : []).filter(object)) {
|
||||
const name = hire.name;
|
||||
if (state.names.includes(name)) { out.push({ name, state: 'exists' }); continue; }
|
||||
const openId = open.get(JSON.stringify([name, project]));
|
||||
// The owner's pack hire approves every line, so an open decision an earlier pack hire of this
|
||||
// same pack left for the owner is replaced by one approved now (its pin may be stale after the
|
||||
// hires approved since). The old one is withdrawn only once the new hire has applied: a
|
||||
// replacement that refuses leaves it open in the owner's inbox. Any other open decision is left alone.
|
||||
let supersedes = null;
|
||||
if (openId) {
|
||||
const by = raisedBy.get(openId);
|
||||
if (caller.owner !== true || !by || by.pack !== entry.id || (by.origin ?? null) !== (entry.origin ?? null) || (by.project ?? null) !== project) { out.push({ name, state: 'open', decision: openId }); continue; }
|
||||
supersedes = openId;
|
||||
}
|
||||
let input;
|
||||
try {
|
||||
if (!state.route) fail('pack-hire-route-missing');
|
||||
input = { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name, role: this.#pinRole(state.noHire, hire), route: structuredClone(state.route),
|
||||
reason: typeof hire.reason === 'string' && hire.reason.trim() ? hire.reason : `Proposed by starter pack ${entry.id}.` };
|
||||
} catch (e) { refused(name, e); continue; }
|
||||
let r;
|
||||
try {
|
||||
r = await this.#raiseHire(s, input, true, { caller: callerOf, pack: provenance, defer: caller.owner !== true });
|
||||
} catch (e) { refused(name, e); continue; }
|
||||
if (r?.deferred) { deferred.push(input); continue; }
|
||||
if (supersedes) this.#store.transaction(() => {
|
||||
if (this.#closed(supersedes)) return;
|
||||
const seq = Number(this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,note,via) VALUES(?,?,?,?,?,?,?)',
|
||||
supersedes, this.#now(), 'withdrawn', caller.actor, null, null, caller.via ?? 'console').lastInsertRowid);
|
||||
this.#event(s, 'human.input', { kind: 'answer', decision: supersedes, op: 'withdrawn', choice: null, via: caller.via ?? 'console', subject: caller.via === 'cli' ? null : s.console, decisionSeq: seq }, supersedes);
|
||||
});
|
||||
out.push({ name, state: 'hired', decision: r.id, routeFrom: state.routeFrom, ...(supersedes ? { supersedes } : {}) });
|
||||
}
|
||||
for (const input of deferred) {
|
||||
try {
|
||||
const r = await this.#raiseHire(s, input, false, { caller: callerOf, pack: provenance, record: true });
|
||||
out.push({ name: input.name, state: 'awaiting-owner', decision: r.id, routeFrom: state.routeFrom });
|
||||
} catch (e) { refused(input.name, e); }
|
||||
}
|
||||
return { hires: out };
|
||||
}
|
||||
|
||||
// opts (ruling 2026-11-14, a person's pack apply is the hire decision):
|
||||
// caller: () => the person's hire caller, read again after prepare. Default #hireCaller(s).
|
||||
// pack: {pack, version, origin, project}; the raise also records action.allowed pack.hire.
|
||||
// defer: a flagged or credentialed hire a non-owner may not approve returns {deferred: true}
|
||||
// instead of refusing hire-owner-required, and records nothing.
|
||||
// record: the person's raise is left open for the owner's inbox (route human, not resolved).
|
||||
async #raiseHire(s, input, immediate, opts = {}) {
|
||||
const b=this.#business(s.business);
|
||||
const human=immediate || opts.record===true;
|
||||
const callerOf=()=>opts.caller ? opts.caller() : this.#hireCaller(s);
|
||||
// Change is a replacement composition and uses the existing role.hire grant.
|
||||
const chiefAllowed=()=>{
|
||||
this.#agent(s);
|
||||
@@ -6767,36 +6944,44 @@ export class Broker {
|
||||
};
|
||||
// #1873 CB1: a copy credential binding is owner-only. A person raising one in one step must be
|
||||
// the organization's owner; a member with org.hire is not.
|
||||
if(immediate) { const c=this.#hireCaller(s); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
|
||||
if(human) { const c=callerOf(); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
|
||||
else chiefAllowed();
|
||||
if(!this.#hires)fail('not-configured');
|
||||
const did=randomUUID(), at=this.#now(), expiresAt=new Date(Date.parse(at)+7*86400000).toISOString();
|
||||
const p=await this.#hires.prepare(s.business,structuredClone(input),{id:did,expiresAt});
|
||||
// Recheck the chief after asynchronous preparation; a released run cannot raise.
|
||||
if(!immediate)chiefAllowed();
|
||||
let caller=null;
|
||||
if(!human)chiefAllowed();
|
||||
else {
|
||||
const caller=this.#hireCaller(s);
|
||||
caller=callerOf();
|
||||
if(p.binding && caller.owner!==true)fail('human-required');
|
||||
if(!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner)))fail('hire-owner-required');
|
||||
const ownerOnly=!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner));
|
||||
if(ownerOnly && opts.defer===true)return {deferred:true,name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
|
||||
if(ownerOnly && opts.record!==true)fail('hire-owner-required');
|
||||
}
|
||||
const action=`role.${p.op}`;
|
||||
const level=decisionAutonomy('authority',b.autonomy);
|
||||
let route='human';
|
||||
// A binding always goes to the owner; no autonomy level moves it (design section 4).
|
||||
if(!immediate && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
if(!human && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
if(level==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
route=b.autonomy?.authorityResolver;
|
||||
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition');
|
||||
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition','the authority resolver is not a role with decision.resolve.authority');
|
||||
if(route===s.role || resolverSubject(b,route,p.name))route='human';
|
||||
}
|
||||
this.#store.transaction(()=>{
|
||||
const raiser=immediate?'human':s.role;
|
||||
const raiser=human?'human':s.role;
|
||||
const run=human?(caller?.via==='cli'?'human-cli':'human-console'):s.run;
|
||||
this.#store.run('INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,blocking) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
did,at,s.business,p.project??null,raiser,immediate?'human-console':s.run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
did,at,s.business,p.project??null,raiser,run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
this.#event(s,'action.allowed',{operation:'decision.raise',decision:did,action,approvalChoice:'yes',target:p.name,hire:p,autonomyLevel:level},did);
|
||||
// The pack this hire came from, for the Agents page and the pack card. No target key: the
|
||||
// decision.raise above is the record the decision readers key on.
|
||||
if(opts.pack)this.#event(s,'action.allowed',{operation:'pack.hire',pack:opts.pack.pack,version:opts.pack.version??null,origin:opts.pack.origin??null,project:opts.pack.project??null,hire:p.name,decision:did},did);
|
||||
});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest},opts.caller ?? null);
|
||||
if(human) return {id:did,op:'raised',name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
|
||||
return {...this.#decisionView(this.#decision(s,did)),hire:bindingSummary(p)};
|
||||
}
|
||||
// The harness fact comes from the host's loaded modules; no host, no account coverage.
|
||||
@@ -6818,7 +7003,7 @@ export class Broker {
|
||||
if(this.#expireHire(s,d,p))fail('decision-expired');
|
||||
if(this.#autonomyLevel(d)==='in the loop')fail('hire-resolution-required');
|
||||
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(!this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority'))fail('not-resolver');
|
||||
};
|
||||
validate();
|
||||
@@ -6838,7 +7023,7 @@ export class Broker {
|
||||
const recheck=()=>{
|
||||
this.#agent(s);
|
||||
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(this.#autonomyLevel(d)==='in the loop' || !this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority') || resolverSubject(this.#business(s.business),s.role,p.name))fail('not-resolver');
|
||||
};
|
||||
recheck();
|
||||
@@ -6853,8 +7038,8 @@ export class Broker {
|
||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'hire.failed',decision:d.id,code:error.code??'outcome-unknown'},d.id));throw error;
|
||||
}
|
||||
}
|
||||
async #hireConsole(s,verb,a) {
|
||||
const caller={...this.#hireCaller(s),now:()=>Math.max(Date.now(),this.#clock)};
|
||||
async #hireConsole(s,verb,a,callerOf=null) {
|
||||
const caller={...(callerOf ? callerOf() : this.#hireCaller(s)),now:()=>Math.max(Date.now(),this.#clock)};
|
||||
keys(a,verb==='hire.preview.console'?['id','adjust']:['id','choice','digest','adjust'],verb==='hire.preview.console'?['id']:['id','choice','digest']);
|
||||
identifier(a.id);
|
||||
const d=this.#decision(s,a.id), raise=this.#raised(s.business,d.id);
|
||||
@@ -6877,8 +7062,9 @@ export class Broker {
|
||||
// A durable close/consume precedes the external file effect. A crash never replays an approval.
|
||||
this.#store.transaction(()=>{
|
||||
if(this.#closed(d.id))fail('decision-closed');
|
||||
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,'console');
|
||||
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via:'console',subject:s.console},d.id);
|
||||
const via=caller.via ?? 'console';
|
||||
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,via);
|
||||
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via,subject:callerOf ? caller.subject ?? null : s.console},d.id);
|
||||
if(a.choice==='yes')this.#event(s,'action.allowed',{operation:'hire.consume',decision:d.id,digest:p.digest,hire:p},d.id);
|
||||
});
|
||||
if(a.choice==='no')return {id:d.id,op:'resolved',choice:a.choice};
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { connect } from 'node:net';
|
||||
import { BusError, PROJECT_SAVE_VERB, PROJECT_SAVE_REQUEST_MAX } from './broker.mjs';
|
||||
// E2E6 fix 6: a connect that fails with one of these never sent the request. The code stays
|
||||
// outcome-unknown for every caller that reads it (the harness, the Console), and the error is marked
|
||||
// notSent so the human and tester shims can exit with NOT_SENT_EXIT and `mosaic` can say the bus is
|
||||
// not running.
|
||||
const NOT_SENT = new Set(['ENOENT', 'ECONNREFUSED', 'ENOTDIR', 'ENOTSOCK']);
|
||||
export const NOT_SENT_EXIT = 5;
|
||||
export class Client {
|
||||
constructor({ path, cap, human, tester, user, console: owner, timeout = 5000 }) {
|
||||
this.path = path;
|
||||
@@ -22,7 +28,8 @@ export class Client {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = connect(this.path);
|
||||
let input = Buffer.alloc(0),
|
||||
settled = false;
|
||||
settled = false,
|
||||
connected = false;
|
||||
const end = (error, value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
@@ -30,8 +37,12 @@ export class Client {
|
||||
error ? reject(error) : resolve(value);
|
||||
};
|
||||
socket.setTimeout(['processing.halt', 'processing.resume'].includes(verb) ? Math.max(this.timeout, 20000) : this.timeout, () => end(new BusError('outcome-unknown')));
|
||||
socket.on('connect', () => socket.write(request));
|
||||
socket.on('error', () => end(new BusError('outcome-unknown')));
|
||||
socket.on('connect', () => { connected = true; socket.write(request); });
|
||||
socket.on('error', (error) => {
|
||||
const unknown = new BusError('outcome-unknown');
|
||||
if (!connected && NOT_SENT.has(error?.code)) unknown.notSent = true;
|
||||
end(unknown);
|
||||
});
|
||||
socket.on('end', () => end(new BusError('outcome-unknown')));
|
||||
socket.on('data', (b) => {
|
||||
input = Buffer.concat([input, b]);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Client } from './client.mjs';
|
||||
import { Client, NOT_SENT_EXIT } from './client.mjs';
|
||||
import { readProcess } from './human.mjs';
|
||||
const file = fileURLToPath(import.meta.url);
|
||||
if (!process.env.MOSAIC_BUS_CLI_NONCE) {
|
||||
@@ -39,5 +39,7 @@ try {
|
||||
process.stdout.write(JSON.stringify(result) + '\n');
|
||||
} catch (e) {
|
||||
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
|
||||
process.exitCode = 2;
|
||||
// E2E6 fix 6: a request that never left (no socket, or the connect refused) keeps its code and
|
||||
// exits NOT_SENT_EXIT, so `mosaic` can say the bus is not running. Every other failure exits 2.
|
||||
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
|
||||
}
|
||||
@@ -218,6 +218,19 @@ group(
|
||||
"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."
|
||||
);
|
||||
// Ruling 2026-11-14: a person's pack apply is the hire decision. The hire action works from the packs
|
||||
// entry an apply recorded, and each hire runs as the chief's harness and model, else the org
|
||||
// assistant's (lane pr2).
|
||||
group(
|
||||
"pack-not-applied",
|
||||
"R8: a pack hire works from the packs entry an apply recorded",
|
||||
"Preview and apply the pack first; its proposed hires come from the packs entry that apply records."
|
||||
);
|
||||
group(
|
||||
"pack-hire-route-missing",
|
||||
"R3/R8: a hire runs as a harness and model the organization names",
|
||||
"Neither the chief of staff nor the organization's assistant resolves a harness and a model. Give the chief of staff or the assistant both in its vars, or set them at the organization or system level, then use the pack's hire action again."
|
||||
);
|
||||
// #1873 SP8: a saved template carries no credential the bus holds. Save checks every kept string and
|
||||
// key against the credential store; a hit names the field, never the text.
|
||||
group(
|
||||
@@ -225,6 +238,12 @@ group(
|
||||
"R1/R10: a saved template carries no credential value the bus holds",
|
||||
"A field the template would keep holds a credential value. Remove it from the named definition, board or workflow text, then preview and save again."
|
||||
);
|
||||
// E2E6 fix 8: save never replaces a template already saved under the name.
|
||||
group(
|
||||
"template-exists",
|
||||
"R10: a saved template is never replaced",
|
||||
"A template of this name is already saved for your account. Save under another name, or list your saved templates to pick a free one."
|
||||
);
|
||||
group(
|
||||
"not-resolver",
|
||||
"Role resolve right and decision route",
|
||||
|
||||
@@ -300,7 +300,7 @@ const COPY_SWEEP_MS = 60000;
|
||||
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 PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.state': 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'); };
|
||||
@@ -501,9 +501,67 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
return `projects.${args.project}.${key}`;
|
||||
};
|
||||
const revisionOf = args => { if (typeof args.revision !== 'string' || !/^[0-9a-f]{64}$/.test(args.revision)) bad(); return args.revision; };
|
||||
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): the
|
||||
// organization facts the broker's pack hire loop and the packs read need, as the file stands.
|
||||
// `pack` names a packs entry the way apply names the pack: saved:NAME is the owner's saved
|
||||
// template, any other name the latest shipped or installed entry of that id. The route is a
|
||||
// resolved harness, model and thinking (system, organization and agent vars): the chief's (the
|
||||
// launch.by instance), else the org assistant's (lane pr2, lead ruling 2026-11-14), else null.
|
||||
// routeFrom names which one gave it.
|
||||
const latestEntries = doc => {
|
||||
const latest = new Map();
|
||||
for (const e of doc.packs ?? []) if (isObject(e) && typeof e.id === 'string') latest.set(canonicalJson([e.id, e.origin ?? null, e.project ?? null]), e);
|
||||
return [...latest.values()];
|
||||
};
|
||||
const agentsOf = doc => {
|
||||
const launched = doc.launch?.instances ?? [];
|
||||
const one = (entry, isLaunched) => ({ hireDecision: typeof entry?.hireDecision === 'string' ? entry.hireDecision : null, launched: isLaunched });
|
||||
return {
|
||||
org: Object.fromEntries(Object.entries(doc.roles ?? {}).map(([name, e]) => [name, one(e, launched.includes(name))])),
|
||||
projects: Object.fromEntries(Object.entries(doc.projects ?? {}).filter(([, p]) => isObject(p) && p.kind !== 'library')
|
||||
.map(([project, p]) => [project, Object.fromEntries(Object.entries(p.agents ?? {}).map(([name, e]) => [name, one(e, true)]))])),
|
||||
};
|
||||
};
|
||||
// The org assistant is the instance whose definition is `assistant` (broker.mjs continuationEffect);
|
||||
// with several, the one named `assistant`, else the first in key order.
|
||||
const packRoute = (doc, id) => {
|
||||
const roles = doc.roles ?? {};
|
||||
let loaded = null;
|
||||
const routeOf = instance => {
|
||||
loaded ??= validateBusinessDocument(doc, `${id}.json`, { rolesDir, dataRoot });
|
||||
const { vars } = resolveInstance({ system, business: loaded, instance });
|
||||
const pick = k => (typeof vars?.[k] === 'string' && vars[k] ? vars[k] : null);
|
||||
if (!pick('harness') || !pick('model')) return null;
|
||||
return { harness: pick('harness'), model: pick('model'), ...(pick('thinking') ? { thinking: pick('thinking') } : {}) };
|
||||
};
|
||||
const by = doc.launch?.by;
|
||||
const chief = typeof by === 'string' && Object.hasOwn(roles, by) ? routeOf(by) : null;
|
||||
if (chief) return { route: chief, routeFrom: 'chief' };
|
||||
const assistants = Object.keys(roles).filter(name => isObject(roles[name]) && roles[name].definition === 'assistant');
|
||||
const assistant = assistants.includes('assistant') ? 'assistant' : assistants[0];
|
||||
const route = assistant === undefined ? null : routeOf(assistant);
|
||||
return route ? { route, routeFrom: 'assistant' } : { route: null, routeFrom: null };
|
||||
};
|
||||
const applied = doc => latestEntries(doc).map(e => ({ id: e.id, origin: e.origin ?? null, project: e.project ?? null, version: e.version ?? null,
|
||||
proposedHires: (Array.isArray(e.proposedHires) ? e.proposedHires : []).filter(isObject).map(h => ({ name: h.name, reason: h.reason ?? null })) }));
|
||||
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 })) }),
|
||||
// Shipped and installed packs only: a saved template is its owner's, read by name. `applied` is
|
||||
// the latest packs entry of each id, origin and project, and `agents` each instance's hire record.
|
||||
packs: async (id) => {
|
||||
const doc = writer.read(id).document;
|
||||
return { packs: (await installed()).map(({ id: pid, origin, pack }) => ({ id: pid, origin, pack })), applied: applied(doc), agents: agentsOf(doc) };
|
||||
},
|
||||
'pack.state': (id, args) => {
|
||||
if (typeof args.pack !== 'string' || !args.pack) bad();
|
||||
const project = args.project ?? null;
|
||||
if (project !== null && (typeof project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(project))) bad();
|
||||
const { document: doc, revision } = writer.read(id);
|
||||
const saved = args.pack.startsWith(SAVED_PREFIX);
|
||||
const packId = saved ? args.pack.slice(SAVED_PREFIX.length) : args.pack;
|
||||
const entry = (doc.packs ?? []).filter(e => isObject(e) && e.id === packId && (e.project ?? null) === project && (saved ? e.origin === 'saved' : e.origin !== 'saved')).at(-1) ?? null;
|
||||
const scope = project === null ? doc.roles ?? {} : doc.projects?.[project]?.agents ?? {};
|
||||
return { revision, entry: entry ? structuredClone(entry) : null, ...packRoute(doc, id), names: Object.keys(scope), noHire: [...(doc.launch?.noHire ?? [])] };
|
||||
},
|
||||
'pack.preview': (id, args, actor, context) => build(id, args, actor, context),
|
||||
'pack.apply': async (id, args, actor, context) => {
|
||||
if (typeof args.digest !== 'string') bad();
|
||||
|
||||
@@ -15,7 +15,7 @@ if (!process.env.MOSAIC_BUS_TESTER_NONCE) {
|
||||
// P19 #876: only the re-executed child, whose initial environment holds the nonce, talks to the
|
||||
// bus. Loading the client (and the broker module graph behind it) here instead of at the top
|
||||
// keeps the re-exec parent to a bare node start.
|
||||
const { Client } = await import('./client.mjs');
|
||||
const { Client, NOT_SENT_EXIT } = await import('./client.mjs');
|
||||
const { readProcess } = await import('./human.mjs');
|
||||
try {
|
||||
const request = JSON.parse(readFileSync(0, 'utf8'));
|
||||
@@ -39,5 +39,6 @@ try {
|
||||
process.stdout.write(JSON.stringify(result) + '\n');
|
||||
} catch (e) {
|
||||
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
|
||||
process.exitCode = 2;
|
||||
// E2E6 fix 6: as human-cli.mjs, a request that never left exits NOT_SENT_EXIT.
|
||||
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ test('AU authority reverse crossing deadline in prepared IO never publishes',asy
|
||||
});
|
||||
test('AU authority resolver rechecks budget removal after a proposal was raised',async t=>{
|
||||
const f=world(t),d=await f.raise(),b=structuredClone(f.loaded());b.plugins['limit-check']=[];f.broker.reloadBusiness('demo',b);
|
||||
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition'});
|
||||
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
assert.equal(f.writer.read('demo').revision,before);assert.equal(f.store.get('SELECT count(*) n FROM decision_events WHERE decision=?',d.id).n,0);
|
||||
});
|
||||
|
||||
@@ -113,7 +113,7 @@ test('AU an account-quota authority raise routes to the resolver only when the h
|
||||
const covered=world(t,{account:true,countsAccount:name=>name==='pi'}),d=await covered.raise();assert.equal(d.route_to,'judge');
|
||||
for(const countsAccount of [undefined,()=>false,()=>null]){
|
||||
const f=world(t,{account:true,countsAccount});
|
||||
await assert.rejects(f.raise(),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.raise(),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
assert.equal(f.store.get("SELECT count(*) n FROM decisions").n,0);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -137,11 +137,11 @@ test('AU authority near requires an enforced organization budget covering every
|
||||
const f=await settingsFixture(t);
|
||||
for(const tokens of [{},{instances:{coder:tokenCap}},{providers:{unrelated:tokenCap}}]){
|
||||
f.business.launch.limits.tokens=tokens;f.broker.reloadBusiness('demo',f.business);
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
}
|
||||
f.business.launch.limits.tokens={providers:{anthropic:{...tokenCap,limit:0}}};
|
||||
f.business.plugins={'limit-check':[]};f.broker.reloadBusiness('demo',f.business);
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
f.business.plugins={'limit-check':['token-limit']};f.broker.reloadBusiness('demo',f.business);
|
||||
await f.set(authorityNear);assert.equal(f.writes(),1);
|
||||
});
|
||||
@@ -153,12 +153,20 @@ test('AU authority out refuses until per-definition agent limits exist, even wit
|
||||
await assert.rejects(f.set({...authorityNear,authority:'out of the loop'}),e=>e.code==='authority-limits-unavailable' && /near the loop/.test(e.nextStep));
|
||||
assert.equal(f.writes(),1);
|
||||
});
|
||||
test('AU a class moves out of the loop only from near the loop, and the refusal says so (E2E6 fix 7)',async t=>{
|
||||
const f=await settingsFixture(t);await f.set({'cross-role':'in the loop'});
|
||||
await assert.rejects(f.set({'cross-role':'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'cross-role moves out of the loop only from near the loop'});
|
||||
assert.equal(f.writes(),1);
|
||||
});
|
||||
test('AU moving out requires an actual near resolution and a later owner review',async t=>{
|
||||
const f=await settingsFixture(t);await f.set({merge:'in the loop'});await f.set({merge:'near the loop',notices:true});
|
||||
// E2E6 fix 7: each refusal names the check that failed.
|
||||
await assert.rejects(f.set({merge:'near the loop'}),{code:'autonomy-precondition',reason:'owner notices are off; a class near the loop needs them on'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs your review of its trail since the last autonomy change'});
|
||||
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
|
||||
const d=f.raise({action:'git.merge.protected'});f.call(f.chief,'decision.resolve',{id:d.id,choice:'yes'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
|
||||
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||
await f.set({merge:'out of the loop',notices:true});
|
||||
});
|
||||
@@ -11,6 +11,8 @@
|
||||
// which shares humanCall's spawn as transport(). The human proof and its spawn are unchanged.
|
||||
// Row 225 (C2-10b) re-pins webui bus.mjs for one STATUS entry, library-revert-not-agent: 409; no proof
|
||||
// or transport change.
|
||||
// E2E6 fix 6 re-pins human-cli.mjs, which exits 5 when its connect failed before the request was
|
||||
// written, and cli transport.mjs, which reads that exit as bus-not-running. The proof is unchanged.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -21,9 +23,10 @@ import { Client } from "../src/client.mjs";
|
||||
|
||||
const baselines = {
|
||||
"packages/bus/src/human.mjs": "bb13c146717cdc46d75d157177e400edac4d3e10f14fe511027a25fd44cec885",
|
||||
"packages/bus/src/human-cli.mjs": "271b9781d73cf31cc562a56180e3ebcd725b5fde148a83347a201fdef2fc28af",
|
||||
"packages/bus/src/human-cli.mjs": "410892787cc70440b0ba4c45d6f24861d12ee5e70cba678cfeb1ed86b796c149",
|
||||
// Row 239 (#1745): EXIT outcome-unknown-revoked 1; no proof or transport change.
|
||||
"packages/cli/src/transport.mjs": "662642a8ce739fcb6c188ad07125a94e008c8a305eced127c8041d472c56e55b",
|
||||
// E2E6 fix 6: shim exit 5 with outcome-unknown becomes bus-not-running (exit 3, start and recover next).
|
||||
"packages/cli/src/transport.mjs": "101870f7ffb47a9cbd54ebd8c1901734cc9f442d6770cb2a0d059afd4d14b160",
|
||||
// Row 165 (#1662): seven STATUS entries for the role instance routes (organization-instance-exists,
|
||||
// organization-unknown-instance, organization-credentials-out-of-scope, organization-launch-not-configured,
|
||||
// organization-no-change, organization-project-mismatch, organization-unresolvable-instance), no proof or
|
||||
|
||||
@@ -89,7 +89,7 @@ function setup(t) {
|
||||
// #797 / #1839 adds the owner-only artifact read to the existing decision and request controls;
|
||||
// no unsuffixed verb is ever a console verb.
|
||||
test('N4: owner Console verbs have an explicit immutable whitelist and exclude decision.resolve', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's
|
||||
// apply records one hire decision per proposed hire in the same act and applies it, so the agents
|
||||
// exist when the call returns. The owner approves every line; a member with org.hire gets the
|
||||
// unflagged hires and the rest wait in the owner's inbox; an agent's apply never hires.
|
||||
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 { DatabaseSync } from 'node:sqlite';
|
||||
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 { templateHash } from '../../organization/src/definitions.mjs';
|
||||
|
||||
const SUBJECT = { provider: 'test', iss: 'test', sub: 'owner' };
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
const ASSISTANT_ROUTE = { harness: 'pi', model: 'glm-5.3-flash', thinking: 'low' };
|
||||
|
||||
// assistant: false, no assistant instance; {} an assistant with no vars; any other object the
|
||||
// assistant's vars. Lane pr2: a pack hire falls back to the org assistant's route.
|
||||
async function harness(t, { route = true, assistant = false, mutate = () => {} } = {}) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'packhire-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
if (route) doc.roles.chief.vars = { ...ROUTE };
|
||||
if (assistant) doc.roles.assistant = { definition: 'assistant', ...(Object.keys(assistant).length ? { vars: { ...assistant } } : {}) };
|
||||
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: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery', 'organization.change'], crossRole: [] } },
|
||||
coder: { definition: 'coder', authority: { withinRole: ['message.send'], crossRole: [] } } };
|
||||
const businesses = { demo: { 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 consoleOwner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const member = b.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
|
||||
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 decisions = list => b.request(human, { verb: 'decisions', args: { list } });
|
||||
// The broker's own database, read-only.
|
||||
const db = (sql, ...a) => { const d = new DatabaseSync(join(data, 'bus/bus.sqlite'), { readOnly: true }); try { return d.prepare(sql).all(...a); } finally { d.close(); } };
|
||||
const store = { all: db, get: (sql, ...a) => db(sql, ...a)[0] };
|
||||
const events = () => store.all("SELECT kind, body FROM events WHERE business='demo' ORDER BY seq").map(r => ({ kind: r.kind, body: JSON.parse(r.body) }));
|
||||
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 });
|
||||
};
|
||||
const op = (name) => events().filter(e => e.kind === 'action.allowed' && e.body.operation === name).map(e => e.body);
|
||||
return { bus, b, root, rolesDir, path, consoleOwner, human, member, call, file, decisions, events, op, store, install };
|
||||
}
|
||||
|
||||
const apply = async (call, args = { pack: 'coding' }, cap) => {
|
||||
const preview = await call('pack.preview.console', args, cap);
|
||||
return { preview, out: await call('pack.apply.console', { ...args, digest: preview.digest }, cap) };
|
||||
};
|
||||
|
||||
// The evidence an inbox-approved hire leaves: a decision.raise naming the hire, a console
|
||||
// resolution yes, a hire.consume and a hire.apply, and the instance's hireDecision.
|
||||
function assertHireRecord(h, name, decision) {
|
||||
const raise = h.op('decision.raise').find(r => r.decision === decision);
|
||||
assert.ok(raise, `decision.raise for ${name}`);
|
||||
assert.equal(raise.hire.name, name);
|
||||
assert.equal(raise.action, 'role.hire');
|
||||
assert.ok(h.op('hire.consume').some(r => r.decision === decision), `hire.consume for ${name}`);
|
||||
assert.ok(h.op('hire.apply').some(r => r.decision === decision), `hire.apply for ${name}`);
|
||||
const resolved = h.store.all('SELECT op, choice, via, by FROM decision_events WHERE decision=?', decision);
|
||||
assert.deepEqual(resolved.map(r => [r.op, r.choice]), [['resolved', 'yes']]);
|
||||
assert.equal(h.file().roles[name].hireDecision, decision);
|
||||
}
|
||||
|
||||
test('PD the owner applies a pack with flagged hires on a fresh org; the agents exist on return, each with its decision record', async t => {
|
||||
const h = await harness(t);
|
||||
const { preview, out } = await apply(h.call);
|
||||
// The preview lists the flagged and credential lines the owner's apply approves.
|
||||
assert.ok(preview.hires.some(x => x.flagged.length || x.credentialLines.length), JSON.stringify(preview.hires));
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
const doc = h.file();
|
||||
for (const x of out.hires) {
|
||||
assert.ok(Object.hasOwn(doc.roles, x.name), `${x.name} exists`);
|
||||
assert.ok(doc.launch.instances.includes(x.name), `${x.name} is launched`);
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
}
|
||||
// The coder's credential lines are approved, not bound: the instance is written with no credential.
|
||||
assert.equal(doc.roles['coder-1'].credentials, undefined);
|
||||
// Each hire names its pack.
|
||||
assert.deepEqual(h.op('pack.hire').map(e => [e.hire, e.pack, e.origin, e.project]), out.hires.map(x => [x.name, 'coding', 'shipped', null]));
|
||||
// The instances read carries the pack each agent came from.
|
||||
const inst = await h.call('instances', {}, h.human);
|
||||
assert.deepEqual(inst.instances['coder-1'].pack, { id: 'coding', origin: 'shipped', project: null });
|
||||
assert.equal(inst.instances.pm.pack, undefined);
|
||||
// The packs read counts the hires and lists nothing open.
|
||||
const packs = await h.call('packs.console');
|
||||
const applied = packs.applied.find(a => a.id === 'coding');
|
||||
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
assert.deepEqual(applied.open, []);
|
||||
});
|
||||
|
||||
test('PD a re-apply hires nothing twice', async t => {
|
||||
const h = await harness(t);
|
||||
await apply(h.call);
|
||||
const raised = h.op('decision.raise').length;
|
||||
const again = await apply(h.call);
|
||||
// The second apply proposes nothing: each proposal's instance exists.
|
||||
assert.deepEqual(again.out.hires, []);
|
||||
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
// The pack action on the same entry skips each instance that exists.
|
||||
const hired = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.equal(h.op('decision.raise').length, raised);
|
||||
assert.ok(hired.hires.every(x => x.state === 'exists'), JSON.stringify(hired));
|
||||
});
|
||||
|
||||
test('PD the owner CLI apply hires through the same path, resolved via cli', async t => {
|
||||
const h = await harness(t);
|
||||
const preview = await h.call('pack.preview', { pack: 'coding' }, h.human);
|
||||
const out = await h.call('pack.apply', { pack: 'coding', digest: preview.digest }, h.human);
|
||||
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
|
||||
for (const x of out.hires) {
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', x.decision).via, 'cli');
|
||||
assert.equal(h.store.get('SELECT raised_by_run FROM decisions WHERE id=?', x.decision).raised_by_run, 'human-cli');
|
||||
}
|
||||
});
|
||||
|
||||
test('PD with no chief route the apply records the pack, hires nothing and says why; the hire action on the existing record hires once a route exists', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
const packs = await h.call('packs.console');
|
||||
assert.deepEqual(packs.applied.find(a => a.id === 'coding').open.map(o => [o.name, o.state, o.code, typeof o.reason]),
|
||||
[['pm-1', 'refused', 'pack-hire-route-missing', 'string'], ['coder-1', 'refused', 'pack-hire-route-missing', 'string'], ['reviewer-1', 'refused', 'pack-hire-route-missing', 'string']]);
|
||||
// The owner gives the chief a route; the pack action hires from the packs entry already recorded.
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const hired = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
for (const x of hired.hires) assertHireRecord(h, x.name, x.decision);
|
||||
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').open, []);
|
||||
// The CLI's pack hire is the same action; nothing is left to hire.
|
||||
const cli = await h.call('pack.hire', { pack: 'coding' }, h.human);
|
||||
assert.ok(cli.hires.every(x => x.state === 'exists'));
|
||||
await assert.rejects(h.call('pack.hire.console', { pack: 'nosuch' }), /pack-not-applied/);
|
||||
});
|
||||
|
||||
// A pack with one hire inside the chief's own grants and two above them.
|
||||
// An installed pack's own definition narrows a template; the scout keeps only read.
|
||||
const mixkit = (rolesDir) => {
|
||||
const SCOUT = { from: { template: 'coder', sha256: templateHash(rolesDir, 'coder') }, role: { tools: ['read'], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] }, instructions: 'Read and report.' };
|
||||
const p = structuredClone(codingPack());
|
||||
p.id = 'mixkit';
|
||||
p.definitions = { scout: SCOUT, coder: p.definitions.coder, reviewer: p.definitions.reviewer };
|
||||
p.hires = [{ name: 'scout-1', definition: 'scout', reason: 'reads and reports' }, { name: 'coder-1', definition: 'coder', reason: 'implements each change' }, { name: 'reviewer-1', definition: 'reviewer', reason: 'reviews each change' }];
|
||||
p.workflows = { change: { description: 'One change.', steps: [{ id: 'build', title: 'Build it', roles: ['coder'], state: 'in-progress' }, { id: 'review', title: 'Review it', roles: ['reviewer'], state: 'in-review' }] } };
|
||||
return p;
|
||||
};
|
||||
|
||||
test('PD a member with org.hire gets the unflagged hires; the flagged ones become open decisions in the owner inbox', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['scout-1', 'hired'], ['coder-1', 'awaiting-owner'], ['reviewer-1', 'awaiting-owner']]);
|
||||
const after = h.file();
|
||||
assert.ok(after.launch.instances.includes('scout-1'));
|
||||
assert.equal(Object.hasOwn(after.roles, 'coder-1'), false);
|
||||
assert.equal(Object.hasOwn(after.roles, 'reviewer-1'), false);
|
||||
assertHireRecord(h, 'scout-1', out.hires[0].decision);
|
||||
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', out.hires[0].decision).via, 'console');
|
||||
// Each flagged hire is an open decision routed to the human, raised by the member's act.
|
||||
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
|
||||
for (const x of waiting) {
|
||||
const d = h.store.get('SELECT route_to, raised_by_role, action FROM decisions WHERE id=?', x.decision);
|
||||
assert.deepEqual([d.route_to, d.raised_by_role, d.action], ['human', 'human', 'role.hire']);
|
||||
assert.equal(h.store.all('SELECT 1 FROM decision_events WHERE decision=?', x.decision).length, 0);
|
||||
}
|
||||
// The packs read lists both as open, awaiting the owner, each with the pack's reason.
|
||||
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
|
||||
assert.deepEqual(applied.hired, ['scout-1']);
|
||||
assert.deepEqual(applied.open.map(o => [o.name, o.state, o.reason, o.decision]), [['coder-1', 'awaiting-owner', 'implements each change', waiting[0].decision], ['reviewer-1', 'awaiting-owner', 'reviews each change', waiting[1].decision]]);
|
||||
// The member's pack action never re-raises a hire an open decision names.
|
||||
const again = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(again.hires.map(x => [x.name, x.state, x.decision ?? null]), [['scout-1', 'exists', null], ['coder-1', 'open', waiting[0].decision], ['reviewer-1', 'open', waiting[1].decision]]);
|
||||
// The member cannot approve a flagged hire; the owner can, from the inbox, and the agent exists.
|
||||
const view = await h.call('hire.preview.console', { id: waiting[0].decision });
|
||||
await assert.rejects(h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest }, h.member), /hire-owner-required|human-required/);
|
||||
await h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest });
|
||||
assert.ok(h.file().launch.instances.includes('coder-1'));
|
||||
// The owner's pack action approves the rest: the open pack decision is withdrawn by the owner and
|
||||
// replaced by one approved in the same act.
|
||||
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'exists', null], ['reviewer-1', 'hired', waiting[1].decision]]);
|
||||
assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', waiting[1].decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
|
||||
assertHireRecord(h, 'reviewer-1', owner.hires[2].decision);
|
||||
const done = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
|
||||
assert.deepEqual(done.hired.sort(), ['coder-1', 'reviewer-1', 'scout-1']);
|
||||
assert.deepEqual(done.open, []);
|
||||
});
|
||||
|
||||
test('PD an agent apply still refuses human-required and hires nothing; the tester and a cli cap on the console name refuse', async t => {
|
||||
const h = await harness(t);
|
||||
const agent = h.b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
|
||||
h.b.request(agent, { verb: 'role.claim' });
|
||||
assert.throws(() => h.b.request(agent, { verb: 'pack.apply.console', args: { pack: 'coding', digest: 'a'.repeat(64) } }), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(h.human, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(h.call('pack.hire', { pack: 'coding' }), /human-required/);
|
||||
for (const args of [{}, { pack: 7 }, { pack: 'coding', extra: 1 }, { pack: 'coding', project: 'Bad Name' }])
|
||||
await assert.rejects(h.call('pack.hire.console', args), /invalid-request/);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
});
|
||||
|
||||
test('PD a project pack hires into projects.<p>.agents', async t => {
|
||||
const h = await harness(t);
|
||||
const pack = structuredClone(codingPack());
|
||||
pack.id = 'projkit'; pack.scope = 'project';
|
||||
h.install(pack);
|
||||
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
|
||||
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
|
||||
const agents = h.file().projects.stack.agents;
|
||||
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.equal(agents[x.name].credentials, undefined); }
|
||||
assert.equal(Object.hasOwn(h.file().roles, 'coder-1'), false);
|
||||
assert.deepEqual(h.op('pack.hire').map(e => e.project), ['stack', 'stack', 'stack']);
|
||||
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'projkit');
|
||||
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
const again = await h.call('pack.hire.console', { pack: 'projkit', project: 'stack' });
|
||||
assert.ok(again.hires.every(x => x.state === 'exists'));
|
||||
});
|
||||
|
||||
test('PD the new codes are in the refusal table with a rail and a next step that names no path', async () => {
|
||||
const { REFUSALS } = await import('../src/refusals.mjs');
|
||||
for (const c of ['pack-not-applied', 'pack-hire-route-missing', 'hire-owner-required', 'no-chief-of-staff']) {
|
||||
assert.ok(Object.hasOwn(REFUSALS, c), c);
|
||||
assert.ok(REFUSALS[c].rail?.length > 5);
|
||||
assert.ok(REFUSALS[c].nextStep?.length > 20);
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[c].nextStep));
|
||||
}
|
||||
});
|
||||
|
||||
test('PD the owner supersede withdraws an inbox decision only after its replacement hires; a refused replacement leaves it open', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const setRoute = (vars) => { const doc = h.file(); if (vars) doc.roles.chief.vars = { ...vars }; else delete doc.roles.chief.vars; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n'); };
|
||||
setRoute(ROUTE);
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
|
||||
assert.equal(waiting.length, 2);
|
||||
// The packs read marks each member-raised line as raised by a pack hire.
|
||||
const open = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit').open;
|
||||
assert.deepEqual(open.map(o => [o.name, o.state, o.fromPack]), [['coder-1', 'awaiting-owner', true], ['reviewer-1', 'awaiting-owner', true]]);
|
||||
// The chief loses its route; the owner's pack hire cannot build a replacement.
|
||||
setRoute(null);
|
||||
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.code ?? null]), [['scout-1', 'exists', null], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
// Both inbox decisions are still open: nothing withdrew them.
|
||||
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op FROM decision_events WHERE decision=?', x.decision), []);
|
||||
// With the route back, the owner's pack hire replaces them, withdrawing each only once its replacement applied.
|
||||
setRoute(ROUTE);
|
||||
const done = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(done.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'hired', waiting[0].decision], ['reviewer-1', 'hired', waiting[1].decision]]);
|
||||
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', x.decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
|
||||
});
|
||||
|
||||
test('PD a second pack hire on the same organization while one runs refuses organization-busy and raises nothing', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
await apply(h.call);
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const first = h.call('pack.hire.console', { pack: 'coding' });
|
||||
const second = h.call('pack.hire.console', { pack: 'coding' });
|
||||
await assert.rejects(second, /organization-busy/);
|
||||
const hired = await first;
|
||||
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
// One decision per hire: the refused call raised nothing.
|
||||
assert.equal(h.op('decision.raise').length, 3);
|
||||
// Once the loop ends the latch is free again: the next pack hire runs and finds nothing to hire.
|
||||
const later = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.ok(later.hires.every(x => x.state === 'exists'), JSON.stringify(later));
|
||||
});
|
||||
|
||||
// Lane pr2 (lead ruling 2026-11-14): a pack hire takes the chief of staff's harness and model, else
|
||||
// the org assistant's, else refuses pack-hire-route-missing.
|
||||
test('PR2 with no chief route the apply hires every proposal with the org assistant harness and model', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'assistant'], ['coder-1', 'hired', 'assistant'], ['reviewer-1', 'hired', 'assistant']]);
|
||||
const doc = h.file();
|
||||
for (const x of out.hires) {
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
assert.deepEqual(doc.roles[x.name].vars, ASSISTANT_ROUTE);
|
||||
assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE);
|
||||
}
|
||||
});
|
||||
|
||||
test('PR2 a chief route wins over a different assistant route', async t => {
|
||||
const h = await harness(t, { assistant: ASSISTANT_ROUTE });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'chief'], ['coder-1', 'hired', 'chief'], ['reviewer-1', 'hired', 'chief']]);
|
||||
for (const x of out.hires) assert.deepEqual(h.file().roles[x.name].vars, ROUTE);
|
||||
});
|
||||
|
||||
test('PR2 an assistant with no harness and model gives no route: the apply refuses as before', async t => {
|
||||
for (const assistant of [{}, { harness: 'pi' }]) {
|
||||
const h = await harness(t, { route: false, assistant });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('PR2 with several assistants the one named assistant gives the route, else the first in key order', async t => {
|
||||
const OTHER = { harness: 'pi', model: 'claude-sonnet-5-5' };
|
||||
const named = await harness(t, { route: false, assistant: ASSISTANT_ROUTE, mutate: doc => { doc.roles = { aide: { definition: 'assistant', vars: { ...OTHER } }, ...doc.roles }; } });
|
||||
const a = await apply(named.call);
|
||||
for (const x of a.out.hires) assert.deepEqual(named.file().roles[x.name].vars, ASSISTANT_ROUTE);
|
||||
const first = await harness(t, { route: false, mutate: doc => { doc.roles.aide = { definition: 'assistant', vars: { ...OTHER } }; doc.roles.zed = { definition: 'assistant', vars: { ...ASSISTANT_ROUTE } }; } });
|
||||
const b = await apply(first.call);
|
||||
assert.deepEqual(b.out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
|
||||
for (const x of b.out.hires) assert.deepEqual(first.file().roles[x.name].vars, OTHER);
|
||||
});
|
||||
|
||||
test('PR2 a member pack hire on the assistant route marks hired and awaiting-owner lines routeFrom assistant', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
// The member's apply would not run; the owner's apply would hire everything. Record the pack first
|
||||
// with the assistant route absent, then give it back and let the member hire.
|
||||
const doc0 = h.file(); delete doc0.roles.assistant.vars; writeFileSync(h.path, JSON.stringify(doc0, null, 2) + '\n');
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const doc = h.file(); doc.roles.assistant.vars = { ...ASSISTANT_ROUTE }; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['scout-1', 'hired', 'assistant'], ['coder-1', 'awaiting-owner', 'assistant'], ['reviewer-1', 'awaiting-owner', 'assistant']]);
|
||||
assert.deepEqual(h.file().roles['scout-1'].vars, ASSISTANT_ROUTE);
|
||||
});
|
||||
|
||||
test('PR2 a project pack with no chief route hires into the project on the assistant route', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
const pack = structuredClone(codingPack());
|
||||
pack.id = 'projkit'; pack.scope = 'project';
|
||||
h.install(pack);
|
||||
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
|
||||
assert.deepEqual(out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
|
||||
const agents = h.file().projects.stack.agents;
|
||||
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE); }
|
||||
});
|
||||
@@ -90,7 +90,7 @@ const ask = (x, state, extra = {}) => x.call('pm', 'request.question', { request
|
||||
options: [{ key: 'web', text: 'Web' }, { key: 'cli', text: 'CLI' }], ...extra });
|
||||
|
||||
test('the console verb list includes the artifact read and existing owner controls', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
|
||||
@@ -154,7 +154,7 @@ test('SP8 argument checks: a second save, a .. name, an unknown key, preview wit
|
||||
const { call, saved } = await harness(t);
|
||||
const { preview } = await save(call, 'demo-shape');
|
||||
const first = readFileSync(saved('demo-shape'));
|
||||
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'invalid-request' && e.reason === 'a template of this name is already saved');
|
||||
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'template-exists' && e.reason === 'a template of this name is already saved; save under another name');
|
||||
assert.deepEqual(readFileSync(saved('demo-shape')), first);
|
||||
for (const name of ['..', '../x', 'a/b']) await assert.rejects(call('template.save.console', { name, preview: true }), { code: 'invalid-request' });
|
||||
for (const args of [{ name: 'x', preview: true, account: 'alex' }, { name: 'x', preview: true, digest: preview.digest }, { name: 'x' }, { preview: true }, { name: 'x', preview: false }])
|
||||
|
||||
@@ -121,3 +121,24 @@ test('committed mutation followed by dropped reply reports unknown and is never
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(store.get('SELECT count(*) n FROM messages').n, 1);
|
||||
});
|
||||
|
||||
// E2E6 fix 6: a connect that fails before the request is written is marked notSent; the code stays
|
||||
// outcome-unknown for every caller. A request that left and got no answer is not marked.
|
||||
test('E2E6 a failed connect is outcome-unknown marked notSent; a dropped answer is not marked', async (t) => {
|
||||
const { createServer } = await import('node:net');
|
||||
const { writeFileSync } = await import('node:fs');
|
||||
const { NOT_SENT_EXIT } = await import('../src/client.mjs');
|
||||
assert.equal(NOT_SENT_EXIT, 5);
|
||||
const dir = mkdtempSync(join(tmpdir(), 'e2e6-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const plain = join(dir, 'plain');
|
||||
writeFileSync(plain, '');
|
||||
for (const path of [join(dir, 'missing.sock'), plain, join(plain, 'below')]) {
|
||||
await assert.rejects(new Client({ path, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === true, path);
|
||||
}
|
||||
const sock = join(dir, 'drop.sock');
|
||||
const server = createServer((c) => c.once('data', () => c.destroy()));
|
||||
await new Promise((r) => server.listen(sock, r));
|
||||
t.after(() => server.close());
|
||||
await assert.rejects(new Client({ path: sock, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === undefined);
|
||||
});
|
||||
@@ -1363,6 +1363,23 @@ message, an answer that never came exits 1, an unknown template exits 2. All of
|
||||
these verbs, reads included, refuse inside an agent run (exit 3) after their
|
||||
usage checks (exit 4) and before any config is read.
|
||||
|
||||
Starter pack hires (ruling 2026-11-14, #1873): `mosaic org pack apply ID PACK
|
||||
--digest D [--project P]` is the owner's hire decision. After the pack commits,
|
||||
the same command hires each proposed agent through the bus's hire-decisions
|
||||
path (`pack.apply` as the organization's human) and the receipt adds `hires`,
|
||||
one `{name, state, decision | code}` per proposal: `hired`, `exists` (an
|
||||
instance by that name is there), `open` (a hire decision already names it),
|
||||
`awaiting-owner` or `refused` with the hire's code. The owner's apply approves
|
||||
the flagged and credential lines; a credential line is approved, not bound, so
|
||||
the agent's launch is refused `credential-unbound` until its services are
|
||||
bound. `mosaic org pack hire ID PACK [--project P]` (`pack.hire`) runs the same
|
||||
loop on a pack already applied, for the proposals an earlier apply left open,
|
||||
and hires none twice; a pack with no packs entry is refused `pack-not-applied`
|
||||
with the hint to preview and apply it first. A proposal is refused
|
||||
`pack-hire-route-missing` when neither the chief of staff nor the
|
||||
organization's assistant has a harness and model to give it; the chief's route
|
||||
wins when both have one. Like the other pack words, both refuse inside an agent run (exit 3).
|
||||
|
||||
`mosaic tasks create|edit|archive` are the task board's three writes. The
|
||||
arguments pass the board's own check, then go to the bus as the person
|
||||
(`tasks.create`, `tasks.edit`, `tasks.archive`), so the bus runs its human,
|
||||
|
||||
@@ -845,6 +845,7 @@ export async function run(argv, io = { env: process.env, stdin: process.stdin, s
|
||||
if (!(error instanceof CliError)) throw error;
|
||||
io.stderr.write(`mosaic: ${error.message}\n`);
|
||||
if (OTHER_TREE_CODES.has(error.code)) io.stderr.write(`mosaic: ${OTHER_TREE}\n`);
|
||||
if (typeof error.next === "string" && error.next !== "") io.stderr.write(`mosaic: next: ${error.next}\n`);
|
||||
return error.exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,15 @@
|
||||
// input, a decision or option that doesn't exist); 3 refused (system or
|
||||
// business config problem, the broker or notifier refused, the human proof
|
||||
// refused, a host already running); 4 usage.
|
||||
//
|
||||
// E2E6: `next` is an optional next-step line. run() prints it after the message as
|
||||
// `mosaic: next: ...`; the message itself stays as callers (the Console among them) match it.
|
||||
export class CliError extends Error {
|
||||
constructor(message, exitCode = 2) {
|
||||
constructor(message, exitCode = 2, { next } = {}) {
|
||||
super(message);
|
||||
this.name = "CliError";
|
||||
this.exitCode = exitCode;
|
||||
if (typeof next === "string" && next !== "") this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,11 @@ const same = (a, b) => a?.pid === b?.pid && a?.startTime === b?.startTime && a?.
|
||||
// tried again, like one that goes before the check. `found` runs once the
|
||||
// lock is found and before it is read, `between` after the stale lock is
|
||||
// read; both are for the tests. Exported for the tests.
|
||||
// E2E6 fix 1: every stale-lock refusal names the verb that clears a host that died.
|
||||
export const recoverNext = (business) =>
|
||||
typeof business === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(business)
|
||||
? `if the bus host died, clear it with mosaic bus recover ${business}; recover refuses while the host still runs`
|
||||
: "if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs";
|
||||
export function claimHostLock(dataRoot, state, { found = () => {}, between = () => {}, refuseStale = false } = {}) {
|
||||
mkdirSync(hostDir(dataRoot), { recursive: true, mode: 0o700 });
|
||||
const file = hostLock(dataRoot);
|
||||
@@ -94,7 +99,8 @@ export function claimHostLock(dataRoot, state, { found = () => {}, between = ()
|
||||
const prior = readState(file, found);
|
||||
if (!prior) continue;
|
||||
if (prior.live) throw new CliError(`a bus host already runs for ${prior.business} (pid ${prior.pid})`, 3);
|
||||
if (refuseStale) throw new CliError("stale bus host lock", 3);
|
||||
// E2E6 fix 1: the message stays (the Console matches it); the next line names the clearing verb.
|
||||
if (refuseStale) throw new CliError("stale bus host lock", 3, { next: recoverNext(prior.business) });
|
||||
between();
|
||||
try {
|
||||
renameSync(file, aside);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveOrg, withOrgLifecycle } from '../../organization/src/org-registry.mjs';
|
||||
import { orgPaths } from './config.mjs';
|
||||
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, startTimeOf, stopHost } from './host.mjs';
|
||||
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, recoverNext, startTimeOf, stopHost } from './host.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
import { readBootStatus } from './boot-status.mjs';
|
||||
|
||||
@@ -27,20 +27,22 @@ async function target(ctx, id, allowDeleting = false) {
|
||||
return { ...org, paths: orgPaths(org.root) };
|
||||
}
|
||||
function checkedState(org) {
|
||||
// E2E6 fix 1: each refusal keeps its message and adds the recover line as its next step.
|
||||
const stale = message => { throw new CliError(message, 3, { next: recoverNext(org.id) }); };
|
||||
const s = hostStatus(org.root);
|
||||
let lock = null;
|
||||
try { lock = JSON.parse(readFileSync(hostLock(org.root), 'utf8')); }
|
||||
catch (e) { if (e.code !== 'ENOENT') fail('bus host lock is unreadable'); }
|
||||
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) fail('stale bus host lock');
|
||||
if (s.host && (!s.host.live || s.host.business !== org.id)) fail('stale or mismatched bus host state');
|
||||
catch (e) { if (e.code !== 'ENOENT') stale('bus host lock is unreadable'); }
|
||||
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) stale('stale bus host lock');
|
||||
if (s.host && (!s.host.live || s.host.business !== org.id)) stale('stale or mismatched bus host state');
|
||||
if (s.host) {
|
||||
const args = cmdlineOf(s.host.pid) ?? [], i = args.indexOf(CLI);
|
||||
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) fail('bus host identity mismatch');
|
||||
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) stale('bus host identity mismatch');
|
||||
}
|
||||
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) fail('bus host lock does not match host state');
|
||||
if (s.writerLock && !s.writerLock.live) fail('stale bus writer lock');
|
||||
if (!s.host && s.writerLock) fail('bus writer lock has no matching host');
|
||||
if (s.host && !lock) fail('bus host lock is missing');
|
||||
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) stale('bus host lock does not match host state');
|
||||
if (s.writerLock && !s.writerLock.live) stale('stale bus writer lock');
|
||||
if (!s.host && s.writerLock) stale('bus writer lock has no matching host');
|
||||
if (s.host && !lock) stale('bus host lock is missing');
|
||||
return s;
|
||||
}
|
||||
export function probeBusSocket(path, { signal, deadline } = {}) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { processState } from '../../seat/src/process-state.mjs';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { request as httpRequest } from 'node:http';
|
||||
import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
|
||||
import { constants, closeSync, fstatSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
|
||||
@@ -60,14 +60,79 @@ function removeStale(ctx, s, warn) {
|
||||
warn(`mosaic: stale console state moved to ${aside}\n`);
|
||||
return true;
|
||||
}
|
||||
function takeLock(ctx) {
|
||||
// E2E6 fix 4: what a start.lock that already exists names. Null when it names no holder: unreadable,
|
||||
// empty (a holder between its open and its write), not a regular file of this user, or a bad pid or
|
||||
// start time. Such a lock is never cleared. A lock its holder marked released ({"released":true},
|
||||
// written through the holder's own descriptor) names no live holder and is cleared (f6c review P3-1).
|
||||
function lockHolder(path) {
|
||||
let fd;
|
||||
try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
||||
catch { return null; }
|
||||
try {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || st.size > 4096) return null;
|
||||
const data = JSON.parse(readFileSync(fd, 'utf8'));
|
||||
if (data?.released === true && Object.keys(data).length === 1) return { released: true, dev: st.dev, ino: st.ino };
|
||||
if (!Number.isSafeInteger(data?.pid) || data.pid <= 0 || typeof data.startTime !== 'string' || !/^\d+$/.test(data.startTime)) return null;
|
||||
return { pid: data.pid, startTime: data.startTime, dev: st.dev, ino: st.ino };
|
||||
} catch { return null; } finally { closeSync(fd); }
|
||||
}
|
||||
// True when the process the lock names (pid and start time) is gone. A /proc read that cannot settle
|
||||
// it counts as live, so an uncertain holder is never cleared.
|
||||
function holderGone(holder) {
|
||||
if (holder.released) return true;
|
||||
let p;
|
||||
try { p = processState(holder.pid); } catch { return false; }
|
||||
return !p.alive || p.startTime !== holder.startTime;
|
||||
}
|
||||
// Moves aside and removes the lock the holder check read, and only that file: a lock another start
|
||||
// took in between is put back and the clear refuses.
|
||||
function clearLock(path, holder) {
|
||||
const aside = `${path}.dead-${randomBytes(4).toString('hex')}`;
|
||||
try { renameSync(path, aside); } catch { fail('console start lock changed while it was being cleared; run the command again'); }
|
||||
const st = lstatSync(aside);
|
||||
if (st.dev !== holder.dev || st.ino !== holder.ino) {
|
||||
// Put back without replacing: if a third start took the path meanwhile, the aside stays for a human.
|
||||
let restored = false;
|
||||
try { linkSync(aside, path); restored = true; } catch { /* left aside */ }
|
||||
if (restored) rmSync(aside, { force: true });
|
||||
fail('console start lock changed while it was being cleared; run the command again');
|
||||
}
|
||||
rmSync(aside, { force: true });
|
||||
}
|
||||
function takeLock(ctx, warn = () => {}) {
|
||||
checkDir(ctx);
|
||||
const path = join(directory(ctx), 'start.lock');
|
||||
let fd; try { fd = openSync(path, 'wx', 0o600); } catch { fail('console start lock exists'); }
|
||||
let fd;
|
||||
for (let cleared = false; fd === undefined;) {
|
||||
try { fd = openSync(path, 'wx', 0o600); }
|
||||
catch (e) {
|
||||
if (e?.code !== 'EEXIST' || cleared) fail('console start lock exists');
|
||||
// E2E6 fix 4: a lock whose named holder (pid and start time) is gone is cleared once, and the
|
||||
// take tried again. A live holder, or a lock that names none, refuses and stays.
|
||||
const holder = lockHolder(path);
|
||||
if (!holder) fail('console start lock exists and names no holder; remove console/start.lock under the data root once no console start or stop runs');
|
||||
if (!holderGone(holder)) fail(`console start lock is held by process ${holder.pid}, which still runs; wait for its start or stop to finish`);
|
||||
clearLock(path, holder);
|
||||
warn(holder.released ? 'mosaic: cleared a console start lock its holder had released\n' : `mosaic: cleared a console start lock left by process ${holder.pid}, which is gone\n`);
|
||||
cleared = true;
|
||||
}
|
||||
}
|
||||
// D1: the lock names its holder, so a detached start that timed out can clear the lock of the
|
||||
// supervisor it killed (clearDeadLock) and no other.
|
||||
// supervisor it killed (clearDeadLock), and a later start or stop can clear it once that holder is gone.
|
||||
try { writeSync(fd, JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) })); } catch { /* an unnamed lock is only never cleared */ }
|
||||
return () => { closeSync(fd); rmSync(path, { force: true }); };
|
||||
// f6c review P3-1: the release marks its own file released, through its own descriptor, and removes
|
||||
// the path only while the path is still that file. A clear that moved the lock aside and puts it back
|
||||
// after this release puts back a released lock, which the next start or stop clears; and the release
|
||||
// never removes a lock another start took meanwhile.
|
||||
// A failed marker write (disk full) still removes the path: an empty lock would refuse forever.
|
||||
return () => {
|
||||
try {
|
||||
try { ftruncateSync(fd, 0); writeSync(fd, JSON.stringify({ released: true }), 0); } catch { /* the matched unlink below still runs */ }
|
||||
const own = fstatSync(fd), now = lstatSync(path);
|
||||
if (own.dev === now.dev && own.ino === now.ino) rmSync(path, { force: true });
|
||||
} catch { /* gone already, or moved aside by a clear */ } finally { closeSync(fd); }
|
||||
};
|
||||
}
|
||||
// Removes start.lock only when it names this exact process (pid and start time) and that process
|
||||
// is gone. A lock that is unreadable, unnamed or another holder's stays.
|
||||
@@ -242,7 +307,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
|
||||
// re-check P1). A Restart Console relaunch goes through relaunch(), not here.
|
||||
refuseInsideAgent(process.env); if (ctx.env) refuseInsideAgent(ctx.env);
|
||||
if (detach && devLocalOwner) return detachedSupervisor(ctx, { port, bind, allowHosts, warn });
|
||||
const release = takeLock(ctx);
|
||||
const release = takeLock(ctx, warn);
|
||||
let run, args;
|
||||
try {
|
||||
const prior = state(ctx);
|
||||
@@ -266,7 +331,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
|
||||
return result;
|
||||
}
|
||||
export async function consoleStop(ctx, { warn = s => process.stderr.write(s) } = {}) {
|
||||
const release = takeLock(ctx);
|
||||
const release = takeLock(ctx, warn);
|
||||
try {
|
||||
const s = state(ctx);
|
||||
if (!s || removeStale(ctx, s, warn)) return { stopped: false };
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
// credential store, whose held-secret check every definition write needs (R1), and no other process
|
||||
// holds the tokens it looks for. Each write prints its receipt.
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { basename } from 'node:path';
|
||||
import { configDir } from '../../organization/src/organization-config.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { definitionVerbs } from '../../organization/src/definition-verbs.mjs';
|
||||
import { checkDefinition } from '../../organization/src/definitions.mjs';
|
||||
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
|
||||
import { rolesDir } from './config.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
import { busExit, refuseInsideAgent } from './transport.mjs';
|
||||
@@ -59,6 +61,33 @@ function refusal(code, verb, name, rev, read) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// E2E6 fix 2: a read or a write's file check that fails says so in one line: an unknown
|
||||
// organization, a missing definition or a bad file, by code. No stack trace, and no host path: a raw
|
||||
// filesystem error is named by its operation and code, and any absolute path left in a message is cut.
|
||||
const NAME_SHOWN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
function missing(id, name) { return `${NAME_SHOWN.test(name ?? '') ? `definitions declares no ${name}` : 'definitions declares no definition by that name'}; list them with mosaic org definitions ${id} list`; }
|
||||
// f6c review P3-3: a path after ':' or a backtick is cut too.
|
||||
function pathFree(message) { return String(message).replace(/(^|[\s'"(=:`])\/[^\s'"),`]*/g, '$1<path>'); }
|
||||
export function definitionsFailure(e, id, name) {
|
||||
if (e instanceof CliError) return e;
|
||||
const coded = (code, text, exit = 3) => Object.assign(new CliError(`${code}: ${text}`, exit), { code });
|
||||
if (typeof e?.syscall === 'string' && typeof e.code === 'string' && /^E[A-Z0-9]+$/.test(e.code)) {
|
||||
// f6c review P3-2: only a missing organization file means no organization; another missing file
|
||||
// (the roles directory for `templates`, a role template) says which operation failed.
|
||||
if (e.code === 'ENOENT' && (typeof e.path !== 'string' || basename(e.path) === `${id}.json`)) return coded('unknown-organization', `this instance has no organization ${id}; list them with mosaic org list`);
|
||||
if (id === 'templates' || id === undefined) return coded('definitions-unreadable', `cannot ${e.syscall} a file the definitions command reads (${e.code})`);
|
||||
return coded('organization-unreadable', `cannot ${e.syscall} the file of organization ${id} (${e.code})`);
|
||||
}
|
||||
const message = typeof e?.message === 'string' ? e.message : '';
|
||||
if (/^definitions declares no /.test(message)) return coded('definition-missing', missing(id, name));
|
||||
if (typeof e?.code === 'string' && /^[a-z][a-z-]{0,63}$/.test(e.code)) {
|
||||
const text = e.code === 'definition-missing' ? missing(id, name) : pathFree(message);
|
||||
return coded(e.code, text);
|
||||
}
|
||||
if (e?.name === 'OrganizationConfigError' || e?.name === 'BusinessError') return coded('organization-invalid', pathFree(message));
|
||||
return coded('definitions-failed', 'the definitions command failed', 1);
|
||||
}
|
||||
|
||||
// deps.callFor(parsed) returns the human's call(verb, args) for the organization parsed names (cli.mjs
|
||||
// passes its callFor). Without one, a write refuses: it never runs without the bus's secret check.
|
||||
export async function definitionsCommand(args, io, deps = {}) {
|
||||
@@ -68,6 +97,10 @@ export async function definitionsCommand(args, io, deps = {}) {
|
||||
const ifRev = () => { const r = need('--if-rev'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid --if-rev', 4); return Number(r); };
|
||||
const [id, verb, name] = pos;
|
||||
if (WRITES.includes(verb)) refuseInsideAgent(io.env);
|
||||
if (id !== 'templates' && id !== undefined && !ID_PATTERN.test(id)) throw new CliError(`invalid organization id: an id is 1 to 64 of a-z, 0-9, '.', '_' and '-', starting with a letter or digit\n${DEFINITIONS_USAGE}`, 4);
|
||||
try { await run(); }
|
||||
catch (e) { throw definitionsFailure(e, id, name); }
|
||||
async function run() {
|
||||
const writer = deps.writer ?? organizationWriter({ dir: configDir(io.env), rolesDir: rolesDir(io.env) });
|
||||
const verbs = definitionVerbs({ writer, rolesDir: rolesDir(io.env) });
|
||||
let result;
|
||||
@@ -93,4 +126,5 @@ export async function definitionsCommand(args, io, deps = {}) {
|
||||
}
|
||||
} else throw new CliError(DEFINITIONS_USAGE, 4);
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,15 @@ export function autonomyDocument(current, changes) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// E2E6 fix 7: the autonomy-precondition check the CLI can see from the read and the document it sent:
|
||||
// owner notices off while a class sits near the loop, or moves away from the loop.
|
||||
const ORDER = ['in the loop', 'near the loop', 'out of the loop'];
|
||||
export function preconditionSeen(current, doc) {
|
||||
if (doc?.notices === true) return undefined;
|
||||
const moved = CLASSES.filter(c => ORDER.indexOf(doc?.[c]) > ORDER.indexOf(current?.levels?.[c] ?? 'in the loop'));
|
||||
if (CLASSES.some(c => doc?.[c] === 'near the loop') || moved.length) return 'owner notices are off; a class near the loop, or one moving away from it, needs them on (--notices on)';
|
||||
return undefined;
|
||||
}
|
||||
// Autonomy codes carry no message from the route; these are the panel's own words (autonomy.js).
|
||||
const AUTONOMY_GUIDANCE = {
|
||||
'revision-conflict': 'the organization changed; read it again with mosaic org autonomy ID',
|
||||
@@ -117,6 +126,10 @@ function refused(answer, what, unknown, guidance = {}) {
|
||||
const code = typeof raw === 'string' && /^[a-z-]{1,64}$/.test(raw) ? raw : `http ${answer.status}`;
|
||||
if (code === 'outcome-unknown' || (answer.status >= 500 && !raw)) return new CliError(`outcome unknown: ${unknown}`, 1);
|
||||
const said = typeof answer.body?.message === 'string' ? answer.body.message.slice(0, 500) : guidance[code];
|
||||
// E2E6 fix 7: a route that forwards the bus's reason (which check failed) has it said first; the
|
||||
// general guidance becomes the next line. A reason is one printable line, never a control byte.
|
||||
const reason = typeof answer.body?.reason === 'string' && /^[\x20-\x7e]{1,300}$/.test(answer.body.reason) ? answer.body.reason : undefined;
|
||||
if (reason) return new CliError(`${what} refused (${code}): ${reason}`, 3, { next: said });
|
||||
return new CliError(`${what} refused (${code})${said ? `: ${said}` : ''}`, 3);
|
||||
}
|
||||
|
||||
@@ -173,8 +186,14 @@ export async function orgOwnerCommand(args, io, deps = {}) {
|
||||
const read = await consoleOrgRequest(ctx, id, { path: 'autonomy' });
|
||||
if (!ok(read)) throw refused(read, 'autonomy set', 'the autonomy read did not finish; nothing was changed', AUTONOMY_GUIDANCE);
|
||||
const unknown = `the setting may have been saved; check mosaic org autonomy ${id} before trying again`;
|
||||
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: autonomyDocument(read.body, changes) }, unknown });
|
||||
if (!ok(answer)) throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
|
||||
const doc = autonomyDocument(read.body, changes);
|
||||
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: doc }, unknown });
|
||||
if (!ok(answer)) {
|
||||
// E2E6 fix 7: a route that forwards no reason still gets the one check this side can see.
|
||||
const local = answer.body?.error === 'autonomy-precondition' && answer.body?.reason === undefined ? preconditionSeen(read.body, doc) : undefined;
|
||||
if (local) throw new CliError(`autonomy set refused (autonomy-precondition): ${local}`, 3, { next: AUTONOMY_GUIDANCE['autonomy-precondition'] });
|
||||
throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
|
||||
}
|
||||
return { value: answer.body, text: b => `saved autonomy for ${id}: revision ${b.revision ?? 'unknown'}${b.transaction ? `, receipt ${b.transaction}` : ''}\n` };
|
||||
};
|
||||
} else if (step === 'review') {
|
||||
|
||||
+30
-15
@@ -15,7 +15,7 @@ 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';
|
||||
// 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 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]... | pack hire ID PACK [--project P] | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
|
||||
// #1873 SP8: saving the organization, or one project, as a template; the owner's alone.
|
||||
export const TEMPLATE_USAGE = 'mosaic org template save ID NAME [--project P] (--preview | --digest D) | template list ID';
|
||||
export const ORG_USAGE = 'mosaic org lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | ' + TEMPLATE_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
|
||||
@@ -63,7 +63,27 @@ const PACK_REFUSALS = {
|
||||
'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',
|
||||
'starter-pack-invalid': 'the pack fails its own checks or the composition check; nothing was written',
|
||||
'starter-pack-template-changed': 'a template the pack names changed since it was loaded; preview again',
|
||||
'not-configured': 'this organization\'s bus has no organization writer configured',
|
||||
// Ruling 2026-11-14: apply and pack hire hire the pack's proposals. These come back as a hire's code.
|
||||
'pack-not-applied': 'that pack has no packs entry in this organization or project; preview and apply it first',
|
||||
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give a hire; set both in either one\'s vars, then run pack hire',
|
||||
'no-chief-of-staff': 'the organization has no chief of staff to raise its hires',
|
||||
'right-required': 'hiring needs the org.hire right',
|
||||
};
|
||||
// E2E6 fix 3: humanTransport throws a CliError whose message and .code are the bus code alone. A code
|
||||
// a table knows gains its hint, as template save's do; a next line it carried is kept. Any other
|
||||
// CliError (bus-not-running with its own next line, a usage error) passes unchanged, and a bare coded
|
||||
// error (a test's call) becomes a CliError named by its code.
|
||||
function hinted(e, ...tables) {
|
||||
const code = typeof e?.code === 'string' ? e.code : '';
|
||||
const table = tables.find(t => Object.hasOwn(t, code));
|
||||
if (!table && (code === '' || e instanceof CliError)) return e;
|
||||
const error = new CliError(table ? `${code}: ${table[code]}` : code, busExit(code), { next: e.next });
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
async function packsCommand(args, io, deps) {
|
||||
const pos = [], values = {}, as = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -86,6 +106,9 @@ async function packsCommand(args, io, deps) {
|
||||
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 === 'pack' && sub === 'hire' && pos.length === 4) {
|
||||
// Ruling 2026-11-14: hire the proposals of a pack already applied, the same loop apply runs.
|
||||
allowed('--project'); verb = 'pack.hire'; request = { pack: name, ...project };
|
||||
} 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 }; }
|
||||
@@ -105,13 +128,7 @@ async function packsCommand(args, io, deps) {
|
||||
}
|
||||
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;
|
||||
}
|
||||
catch (e) { throw hinted(e, PACK_REFUSALS); }
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
// #1873 SP8: template save previews (--preview) or writes the previewed JSON (--digest); template
|
||||
@@ -120,7 +137,8 @@ async function packsCommand(args, io, deps) {
|
||||
const TEMPLATE_REFUSALS = {
|
||||
'template-secret-suspected': 'a field the template would keep holds a credential the organization\'s bus holds; remove it and preview again (nothing was written)',
|
||||
'pack-plan-stale': 'the organization or a template changed since the preview; preview again and save its digest',
|
||||
'invalid-request': 'the bus refused the request: a bad name, a name already saved, an unknown project, or an organization the template cannot hold',
|
||||
'template-exists': 'a template of this name is already saved for your account; nothing was written',
|
||||
'invalid-request': 'the bus refused the request: a bad name, an unknown project, or an organization the template cannot hold',
|
||||
'human-required': 'only the organization\'s owner, from a human shell, may do this',
|
||||
'not-configured': 'the templates directory is missing or not private to this instance\'s user',
|
||||
'starter-pack-invalid': 'the template would not be a valid pack: more than 8 hires, or a definition wider than its template',
|
||||
@@ -147,12 +165,9 @@ async function templateCommand(args, io, deps) {
|
||||
let result;
|
||||
try { result = await packCall(id, io, deps)(verb, request); }
|
||||
catch (e) {
|
||||
// humanTransport throws a CliError named by the bus code alone: a known code gains its hint.
|
||||
const why = typeof e?.code !== 'string' ? undefined
|
||||
: Object.hasOwn(TEMPLATE_REFUSALS, e.code) ? TEMPLATE_REFUSALS[e.code] : Object.hasOwn(PACK_REFUSALS, e.code) ? PACK_REFUSALS[e.code] : undefined;
|
||||
if (!why) throw e;
|
||||
const error = new CliError(`${e.code}: ${why}`, busExit(e.code));
|
||||
error.code = e.code;
|
||||
const error = hinted(e, TEMPLATE_REFUSALS, PACK_REFUSALS);
|
||||
// E2E6 fix 8: a taken name says what to do next.
|
||||
if (error.code === 'template-exists' && error.next === undefined) error.next = `preview and save under another name, or see the saved names with mosaic org template list ${id}`;
|
||||
throw error;
|
||||
}
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
|
||||
@@ -41,6 +41,7 @@ const EXIT = {
|
||||
"tester-required": 3,
|
||||
"tester-off": 3,
|
||||
"tester-refused": 3,
|
||||
"bus-not-running": 3,
|
||||
"outcome-unknown": 1,
|
||||
"outcome-unknown-revoked": 1,
|
||||
"response-too-large": 1,
|
||||
@@ -51,6 +52,17 @@ export function busExit(code) {
|
||||
return EXIT[code] ?? 2;
|
||||
}
|
||||
|
||||
// E2E6 fix 6: the shim exits 5 (packages/bus/src/client.mjs NOT_SENT_EXIT) when its connect failed
|
||||
// before the request was written: no socket, or the connect refused. That is a stopped bus, and
|
||||
// nothing happened; outcome-unknown stays for a request that left and got no answer.
|
||||
const NOT_SENT_EXIT = 5;
|
||||
export function busNotRunning(business) {
|
||||
const error = new CliError(`bus-not-running: the bus for ${business} is not running, so the request was not sent`, 3);
|
||||
error.code = "bus-not-running";
|
||||
error.next = `start it with mosaic bus start ${business}, or clear a host that died with mosaic bus recover ${business}`;
|
||||
return error;
|
||||
}
|
||||
|
||||
// Returns a call(verb, args) for one business. `cli` and `spawn` exist for
|
||||
// the tests; the command line never sets them.
|
||||
export function humanTransport({ socket, business, env = process.env, cli = HUMAN_CLI, spawn = spawnSync, timeoutMs = 30000 }) {
|
||||
@@ -65,6 +77,7 @@ export function humanTransport({ socket, business, env = process.env, cli = HUMA
|
||||
if (proc.error || proc.status === null) throw new CliError("outcome-unknown: the bus transport did not finish", 1);
|
||||
if (proc.status !== 0) {
|
||||
const code = String(proc.stderr ?? "").trim().split("\n").reverse().find((l) => /^[a-z-]{1,64}$/.test(l)) ?? "invalid-response";
|
||||
if (proc.status === NOT_SENT_EXIT && code === "outcome-unknown") throw busNotRunning(business);
|
||||
const error = new CliError(code, busExit(code));
|
||||
error.code = code;
|
||||
throw error;
|
||||
|
||||
@@ -89,6 +89,8 @@ function organizations({ send = true } = {}) {
|
||||
calls.push({ verb, args, opts });
|
||||
if (verb === 'autonomy.review.console') return { reviewed: args.decisionClass };
|
||||
if (args.revision !== state.revision) throw new BusReadError('revision-conflict');
|
||||
// E2E6 fix 7: the bus refuses policy out of the loop here; the route forwards the code alone.
|
||||
if (args.autonomy.policy === 'out of the loop') throw new BusReadError('autonomy-precondition');
|
||||
const { notices, reverseWindowHours, authorityResolver, ...levels } = args.autonomy;
|
||||
state = { revision: REV(parseInt(state.revision, 16) + 1), levels, autonomy: { notices, reverseWindowHours, ...(authorityResolver ? { authorityResolver } : {}) } };
|
||||
return { revision: state.revision, transaction: `tx-${parseInt(state.revision, 16)}` };
|
||||
@@ -259,6 +261,21 @@ test('autonomy reads, saves with the panel\'s revision check and records a revie
|
||||
assert.equal((await page(c.port, 'GET', '/api/orgs/alpha/autonomy')).body.revision, REV(5));
|
||||
c.calls.splice(0);
|
||||
|
||||
// E2E6 fix 7: an autonomy-precondition the route sends without a reason still names the one check the
|
||||
// terminal can see from its read and the document it sent (notices off while a class moves away),
|
||||
// and the general guidance becomes the next line.
|
||||
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'set', '--revision', REV(5), '--policy', 'out']);
|
||||
assert.equal(r.status, 3, r.stderr);
|
||||
assert.match(r.stderr, /^mosaic: autonomy set refused \(autonomy-precondition\): owner notices are off; a class near the loop, or one moving away from it, needs them on \(--notices on\)$/m);
|
||||
assert.match(r.stderr, /^mosaic: next: this move needs a separate resolver/m);
|
||||
const { preconditionSeen } = await import('../src/org-owner.mjs');
|
||||
const shown = { levels: { ...LOOP, merge: 'near the loop' } };
|
||||
assert.equal(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: true }), undefined);
|
||||
assert.equal(preconditionSeen(shown, { ...LOOP, notices: false }), undefined, 'moving back toward the loop needs no notices');
|
||||
assert.match(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: false }), /^owner notices are off/);
|
||||
assert.match(preconditionSeen({ levels: LOOP }, { ...LOOP, authority: 'out of the loop', notices: false }), /^owner notices are off/);
|
||||
c.calls.splice(0);
|
||||
|
||||
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'review', 'merge']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, 'recorded your trail review for merge on alpha\n');
|
||||
|
||||
@@ -67,6 +67,15 @@ test('two organization buses are isolated and refusals never select a sibling',
|
||||
writeFileSync(join(alpha.root, 'bus-host/host.json'), JSON.stringify(staleHost), { mode: 0o600 });
|
||||
writeFileSync(join(alpha.root, 'bus-host/host.lock'), JSON.stringify(staleHost), { mode: 0o600 });
|
||||
writeFileSync(join(alpha.root, 'bus/writer.lock'), JSON.stringify({ pid: 2147483647, at: '2026-01-01T00:00:00Z' }), { mode: 0o600 });
|
||||
// E2E6 fix 1: status, start, stop and restart refuse a dead host's lock with the message unchanged and a
|
||||
// next line naming the verb that clears it.
|
||||
for (const args of [['status', 'alpha', '--json'], ['start', 'alpha', '--no-launch', '--detach'], ['stop', 'alpha'], ['restart', 'alpha']]) {
|
||||
const r = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', ...args], { env, encoding: 'utf8', timeout: 30000 });
|
||||
assert.equal(r.status, 3, `${args[0]}: ${r.stderr}`);
|
||||
assert.match(r.stderr, /^mosaic: stale bus host lock$/m, args[0]);
|
||||
assert.match(r.stderr, /^mosaic: next: if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs$/m, args[0]);
|
||||
}
|
||||
await assert.rejects(busStatus(ctx, 'alpha'), e => e.message === 'stale bus host lock' && e.exitCode === 3 && /mosaic bus recover alpha/.test(e.next));
|
||||
const recovery = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', 'recover', 'alpha'], { env, encoding: 'utf8' });
|
||||
assert.equal(recovery.status, 0, recovery.stderr);
|
||||
const restarted = await busStart(ctx, 'alpha', { detach: true, noLaunch: true });
|
||||
|
||||
@@ -417,3 +417,60 @@ test('a detached console without the dev owner has no supervisor, so it refuses
|
||||
assert.equal(start.stderr, '');
|
||||
assert.equal((await consoleStop(ctx)).stopped, true);
|
||||
});
|
||||
|
||||
// E2E6 fix 4: console start and stop clear a start.lock whose named supervisor (pid and start time) is
|
||||
// gone, and never one whose holder still runs or that names no holder.
|
||||
test('E2E6 a start.lock whose holder is gone is cleared by stop and by start; a live or unnamed one refuses and stays', { timeout: 60000 }, async t => {
|
||||
const { startTimeOf } = await import('../src/host.mjs');
|
||||
const { ctx } = await instance(t);
|
||||
const dir = join(ctx.dataRoot, 'console'), lock = join(dir, 'start.lock');
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
// A process this test starts and lets end: its pid and start time name a supervisor that is gone.
|
||||
const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], { stdio: 'ignore' });
|
||||
await new Promise(r => child.once('spawn', r));
|
||||
const deadHolder = { pid: child.pid, startTime: startTimeOf(child.pid) };
|
||||
assert.match(deadHolder.startTime, /^\d+$/);
|
||||
child.kill('SIGKILL');
|
||||
await new Promise(r => child.once('exit', r));
|
||||
|
||||
const warnings = [];
|
||||
writeFileSync(lock, JSON.stringify(deadHolder), { mode: 0o600 });
|
||||
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
|
||||
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${child.pid}, which is gone\n`]);
|
||||
assert.equal(existsSync(lock), false);
|
||||
assert.deepEqual(readdirSync(dir).filter(x => x.startsWith('start.lock')), []);
|
||||
|
||||
// A live pid with another start time is a reused pid: its holder is gone too.
|
||||
writeFileSync(lock, JSON.stringify({ pid: process.pid, startTime: '1' }), { mode: 0o600 });
|
||||
warnings.length = 0;
|
||||
const result = await consoleStart(ctx, { detach: true, port: 'auto', warn: s => warnings.push(s) });
|
||||
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${process.pid}, which is gone\n`]);
|
||||
assert.equal(existsSync(lock), false, 'the start released its own lock');
|
||||
assert.equal((await consoleStop(ctx)).stopped, true);
|
||||
assert.ok(Number.isSafeInteger(result.pid));
|
||||
|
||||
// A live holder refuses on start and stop, and the lock stays as it was.
|
||||
const live = JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) });
|
||||
writeFileSync(lock, live, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), e => e.message === `console start lock is held by process ${process.pid}, which still runs; wait for its start or stop to finish`);
|
||||
await assert.rejects(consoleStart(ctx, { detach: true, port: 'auto' }), /which still runs/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), live);
|
||||
// A lock that names no holder (empty: a holder between its open and its write; or bad JSON) stays too.
|
||||
for (const body of ['', '{"pid":', JSON.stringify({ pid: 0, startTime: '1' }), JSON.stringify({ pid: child.pid, startTime: 7 })]) {
|
||||
writeFileSync(lock, body, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), body);
|
||||
}
|
||||
// f6c review P3-1: a lock its holder marked released (a clear put it back after the release) is
|
||||
// cleared; a released marker with anything else in it names no holder and stays.
|
||||
writeFileSync(lock, JSON.stringify({ released: true }), { mode: 0o600 });
|
||||
warnings.length = 0;
|
||||
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
|
||||
assert.deepEqual(warnings, ['mosaic: cleared a console start lock its holder had released\n']);
|
||||
assert.equal(existsSync(lock), false);
|
||||
const odd = JSON.stringify({ released: true, pid: 1 });
|
||||
writeFileSync(lock, odd, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), odd);
|
||||
rmSync(lock);
|
||||
});
|
||||
@@ -136,3 +136,55 @@ test('T1 mosaic org definitions: writes go through the bus and its secret check,
|
||||
await assert.rejects(orgCommand(['definitions', 'acme', 'remove', 'copy', '--if-rev', '1'], x), (e) => e.exitCode === 3 && /organization bus/.test(e.message));
|
||||
assert.deepEqual(readFileSync(file), before);
|
||||
});
|
||||
|
||||
// E2E6 fix 2: an unknown definition, an unknown organization, a bad id and a bad name each end in
|
||||
// one usage or refusal line: no stack trace and no host path.
|
||||
test('E2E6 mosaic org definitions: unknown names, an unknown org and a bad id give one line, no stack and no path', async (t) => {
|
||||
const root = tmp(t);
|
||||
const f = fixture(root, 'acme');
|
||||
const { run } = await import('../src/cli.mjs');
|
||||
const cases = [
|
||||
[['acme', 'show', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
|
||||
[['acme', 'diff', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
|
||||
[['acme', 'show', 'Bad Name'], 3, 'mosaic: definition-missing: definitions declares no definition by that name; list them with mosaic org definitions acme list'],
|
||||
[['nosuch', 'list'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
|
||||
[['nosuch', 'show', 'x'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
|
||||
];
|
||||
for (const [args, exit, line] of cases) {
|
||||
const x = io(f.env);
|
||||
assert.equal(await run(['org', 'definitions', ...args], x, {}), exit, args.join(' '));
|
||||
assert.equal(x.err.text, `${line}\n`, args.join(' '));
|
||||
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text), args.join(' '));
|
||||
}
|
||||
for (const args of [['Bad/Id', 'list'], ['../x', 'show', 'y']]) {
|
||||
const x = io(f.env);
|
||||
assert.equal(await run(['org', 'definitions', ...args], x, {}), 4, args.join(' '));
|
||||
assert.match(x.err.text, /^mosaic: invalid organization id: an id is 1 to 64 of a-z/);
|
||||
assert.match(x.err.text, /\nmosaic org definitions templates \| definitions ID list/);
|
||||
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text));
|
||||
}
|
||||
});
|
||||
|
||||
test('E2E6 definitionsFailure: a raw filesystem error is named by its operation and code, a message path is cut, an unknown error says only that it failed', async () => {
|
||||
const { definitionsFailure } = await import('../src/org-definitions.mjs');
|
||||
const fsError = (code, syscall) => Object.assign(new Error(`${code}: no such file, open '/home/someone/.config/x/acme.json'`), { code, syscall, path: '/home/someone/.config/x/acme.json' });
|
||||
let e = definitionsFailure(fsError('EACCES', 'open'), 'acme');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['organization-unreadable', 3, 'organization-unreadable: cannot open the file of organization acme (EACCES)']);
|
||||
e = definitionsFailure(Object.assign(new Error("organization file /srv/x/acme.json is not valid"), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: organization file <path> is not valid');
|
||||
e = definitionsFailure(new TypeError('Cannot read properties of undefined'), 'acme');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-failed', 1, 'definitions-failed: the definitions command failed']);
|
||||
// f6c review P3-2: only the organization file missing means no organization.
|
||||
e = definitionsFailure(fsError('ENOENT', 'open'), 'acme');
|
||||
assert.deepEqual([e.code, e.message], ['unknown-organization', 'unknown-organization: this instance has no organization acme; list them with mosaic org list']);
|
||||
const rolesGone = Object.assign(new Error("ENOENT: no such file or directory, scandir '/home/someone/roles'"), { code: 'ENOENT', syscall: 'scandir', path: '/home/someone/roles' });
|
||||
e = definitionsFailure(rolesGone, 'templates');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-unreadable', 3, 'definitions-unreadable: cannot scandir a file the definitions command reads (ENOENT)']);
|
||||
e = definitionsFailure(rolesGone, 'acme');
|
||||
assert.equal(e.code, 'organization-unreadable');
|
||||
// f6c review P3-3: a path after ':' or inside backticks is cut.
|
||||
e = definitionsFailure(Object.assign(new Error('organization file:/srv/x/acme.json is not valid'), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: organization file:<path> is not valid');
|
||||
e = definitionsFailure(Object.assign(new Error('bad role at `/srv/roles/x.json`'), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: bad role at `<path>`');
|
||||
});
|
||||
@@ -97,3 +97,55 @@ test('SP4 an agent shell refuses every pack, board and workflow word, pack list
|
||||
assert.deepEqual(s.calls, []);
|
||||
assert.deepEqual(readFileSync(s.file), before);
|
||||
});
|
||||
|
||||
// E2E6 fix 3: the real transport shape. humanTransport throws a CliError whose message and .code are
|
||||
// the bus code alone (packages/cli/src/transport.mjs); pack, board and workflow refusals must still
|
||||
// gain their hint, as template save's do, and a CliError with its own next line passes unchanged.
|
||||
test('E2E6 pack, board and workflow refusals from a CliError-shaped transport print the hint', async (t) => {
|
||||
const { CliError } = await import('../src/errors.mjs');
|
||||
const { busExit, busNotRunning } = await import('../src/transport.mjs');
|
||||
const root = tmp(t);
|
||||
const f = fixture(root, 'acme');
|
||||
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 });
|
||||
let down = false;
|
||||
const deps = { system: { dataRoot: f.dataRoot }, transport: () => async (verb, args = {}) => {
|
||||
if (down) throw busNotRunning('acme');
|
||||
try { return structuredClone(await b.broker.request(human, { verb, args })); }
|
||||
catch (e) { if (!(e instanceof BusError)) throw e; throw Object.assign(new CliError(e.code, busExit(e.code)), { code: e.code }); }
|
||||
} };
|
||||
const run = async (args) => { const x = io(f.env); await main(['org', ...args], x, deps); return JSON.parse(x.out.text); };
|
||||
const hinted = (e) => typeof e.code === 'string' && e instanceof CliError && e.message.startsWith(`${e.code}: `) && e.message.length > e.code.length + 10;
|
||||
|
||||
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'starter-pack-not-found' && e.message === 'starter-pack-not-found: no installed, shipped or saved pack has that name');
|
||||
const spec = join(root, 'board.json');
|
||||
writeFileSync(spec, JSON.stringify({ columns: [{ state: 'todo', label: 'Backlog' }], layout: 'kanban' }));
|
||||
await assert.rejects(run(['board', 'set', 'acme', spec]), (e) => hinted(e) && e.exitCode === busExit(e.code));
|
||||
await assert.rejects(run(['workflow', 'remove', 'acme', 'ghost']), (e) => hinted(e) && e.exitCode === busExit(e.code));
|
||||
|
||||
// A stopped bus keeps its own message and next line.
|
||||
down = true;
|
||||
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'bus-not-running' && e.exitCode === 3
|
||||
&& e.message === 'bus-not-running: the bus for acme is not running, so the request was not sent' && /mosaic bus start acme/.test(e.next) && /mosaic bus recover acme/.test(e.next));
|
||||
});
|
||||
|
||||
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" The owner's apply
|
||||
// hires the proposals in the same act; pack hire runs the same loop on the packs entry and hires none twice.
|
||||
test('PD mosaic org pack apply hires the proposals; pack hire on the same record hires nothing twice', async (t) => {
|
||||
const s = await setup(t);
|
||||
assert.ok(PACKS_USAGE.includes('pack hire ID PACK [--project P]'));
|
||||
const preview = await s.run(['pack', 'preview', 'acme', 'coding']);
|
||||
const applied = await s.run(['pack', 'apply', 'acme', 'coding', '--digest', preview.digest]);
|
||||
assert.deepEqual(applied.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
for (const x of applied.hires) assert.match(String(x.decision), /^[0-9a-f-]{36}$/);
|
||||
const doc = s.doc();
|
||||
for (const x of applied.hires) { assert.equal(doc.roles[x.name].hireDecision, x.decision); assert.ok(doc.launch.instances.includes(x.name), x.name); }
|
||||
|
||||
const again = await s.run(['pack', 'hire', 'acme', 'coding']);
|
||||
assert.deepEqual(again.hires.map((x) => [x.name, x.state]), [['pm-1', 'exists'], ['coder-1', 'exists'], ['reviewer-1', 'exists']]);
|
||||
assert.deepEqual(s.calls.at(-1), ['pack.hire', ['pack']]);
|
||||
await assert.rejects(s.run(['pack', 'hire', 'acme', 'ghost-pack']), (e) => e.code === 'pack-not-applied' && /apply it first/.test(e.message));
|
||||
await assert.rejects(s.run(['pack', 'hire', 'acme']), (e) => e.exitCode === 4 && e.message === PACKS_USAGE);
|
||||
});
|
||||
@@ -37,8 +37,13 @@ test('organization host claim refuses a stale lock without removing it', t => {
|
||||
const stale = { pid: 99999999, startTime: '0', business: 'alpha', startedAt: 'old' };
|
||||
writeFileSync(hostLock(root), JSON.stringify(stale), { mode: 0o600 });
|
||||
const mine = { pid: process.pid, startTime: startTimeOf(process.pid), business: 'alpha', startedAt: 'now' };
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), /stale.*lock/i);
|
||||
// E2E6 fix 1: the message stays; the next line names the verb that clears the dead host.
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.message === 'stale bus host lock' && e.exitCode === 3
|
||||
&& e.next === 'if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs');
|
||||
assert.deepEqual(JSON.parse(readFileSync(hostLock(root), 'utf8')), stale);
|
||||
// A lock naming no valid organization id still names the verb, with a placeholder.
|
||||
writeFileSync(hostLock(root), JSON.stringify({ ...stale, business: '../x\nsecret' }), { mode: 0o600 });
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.next === 'if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs');
|
||||
});
|
||||
|
||||
import { busStatus } from '../src/org-bus.mjs';
|
||||
|
||||
@@ -40,7 +40,7 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
|
||||
const before = readFileSync(s.file);
|
||||
const preview = await s.run(['template', 'save', 'acme', 'acme-shape', '--preview']);
|
||||
assert.match(preview.digest, /^[0-9a-f]{64}$/);
|
||||
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.replacements));
|
||||
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.mentions) && !('replacements' in preview));
|
||||
assert.ok(!existsSync(s.saved('acme-shape')), 'preview writes no file');
|
||||
|
||||
const out = await s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]);
|
||||
@@ -49,7 +49,9 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
|
||||
assert.equal(lstatSync(s.saved('acme-shape')).mode & 0o777, 0o600);
|
||||
assert.deepEqual(readFileSync(s.file), before, 'save writes nothing to the organization file');
|
||||
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'invalid-request' && /already saved/.test(e.message));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'template-exists' && e.exitCode === 2
|
||||
&& e.message === 'template-exists: a template of this name is already saved for your account; nothing was written'
|
||||
&& /under another name/.test(e.next) && /mosaic org template list acme/.test(e.next));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'other', '--digest', preview.digest]), (e) => e.code === 'pack-plan-stale' && /preview again/.test(e.message));
|
||||
const listed = await s.run(['template', 'list', 'acme']);
|
||||
assert.deepEqual(listed.templates.map((x) => x.name), ['acme-shape']);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { busExit, humanTransport, refuseInsideAgent } from "../src/transport.mjs";
|
||||
import { busExit, humanTransport, refuseInsideAgent, HUMAN_CLI } from "../src/transport.mjs";
|
||||
import { fakeCli, humanEnv, tmp } from "./helpers.mjs";
|
||||
|
||||
// The fake records argv and stdin, then answers per verb. The real
|
||||
@@ -15,6 +15,8 @@ const { verb } = JSON.parse(input);
|
||||
if (verb === "inbox") process.stdout.write(JSON.stringify([{ id: "d1" }]) + "\\n");
|
||||
else if (verb === "garbage") process.stdout.write("not json");
|
||||
else if (verb === "hang") setTimeout(() => {}, 60000);
|
||||
else if (verb === "not-sent") { process.stderr.write("outcome-unknown\\n"); process.exit(5); }
|
||||
else if (verb === "not-sent-other") { process.stderr.write("human-required\\n"); process.exit(5); }
|
||||
else { process.stderr.write("some noise\\n" + verb + "\\n"); process.exit(2); }
|
||||
`;
|
||||
|
||||
@@ -50,3 +52,28 @@ test("busExit and refuseInsideAgent", () => {
|
||||
assert.doesNotThrow(() => refuseInsideAgent(humanEnv()));
|
||||
assert.throws(() => refuseInsideAgent({ PI_AGENT_DIR: "/x" }), (e) => e.exitCode === 3 && /PI_AGENT_DIR/.test(e.message));
|
||||
});
|
||||
|
||||
// E2E6 fix 6: the shim exits 5 when its connect failed before the request was written. That is a stopped
|
||||
// bus: mosaic says so with the start and recover line. outcome-unknown stays for a request that left.
|
||||
test("E2E6 exit 5 with outcome-unknown is bus-not-running; exit 2 with outcome-unknown is unchanged", async (t) => {
|
||||
const s = setup(t);
|
||||
await assert.rejects(s.call("not-sent"), (e) => e.code === "bus-not-running" && e.exitCode === 3
|
||||
&& e.message === "bus-not-running: the bus for acme is not running, so the request was not sent"
|
||||
&& e.next === "start it with mosaic bus start acme, or clear a host that died with mosaic bus recover acme");
|
||||
await assert.rejects(s.call("outcome-unknown"), (e) => e.code === "outcome-unknown" && e.exitCode === 1 && e.message === "outcome-unknown" && e.next === undefined);
|
||||
// Exit 5 says only that nothing was sent; any other code it carries keeps its own meaning.
|
||||
await assert.rejects(s.call("not-sent-other"), (e) => e.code === "human-required" && e.exitCode === 3);
|
||||
assert.equal(busExit("bus-not-running"), 3);
|
||||
});
|
||||
|
||||
// The real shim, with no bus behind the path: nothing reaches a broker, so no proof runs. A missing socket
|
||||
// and a path that is not a listening socket are both a bus that is not running.
|
||||
test("E2E6 the real human shim against a missing socket or a plain file says the bus is not running", async (t) => {
|
||||
const root = tmp(t);
|
||||
const plain = join(root, "plain.sock");
|
||||
writeFileSync(plain, "");
|
||||
for (const socket of [join(root, "missing.sock"), plain]) {
|
||||
const call = humanTransport({ socket, business: "acme", env: humanEnv(), cli: HUMAN_CLI, timeoutMs: 20000 });
|
||||
await assert.rejects(call("inbox"), (e) => e.code === "bus-not-running" && e.exitCode === 3, socket);
|
||||
}
|
||||
});
|
||||
@@ -36,9 +36,9 @@
|
||||
import { refusalGuidance } from "../../bus/src/refusals.mjs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { chmodSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, closeSync } from "node:fs";
|
||||
import { chmodSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, closeSync } from "node:fs";
|
||||
import { createServer, connect } from "node:net";
|
||||
import { join } from "node:path";
|
||||
import { basename, join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
import { LENGTH_FAILURE_NOTICE_PREFIX } from "./failure-notice.mjs";
|
||||
@@ -384,13 +384,56 @@ export function toolServer({ path, tools, client, local }) {
|
||||
});
|
||||
}
|
||||
|
||||
// #1873 r127: exit 127 is the shell's "command not found". The turn's stderr then holds the
|
||||
// shell's own line for it, the last one nearest the exit:
|
||||
// bash X: line N: [exec: ]CMD: No such file or directory | [command ]not found
|
||||
// dash X: N: [exec: ]CMD: not found
|
||||
// env [/usr/bin/]env: 'CMD': No such file or directory
|
||||
// Only those shapes count, so another program's missing file (cat: F: No such file…) doesn't.
|
||||
// The answer is CMD's basename, which the person reads in the failure; never its host path, and
|
||||
// nothing that isn't a plain program name. A run of 16 letters and digits looks like a key, not a
|
||||
// program, so it stays in the run's private stderr.
|
||||
const NOT_FOUND = [
|
||||
/(?:^|: )line \d+: (?:exec: )?([^\s:]+): (?:(?:command )?not found|No such file or directory)$/,
|
||||
/: \d+: (?:exec: )?([^\s:]+): not found$/,
|
||||
/^(?:\S*\/)?env: ['\u2018]([^\s:'\u2019]+)['\u2019]: No such file or directory$/,
|
||||
];
|
||||
export function missingCommand(text) {
|
||||
let name = null;
|
||||
for (const line of String(text).split(/\r?\n/)) {
|
||||
const m = NOT_FOUND.map((re) => re.exec(line)).find(Boolean);
|
||||
if (m) name = basename(m[1]);
|
||||
}
|
||||
return name && /^[A-Za-z0-9._+-]{1,64}$/.test(name) && !/[A-Za-z0-9]{16}/.test(name) ? name : null;
|
||||
}
|
||||
|
||||
// The last 16 KiB of a turn's stderr file from a line start, or "" when it can't be read.
|
||||
const TAIL = 16384;
|
||||
function stderrTail(path) {
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(path, "r");
|
||||
const size = fstatSync(fd).size, length = Math.min(size, TAIL);
|
||||
const buf = Buffer.alloc(length);
|
||||
readSync(fd, buf, 0, length, size - length);
|
||||
const text = buf.toString("utf8");
|
||||
// A window that starts mid-file starts mid-line; that partial line is dropped.
|
||||
return size > TAIL ? text.slice(text.indexOf("\n") + 1) : text;
|
||||
} catch {
|
||||
return "";
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// Run one turn. Resolves { ok, text, reason }.
|
||||
function runTurn({ session, request, n, env, onChild }) {
|
||||
const marker = session.turnMarker;
|
||||
rmSync(marker, { force: true });
|
||||
const turns = join(session.runDir, "turns");
|
||||
mkdirSync(turns, { recursive: true, mode: 0o700 });
|
||||
const errFd = openSync(join(turns, `${String(n).padStart(4, "0")}.stderr`), "wx", 0o600);
|
||||
const errPath = join(turns, `${String(n).padStart(4, "0")}.stderr`);
|
||||
const errFd = openSync(errPath, "wx", 0o600);
|
||||
// Adapters are 0644 in the repository (the image sets the mode), so the
|
||||
// host runs them through sh.
|
||||
const child = spawn("/bin/sh", [session.adapter], {
|
||||
@@ -461,6 +504,10 @@ function runTurn({ session, request, n, env, onChild }) {
|
||||
if (status?.stopReason === "length" && status.hasText === false && status.hasToolCall === false)
|
||||
return resolve({ ok: false, emptyLength: true, reason: "output limit reached while thinking before any answer or tool call" });
|
||||
}
|
||||
if (code === 127) {
|
||||
const missing = missingCommand(stderrTail(errPath));
|
||||
return resolve({ ok: false, reason: `adapter exited 127${missing ? ` (command not found: ${missing})` : ""}` });
|
||||
}
|
||||
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
|
||||
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
|
||||
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
|
||||
|
||||
@@ -13,7 +13,7 @@ import { join } from "node:path";
|
||||
import { Store } from "../../bus/src/store.mjs";
|
||||
import { Broker, BusError } from "../../bus/src/broker.mjs";
|
||||
import { serve } from "../../bus/src/server.mjs";
|
||||
import { EXIT, founderCheck, landingRequest, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
|
||||
import { EXIT, founderCheck, landingRequest, missingCommand, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
|
||||
import { typedTools } from "../src/tools.mjs";
|
||||
import { resolvedFor, scratch } from "./helpers.mjs";
|
||||
|
||||
@@ -298,6 +298,88 @@ test("SIGKILL of the model child keeps base failure receipts through the real ad
|
||||
assert.equal(records[1].body, records[0].body);
|
||||
});
|
||||
|
||||
// #1873 r127: on the dev instance /usr/bin/claude is a wrapper that execs a binary outside /usr.
|
||||
// The sandbox binds /usr only, so the wrapper starts and its target is missing: the shell exits
|
||||
// 127 and the person read only "adapter exited 127". The reason now names the missing program.
|
||||
test("r127 an adapter exit 127 names the program that wasn't found, through the real claude adapter", async t => {
|
||||
const ctx = await setup(t, {session:{harness:"claude-code", turnEnd:"exit", adapter:new URL("../../../adapters/claude/adapter.sh", import.meta.url).pathname}});
|
||||
const sessionFile = join(ctx.runDir, "session.json");
|
||||
const session = JSON.parse(readFileSync(sessionFile, "utf8"));
|
||||
const wrapper = join(ctx.dir, "bin", "claude");
|
||||
mkdirSync(join(ctx.dir, "bin"));
|
||||
writeFileSync(wrapper, `#!/bin/sh\nexport DISABLE_UPDATES=1\nexec ${join(ctx.dir, "not-mounted", "claude-code", "bin", "claude")} "$@"\n`, {mode:0o755});
|
||||
session.harnessEnv = {MOSAIC_CLAUDE_BIN:wrapper, MOSAIC_THINKING:"low", MOSAIC_CLAUDE_SETTINGS:session.bundle.policy, MOSAIC_CLAUDE_MCP_CONFIG:session.bundle.tools};
|
||||
writeFileSync(sessionFile, JSON.stringify(session));
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
const sent = ctx.call(ctx.pm, "message.send", {to:"coder", body:"hello", class:"REQUEST"});
|
||||
const [reply] = await until(replies(ctx));
|
||||
await until(() => ctx.store.get("SELECT 1 FROM deliveries WHERE message=? AND op='read'", sent.id));
|
||||
assert.equal(reply.body, "The turn failed: adapter exited 127 (command not found: claude)");
|
||||
assert.doesNotMatch(reply.body, /not-mounted|\/bin\//, "the reason names the program, never its host path");
|
||||
assert.match(r.stderr(), /failed: adapter exited 127 \(command not found: claude\)/);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("r127 an adapter whose own command is missing names it; a 127 with no such line keeps the bare reason", async t => {
|
||||
const ctx = await setup(t);
|
||||
const adapter = join(ctx.dir, "adapter.sh");
|
||||
writeFileSync(adapter, `case "$MOSAIC_REQUEST" in *QUIET*) echo "nothing useful" >&2; exit 127 ;; esac\nexec mosaic-r127-no-such-harness -p "$MOSAIC_REQUEST"\n`);
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
ctx.call(ctx.pm, "message.send", {to:"coder", body:"one"});
|
||||
ctx.call(ctx.pm, "message.send", {to:"coder", body:"QUIET"});
|
||||
await until(() => replies(ctx)() && ctx.inbox.length >= 2);
|
||||
assert.deepEqual(ctx.inbox.map(m => m.body), [
|
||||
"The turn failed: adapter exited 127 (command not found: mosaic-r127-no-such-harness)",
|
||||
"The turn failed: adapter exited 127",
|
||||
]);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("r127 missingCommand reads the shells' not-found lines and gives a safe basename only", () => {
|
||||
assert.equal(missingCommand("/usr/bin/claude: line 4: /opt/claude-code/bin/claude: No such file or directory\nclaude adapter: invalid or incomplete model stream\n"), "claude");
|
||||
assert.equal(missingCommand("/usr/bin/claude: 4: exec: /opt/claude-code/bin/claude: not found\n"), "claude");
|
||||
assert.equal(missingCommand("/x/adapters/pi/adapter.sh: 140: exec: pi: not found\n"), "pi");
|
||||
assert.equal(missingCommand("/x/adapter.sh: line 9: exec: pi: not found\n"), "pi");
|
||||
assert.equal(missingCommand("sh: line 1: pi: command not found\n"), "pi");
|
||||
assert.equal(missingCommand("/usr/bin/env: 'node': No such file or directory\n"), "node");
|
||||
assert.equal(missingCommand("/usr/bin/env: ‘node’: No such file or directory\n"), "node");
|
||||
// The last such line is the one nearest the exit.
|
||||
assert.equal(missingCommand("a: 1: exec: first: not found\nb: 2: exec: second: not found\n"), "second");
|
||||
assert.equal(missingCommand(""), null);
|
||||
assert.equal(missingCommand("error: model refused\n"), null);
|
||||
// A name that isn't a plain program name is left out, never echoed.
|
||||
assert.equal(missingCommand("a: 1: exec: $(rm -rf x): not found\n"), null);
|
||||
assert.equal(missingCommand(`a: 1: exec: ${"x".repeat(80)}: not found\n`), null);
|
||||
// Review r127 P3-5: tokens without spaces reach the name check, and it refuses them.
|
||||
assert.equal(missingCommand("a: 1: exec: $(id): not found\n"), null);
|
||||
assert.equal(missingCommand("a: line 2: x;id: command not found\n"), null);
|
||||
assert.equal(missingCommand("a: line 2: `id`: command not found\n"), null);
|
||||
// P3-2: a long run of letters and digits looks like a key, not a program; it stays in stderr.
|
||||
assert.equal(missingCommand("adapter.sh: line 3: sk-proj-abcDEF1234567890xyz: command not found\n"), null);
|
||||
assert.equal(missingCommand("adapter.sh: line 3: 0123456789abcdef0123: command not found\n"), null);
|
||||
// P3-1: only a shell's or env's own line counts; other programs' missing files don't.
|
||||
assert.equal(missingCommand("cat: /nope/file: No such file or directory\n"), null);
|
||||
assert.equal(missingCommand("w.sh: line 1: /opt/x/claude: No such file or directory\ncat: /run/state.json: No such file or directory\n"), "claude");
|
||||
// P3-4: CRLF lines read the same.
|
||||
assert.equal(missingCommand("sh: line 1: pi: command not found\r\n"), "pi");
|
||||
});
|
||||
|
||||
test("r127 a not-found line cut by the 16 KiB stderr window is not read as a name", async t => {
|
||||
const ctx = await setup(t, { session: { harness: 'pi', turnEnd: 'exit' } });
|
||||
ctx.inbox = [];
|
||||
// 52 + 16351 + 1 bytes: the 16 KiB window starts inside "claude", at "aude: No such file…".
|
||||
writeFileSync(join(ctx.dir, 'adapter.sh'),
|
||||
`printf 'x: line 1: /opt/x/claude: No such file or directory\\n' >&2\nhead -c 16351 /dev/zero | tr '\\0' 'z' >&2\nprintf '\\n' >&2\nexit 127\n`);
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(async () => { r.child.kill('SIGTERM'); await r.exited; });
|
||||
const reply = await ask(ctx);
|
||||
assert.equal(reply.body, "The turn failed: adapter exited 127");
|
||||
});
|
||||
|
||||
// Claude's private stream reader owns model activity; final result stdout alone
|
||||
// (even a synthetic success) must not cancel the model watchdog. Other adapters
|
||||
// still need the stdout fallback when no streaming producer is installed.
|
||||
|
||||
@@ -684,3 +684,11 @@ After the pinned window, use an ordinary new decision.
|
||||
Policy has no effect executor. Per the Lead ruling, its in and existing out
|
||||
levels work, while near refuses `policy-reverse-unavailable` and directs the
|
||||
owner to choose in or out. Policy near and its reverse wait for that executor.
|
||||
|
||||
### Pack hires and rights (ruling 2026-11-14, #1873)
|
||||
|
||||
`src/org-rights.mjs` maps `pack.hire.console` to `org.hire`: hiring a starter
|
||||
pack's proposed agents is a hire, so a member with that right hires the
|
||||
unflagged proposals and the rest wait for the owner (invariant 7). The read
|
||||
`instanceSettings` returns each instance's `hireDecision`, which the bus's
|
||||
`instances` read uses to name the pack an agent came from.
|
||||
@@ -183,6 +183,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
||||
protected: closed(entry.definition),
|
||||
kept: (launch?.keep ?? []).includes(name),
|
||||
endProtected: protectedRefusal(document, name, actor) !== null,
|
||||
// Ruling 2026-11-14: a hired instance names its hire decision; the bus adds the pack it came from.
|
||||
...(typeof entry.hireDecision === 'string' ? { hireDecision: entry.hireDecision } : {}),
|
||||
}]));
|
||||
// Row 194 (D1): the human's forbid lists and the retired names. The bus adds running runs.
|
||||
return {
|
||||
|
||||
@@ -94,6 +94,9 @@ export const VERB_RIGHTS = record({
|
||||
'packs.console': 'board.read',
|
||||
'pack.preview.console': null,
|
||||
'pack.apply.console': null,
|
||||
// Ruling 2026-11-14: hiring a pack's proposed agents is a hire; a member with org.hire gets the
|
||||
// unflagged ones and the rest wait for the owner (invariant 7).
|
||||
'pack.hire.console': 'org.hire',
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// #1873 SP8: saving a template, and listing the saved ones, are the owner's alone: a template is a
|
||||
|
||||
@@ -10,10 +10,13 @@
|
||||
// (instance credentials, copyBindings, copyId, orgIncarnation, generation), launch, plugins, vars,
|
||||
// project roots and git state, definition revs and hire decisions, and everything on the bus.
|
||||
//
|
||||
// Free text is kept, with the organization id, its project ids, its agent names, the owner's
|
||||
// account and the project roots replaced by {org}, {project}, {agent}, {owner} and {root}. The
|
||||
// preview lists each replacement and every kept free-text field by path, and the exact JSON save
|
||||
// writes; save takes that JSON's digest. Every string and key is passed to the credential store's
|
||||
// Free text is kept verbatim: save never rewrites prose (E2E6 fix 5, Lead ruling). A placeholder
|
||||
// could stand only where a field's whole value is an organization identifier, and a pack carries no
|
||||
// such field (hire names are <role>-<n>, step roles name definitions or templates), so save writes
|
||||
// none and apply has none to resolve. The preview lists every kept free-text field by path, each
|
||||
// one that mentions the organization id, a project id, an agent name, the owner's account or a
|
||||
// project root (so the owner can edit it before saving), and the exact JSON save writes; save takes
|
||||
// that JSON's digest. Every string and key is passed to the credential store's
|
||||
// assertClean; a hit refuses template-secret-suspected naming the path, never the text.
|
||||
//
|
||||
// A refusal is a TemplateError: a bus code and a reason that names a path or a checked name only,
|
||||
@@ -49,8 +52,8 @@ export const DEFAULT_BOARD = Object.freeze({
|
||||
layout: "kanban",
|
||||
});
|
||||
const HIRE_REASON = "The organization this template was saved from ran this agent.";
|
||||
// A word boundary for placeholder replacement: an identifier character on either side means the
|
||||
// literal is part of a longer name, which stays as it is.
|
||||
// A word boundary for a mention: an identifier character on either side means the literal is part of
|
||||
// a longer name, which is not a mention.
|
||||
const WORD = "A-Za-z0-9_-";
|
||||
|
||||
export class TemplateError extends Error {
|
||||
@@ -100,63 +103,63 @@ function templateOrNull(rolesDir, name, cache) {
|
||||
return cache.get(name);
|
||||
}
|
||||
|
||||
// ---- Placeholders ----
|
||||
// ---- Mentions ----
|
||||
|
||||
// The literals section 5 replaces, longest first so a root path is replaced before the ids inside
|
||||
// it. A name that is also a template or a definition name is a role's name, not a person's or a
|
||||
// client's, and stays: replacing "coder" would rewrite every role text that says coder.
|
||||
function literals(document, { rolesDir, cache }) {
|
||||
// The organization-specific names the preview looks for in kept text, longest first so a root path
|
||||
// is found before the ids inside it. A name that is also a template or a definition name is a role's
|
||||
// name, not a person's or a client's, and is not a mention: role text says "coder" on purpose. A
|
||||
// mention is labelled by kind and name; a project root is labelled by kind alone, so the preview
|
||||
// names no host path beyond the text it already shows.
|
||||
function orgNames(document, { rolesDir, cache }) {
|
||||
const out = [];
|
||||
const add = (text, placeholder) => {
|
||||
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, placeholder });
|
||||
const add = (text, label) => {
|
||||
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, label });
|
||||
};
|
||||
for (const project of Object.values(document.projects ?? {})) {
|
||||
add(project?.root, "{root}");
|
||||
add(project?.repo, "{root}");
|
||||
add(project?.root, "project root");
|
||||
add(project?.repo, "project root");
|
||||
}
|
||||
add(document.id, "{org}");
|
||||
for (const id of Object.keys(document.projects ?? {})) add(id, "{project}");
|
||||
add(document.human, "{owner}");
|
||||
if (typeof document.id === "string") add(document.id, `organization ${document.id}`);
|
||||
for (const id of Object.keys(document.projects ?? {})) add(id, `project ${id}`);
|
||||
if (typeof document.human === "string") add(document.human, `owner ${document.human}`);
|
||||
const role = (name) => Object.hasOwn(document.definitions ?? {}, name) || templateOrNull(rolesDir, name, cache) !== null;
|
||||
const agents = new Set([...Object.keys(document.roles ?? {}), ...(Array.isArray(document.retired) ? document.retired : [])]);
|
||||
for (const project of Object.values(document.projects ?? {})) for (const name of Object.keys(project?.agents ?? {})) agents.add(name);
|
||||
for (const name of agents) if (!role(name)) add(name, "{agent}");
|
||||
for (const name of agents) if (!role(name)) add(name, `agent ${name}`);
|
||||
out.sort((a, b) => b.text.length - a.text.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Returns the text with every literal replaced, and counts each placeholder used. One pass over the
|
||||
// text with one alternation, longest literal first: a placeholder written in never matches a later
|
||||
// literal, so an instance named "root" or "agent" cannot rewrite {root} or {agent}.
|
||||
// The labels of every name the text mentions, in first-mention order, each once. One pass with one
|
||||
// alternation, longest name first, so a root path is one mention and not the ids inside it.
|
||||
const combined = new WeakMap();
|
||||
function replace(text, list, counts) {
|
||||
if (list.length === 0) return text;
|
||||
function mentions(text, list) {
|
||||
if (list.length === 0) return [];
|
||||
let entry = combined.get(list);
|
||||
if (!entry) {
|
||||
const by = new Map(list.map((l) => [l.text, l.placeholder]));
|
||||
const by = new Map(list.map((l) => [l.text, l.label]));
|
||||
entry = { by, pattern: new RegExp(`(?<![${WORD}])(?:${list.map((l) => escape(l.text)).join("|")})(?![${WORD}])`, "g") };
|
||||
combined.set(list, entry);
|
||||
}
|
||||
return text.replace(entry.pattern, (match) => {
|
||||
const placeholder = entry.by.get(match);
|
||||
counts[placeholder] = (counts[placeholder] ?? 0) + 1;
|
||||
return placeholder;
|
||||
});
|
||||
const found = [];
|
||||
for (const match of text.matchAll(entry.pattern)) {
|
||||
const label = entry.by.get(match[0]);
|
||||
if (!found.includes(label)) found.push(label);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- Capture ----
|
||||
|
||||
// Builds the template document. With list null, free text is kept as it is (the scan's second
|
||||
// copy); otherwise each replacement and each kept free-text field is recorded by path.
|
||||
// Builds the template document. Free text is copied verbatim; each kept free-text field, and each
|
||||
// one that mentions an organization-specific name, is recorded by path.
|
||||
function capture(document, { name, project, rolesDir, list, record }) {
|
||||
const cache = new Map();
|
||||
const text = (value, path) => {
|
||||
if (list === null) return value;
|
||||
const counts = {};
|
||||
const out = replace(value, list, counts);
|
||||
for (const [placeholder, count] of Object.entries(counts)) record.replacements.push({ path, placeholder, count });
|
||||
record.freeText.push({ path, text: out });
|
||||
return out;
|
||||
record.freeText.push({ path, text: value });
|
||||
const names = mentions(value, list);
|
||||
if (names.length > 0) record.mentions.push({ path, names });
|
||||
return value;
|
||||
};
|
||||
const orgDefinitions = plain(document.definitions) ? document.definitions : {};
|
||||
const scope = project === undefined ? "org" : "project";
|
||||
@@ -233,7 +236,7 @@ function capture(document, { name, project, rolesDir, list, record }) {
|
||||
if (!template) refuse("starter-pack-invalid", `${at}.from names a template that is not a version 2 role`);
|
||||
// A template that changed since the definition copied it: the saved from names its current
|
||||
// hash, and the role must still narrow the current template. The preview lists the re-pin.
|
||||
if (template.sha256 !== entry.from.sha256 && list !== null) record.repinned.push(`${at}.from`);
|
||||
if (template.sha256 !== entry.from.sha256) record.repinned.push(`${at}.from`);
|
||||
out.from = { template: template.name, sha256: template.sha256 };
|
||||
let composition;
|
||||
try {
|
||||
@@ -323,11 +326,12 @@ function capture(document, { name, project, rolesDir, list, record }) {
|
||||
seen.add(k);
|
||||
packs.push({ id: entry.id, version: entry.version });
|
||||
}
|
||||
if (list !== null) record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
|
||||
record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
|
||||
const keptPacks = packs.slice(Math.max(0, packs.length - PACK_BOUNDS.packs));
|
||||
|
||||
const label = name.slice(0, PACK_BOUNDS.label);
|
||||
const descriptionText = scope === "org" ? "Saved from {org}." : "Saved from {project} in {org}.";
|
||||
// No placeholder: apply copies the description as it stands, so a "{org}" here would stay literal.
|
||||
const descriptionText = scope === "org" ? "Saved from an organization." : "Saved from one project of an organization.";
|
||||
return {
|
||||
packVersion: PACK_VERSION, id: name, version: "1.0.0", label, description: descriptionText, scope,
|
||||
definitions, hires, board, workflows, skills, packs: keptPacks,
|
||||
@@ -356,20 +360,16 @@ function scan(value, path, assertClean) {
|
||||
}
|
||||
}
|
||||
|
||||
// The preview: the exact JSON save writes, its digest, each replacement and each kept free-text
|
||||
// field by path. Refuses before returning when any string or key holds a held credential value.
|
||||
// The preview: the exact JSON save writes, its digest, each kept free-text field by path, each such
|
||||
// field that mentions an organization-specific name, with the names it mentions, and each re-pin.
|
||||
// Refuses before returning when any string or key holds a held credential value.
|
||||
export function templatePreview({ document, name, project, rolesDir, assertClean }) {
|
||||
checkTemplateName(name);
|
||||
if (project !== undefined && (typeof project !== "string" || !ID_PATTERN.test(project))) refuse("invalid-request", "the project id is invalid");
|
||||
if (typeof assertClean !== "function") throw new TypeError("templatePreview needs the credential store's assertClean");
|
||||
if (!plain(document)) refuse("invalid-request", "the organization file is not readable");
|
||||
const scope = { name, project, rolesDir };
|
||||
// The scan reads both copies: the kept text before replacement (a held value a placeholder would
|
||||
// break up still refuses) and the document save writes.
|
||||
const raw = capture(document, { ...scope, list: null, record: null });
|
||||
scan(raw, "", assertClean);
|
||||
const record = { replacements: [], freeText: [], repinned: [], packsDropped: 0 };
|
||||
const template = capture(document, { ...scope, list: literals(document, { rolesDir, cache: new Map() }), record });
|
||||
const record = { freeText: [], mentions: [], repinned: [], packsDropped: 0 };
|
||||
const template = capture(document, { name, project, rolesDir, list: orgNames(document, { rolesDir, cache: new Map() }), record });
|
||||
scan(template, "", assertClean);
|
||||
let checked;
|
||||
try {
|
||||
@@ -386,13 +386,27 @@ export function templatePreview({ document, name, project, rolesDir, assertClean
|
||||
return {
|
||||
name, scope: checked.scope, ...(project === undefined ? {} : { project }),
|
||||
template: checked, json, digest: sha256(json),
|
||||
replacements: record.replacements.sort(byPath), freeText: record.freeText.sort(byPath),
|
||||
freeText: record.freeText.sort(byPath), mentions: record.mentions.sort(byPath),
|
||||
repinned: record.repinned.sort(), packsDropped: record.packsDropped,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- The file ----
|
||||
|
||||
const TEMPLATE_EXISTS = "a template of this name is already saved; save under another name";
|
||||
// Whether a file (or anything, a symlink included) already holds the name. It looks only through a
|
||||
// templates and an account directory that are real directories, so a link is never followed to say
|
||||
// what lies elsewhere; any other case is left to the directory checks and the exclusive create.
|
||||
function taken(templates, home, file) {
|
||||
try {
|
||||
if (!lstatSync(templates).isDirectory() || !lstatSync(home).isDirectory()) return false;
|
||||
lstatSync(file);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A directory save writes under: real, the uid's own, writable by nobody else. The account's own
|
||||
// directory is private (0700 or narrower), as readSavedTemplate requires.
|
||||
function directory(path, uid, { private: closed }) {
|
||||
@@ -413,23 +427,25 @@ function directory(path, uid, { private: closed }) {
|
||||
}
|
||||
|
||||
// Save: the preview again, its digest compared, then the file created exclusively (wx, 0600). A
|
||||
// name already saved refuses; nothing is replaced.
|
||||
// name already saved refuses template-exists; nothing is replaced. The name is checked before the
|
||||
// digest, so a save under a taken name says so even when the preview is stale.
|
||||
export function templateSave({ document, name, project, digest, rolesDir, assertClean, configDir, account, uid = process.getuid() }) {
|
||||
checkAccount(account);
|
||||
checkTemplateName(name);
|
||||
if (typeof digest !== "string" || !/^[0-9a-f]{64}$/.test(digest)) refuse("invalid-request", "save takes the preview's digest");
|
||||
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
|
||||
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
|
||||
const templates = join(configDir, "templates");
|
||||
const home = join(templates, account);
|
||||
const file = join(home, `${name}.json`);
|
||||
if (taken(templates, home, file)) refuse("template-exists", TEMPLATE_EXISTS);
|
||||
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
|
||||
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
|
||||
directory(templates, uid, { private: false });
|
||||
directory(home, uid, { private: true });
|
||||
const file = join(home, `${name}.json`);
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
} catch (error) {
|
||||
if (error?.code === "EEXIST") refuse("invalid-request", "a template of this name is already saved");
|
||||
if (error?.code === "EEXIST") refuse("template-exists", TEMPLATE_EXISTS);
|
||||
refuse("not-configured", "the template file cannot be created");
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -86,6 +86,7 @@ const VERBS = {
|
||||
'packs.console': 'board.read',
|
||||
'pack.preview.console': null,
|
||||
'pack.apply.console': null,
|
||||
'pack.hire.console': 'org.hire',
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// Starter packs SP8 (#1873): saving a template and listing the saved ones are the owner's alone.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Starter packs SP8 (#1873): saving an organization or one of its projects as a template. The saved
|
||||
// file carries no credential material and no member, keeps each role's credential request lines,
|
||||
// replaces the organization's own names with placeholders, and reads back as an origin-saved pack.
|
||||
// keeps free text verbatim (E2E6 fix 5) while the preview lists the fields that mention the
|
||||
// organization's own names, and reads back as an origin-saved pack.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
@@ -94,34 +95,56 @@ test("SP8 the saved file keeps each role's credential request lines", (t) => {
|
||||
assert.ok(template.definitions.writer.role.credentials.length > 0);
|
||||
});
|
||||
|
||||
test("SP8 placeholders replace the org and project ids, the owner, agent names and project roots, in free text only", (t) => {
|
||||
// E2E6 fix 5, red before: the old save rewrote prose word by word, so a project named "work" turned
|
||||
// "hand finished work to review" into "hand finished {project} to review", and apply never resolves
|
||||
// a placeholder. Save now keeps every free-text field as it stands.
|
||||
test("E2E6 red before: save never rewrites prose; a project named work leaves \"hand finished work to review\" as it is", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.projects.work = { ...structuredClone(doc.projects.stack), root: join(doc.projects.stack.root, "..", "work-root") };
|
||||
doc.workflows.change.steps[1].title = "hand finished work to review";
|
||||
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
|
||||
assert.equal(preview.template.workflows.change.steps[1].title, "hand finished work to review");
|
||||
assert.ok(!preview.json.includes("{project}"));
|
||||
// The owner sees the mention and may edit the text before saving.
|
||||
assert.deepEqual(preview.mentions.find((m) => m.path === "workflows.change.steps[1].title"), { path: "workflows.change.steps[1].title", names: ["project work"] });
|
||||
});
|
||||
|
||||
test("E2E6 free text is kept verbatim, no placeholder is written, and the preview lists each field that mentions an org-specific name", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
|
||||
const { template } = preview;
|
||||
assert.equal(template.definitions.writer.instructions, "Write code for {org} in {root}/src. Ask {owner}; pair with {agent} on {project}.");
|
||||
assert.equal(template.definitions.writer.personality.summary, "Careful {org} engineer.");
|
||||
assert.deepEqual(template.definitions.writer.personality.traits, ["works with {agent}", "plain"]);
|
||||
assert.equal(template.board.columns[0].label, "{org} backlog");
|
||||
assert.equal(template.workflows.change.description, "Change for {project}");
|
||||
assert.equal(template.workflows.change.steps[0].title, "{agent} writes it");
|
||||
// Agent names that are role names (pm, coder) stay; role text says "coder" on purpose.
|
||||
const all = JSON.stringify(template);
|
||||
for (const literal of ["acme", "jason", "ana", doc.projects.stack.root]) assert.ok(!all.includes(literal), literal);
|
||||
assert.equal(template.description, "Saved from {org}.");
|
||||
// Each replacement is listed by path.
|
||||
const at = (path) => preview.replacements.filter((r) => r.path === path).map((r) => r.placeholder).sort();
|
||||
assert.deepEqual(at("definitions.writer.instructions"), ["{agent}", "{org}", "{owner}", "{project}", "{root}"]);
|
||||
assert.equal(template.definitions.writer.instructions, doc.definitions.writer.instructions);
|
||||
assert.equal(template.definitions.writer.personality.summary, "Careful acme engineer.");
|
||||
assert.deepEqual(template.definitions.writer.personality.traits, ["works with ana", "plain"]);
|
||||
assert.equal(template.board.columns[0].label, "acme backlog");
|
||||
assert.equal(template.workflows.change.description, "Change for stack");
|
||||
assert.equal(template.workflows.change.steps[0].title, "ana writes it");
|
||||
for (const placeholder of ["{org}", "{project}", "{agent}", "{owner}", "{root}"]) assert.ok(!preview.json.includes(placeholder), placeholder);
|
||||
assert.equal(template.description, "Saved from an organization.");
|
||||
assert.ok(!Object.hasOwn(preview, "replacements"));
|
||||
const at = (path) => preview.mentions.find((m) => m.path === path)?.names;
|
||||
// A root path is one mention, labelled by kind alone, not the ids inside it.
|
||||
assert.deepEqual(at("definitions.writer.instructions"), ["organization acme", "project root", "owner jason", "agent ana", "project stack"]);
|
||||
assert.deepEqual(at("definitions.writer.personality.traits[1]"), undefined);
|
||||
assert.deepEqual(at("board.columns[0].label"), ["organization acme"]);
|
||||
// Role names (writer, coder) are not mentions; a longer word holding a name is not one either.
|
||||
assert.equal(at("board.columns[1].label"), undefined);
|
||||
doc.board.columns[1].label = "acmes and anas";
|
||||
assert.equal(templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean }).mentions.find((m) => m.path === "board.columns[1].label"), undefined);
|
||||
// Every mention is a kept free-text field, in path order.
|
||||
const paths = preview.mentions.map((m) => m.path);
|
||||
assert.deepEqual(paths, [...paths].sort());
|
||||
for (const p of paths) assert.ok(preview.freeText.some((f) => f.path === p), p);
|
||||
});
|
||||
|
||||
test("SP8 an instance named root, org or agent never rewrites a placeholder already written in", (t) => {
|
||||
test("E2E6 text that looks like a placeholder, or an instance named root, org or agent, stays verbatim", (t) => {
|
||||
const { doc, rolesDir } = fixture(t);
|
||||
doc.roles.root = { definition: "org:writer" };
|
||||
doc.roles.org = { definition: "org:writer" };
|
||||
doc.definitions.writer.instructions = "Work for acme with root on stack. Ask org, then jason.";
|
||||
doc.definitions.writer.instructions = "Work for acme with root on stack. Ask org, then jason. Keep {org} and {agent} literal.";
|
||||
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
|
||||
assert.equal(preview.template.definitions.writer.instructions, "Work for {org} with {agent} on {project}. Ask {agent}, then {owner}.");
|
||||
const at = preview.replacements.filter((r) => r.path === "definitions.writer.instructions").map((r) => r.placeholder).sort();
|
||||
assert.deepEqual(at, ["{agent}", "{org}", "{owner}", "{project}"]);
|
||||
assert.equal(preview.template.definitions.writer.instructions, doc.definitions.writer.instructions);
|
||||
assert.deepEqual(preview.mentions.find((m) => m.path === "definitions.writer.instructions").names, ["organization acme", "agent root", "project stack", "agent org", "owner jason"]);
|
||||
});
|
||||
|
||||
test("SP8 the preview lists every kept free-text field with its saved text", (t) => {
|
||||
@@ -151,7 +174,7 @@ test("SP8 a held credential in kept text refuses template-secret-suspected namin
|
||||
doc.definitions.writer.personality.voice = `short, key ${TOKEN}`;
|
||||
refused(() => templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }), "template-secret-suspected", "definitions.writer.personality.voice");
|
||||
try { templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }); } catch (e) { assert.ok(!e.message.includes(TOKEN)); }
|
||||
// A held value a placeholder would split still refuses: the scan reads the text before replacement.
|
||||
// A held value inside other text still refuses: the scan reads the text save keeps.
|
||||
const second = fixture(t);
|
||||
second.doc.workflows.change.steps[1].title = `acme${TOKEN}`;
|
||||
refused(() => templatePreview({ document: second.doc, name: "acme-shape", rolesDir: second.rolesDir, assertClean }), "template-secret-suspected", "workflows.change.steps[1].title");
|
||||
@@ -170,7 +193,9 @@ test("SP8 a second save to the same name refuses and leaves the first file", (t)
|
||||
const first = readFileSync(file);
|
||||
doc.definitions.writer.instructions = "Changed.";
|
||||
const next = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest: next.digest, rolesDir, assertClean, configDir, account: "jason" }), "invalid-request", "a template of this name is already saved");
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest: next.digest, rolesDir, assertClean, configDir, account: "jason" }), "template-exists", "a template of this name is already saved; save under another name");
|
||||
// E2E6 fix 8: the name is checked first, so a stale or malformed-but-valid digest still says the name is taken.
|
||||
refused(() => templateSave({ document: doc, name: "acme-shape", digest: "0".repeat(64), rolesDir, assertClean, configDir, account: "jason" }), "template-exists");
|
||||
assert.deepEqual(readFileSync(file), first);
|
||||
assert.equal(lstatSync(file).mode & 0o777, 0o600);
|
||||
assert.equal(lstatSync(join(configDir, "templates", "jason")).mode & 0o777, 0o700);
|
||||
@@ -246,7 +271,7 @@ test("SP8 a project template carries the project's agents, the definitions it na
|
||||
assert.deepEqual(Object.keys(template.definitions).sort(), ["reviewer", "writer"]);
|
||||
assert.deepEqual(template.board, JSON.parse(JSON.stringify(DEFAULT_BOARD)));
|
||||
assert.deepEqual(template.workflows, {});
|
||||
assert.equal(template.description, "Saved from {project} in {org}.");
|
||||
assert.equal(template.description, "Saved from one project of an organization.");
|
||||
refused(() => templatePreview({ document: doc, name: "x", project: "nope", rolesDir, assertClean }), "invalid-request");
|
||||
});
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ baseline CLI.
|
||||
| Restart the Console | Stop and run `mosaic console start` again | Enabled (F3) when `mosaic console start` runs it in the foreground, or with `--dev-local-owner --detach` under a detached supervisor (D1): Settings > Console; the owner only; trailed. Other Consoles answer `not-supervised` |
|
||||
| Save, review, confirm or reverse an organization's autonomy | Read, save and review: `mosaic org autonomy ORG`, `mosaic org autonomy ORG set --revision REV [--cross-role|--merge|--policy|--authority in|near|out] [--notices on|off] [--reverse-window-hours 1-168] [--authority-resolver NAME|""]`, `mosaic org autonomy ORG review CLASS` (E2, through this route and its revision check); confirm and reverse act on inbox decisions and have no verb yet | Enabled (D1) on a `--dev-local-owner` Console: the owner only, on the selected organization's bus, behind a fence that passes only the four console verbs `autonomy.set.console`, `autonomy.review.console`, `decision.confirm.console` and `decision.reverse.console` |
|
||||
| Hire, fire or change an agent; read role templates | `mosaic org role-templates ORG`; `mosaic org hire|change ORG --name NAME --template TEMPLATE --harness H --model M [--thinking T] [--level org|project|root] [--project P] --reason TEXT`; `mosaic org fire ORG --name NAME [--level ...] --reason TEXT` (E2, through this route) | Enabled (D4) for the owner on a selected organization's bus: one decision raised and approved through `hire.start.console`, with the bus's hire checks |
|
||||
| Apply a starter pack; hire its proposed agents; fire an agent from its card | `mosaic org pack preview|apply ID PACK [--digest D] [--project P]`; `mosaic org pack hire ID PACK [--project P]`; `mosaic org fire ORG --name NAME --reason TEXT` | Enabled for the owner (ruling 2026-11-14): applying is the hire decision; see "Starter pack hires" |
|
||||
| Create, edit or archive a board task | `mosaic tasks create --title T --requirement REQ [--project P] [--state S] [--assignees R,...] [--priority 0-5] [--due ISO|none]`; `mosaic tasks edit task:N --expect DIGEST ...`; `mosaic tasks archive task:N --expect DIGEST` (E2: the board's own check, then the person's `tasks.create|edit|archive` on the bus) | Enabled for the owner on an organization with the built-in task store |
|
||||
| Create chat project linked to a configured repository | `mosaic project create <name> --repo <project> --org <id>` | Enabled |
|
||||
| Create a thread | `mosaic thread create <project> <name> --org <id>` | Planned enabled |
|
||||
@@ -70,6 +71,38 @@ as the owner's page can. The startup warning says so. Use a dev instance for UI
|
||||
testing only. The real boundary is sign-in (`--sso`); a refusal for local agent
|
||||
peers in dev mode is a recorded follow-up.
|
||||
|
||||
### Starter pack hires (ruling 2026-11-14, #1873)
|
||||
|
||||
"Damnit. If I choose a starter pack and apply it, that is a decision!"
|
||||
`POST /api/orgs/<id>/packs/apply` (`pack.apply.console`) hires the pack's
|
||||
proposed agents in the same act, and its receipt is `{revision, added, pack,
|
||||
hires}`; when the apply committed but its hire loop did not run, `hires` is
|
||||
empty and `hireError` names the code, and the card says the hires did not run.
|
||||
`POST /api/orgs/<id>/packs/hire` with `{pack, project?}`
|
||||
(`pack.hire.console`) runs the same loop on a pack already applied and answers
|
||||
`{pack, hires}`; `pack-not-applied` is 404 and `right-required` 403. Each hire
|
||||
line is `{name, state, decision | code}`, and a `hired` or `awaiting-owner`
|
||||
line adds `routeFrom: 'chief' | 'assistant'`, whose harness and model the hire
|
||||
got (the chief of staff's, else the organization assistant's). `GET /api/orgs/<id>/packs` adds, to
|
||||
each applied entry, `hired` (the agents its hires created) and `open` (each
|
||||
proposal not hired, with its reason, its state and its decision or code, and
|
||||
`fromPack: true` on an `awaiting-owner` line this pack's own hire raised). The
|
||||
packs routes stay the owner's: a member's pack hire is the bus verb's
|
||||
(`pack.hire.console` needs `org.hire`, and the flagged hires wait for the
|
||||
owner), but no member page calls it yet.
|
||||
|
||||
The pack card says what applying does before the click ("applying is the hire
|
||||
decision, and approves the flagged and credential lines below"), shows "N
|
||||
agents hired" and the open proposals with their reasons after it, and offers
|
||||
"Hire the N proposed agents" for proposals not waiting for the owner, and for
|
||||
the owner's own `fromPack` lines, which the owner's hire replaces and approves. Apply,
|
||||
hire and fire dispatch `mosaic-org-changed`, so the Agents page and the
|
||||
organization page redraw in the same cycle instead of at the next 10-second
|
||||
poll. Each agent card a pack hire made says "from pack X". The owner's Agents
|
||||
page offers Fire on each agent but the chief of staff and the assistant, with a confirm step;
|
||||
Fire sends `{op: 'fire'}` through `/api/decisions/hire/start`, removes the
|
||||
card at once and leaves a receipt naming the decision.
|
||||
|
||||
### Route registration
|
||||
|
||||
A module may export `registerRoutes(table)` and be included with one entry in
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
// 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.
|
||||
// GET /api/orgs/<id>/packs {packs, applied, writable}: packs.console, the shipped and installed
|
||||
// packs (never a saved template), and each applied entry with the
|
||||
// agents its hires created and its open proposals. /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>/packs/apply {pack, digest, project?, as?}: pack.apply.console. Ruling 2026-11-14:
|
||||
// the owner's apply is the hire decision; the receipt carries `hires`
|
||||
// POST /api/orgs/<id>/packs/hire {pack, project?}: pack.hire.console, the proposals of a pack already
|
||||
// applied, hired through the same loop. {pack, hires}
|
||||
// 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
|
||||
@@ -15,17 +19,17 @@
|
||||
// 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
|
||||
// is the owner's Console call fenced to the four 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(?:\/([^/]+))?)$/;
|
||||
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|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 PACK_WRITE_VERBS = Object.freeze(['pack.apply.console', 'pack.hire.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);
|
||||
@@ -38,9 +42,9 @@ const REVISION = /^[a-f0-9]{64}$/;
|
||||
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,
|
||||
'starter-pack-not-found': 404, 'project-not-found': 404, 'pack-not-applied': 404,
|
||||
'pack-plan-stale': 409, 'revision-conflict': 409, 'organization-busy': 409,
|
||||
'human-required': 403, 'read-only': 403,
|
||||
'human-required': 403, 'read-only': 403, 'right-required': 403,
|
||||
'not-configured': 503, 'no-bus-host': 503,
|
||||
};
|
||||
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
|
||||
@@ -89,7 +93,7 @@ export async function packsHTTP(req, res, { path, owner, read, write, workflows
|
||||
let verb, args = {};
|
||||
if (list) verb = 'packs.console';
|
||||
else if (step !== null) {
|
||||
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], ['project', 'as']);
|
||||
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], step === 'hire' ? ['project'] : ['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)))
|
||||
@@ -124,16 +128,29 @@ export async function packsHTTP(req, res, { path, owner, read, write, workflows
|
||||
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) });
|
||||
const applied = Array.isArray(result.applied) ? result.applied.filter(plain).map(a => ({ id: a.id, origin: a.origin ?? null, project: a.project ?? null,
|
||||
hired: Array.isArray(a.hired) ? a.hired.filter(n => typeof n === 'string') : [],
|
||||
open: Array.isArray(a.open) ? a.open.filter(plain).map(o => ({ name: o.name, reason: typeof o.reason === 'string' ? o.reason : '', state: o.state, ...(typeof o.code === 'string' ? { code: o.code } : {}), ...(typeof o.decision === 'string' ? { decision: o.decision } : {}), ...(o.fromPack === true ? { fromPack: true } : {}) })) : [] })) : [];
|
||||
return json(res, 200, { packs: result.packs, applied, 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.
|
||||
// meanwhile, never reported as not done. Each hire line is its name, state and decision or code,
|
||||
// and for a raised hire routeFrom, whose harness and model it got (lane pr2).
|
||||
const hires = Array.isArray(result.hires) ? result.hires.filter(plain).map(h => ({ name: h.name, state: h.state,
|
||||
...(typeof h.decision === 'string' ? { decision: h.decision } : {}), ...(typeof h.code === 'string' ? { code: h.code } : {}),
|
||||
...(['chief', 'assistant'].includes(h.routeFrom) ? { routeFrom: h.routeFrom } : {}) })) : null;
|
||||
if (step === 'hire') {
|
||||
if (!hires) return refuse(503, 'outcome-unknown');
|
||||
return json(res, 200, { pack: result.pack, hires });
|
||||
}
|
||||
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 } : {}) });
|
||||
// hireError: the apply committed but its hire loop did not run (organization-busy, outcome-unknown).
|
||||
const hireError = step === 'apply' && typeof result.hireError === 'string' && /^[a-z0-9-]{1,64}$/.test(result.hireError) ? { hireError: result.hireError } : {};
|
||||
return json(res, 200, { revision: result.revision, added: Array.isArray(result.added) ? result.added : [], ...(step === 'apply' ? { pack: result.pack, hires: hires ?? [], ...hireError } : {}) });
|
||||
}
|
||||
|
||||
// SP6: the workflow list and editor's read. Only workflows, the names a step role may resolve to and the
|
||||
|
||||
@@ -76,8 +76,11 @@
|
||||
if (!usable() || busy || pending || !view) return;
|
||||
const [url, payload] = plan(action, name);
|
||||
busy = true; confirming = null; receipt = ''; redraw();
|
||||
const gen = generation;
|
||||
let answer;
|
||||
try { answer = await post(url, payload); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
|
||||
// #1873 SP1: an organization switch while this was in flight drops the answer; the switch already cleared busy.
|
||||
if (gen !== generation) return;
|
||||
busy = false;
|
||||
if (answer === null) return;
|
||||
const { ok, result } = answer;
|
||||
@@ -122,8 +125,10 @@
|
||||
const instance = create.instance.trim(), definition = create.definition;
|
||||
if (!instance || !definition) { receipt = 'Name the instance and choose a definition.'; redraw(); return; }
|
||||
busy = true; receipt = ''; redraw();
|
||||
const gen = generation;
|
||||
let answer;
|
||||
try { answer = await post('/api/instances', { revision: view.revision, instance, op: 'add', definition }); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
|
||||
if (gen !== generation) return;
|
||||
busy = false;
|
||||
if (answer === null) return;
|
||||
if (answer.ok && /^[a-f0-9]{64}$/.test(answer.result?.revision ?? '')) { create = { instance: '', definition: '' }; receipt = `Created ${instance}. ${answer.result.restart ? restartText() : NO_RESTART_TEXT}`; reread(); }
|
||||
@@ -154,19 +159,31 @@
|
||||
document.addEventListener('submit', e => { if (e.target?.id !== 'agent-create-form') return; e.preventDefault(); createAgent(); });
|
||||
// A sign-out stops any poll; nothing that was asked is retried.
|
||||
document.addEventListener('mosaic-signed-out', () => { generation++; pending = null; confirming = null; });
|
||||
// #1873 SP1: opening another organization stops any poll and clears what this section held for the
|
||||
// old one. A request already sent finishes on the old organization's bus; its page reads it again there.
|
||||
document.addEventListener('mosaic-org-switch', () => {
|
||||
generation++; pending = null; receipt = ''; editing = null; confirming = null; busy = false;
|
||||
create = { instance: '', definition: '' };
|
||||
for (const k of Object.keys(reasons)) delete reasons[k];
|
||||
});
|
||||
|
||||
// F3: restart an agent so a route change reaches it now, offered by the Routing receipt. One
|
||||
// terminate; then reads of the instances until the run has left (up to the 60 s regenerate
|
||||
// allows); then one launch. A thread definition is not launched: its next message starts it.
|
||||
// A refusal, a sign-out or an unknown outcome stops the chain and says so; nothing is retried.
|
||||
const restarts = Object.create(null);
|
||||
let restarts = Object.create(null);
|
||||
// #1873 SP1: the chain's reads and writes go to the organization it started in, which the fetch
|
||||
// wrapper passes through unchanged. A switch clears what the new page shows; the old chain keeps
|
||||
// its own entry and stops painting.
|
||||
const pin = (org, path) => org ? `/api/orgs/${encodeURIComponent(org)}/${path.slice('/api/'.length)}` : path;
|
||||
document.addEventListener('mosaic-org-switch', () => { restarts = Object.create(null); });
|
||||
const RESTART_WAIT = 30;
|
||||
function restartMarkup(name, thread = false) {
|
||||
const r = restarts[name];
|
||||
return `<span class="agent-restart"><button type="button" class="btn" data-agent-restart="${esc(name)}" data-agent-thread="${thread ? 'yes' : 'no'}"${r?.busy ? ' disabled' : ''}>${r?.busy ? 'Restarting…' : `Restart ${esc(name)} now`}</button> <span role="status" data-agent-restart-status="${esc(name)}">${esc(r?.text ?? '')}</span></span>`;
|
||||
}
|
||||
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
const paintRestart = name => document.querySelectorAll('.agent-restart').forEach(el => {
|
||||
const paintRestart = (name, org = window.MosaicOrg?.id ?? null) => (window.MosaicOrg?.id ?? null) !== org ? undefined : document.querySelectorAll('.agent-restart').forEach(el => {
|
||||
const b = el.querySelector('[data-agent-restart]');
|
||||
if (b?.dataset.agentRestart === name) el.outerHTML = restartMarkup(name, b.dataset.agentThread === 'yes');
|
||||
});
|
||||
@@ -179,45 +196,47 @@
|
||||
return { ok: res.ok, result };
|
||||
}
|
||||
// The request's closing read, or a reason the chain stops.
|
||||
async function closing(request) {
|
||||
async function closing(request, org) {
|
||||
for (let tries = 0; tries < POLL_LIMIT; tries++) {
|
||||
await new Promise(r => setTimeout(r, POLL_MS));
|
||||
let res, r = null;
|
||||
try { res = await fetch(`/api/agent/request?id=${encodeURIComponent(request)}`, { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
|
||||
try { res = await fetch(pin(org, `/api/agent/request?id=${encodeURIComponent(request)}`), { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
|
||||
if (res.type === 'opaqueredirect') return { stop: 'Sign in again, then read the agents.' };
|
||||
try { r = await res.json(); } catch { continue; }
|
||||
if (res.ok && r?.request === request && r.state === 'closed') return { done: r };
|
||||
}
|
||||
return { stop: `Request ${request} is still open. Read the agents again later.` };
|
||||
}
|
||||
async function runs(name) {
|
||||
async function runs(name, org) {
|
||||
try {
|
||||
const res = await fetch('/api/bus/instances', { cache: 'no-store', redirect: 'manual' });
|
||||
const res = await fetch(pin(org, '/api/bus/instances'), { cache: 'no-store', redirect: 'manual' });
|
||||
if (!res.ok || res.type === 'opaqueredirect') return null;
|
||||
const e = (await res.json())?.rows?.[0]?.instances?.[name];
|
||||
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
|
||||
} catch { return null; }
|
||||
}
|
||||
async function restartAgent(name, thread) {
|
||||
const org = window.MosaicOrg?.id ?? null;
|
||||
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
|
||||
const stop = text => { r.busy = false; r.text = text; paintRestart(name); };
|
||||
paintRestart(name);
|
||||
const asked = await send('/api/agent/terminate', { instance: name, reason: 'route change' });
|
||||
const paint = () => paintRestart(name, org);
|
||||
const stop = text => { r.busy = false; r.text = text; paint(); };
|
||||
paint();
|
||||
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
|
||||
if (asked.signedOut) return stop('Sign in again, then retry.');
|
||||
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
|
||||
const ended = await closing(asked.result.request);
|
||||
const ended = await closing(asked.result.request, org);
|
||||
if (ended.stop) return stop(ended.stop);
|
||||
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
|
||||
r.text = `Terminated ${name}. Waiting for its session to end…`; paintRestart(name);
|
||||
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
|
||||
let left = false;
|
||||
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name)) === 0; }
|
||||
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
|
||||
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
|
||||
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
|
||||
r.text = `Launching ${name}…`; paintRestart(name);
|
||||
const launch = await send('/api/agent/launch', { instance: name });
|
||||
r.text = `Launching ${name}…`; paint();
|
||||
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
|
||||
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
|
||||
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
|
||||
const started = await closing(launch.result.request);
|
||||
const started = await closing(launch.result.request, org);
|
||||
if (started.stop) return stop(started.stop);
|
||||
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
|
||||
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
// Show machine sessions (#1589): off by default, kept with the page's settings. While it is off the
|
||||
// page doesn't read /api/board at all; the held roles above come from the bus (bus.js).
|
||||
let machine = false;
|
||||
const boardKey = window.MosaicOrg ? `mosaic-console-board:${window.MosaicOrg.id}` : 'mosaic-console-board';
|
||||
try { machine = JSON.parse(localStorage.getItem(boardKey))?.machine === true; } catch {}
|
||||
// #1873 SP1: kept per organization, read again when the open organization changes.
|
||||
const boardKey = () => window.MosaicOrg?.id ? `mosaic-console-board:${window.MosaicOrg.id}` : 'mosaic-console-board';
|
||||
const readMachine = () => { try { return JSON.parse(localStorage.getItem(boardKey()))?.machine === true; } catch { return false; } };
|
||||
machine = readMachine();
|
||||
// Signed out (#1589): a Console fetch answered with a redirect, so the sign-in proxy turned it away.
|
||||
// The first one sets body.signed-out (the listener below); after that no Console fetch is made.
|
||||
const out = () => document.body.classList.contains('signed-out');
|
||||
@@ -58,6 +60,10 @@
|
||||
const darkPreference = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const APPEARANCE_KEY = 'mosaic-console-appearance', LAST_KEY = 'mosaic-console-appearance-last';
|
||||
const orgKey = id => `${APPEARANCE_KEY}:${id}`;
|
||||
// #1873 SP2: the system dashboard is no organization's page. It shows the system theme: this browser's
|
||||
// own choice made there, else the default, never the theme of the organization opened last.
|
||||
const SYSTEM_KEY = 'mosaic-console-appearance-system';
|
||||
const onSystem = () => !!window.MosaicOrg && !/^#\/orgs\//.test(location.hash) && ['', '/', '/dashboard'].includes(location.hash.replace(/^#/, '').split('?')[0]);
|
||||
const store = {
|
||||
read(k) { try { const v = JSON.parse(localStorage.getItem(k)); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } },
|
||||
write(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch { return false; } },
|
||||
@@ -66,7 +72,10 @@
|
||||
const orgId = v => typeof v === 'string' && v.length > 0 && v.length <= 64;
|
||||
// org: null until the Console knows which organization it shows. Then the override lives under that organization's own key;
|
||||
// before that, and for a Console with no organization, it is the browser-wide record this page has always kept.
|
||||
let org = null, override = null, themes = null, themesUnavailable = false, current = null, applied = [];
|
||||
let org = null, override = null, themes = null, themesUnavailable = false, current = null, applied = [], system = false;
|
||||
const shown = () => (system ? null : org);
|
||||
// Kept in memory too: a choice storage refused still shows until reload, as an organization's does.
|
||||
let systemOverride = Brand.appearanceOf(store.read(SYSTEM_KEY));
|
||||
const readOverride = () => {
|
||||
if (org) return Brand.appearanceOf(store.read(orgKey(org.id)));
|
||||
const v = store.read(APPEARANCE_KEY);
|
||||
@@ -78,7 +87,7 @@
|
||||
$('theme-switch').setAttribute('aria-checked', String(dark));
|
||||
}
|
||||
function paintNotices() {
|
||||
const w = current.warning, banner = $('theme-warning'), cue = $('org-cue'), label = org?.label;
|
||||
const w = current.warning, banner = $('theme-warning'), cue = $('org-cue'), label = shown()?.label;
|
||||
banner.hidden = !w;
|
||||
if (w) {
|
||||
const asked = String(w.theme).slice(0, 64), kept = w.source === 'browser' ? 'The choice is kept.' : 'The saved value is unchanged.';
|
||||
@@ -91,11 +100,12 @@
|
||||
$('theme-clear').textContent = label ? `Use ${label}’s theme` : 'Use the default theme';
|
||||
}
|
||||
// Colour is never the only cue to which organization this is: whenever the theme is not the built-in one, the name is written out.
|
||||
cue.hidden = !(org && (current.theme !== Brand.DEFAULT_THEME || w));
|
||||
cue.hidden = !(shown() && (current.theme !== Brand.DEFAULT_THEME || w));
|
||||
if (!cue.hidden) cue.textContent = w ? `${label} · Harbor shown instead of “${String(w.theme).slice(0, 64)}”` : `${label} · ${nameOf(current.theme)} theme · ${current.themeSource === 'browser' ? 'your choice in this browser' : 'set by the organization'}`;
|
||||
}
|
||||
function paint() {
|
||||
current = Brand.resolveAppearance({ themes, unavailable: themesUnavailable, saved: org?.saved ?? null, override });
|
||||
system = onSystem();
|
||||
current = Brand.resolveAppearance({ themes, unavailable: themesUnavailable, saved: shown()?.saved ?? null, override: system ? systemOverride : override });
|
||||
const root = document.documentElement;
|
||||
root.dataset.palette = current.theme;
|
||||
if (current.mode === 'system') delete root.dataset.mode; else root.dataset.mode = current.mode;
|
||||
@@ -126,15 +136,16 @@
|
||||
ready: null,
|
||||
// The installed, valid themes as the server listed them, or null until /api/themes has answered.
|
||||
themes: () => themes && themes.map(t => ({ id: t.id, displayName: t.displayName, tokens: t.tokens })),
|
||||
state: () => ({ theme: current.theme, mode: current.mode, requested: current.requested, themeSource: current.themeSource, modeSource: current.modeSource, warning: current.warning, provisional: current.provisional, organization: org && { id: org.id, label: org.label }, saved: org?.saved ?? null, override: override && { ...override } }),
|
||||
state: () => { const o = shown(), v = system ? systemOverride : override; return { theme: current.theme, mode: current.mode, requested: current.requested, themeSource: current.themeSource, modeSource: current.modeSource, warning: current.warning, provisional: current.provisional, organization: o && { id: o.id, label: o.label }, saved: o?.saved ?? null, override: v && { ...v } }; },
|
||||
// Writes this browser's override for the organization (a theme, a mode, or both). false when storage refused it; the page still shows it until reload.
|
||||
set(patch) {
|
||||
if (onSystem()) { const next = Brand.appearanceOf({ ...(systemOverride || {}), ...patch }), ok = next ? store.write(SYSTEM_KEY, next) : true; systemOverride = next; showAppearance(ok); return ok; }
|
||||
const next = Brand.appearanceOf({ ...(override || {}), ...patch });
|
||||
const ok = next ? (org ? store.write(orgKey(org.id), next) : store.write(APPEARANCE_KEY, next)) : true;
|
||||
override = next; showAppearance(ok); return ok;
|
||||
},
|
||||
// Removes the override: the organization's saved value, or else the default, shows again.
|
||||
clear() { const ok = org ? store.remove(orgKey(org.id)) : store.remove(APPEARANCE_KEY); override = null; showAppearance(ok); return ok; },
|
||||
clear() { if (onSystem()) { const ok = store.remove(SYSTEM_KEY); systemOverride = null; showAppearance(ok); return ok; } const ok = org ? store.remove(orgKey(org.id)) : store.remove(APPEARANCE_KEY); override = null; showAppearance(ok); return ok; },
|
||||
// The seam for the organization switcher (stream S5): call it with the organization now shown and its saved appearance.
|
||||
organization(id, saved, label) {
|
||||
if (!orgId(id)) return;
|
||||
@@ -151,6 +162,20 @@
|
||||
override = readOverride();
|
||||
paint();
|
||||
document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette: current.theme, mode: current.mode, stored: true, warning: null, picked: current.theme}}));
|
||||
// The open organization's saved appearance, read again when another organization opens (#1873 SP1).
|
||||
const readBusiness = async () => {
|
||||
try {
|
||||
const { ok, body } = await getJSON('/api/business');
|
||||
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
|
||||
} catch (err) { if (err?.signedOut) return; }
|
||||
// No fresh answer: keep the organization this browser last showed for its own override, but not its stale saved value.
|
||||
if (org && !org.confirmed) { org.saved = null; showAppearance(); }
|
||||
};
|
||||
document.addEventListener('mosaic-org-switch', () => { readBusiness(); });
|
||||
// The dashboard and an organization page share the shell: moving between them repaints the theme.
|
||||
const repaintScope = () => { if (onSystem() !== system) showAppearance(); };
|
||||
window.addEventListener('hashchange', repaintScope);
|
||||
window.MosaicOrg?.ready?.then(repaintScope);
|
||||
window.MosaicAppearance.ready = (async () => {
|
||||
await Promise.allSettled([
|
||||
(async () => {
|
||||
@@ -161,14 +186,7 @@
|
||||
} catch (err) { if (err?.signedOut) return; themes = []; themesUnavailable = true; }
|
||||
showAppearance();
|
||||
})(),
|
||||
(async () => {
|
||||
try {
|
||||
const { ok, body } = await getJSON('/api/business');
|
||||
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
|
||||
} catch (err) { if (err?.signedOut) return; }
|
||||
// No fresh answer: keep the organization this browser last showed for its own override, but not its stale saved value.
|
||||
if (org && !org.confirmed) { org.saved = null; showAppearance(); }
|
||||
})(),
|
||||
readBusiness(),
|
||||
]);
|
||||
})();
|
||||
$('palette').onchange = e => window.MosaicAppearance.set({ theme: e.target.value });
|
||||
@@ -488,12 +506,22 @@
|
||||
const box = $('bus-down');
|
||||
// E2E5 review P2: the organization list is read first and on its own, so a failed bus-status read
|
||||
// (likely when the bus is down) still refreshes the list, its banner and the Settings Start control.
|
||||
// #1873 SP1: the dashboard lists every organization's bus on its own rows; this banner is an organization page's.
|
||||
if (window.MosaicOrg && window.MosaicOrg.route().split('?')[0] === '/dashboard') { box.hidden = true; return; }
|
||||
// An answer about an organization that is no longer open is dropped: the new one's read draws the banner.
|
||||
// So is one drawn for a page left while it was read (#1873 SP2: the organization page draws none).
|
||||
const where = () => window.MosaicOrg?.route().split('?')[0] === '/organization';
|
||||
const asked = window.MosaicOrg?.id ?? null, onPage = where(), stale = () => (window.MosaicOrg?.id ?? null) !== asked || where() !== onPage;
|
||||
if (window.MosaicOrg) {
|
||||
const org = (await window.MosaicOrg.readList()).find(row => row.id === window.MosaicOrg.id);
|
||||
const org = (await window.MosaicOrg.readList()).find(row => row.id === asked);
|
||||
if (stale()) return;
|
||||
// #1873 SP2: the organization's own page says it in its down banner, with the restart action: one banner, not two.
|
||||
if (org?.busHealthy === false && onPage) { box.hidden = true; return; }
|
||||
if (org?.busHealthy === false) { box.textContent = 'Bus unavailable'; box.hidden = false; window.MosaicConsole?.attachBus(box, 'Restart the bus'); return; }
|
||||
}
|
||||
try {
|
||||
const s = await api('/api/bus-status');
|
||||
if (stale()) return;
|
||||
if (!s.down) { box.hidden = true; return; }
|
||||
const b = s.boot;
|
||||
box.replaceChildren(node('b', '', 'Bus down: organization file invalid. '), node('span', '', `${b.reason} `), node('span', 'small muted', `File ${b.file}. Refused at ${b.at}. Last good load: ${b.lastGood ?? 'none'}. Fix the file, then restart the bus.`));
|
||||
@@ -528,11 +556,28 @@
|
||||
function showMachine() { $('show-machine').checked = machine; document.body.classList.toggle('machine-off', !machine); }
|
||||
$('show-machine').onchange = e => {
|
||||
machine = e.target.checked; showMachine();
|
||||
try { localStorage.setItem(boardKey, JSON.stringify({ machine })); } catch {}
|
||||
try { localStorage.setItem(boardKey(), JSON.stringify({ machine })); } catch {}
|
||||
if (machine) { $('status').textContent = 'Loading board…'; fresh(); refresh(); } else hideMachine();
|
||||
};
|
||||
showMachine();
|
||||
if (!machine) hideMachine();
|
||||
// #1873 SP1: another organization opened in place. Its board setting and bus state are its own.
|
||||
const onOrgSwitch = () => {
|
||||
machine = readMachine(); showMachine();
|
||||
if (machine) { fresh(); refresh(); } else { hideMachine(); busDown(); }
|
||||
};
|
||||
document.addEventListener('mosaic-org-switch', onOrgSwitch);
|
||||
// An address with no organization picks one after the first list read; its own setting applies then.
|
||||
window.MosaicOrg?.ready?.then(() => { if (readMachine() !== machine) onOrgSwitch(); });
|
||||
// The banner hides on the system dashboard, gives way to the organization page's own down banner,
|
||||
// and shows on the organization's other pages, so a move across those lines redraws it. Other moves
|
||||
// inside one organization read nothing (the switch path reads its own).
|
||||
let busPlace = null;
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (!window.MosaicOrg) return;
|
||||
const path = window.MosaicOrg.route().split('?')[0], now = ['/dashboard', '/organization'].includes(path) ? path : 'page';
|
||||
if (now !== busPlace) { busPlace = now; busDown(); }
|
||||
});
|
||||
$('refresh').onclick = refresh;
|
||||
$('mobile-pause').onclick = () => $('pause').click();
|
||||
$('pause').onclick = () => { paused = !paused; $('pause').querySelector('span').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-label', paused ? 'Resume' : 'Pause'); $('pause').title = paused ? 'Resume' : 'Pause'; $('mobile-pause').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-pressed', String(paused)); schedule(); if (data) render(); };
|
||||
|
||||
@@ -181,10 +181,22 @@
|
||||
menu.addEventListener('click', e => { if (e.target.closest('a')) close(); });
|
||||
document.addEventListener('click', e => { if (!e.target.closest('.avatar-wrap')) close(); });
|
||||
function breadcrumbs() {
|
||||
const path = location.hash.slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs');
|
||||
draw();
|
||||
// SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ...
|
||||
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null;
|
||||
if (!box || !org?.id || box.querySelector('[data-crumb-org]') || /^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) return;
|
||||
box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
|
||||
}
|
||||
window.MosaicBreadcrumbs = breadcrumbs;
|
||||
function draw() {
|
||||
// SP1: an organization's pages are routes under #/orgs/<id>; the crumb reads the route inside it.
|
||||
const path = location.hash.replace(/^#\/orgs\/[^/?]+/, '#').slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs');
|
||||
if (!box || !$('bus-view')) return;
|
||||
if (window.MosaicProjects?.breadcrumb?.(box, $('bus-view'))) return;
|
||||
if (!parts.length || parts[0] === 'board') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
|
||||
// Inside an organization the board is its control board; the system dashboard is the crumb before it.
|
||||
if (parts[0] === 'board' && /^#\/orgs\//.test(location.hash)) { box.innerHTML = '<span aria-current="page">Control board</span>'; return; }
|
||||
if (!parts.length || parts[0] === 'board' || parts[0] === 'dashboard') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
|
||||
if (parts[0] === 'organization') { const h = $('bus-view').querySelector('[data-org-dashboard] h1')?.textContent?.trim(); box.innerHTML = `<a href="#/dashboard">Dashboard</a>${h ? `<span aria-hidden="true">/</span><span aria-current="page">${escape(h)}</span>` : ''}`; return; }
|
||||
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
|
||||
if (parts[0] === 'settings' && parts[1] === 'business' && $('bus-view').querySelector('#settings-page-title')?.textContent.trim() === 'Business') { box.innerHTML = '<a href="#/settings">Settings</a><span aria-hidden="true">/</span><span aria-current="page">Business</span>'; return; }
|
||||
const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim();
|
||||
|
||||
@@ -75,13 +75,17 @@
|
||||
window.MosaicIcons.succeeded();
|
||||
return body;
|
||||
}
|
||||
// #1873 SP1: bumped by each in-place organization switch. A write, or a read that keeps its answer,
|
||||
// captures it before its await and drops the answer when it changed, so nothing the old organization
|
||||
// answered lands on the new page or in its kept answers.
|
||||
let orgEpoch = 0;
|
||||
// A reader for one render. `live` asks the server; otherwise only kept answers are used.
|
||||
function reader(live) {
|
||||
const used = [];
|
||||
const get = async (verb, subject) => {
|
||||
const k = subject === undefined ? verb : `${verb}:${subject}`;
|
||||
let r;
|
||||
if (live) { r = await fetchRead(verb, subject); last.set(k, r); }
|
||||
if (live) { const epoch = orgEpoch; r = await fetchRead(verb, subject); if (epoch === orgEpoch) last.set(k, r); }
|
||||
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
|
||||
used.push(r.at);
|
||||
if (verb === 'messages') { messageCount = r.unread; return r; }
|
||||
@@ -90,7 +94,7 @@
|
||||
get.api = async path => {
|
||||
const k = `api:${path}`;
|
||||
let r;
|
||||
if (live) { r = await fetchApi(path); last.set(k, r); }
|
||||
if (live) { const epoch = orgEpoch; r = await fetchApi(path); if (epoch === orgEpoch) last.set(k, r); }
|
||||
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
|
||||
used.push(r.at);
|
||||
return r;
|
||||
@@ -275,9 +279,10 @@
|
||||
const focused = $('sections').contains(active) || foot.contains(active) ? active.getAttribute('href') : null;
|
||||
const icon = id => window.MosaicWorkspace?.icon?.(id) ?? `<svg class="i" aria-hidden="true"><use href="/icons.svg#i-${id}"/></svg>`;
|
||||
const n = (count, what) => count > 0 ? `<span class="ws-n hot" aria-label="${count} ${what}">${count}</span>` : '';
|
||||
const items = [['/', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/side-by-side', 'Side by side', '', 'columns'], ['/agents', 'Agents', '', 'agents'], ['/messages', 'Assistant', n(messageCount, 'unread messages'), 'talk']];
|
||||
const items = [['/dashboard', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/side-by-side', 'Side by side', '', 'columns'], ['/agents', 'Agents', '', 'agents'], ['/messages', 'Assistant', n(messageCount, 'unread messages'), 'talk']];
|
||||
const link = ([h, l, extra, id]) => {
|
||||
const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
|
||||
// #1873 SP1: the Dashboard item is the system dashboard, `#/dashboard`, outside any organization.
|
||||
const cur = h === '/dashboard' ? (route === '/dashboard' || route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
|
||||
return `<a href="#${h}" class="s1-section ws-nav"${cur ? ' aria-current="page"' : ''}>${icon(id)}<span class="t">${l}</span>${extra}</a>`;
|
||||
};
|
||||
// No project tree under Projects here: the sidebar's Projects group lists every organization's
|
||||
@@ -342,6 +347,8 @@
|
||||
});
|
||||
|
||||
let configRead = Promise.resolve();
|
||||
// #1873 SP1: the config read an organization switch started, until the next render has waited for it.
|
||||
let switchRead = null;
|
||||
let canSend = false, canMessage = false, chatSend = false, sendRoles = null, sending = false, receipt = null, replies = [];
|
||||
const REPLIES = 50; // the broker's cap
|
||||
function repliesHtml() {
|
||||
@@ -462,14 +469,67 @@
|
||||
if(!templatesOnly && d.op!=='fire' && !template){hireStatus='Read and choose a role template first.';hireCode='';paintHireStart();return;}
|
||||
const thinking=d.thinking?.trim(),hire={op:d.op,level:d.level,name:d.name,reason:d.reason,...(d.level==='project'?{project:d.project}:{}),...(d.op==='fire'?{}:{role:{template:template?.name,sha256:template?.sha256},route:{harness:d.harness,model:d.model,...(thinking?{thinking}:{})}})};
|
||||
hireBusy=true;hireStatus='';hireCode='';paintHireStart();
|
||||
const epoch=orgEpoch;
|
||||
const {res,json}=await decidePost(`/api/decisions/hire/${templatesOnly?'templates':'start'}`,{business:hireOrg() ?? d.business,...(templatesOnly?{}:{hire})});
|
||||
if(epoch!==orgEpoch){if(res?.type==='opaqueredirect')signOut();return;}
|
||||
hireBusy=false;
|
||||
if(res?.type==='opaqueredirect'){signOut();return;}
|
||||
if(res?.ok && templatesOnly && Array.isArray(json?.templates)){hireTemplates=json.templates;hireStatus=hireTemplates.length?'Templates read.':'No templates available.';}
|
||||
else if(res?.ok && !templatesOnly && json?.op==='resolved'){hireStatus=`Recorded decision ${json.id}.`;}
|
||||
else {const r=decideRefusal(res,json,templatesOnly?'confirmation-unavailable':'outcome-unknown');hireStatus=r.message;hireCode=r.code;}
|
||||
paintHireStart();
|
||||
// A hire, fire or change applied: the Agents page and any pane showing this organization draw it now.
|
||||
if(res?.ok && !templatesOnly && json?.op==='resolved' && hireOrg())document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:hireOrg()}}));
|
||||
}
|
||||
// Fire from an agent card on the Agents page (ruling 2026-11-14, visibility): the same hire decision the
|
||||
// form above raises with op fire, after an inline confirmation. On success the card goes at once, a
|
||||
// receipt names the decision, and the page reads the organization again. The confirmation and the
|
||||
// receipt live here so a redraw keeps them; workspace.js draws them from MosaicDecide.
|
||||
const FIRE_REASON='Fired from the Agents page.';
|
||||
let fireAsk=null,fireBusy=false,fireReceipt=null;
|
||||
const fireKey=(org,name)=>`${org}\u0000${name}`;
|
||||
function fireNote(){const org=hireOrg();const r=fireReceipt&&fireReceipt.org===org?fireReceipt:null;
|
||||
return r?`<p class="receipt${r.failed?' failed':''}" data-agents-receipt-text>${txt(r.text)}${r.code?` (<code>${txt(r.code)}</code>)`:''}</p>`:'';}
|
||||
function paintFireNote(){for(const e of document.querySelectorAll('[data-agents-receipt]'))e.innerHTML=fireNote();}
|
||||
async function fireAgent(name){
|
||||
const org=hireOrg();
|
||||
if(fireBusy||!org||out()||!canDecide)return;
|
||||
fireBusy=true;
|
||||
for(const b of document.querySelectorAll('[data-agent-fire-yes],[data-agent-fire-no]'))b.disabled=true;
|
||||
const epoch=orgEpoch;
|
||||
const {res,json}=await decidePost('/api/decisions/hire/start',{business:org,hire:{op:'fire',level:'org',name,reason:FIRE_REASON}});
|
||||
if(epoch!==orgEpoch){if(res?.type==='opaqueredirect')signOut();return;}
|
||||
fireBusy=false;fireAsk=null;
|
||||
if(res?.type==='opaqueredirect'){signOut();return;}
|
||||
if(res?.ok && json?.op==='resolved'){
|
||||
for(const c of document.querySelectorAll(`[data-org="${CSS.escape(org)}"] [data-agent-card="${CSS.escape(name)}"]`))c.remove();
|
||||
for(const r of document.querySelectorAll(`[data-agents-org="${CSS.escape(org)}"] tr[data-agent="${CSS.escape(name)}"]`))r.remove();
|
||||
fireReceipt={org,text:`Fired ${name}. Recorded decision ${json.id}.`};
|
||||
paintFireNote();announce(fireReceipt.text);
|
||||
document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org}}));
|
||||
} else {
|
||||
const r=decideRefusal(res,json,'outcome-unknown');
|
||||
fireReceipt={org,failed:true,text:`${name} was not fired: ${r.message}`,code:r.code};
|
||||
paintFireNote();
|
||||
for(const c of document.querySelectorAll(`[data-agent-fire-confirm="${CSS.escape(name)}"]`))c.outerHTML=fireButton(name);
|
||||
}
|
||||
}
|
||||
const fireButton=name=>`<button type="button" class="btn small" data-agent-fire="${esc(name)}" data-focus-key="${esc(`fire:${name}`)}" aria-label="Fire ${esc(name)}">Fire</button>`;
|
||||
const fireConfirm=name=>`<span class="ws-fire-confirm" role="group" aria-label="Fire ${esc(name)}?" data-agent-fire-confirm="${esc(name)}">Fire ${txt(name)}? <button type="button" class="btn small primary" data-agent-fire-yes="${esc(name)}" data-focus-key="${esc(`fire-yes:${name}`)}"${fireBusy?' disabled':''}>Confirm fire</button><button type="button" class="btn small" data-agent-fire-no="${esc(name)}"${fireBusy?' disabled':''}>Cancel</button></span>`;
|
||||
// What the agent card shows for one agent: nothing without the decide right or outside the page's own organization.
|
||||
function fireControl(org,name){
|
||||
if(!canDecide||isTester||org!==hireOrg())return '';
|
||||
return fireAsk===fireKey(org,name)?fireConfirm(name):fireButton(name);
|
||||
}
|
||||
document.addEventListener('click',e=>{
|
||||
const t=e.target.closest?.('[data-agent-fire],[data-agent-fire-yes],[data-agent-fire-no]');
|
||||
if(!t)return;
|
||||
const org=hireOrg();
|
||||
if(t.hasAttribute('data-agent-fire')){const name=t.dataset.agentFire;fireAsk=fireKey(org,name);t.outerHTML=fireConfirm(name);document.querySelector(`[data-agent-fire-yes="${CSS.escape(name)}"]`)?.focus();}
|
||||
else if(t.hasAttribute('data-agent-fire-no')){const name=t.dataset.agentFireNo;fireAsk=null;t.closest('[data-agent-fire-confirm]').outerHTML=fireButton(name);announce('Cancelled. Nothing was fired.');}
|
||||
else void fireAgent(t.dataset.agentFireYes);
|
||||
});
|
||||
window.MosaicDecide=Object.freeze({fireControl,fireNote});
|
||||
document.addEventListener('click',e=>{if(e.target.closest?.('[data-hire-load]'))hireSubmit(true);});
|
||||
document.addEventListener('submit',e=>{if(e.target.id==='hire-start-form'){e.preventDefault();hireSubmit();}});
|
||||
const answerChoices = c => ['decision','hire'].includes(c.kind)
|
||||
@@ -989,9 +1049,9 @@
|
||||
document.addEventListener('change',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}});
|
||||
document.addEventListener('click',e=>{if(e.target.id!=='launch-settings-reload')return;settingsInputs=null;settingsSnapshot=null;settingsReceipt='';last.delete('api:settings');render(true);});
|
||||
document.addEventListener('submit',async e=>{
|
||||
if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false);
|
||||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}}
|
||||
catch{settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{settingsSaving=false;if(!out())render(false);}
|
||||
if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false);const epoch=orgEpoch;
|
||||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}}
|
||||
catch{if(epoch!==orgEpoch)return;settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(false);}}
|
||||
});
|
||||
// Row 125 (#1619, REQ-LIMIT-3, REQ-LIMIT-4): each token limit as the bus's checks report it. A
|
||||
// limit no switched-on check counts reads "not enforced". Reset counts it again from now. Row 126
|
||||
@@ -1012,9 +1072,9 @@
|
||||
document.addEventListener('click',async e=>{
|
||||
const path=e.target.dataset?.limitReset;if(path===undefined||!canSend||out()||settingsSaving)return;
|
||||
const revision=settingsSnapshot?.revision;if(!/^[a-f0-9]{64}$/.test(revision??''))return;
|
||||
settingsSaving=true;resetReceipt='';render(false);let reread=false;
|
||||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){resetReceipt='Sign in again.';signOut();}else{const result=await response.json();if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});reread=true;resetReceipt='Limit reset.';}else resetReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again.':`${result?.message||'Reset refused.'}`;}}
|
||||
catch{resetReceipt='Outcome unknown. Read current settings before trying again.';}finally{settingsSaving=false;if(!out())render(reread);}
|
||||
settingsSaving=true;resetReceipt='';render(false);let reread=false;const epoch=orgEpoch;
|
||||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){resetReceipt='Sign in again.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});reread=true;resetReceipt='Limit reset.';}else resetReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again.':`${result?.message||'Reset refused.'}`;}}
|
||||
catch{if(epoch!==orgEpoch)return;resetReceipt='Outcome unknown. Read current settings before trying again.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(reread);}}
|
||||
});
|
||||
function tokenUsage(value) {
|
||||
if (!value?.total) return '<section class="panel" aria-labelledby="token-usage-title"><h2 id="token-usage-title">Token usage</h2><p>Usage unavailable. No count was read.</p></section>';
|
||||
@@ -1069,9 +1129,9 @@
|
||||
}
|
||||
const unknownAssistant='Outcome unknown. Read current settings before trying again. Draft kept.';
|
||||
async function assistantPost(url,payload,instance,ok,kind='tester'){
|
||||
if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false);
|
||||
try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}}
|
||||
catch{assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);}
|
||||
if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false);const epoch=orgEpoch;
|
||||
try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}}
|
||||
catch{if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(epoch===orgEpoch){if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);}}
|
||||
}
|
||||
const assistantForm=el=>el?.closest?.('.assistant-form');
|
||||
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};if(field){markSettingsDraft('assistant',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-assistant-discard]');if(discard)discard.hidden=false;}});
|
||||
@@ -1136,11 +1196,11 @@
|
||||
const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||!instanceView)return;
|
||||
const op=form.dataset.op;if(instanceBusyOps.has(op))return;instanceReceiptOp=op;instanceDrafts[op]=instanceFields(form);let payload;
|
||||
try{payload=instancePayload(op,instanceDrafts[op]);}catch(err){instanceReceipt=err.message;instanceReceipts[op]=instanceReceipt;render(false);return;}
|
||||
instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false);
|
||||
try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();
|
||||
instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false);const epoch=orgEpoch;
|
||||
try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
|
||||
if(response.ok&&instanceAnswer(result)){instanceDrafts[op]=null;instanceView=result;const prior=last.get('instances');if(prior)last.set('instances',{...prior,rows:[result]});instanceReceipt=`${op==='add'?'Added':'Changed'} ${payload.instance}. ${result.restart?restartText():NO_RESTART_TEXT}`;}
|
||||
else instanceReceipt=response.ok||result?.sent==='unknown'?unknownInstance:`${result?.message||'Refused.'} Draft kept.`;}}
|
||||
catch{instanceReceipt=unknownInstance;}finally{instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);}
|
||||
catch{if(epoch!==orgEpoch)return;instanceReceipt=unknownInstance;}finally{if(epoch===orgEpoch){instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);}}
|
||||
});
|
||||
// Row 65 (mos-0840): the routing table. One row per instance: harness, model and thinking, and
|
||||
// the fallback's three. Each cell offers the switched-on harnesses, the model table's keys and the
|
||||
@@ -1166,8 +1226,8 @@
|
||||
const routesApplyMarkup=()=>routesApply?.length?`<ul class="routes-apply" aria-label="How the change reaches each agent">${routesApply.map(a=>`<li><b>${txt(a.name)}</b>: ${txt(a.text)}${a.restart&&canSend&&!isTester?` ${window.MosaicAgents?.restartMarkup(a.name,a.thread)??''}`:''}</li>`).join('')}</ul>`:'';
|
||||
let harnessSettings=null, harnessDraft=null, harnessLoading=false, harnessReceipt='', harnessBusy=false;
|
||||
function readHarnesses(){
|
||||
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;
|
||||
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
|
||||
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;const epoch=orgEpoch;
|
||||
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{if(epoch!==orgEpoch)return;harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{if(epoch!==orgEpoch)return;harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
|
||||
}
|
||||
const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']];
|
||||
const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''});
|
||||
@@ -1244,32 +1304,32 @@
|
||||
if(harnessSettings.revision!==routesView?.revision){harnessReceipt='The business changed. Reload this page before saving harnesses.';render(false);return;}
|
||||
const used=old.filter(n=>!selected.includes(n) && Object.values(routesView.instances).some(r=>r.harness===n || r.fallback?.harness===n));
|
||||
if(used.length){harnessReceipt=`A saved route uses ${used.join(', ')}. Change the route before switching it off.`;render(false);return;}
|
||||
harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt='';
|
||||
try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');}
|
||||
catch{harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
|
||||
finally{harnessBusy=false;if(!out())render(false);}
|
||||
harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt='';const epoch=orgEpoch;
|
||||
try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(epoch!==orgEpoch)return;if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');}
|
||||
catch{if(epoch!==orgEpoch)return;harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
|
||||
finally{if(epoch===orgEpoch){harnessBusy=false;if(!out())render(false);}}
|
||||
});
|
||||
document.addEventListener('click',async e=>{if(e.target.id!=='provider-switch'||!canSend||isTester)return;
|
||||
const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;
|
||||
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
|
||||
const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;const epoch=orgEpoch;
|
||||
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(epoch!==orgEpoch)return;if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
|
||||
const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[];
|
||||
// The fresh read decides: a stale label never turns the proxy module on when it meant off.
|
||||
const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=`${on?'Disable':'Enable'} model proxy catalogue`;button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;}
|
||||
const next=on?names.filter(n=>n!=='cliproxy'):[...names,'cliproxy'];
|
||||
const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});
|
||||
if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
|
||||
}catch(error){status.textContent=error.message;button.disabled=false;}
|
||||
if(epoch!==orgEpoch)return;if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
|
||||
}catch(error){if(epoch!==orgEpoch)return;status.textContent=error.message;button.disabled=false;}
|
||||
});
|
||||
document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');});
|
||||
document.addEventListener('click',e=>{if(e.target.id!=='routes-reload')return;routesDraft=null;routesView=null;routesReceipt='';routesApply=null;last.delete('routes');render(true);});
|
||||
document.addEventListener('submit',async e=>{
|
||||
if(e.target.id!=='routes-form')return;e.preventDefault();if(!(canSend || isTester)||out()||routesBusy||!routesView)return;
|
||||
routesDraft=routesFields(e.target);let payload;try{payload=routesPayload(routesDraft);}catch(err){routesReceipt=err.message;render(false);return;}
|
||||
routesBusy=true;routesReceipt='';routesApply=null;render(false);
|
||||
try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();
|
||||
if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;routesApply=await routesApplyRead(Object.keys(payload.routes));}
|
||||
routesBusy=true;routesReceipt='';routesApply=null;render(false);const epoch=orgEpoch;
|
||||
try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
|
||||
if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;const applied=await routesApplyRead(Object.keys(payload.routes));if(epoch!==orgEpoch)return;routesApply=applied;}
|
||||
else routesReceipt=response.ok||result?.sent==='unknown'?unknownRoutes:`${result?.message||'Refused.'}${catalogueStep(result?.error,payload.routes)} Draft kept.`;}}
|
||||
catch{routesReceipt=unknownRoutes;}finally{routesBusy=false;if(!out())render(false);}
|
||||
catch{if(epoch!==orgEpoch)return;routesReceipt=unknownRoutes;}finally{if(epoch===orgEpoch){routesBusy=false;if(!out())render(false);}}
|
||||
});
|
||||
// Row 194 (#1692, D7): the Agents section lives in agents.js (window.MosaicAgents) and draws from
|
||||
// the same instances read. A refresh drops that read so the next render asks the bus again.
|
||||
@@ -1480,6 +1540,7 @@
|
||||
if (!s || !saveable(s)) return;
|
||||
const sent = { project: s.project, path: s.path, base: s.commit, content: s.text }, unknown = 'Outcome unknown: the save may have gone through. Copy your text, then reload the file to check before saving again. Draft kept.';
|
||||
s.saving = true; s.status = '';
|
||||
const epoch = orgEpoch;
|
||||
let res = null, body = null;
|
||||
try {
|
||||
paintDoc();
|
||||
@@ -1491,13 +1552,16 @@
|
||||
} else if (body?.sent === false) s.status = `${typeof body.message === 'string' && body.message ? body.message : 'Not saved.'} Draft kept.`;
|
||||
else s.status = unknown;
|
||||
} finally { s.saving = false; } // a throw above must not leave Save off and Reload refused
|
||||
// #1873 SP1: a switch while this was in flight cleared the drafts; the old file's outcome is not
|
||||
// painted or announced on the new organization's page.
|
||||
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
|
||||
paintDoc();
|
||||
announce(s.status);
|
||||
if (res?.type === 'opaqueredirect') signOut();
|
||||
});
|
||||
|
||||
// Not found and states
|
||||
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="#/">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
|
||||
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="${window.MosaicOrg ? '#/dashboard' : '#/'}">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
|
||||
const loadingView = (source = null) => `${head('Reading…')}<div class="skel-rows" aria-busy="true"><span class="sr-only">${source ? `Reading the ${esc(source.toLowerCase())}.` : 'Reading from the bus.'}</span><span class="skel"></span><span class="skel"></span><span class="skel"></span><span class="skel"></span></div>`;
|
||||
const retry = '<div class="actions"><button type="button" class="btn" data-retry>Read again</button></div>';
|
||||
// Why a read failed, in words, with the bus code as given. Never a path or a guess.
|
||||
@@ -1552,7 +1616,8 @@
|
||||
const parts = path.split('/').filter(Boolean).map(p => { try { return decodeURIComponent(p); } catch { return null; } });
|
||||
if (parts.includes(null)) return notFound();
|
||||
const [a, b, c] = parts, n = parts.length;
|
||||
if (n === 0 && window.MosaicOrg) return window.MosaicWorkspace.home();
|
||||
// #1873 SP1: `#/dashboard` is the system dashboard, every organization on one page.
|
||||
if ((n === 0 || (a === 'dashboard' && n === 1)) && window.MosaicOrg) return window.MosaicWorkspace.home();
|
||||
if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q);
|
||||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard();
|
||||
if (a === 'inbox' && n === 1 && window.MosaicOrg) return configRead.then(() => window.MosaicWorkspace.inboxPage(q, { hire: hireStartHtml }));
|
||||
@@ -1577,7 +1642,7 @@
|
||||
const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true';
|
||||
// A file open in the editor is never refreshed from under its draft; Reload is the person's to press.
|
||||
// The cross-organization pages (U3) poll at the workspace read's pollMs.
|
||||
const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/projects' || path === '/inbox');
|
||||
const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox');
|
||||
function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), wsPage(routeOf().split('?')[0]) ? window.MosaicWorkspace?.pollMs || 10000 : 10000); }
|
||||
// Keep focus, open <details> and the copy status across a refresh of the same page.
|
||||
// In the send form, the focused field and its caret too (its values come from `draft`).
|
||||
@@ -1627,6 +1692,14 @@
|
||||
// A refresh due while this render reads would replace it: a navigation would lose its heading focus.
|
||||
clearTimeout(timer);
|
||||
if (out()) return;
|
||||
// #1873 SP1: an address with no organization waits for the first list read to pick one, and a
|
||||
// page drawn right after a switch waits for the new organization's config.
|
||||
if ((window.MosaicOrg && !window.MosaicOrg.id) || switchRead) {
|
||||
const g0 = ++gen, waiting = switchRead;
|
||||
await window.MosaicOrg?.ready; await waiting;
|
||||
if (waiting && switchRead === waiting) switchRead = null;
|
||||
if (g0 !== gen || out()) return;
|
||||
}
|
||||
const route = routeOf(), [path, query = ''] = route.split('?'), board = window.MosaicOrg ? path === '/board' : path === '/' || path === '' || path === '/board';
|
||||
// On the cross-organization pages a filter or selection changes only the query: that is a
|
||||
// repaint of the same page, not a navigation (no loading view, focus and scroll kept).
|
||||
@@ -1688,12 +1761,15 @@
|
||||
// The board page keeps its own title; the Inbox count still follows the bus.
|
||||
if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Dashboard · Mosaic Console'; if (navigated) $('main').focus(); }
|
||||
// The held roles (row 95) are read with it. A refusal of either forgets both, as on the bus pages.
|
||||
const epoch = orgEpoch;
|
||||
const [inbox, agents, messages, tasks, queue, business, projects] = await Promise.allSettled([
|
||||
fetchRead('inbox'), fetchRead('agents'), fetchRead('messages'), fetchRead('tasks'), fetchApi('queue'), fetchApi('business'),
|
||||
fetch('/api/chat/projects', { cache: 'no-store', redirect: 'manual' }).then(async r => { if (r.type === 'opaqueredirect') { signOut(); throw signedOut(); } const body = await r.json(); if (signInRequired(r, body)) { signOutSso(); throw signedOut(); } if (!r.ok || !Array.isArray(body.rows)) throw new ReadError(body?.error, body?.message, r.status); return body; })
|
||||
]);
|
||||
const failed = [inbox, agents, messages, tasks].filter(s => s.status === 'rejected').map(s => s.reason);
|
||||
if (failed.some(err => err.code === 'signed-out')) return;
|
||||
// #1873 SP1: an answer read for an organization that is no longer open is not kept.
|
||||
if (epoch !== orgEpoch) return;
|
||||
if (inbox.status === 'fulfilled') last.set('inbox', inbox.value);
|
||||
if (agents.status === 'fulfilled') last.set('agents', agents.value);
|
||||
if (messages.status === 'fulfilled') last.set('messages', messages.value);
|
||||
@@ -1834,7 +1910,9 @@
|
||||
if (d.open) return;
|
||||
pkBack = document.activeElement; pkAt = 0; $('cmdk-input').value = '';
|
||||
pkItems(); pkFill(); d.showModal(); $('cmdk-input').focus();
|
||||
Promise.allSettled(['inbox', 'tasks'].map(async v => last.set(v, await fetchRead(v)))).then(rs => {
|
||||
const epoch = orgEpoch;
|
||||
Promise.allSettled(['inbox', 'tasks'].map(async v => { const r = await fetchRead(v); if (epoch === orgEpoch) last.set(v, r); })).then(rs => {
|
||||
if (epoch !== orgEpoch) return;
|
||||
if (rs.some(r => r.status === 'rejected' && refusal(r.reason))) { forget(); sections(routeOf().split('?')[0]); }
|
||||
if (d.open) { pkItems(); pkFill(); }
|
||||
});
|
||||
@@ -1874,11 +1952,13 @@
|
||||
if (out()) { receipt = { kind: 'refused', to: to || 'no role', code: 'sign-in', message: 'signed out; reload the page to sign in again' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
|
||||
if (!to || !text.trim()) { receipt = { kind: 'refused', to: to || 'no role', code: 'invalid-request', message: to ? 'the message is empty' : 'choose a role first' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
|
||||
sending = true; receipt = null; paintSend();
|
||||
const epoch = orgEpoch;
|
||||
let res = null, body = null;
|
||||
try {
|
||||
res = await fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });
|
||||
try { body = await res.json(); } catch { body = null; }
|
||||
} catch { res = null; }
|
||||
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
|
||||
// Sent: an id came back. Not sent: a 4xx (refused before the bus wrote), the server's
|
||||
// sent:false, or a redirect, which only the sign-in proxy gives (an expired session), so the
|
||||
// request never reached the Console. Anything else, no answer included, may have been sent,
|
||||
@@ -1909,7 +1989,7 @@
|
||||
// F3: `settingsSend` lets the owner of an organization Console save Settings on the selected
|
||||
// organization's bus; messaging a role still follows `send` (canMessage) and `chatSend`.
|
||||
// A bus restart reads the config again and sends it here as a mosaic-config event.
|
||||
const applyConfig = c => {
|
||||
const applyConfig = (c, opts = {}) => {
|
||||
isTester = c?.tester === true;
|
||||
canEdit = !isTester && c?.edit === true;
|
||||
canSend = !isTester && (c?.send === true || c?.settingsSend === true);
|
||||
@@ -1926,7 +2006,7 @@
|
||||
banner.setAttribute('role', 'status'); banner.textContent = 'Tester Console. Changes are recorded as tester, never as the human.';
|
||||
$('main').prepend(banner);
|
||||
}
|
||||
if (!canSend && !isTester && !ssoOn) return;
|
||||
if (opts.quiet || (!canSend && !isTester && !ssoOn)) return;
|
||||
const path = routeOf().split('?')[0];
|
||||
if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr);
|
||||
};
|
||||
@@ -1934,7 +2014,34 @@
|
||||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line now, not at the next poll.
|
||||
// E2E6 P2-2: a write on the organization page that changes other sections (a pack apply) asks for a
|
||||
// fresh read of the page; editors in progress are kept by holdLive.
|
||||
document.addEventListener('mosaic-org-changed', e => { if (window.MosaicOrg && e.detail?.org === window.MosaicOrg.id && routeOf().split('?')[0] === '/organization') render(false); });
|
||||
// Ruling 2026-11-14: an apply, hire or fire redraws the Agents page in the same response cycle, not at the next poll.
|
||||
document.addEventListener('mosaic-org-changed', e => { if (window.MosaicOrg && e.detail?.org === window.MosaicOrg.id && ['/organization', '/agents'].includes(routeOf().split('?')[0])) render(false); });
|
||||
// #1873 SP1: another organization opened in place (display.js, before this file's hashchange
|
||||
// render). Nothing read, drafted or confirmed for the old one carries over; the new one's config
|
||||
// is read before the next page draws. A write already sent finishes against the old organization,
|
||||
// and its answer is not drawn on the new one.
|
||||
document.addEventListener('mosaic-org-switch', () => {
|
||||
// Writes still in flight keep going to the old organization; their answers are dropped (orgEpoch)
|
||||
// and every busy flag and receipt starts clean here.
|
||||
orgEpoch++;
|
||||
sending = false; receipt = null; replies = [];
|
||||
hireBusy = false; fireBusy = false; settingsSaving = false; resetReceipt = '';
|
||||
assistantBusy = false; assistantFormsBusy.clear(); instanceBusyOps = new Set();
|
||||
routesBusy = false; routesApply = null; harnessBusy = false; harnessLoading = false;
|
||||
forget(); clearTimeout(timer);
|
||||
answer = null; heldErr = null; heldHtml = null; readAt = null; shown = null; projectContext = null;
|
||||
draft.to = ''; draft.body = '';
|
||||
hireDraft = { op: 'hire', level: 'org' }; hireTemplates = []; hireStatus = ''; hireCode = '';
|
||||
fireAsk = null; fireReceipt = null;
|
||||
settingsSnapshot = null; settingsInputs = null; settingsReceipt = ''; settingInvalidKey = null;
|
||||
assistantDrafts = Object.create(null); nameDrafts = Object.create(null); assistantReceipts = Object.create(null); assistantReceiptKinds = Object.create(null); assistantCardReceipts = Object.create(null);
|
||||
instanceView = null; instanceDrafts = { add: null, change: null }; instanceReceipt = ''; instanceReceiptOp = null; instanceReceipts = Object.create(null);
|
||||
routesView = null; routesDraft = null; routesReceipt = ''; routesEditVersion++;
|
||||
harnessSettings = null; harnessDraft = null; harnessReceipt = '';
|
||||
// A file draft is keyed by project and path only; the page reload that used to drop it is gone.
|
||||
docKey = null; docStates.clear(); pkAll = []; pkShown = []; pkAt = 0;
|
||||
configRead = switchRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => applyConfig(c, { quiet: true })).catch(() => {});
|
||||
});
|
||||
document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') { applyConfig(e.detail); if (window.MosaicOrg && routeOf().split('?')[0] === '/organization') render(false); } });
|
||||
// The cross-organization pages ask for a repaint after a filter, sort or selection change,
|
||||
// and report the inbox count across organizations for the sidebar.
|
||||
|
||||
@@ -1,60 +1,67 @@
|
||||
window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : 'unknown';
|
||||
// An organization switch reloads the page, which drops every per-page cache and
|
||||
// subscription. Requests already sent keep the organization captured here.
|
||||
// #1873 SP1: one shell for the whole system. `#/dashboard` is the system landing route and
|
||||
// `#/orgs/<id>/...` is a route inside the same page, not a mode: opening another organization
|
||||
// changes the scope of later /api reads and fires `mosaic-org-switch`. Nothing reloads.
|
||||
// Requests already sent keep the organization they were sent with.
|
||||
(() => {
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
const match = /^#\/orgs\/([^/]+)(\/.*)?$/.exec(location.hash);
|
||||
const id = match?.[1] ?? null;
|
||||
if (!id) {
|
||||
if (!document.documentElement.hasAttribute('data-organizations')) return;
|
||||
const readInitialOrganizations = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
|
||||
if (r.ok) { window.MosaicOrganizationError = null; return r.json(); }
|
||||
const body = await r.json().catch(() => ({}));
|
||||
window.MosaicOrganizationError = body.message || 'Organization registry could not be read';
|
||||
return null;
|
||||
}).catch(() => { window.MosaicOrganizationError = 'Organization registry could not be read'; return null; });
|
||||
const refreshInitial = () => {
|
||||
const initialOrganizations = window.MosaicInitialOrganizations = readInitialOrganizations();
|
||||
initialOrganizations.then(async rows => {
|
||||
if (!Array.isArray(rows) || !rows.length || location.hash.startsWith('#/orgs/')) return;
|
||||
rows = rows.filter(row => !row.invalid);
|
||||
if (!rows.length) return;
|
||||
let preferred;
|
||||
try { preferred = (await (await nativeFetch('/api/config', { cache: 'no-store', redirect: 'manual' })).json()).preselect; } catch { /* first authorized organization */ }
|
||||
const selected = rows.find(row => row.id === preferred) ?? rows[0];
|
||||
const tail = location.hash.startsWith('#/') ? location.hash.slice(1) : '/';
|
||||
history.replaceState(null, '', `#/orgs/${encodeURIComponent(selected.id)}${tail}`);
|
||||
location.reload();
|
||||
}).catch(() => {});
|
||||
return initialOrganizations;
|
||||
};
|
||||
window.MosaicRefreshOrganizations = refreshInitial;
|
||||
refreshInitial();
|
||||
return;
|
||||
}
|
||||
const route = () => location.hash.replace(/^#\/orgs\/[^/]+/, '') || '/';
|
||||
const orgOf = hash => /^#\/orgs\/([^/]+)/.exec(hash)?.[1] ?? null;
|
||||
const atLoad = orgOf(location.hash);
|
||||
if (!atLoad && !document.documentElement.hasAttribute('data-organizations')) return;
|
||||
// current: the scoping organization as its hash segment. settled: false only while the first
|
||||
// list read picks one for an address that names none. With no valid organization at all the
|
||||
// page stays in its first-run mode (window.MosaicOrg reads undefined), as before.
|
||||
let current = atLoad, settled = !!atLoad, markReady;
|
||||
const ready = new Promise(resolve => { markReady = resolve; });
|
||||
const settle = seg => { current = seg; settled = true; markReady(seg ? decodeURIComponent(seg) : null); };
|
||||
// An address that names its organization is settled at load: anything waiting on ready goes on.
|
||||
if (atLoad) markReady(decodeURIComponent(atLoad));
|
||||
const tail = hash => { const m = /^#\/orgs\/[^/]+(.*)$/.exec(hash); return m ? (m[1] || '/') : hash.startsWith('#/') ? hash.slice(1) : '/'; };
|
||||
const route = () => tail(location.hash);
|
||||
// The bare address and the old per-organization dashboard address are the system dashboard;
|
||||
// an organization page without the prefix gets the current organization's. #1873 SP2: an
|
||||
// organization's own bare address (#/orgs/<id>, no trailing slash) is that organization's page;
|
||||
// #/orgs/<id>/ stays the old dashboard address.
|
||||
const normalize = (hash, seg = current) => {
|
||||
const path = tail(hash), bare = path.split('?')[0], named = /^#\/orgs\/([^/?]+)$/.exec(hash.split('?')[0])?.[1];
|
||||
if (named) return `#/orgs/${named}/organization${hash.slice(hash.split('?')[0].length)}`;
|
||||
if (bare === '/' || bare === '/dashboard') return `#/dashboard${path.slice(bare.length)}`;
|
||||
return orgOf(hash) || !seg ? hash : `#/orgs/${seg}${path}`;
|
||||
};
|
||||
// /api/workspace reads and writes across organizations (U1, U4b), so it keeps its own path.
|
||||
const unscoped = /^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$))/;
|
||||
window.fetch = (input, init) => {
|
||||
if (typeof input === 'string' && input.startsWith('/api/') && !/^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$))/.test(input))
|
||||
input = `/api/orgs/${id}/${input.slice('/api/'.length)}`;
|
||||
return nativeFetch(input, init);
|
||||
if (typeof input !== 'string' || !input.startsWith('/api/') || unscoped.test(input)) return nativeFetch(input, init);
|
||||
const send = () => nativeFetch(current ? `/api/orgs/${current}/${input.slice('/api/'.length)}` : input, init);
|
||||
return settled ? send() : ready.then(send);
|
||||
};
|
||||
// A failed read keeps its reason, so the header can say why the list is empty.
|
||||
let listError = null;
|
||||
const readList = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
|
||||
let listError = null, rowsSeen = [];
|
||||
const readRows = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
|
||||
if (r.ok) {
|
||||
const body = await r.json(); listError = null;
|
||||
const body = await r.json(); listError = null; window.MosaicOrganizationError = null;
|
||||
const rows = Array.isArray(body) ? body : [];
|
||||
// E2E5 review P2: an open panel (Settings > Organizations) follows every fresh list read, not only its own.
|
||||
document.dispatchEvent(new CustomEvent('mosaic-org-list', { detail: { rows } }));
|
||||
return rows;
|
||||
}
|
||||
const body = await r.json().catch(() => ({}));
|
||||
listError = typeof body.message === 'string' && body.message ? body.message : 'Organization registry could not be read';
|
||||
return [];
|
||||
}).catch(() => { listError = 'Organization registry could not be read'; return []; });
|
||||
// Idempotent: each read replaces the banner and the wordmark name, and removes them on recovery.
|
||||
listError = window.MosaicOrganizationError = typeof body.message === 'string' && body.message ? body.message : 'Organization registry could not be read';
|
||||
return null;
|
||||
}).catch(() => { listError = window.MosaicOrganizationError = 'Organization registry could not be read'; return null; });
|
||||
const readList = () => readRows().then(rows => rows ?? []);
|
||||
// The bus banner belongs to an organization page; the dashboard lists every bus on its own rows.
|
||||
// #1873 SP2: the organization's own page draws its down banner with the restart action, so this one hides there.
|
||||
const paintBus = () => {
|
||||
const banner = document.getElementById('bus-down');
|
||||
if (!banner) return;
|
||||
const org = rowsSeen.find(row => current && row.id === decodeURIComponent(current) && !row.invalid), path = route().split('?')[0];
|
||||
if (path === '/dashboard' || (path === '/organization' && org?.busHealthy === false) || (banner.dataset.orgBus && org?.busHealthy !== false)) { banner.hidden = true; delete banner.dataset.orgBus; return; }
|
||||
if (org?.busHealthy === false) { banner.textContent = 'Bus unavailable'; banner.hidden = false; banner.dataset.orgBus = '1'; window.MosaicConsole?.attachBus(banner, 'Restart the bus'); }
|
||||
};
|
||||
// Idempotent: each read replaces the banner, and removes it on recovery.
|
||||
const paintHeader = rows => {
|
||||
rowsSeen = rows;
|
||||
document.getElementById('org-list-banner')?.remove();
|
||||
const lines = [...(listError ? [listError] : []), ...rows.filter(row => row.invalid).map(row => `${row.id}: invalid — ${row.reason}`)];
|
||||
if (lines.length) {
|
||||
@@ -62,58 +69,115 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
banner.textContent = lines.join('; ');
|
||||
document.body.prepend(banner);
|
||||
}
|
||||
// The shell no longer names one organization in its wordmark: the breadcrumb does.
|
||||
document.getElementById('current-organization')?.remove();
|
||||
const org = rows.find(row => row.id === decodeURIComponent(id) && !row.invalid);
|
||||
const mark = document.querySelector('.wordmark');
|
||||
if (mark && org) { const name = document.createElement('span'); name.id = 'current-organization'; name.textContent = ` · ${org.label || org.id}`; mark.append(name); }
|
||||
if (org?.busHealthy === false) { const banner = document.getElementById('bus-down'); if (banner) { banner.textContent = 'Bus unavailable'; banner.hidden = false; window.MosaicConsole?.attachBus(banner, 'Restart the bus'); } }
|
||||
paintBus();
|
||||
window.MosaicBreadcrumbs?.();
|
||||
return rows;
|
||||
};
|
||||
let list = readList().then(paintHeader);
|
||||
let list;
|
||||
const refreshList = () => (list = readList().then(paintHeader));
|
||||
window.MosaicRefreshOrganizations = refreshList;
|
||||
let previous = location.hash;
|
||||
if (atLoad) {
|
||||
const first = normalize(location.hash);
|
||||
if (first !== location.hash) history.replaceState(null, '', first);
|
||||
refreshList();
|
||||
} else {
|
||||
const initial = window.MosaicInitialOrganizations = readRows();
|
||||
list = initial.then(rows => paintHeader(rows ?? []));
|
||||
initial.then(async rows => {
|
||||
const valid = Array.isArray(rows) ? rows.filter(row => !row.invalid) : [];
|
||||
if (!valid.length) return null;
|
||||
let preferred;
|
||||
try { preferred = (await (await nativeFetch('/api/config', { cache: 'no-store', redirect: 'manual' })).json()).preselect; } catch { /* first authorized organization */ }
|
||||
return encodeURIComponent((valid.find(row => row.id === preferred) ?? valid[0]).id);
|
||||
}).catch(() => null).then(seg => {
|
||||
settle(orgOf(location.hash) ?? seg);
|
||||
if (!current) return;
|
||||
const next = normalize(location.hash);
|
||||
if (next !== location.hash) history.replaceState(null, '', next);
|
||||
previous = location.hash; paintBus();
|
||||
});
|
||||
}
|
||||
// From the first-run page (no organization yet) the first one changes the page's mode, which
|
||||
// still takes one reload. Once an organization is open, a list refresh repaints in place.
|
||||
window.MosaicRefreshOrganizations = () => {
|
||||
if (current || !settled) return refreshList();
|
||||
const read = window.MosaicInitialOrganizations = readRows();
|
||||
list = read.then(rows => paintHeader(rows ?? []));
|
||||
read.then(rows => {
|
||||
const valid = Array.isArray(rows) ? rows.filter(row => !row.invalid) : [];
|
||||
if (!valid.length || orgOf(location.hash)) return;
|
||||
history.replaceState(null, '', `#/orgs/${encodeURIComponent(valid[0].id)}${tail(location.hash) === '/' ? '/organization' : tail(location.hash)}`);
|
||||
location.reload();
|
||||
});
|
||||
return read;
|
||||
};
|
||||
let previous = location.hash, skipGuard = false;
|
||||
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || [...document.querySelectorAll('#reply, #conv-reply, #doc-source')].some(el => !!el.value?.trim());
|
||||
function change(next) {
|
||||
history.replaceState(null, '', next);
|
||||
location.reload();
|
||||
// A switch scopes later reads to the new organization; listeners drop what they held for the old one.
|
||||
function rescope(seg) {
|
||||
const from = current;
|
||||
current = seg;
|
||||
document.dispatchEvent(new CustomEvent('mosaic-org-switch', { detail: { from: from ? decodeURIComponent(from) : null, to: decodeURIComponent(seg) } }));
|
||||
}
|
||||
function discard() {
|
||||
window.MosaicChat?.forget?.();
|
||||
for (const el of document.querySelectorAll('#reply, #conv-reply, #doc-source')) el.value = '';
|
||||
}
|
||||
function confirmSwitch(next) {
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.setAttribute('aria-label', 'Unsaved draft');
|
||||
dialog.innerHTML = '<p>You have an unsaved draft. Stay here or discard it and continue.</p><button type="button" data-stay>Stay</button> <button type="button" data-discard>Discard</button>';
|
||||
document.body.append(dialog);
|
||||
const stay = () => { const picker = document.getElementById('org-picker'); if (picker) picker.value = decodeURIComponent(id); dialog.close(); dialog.remove(); };
|
||||
const close = () => { dialog.close(); dialog.remove(); };
|
||||
const stay = () => { const picker = document.getElementById('org-picker'); if (picker && current) picker.value = decodeURIComponent(current); close(); };
|
||||
dialog.querySelector('[data-stay]').onclick = stay;
|
||||
dialog.querySelector('[data-discard]').onclick = () => change(next);
|
||||
dialog.querySelector('[data-discard]').onclick = () => { close(); discard(); skipGuard = true; location.hash = next; };
|
||||
dialog.addEventListener('cancel', e => { e.preventDefault(); stay(); });
|
||||
dialog.showModal(); dialog.querySelector('[data-stay]').focus();
|
||||
}
|
||||
// Capture phase: this runs before bus.js renders, so a switch is scoped before the page reads.
|
||||
window.addEventListener('hashchange', event => {
|
||||
const oldHash = event.oldURL ? new URL(event.oldURL).hash : previous;
|
||||
let next = location.hash;
|
||||
if (!next.startsWith('#/orgs/')) { next = `#/orgs/${id}${next.startsWith('#/') ? next.slice(1) : '/'}`; history.replaceState(null, '', next); }
|
||||
const nextId = /^#\/orgs\/([^/]+)/.exec(next)?.[1];
|
||||
if ((nextId && nextId !== id) || (next !== oldHash && window.MosaicOrgCreate?.hasDraft?.())) {
|
||||
const raw = location.hash;
|
||||
// First run (no organization yet) keeps its own addresses: #/ is its board, not #/dashboard.
|
||||
// Before the first list read settles, the settle step normalizes whatever address it finds.
|
||||
if (!settled || !current) { previous = raw; return; }
|
||||
const seg = orgOf(raw) ?? current, next = normalize(raw, seg);
|
||||
if (next !== raw) history.replaceState(null, '', next);
|
||||
const switching = seg !== current;
|
||||
if (!skipGuard && next !== oldHash && (switching || window.MosaicOrgCreate?.hasDraft?.()) && dirty()) {
|
||||
event.stopImmediatePropagation();
|
||||
if (dirty()) { history.replaceState(null, '', oldHash); confirmSwitch(next); } else change(next);
|
||||
history.replaceState(null, '', oldHash); confirmSwitch(next);
|
||||
return;
|
||||
}
|
||||
previous = next;
|
||||
skipGuard = false; previous = next;
|
||||
if (switching) rescope(seg);
|
||||
paintBus();
|
||||
}, true);
|
||||
window.MosaicOrg = Object.freeze({ id: decodeURIComponent(id), route, get list() { return list; }, readList, refreshList, switchTo: next => { location.hash = `#/orgs/${encodeURIComponent(next)}${route()}`; } });
|
||||
const api = Object.freeze({
|
||||
get id() { return current ? decodeURIComponent(current) : null; },
|
||||
// The open organization's name as the last list read gave it, for the breadcrumb.
|
||||
get label() { const id = current ? decodeURIComponent(current) : null, row = id && rowsSeen.find(r => r.id === id); return id ? (typeof row?.label === 'string' && row.label ? row.label : id) : null; },
|
||||
ready, route, get list() { return list; }, readList, refreshList,
|
||||
switchTo: next => { const path = route().split('?')[0]; location.hash = `#/orgs/${encodeURIComponent(next)}${path === '/dashboard' || path === '/' ? '/organization' : route()}`; },
|
||||
});
|
||||
Object.defineProperty(window, 'MosaicOrg', { configurable: true, enumerable: true, get: () => (current || !settled ? api : undefined) });
|
||||
})();
|
||||
if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-proxy';
|
||||
/* Browser-local sidebar density. No authority or project data is stored here. */
|
||||
(() => {
|
||||
const key=window.MosaicOrg ? `mosaic-sidebar-display-v1:${window.MosaicOrg.id}` : 'mosaic-sidebar-display-v1';
|
||||
// #1873 SP1: the key follows the open organization, read again when it changes.
|
||||
const key=()=>window.MosaicOrg?.id ? `mosaic-sidebar-display-v1:${window.MosaicOrg.id}` : 'mosaic-sidebar-display-v1';
|
||||
const defaults=()=>({version:1,density:'comfortable',order:'title-first'});
|
||||
const valid=x=>x&&x.version===1&&['comfortable','compact'].includes(x.density)&&['title-first','contact-first'].includes(x.order)&&Object.keys(x).sort().join(',')==='density,order,version';
|
||||
let saved=defaults();
|
||||
try {const value=JSON.parse(localStorage.getItem(key));if(valid(value))saved=value;} catch {}
|
||||
const load=()=>{saved=defaults();try {const value=JSON.parse(localStorage.getItem(key()));if(valid(value))saved=value;} catch {}};
|
||||
const apply=()=>{document.documentElement.dataset.sidebarDensity=saved.density;document.documentElement.dataset.sidebarOrder=saved.order;document.dispatchEvent(new CustomEvent('mosaic-display-change',{detail:{...saved}}));};
|
||||
apply();
|
||||
window.MosaicDisplay={get:()=>({...saved}),setDensity(density){if(!['comfortable','compact'].includes(density))return false;saved={...saved,density};apply();try{localStorage.setItem(key,JSON.stringify(saved));return true;}catch{return false;}}};
|
||||
load();apply();
|
||||
window.MosaicOrg?.ready?.then(()=>{load();apply();});
|
||||
document.addEventListener('mosaic-org-switch',()=>{load();apply();});
|
||||
window.MosaicDisplay={get:()=>({...saved}),setDensity(density){if(!['comfortable','compact'].includes(density))return false;saved={...saved,density};apply();try{localStorage.setItem(key(),JSON.stringify(saved));return true;}catch{return false;}}};
|
||||
})();
|
||||
|
||||
// P4 page: credentials and OAuth state exist only during the current operation.
|
||||
|
||||
@@ -17,3 +17,7 @@
|
||||
: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}
|
||||
.pack-applied{border-left:3px solid var(--border);padding:4px 0 4px 12px;margin:8px 0}
|
||||
.pack-applied p{margin:0 0 6px}
|
||||
.pack-open{list-style:none;margin:6px 0 8px;padding:0}
|
||||
.pack-open li{padding:4px 0;overflow-wrap:anywhere}
|
||||
@@ -3,6 +3,10 @@
|
||||
// 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.
|
||||
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): the owner's apply
|
||||
// hires the proposals in the same act. Each pack card says how many agents it hired and lists the
|
||||
// proposals still open with their reasons; "Hire the N proposed agents" (POST .../packs/hire) runs the
|
||||
// same hire loop on the recorded entry.
|
||||
(() => {
|
||||
'use strict';
|
||||
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
@@ -25,7 +29,23 @@
|
||||
'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.',
|
||||
'pack-not-applied': 'Apply this pack first; its hires come from the applied entry.',
|
||||
'right-required': 'Hiring needs the org.hire right.',
|
||||
};
|
||||
// Why a hire did not happen, by the code the bus recorded. An unknown code is shown as itself.
|
||||
const HIRE_WHY = {
|
||||
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing',
|
||||
'no-chief-of-staff': 'the organization has no chief of staff',
|
||||
'hire-owner-required': 'it has flagged or credential lines only the owner approves',
|
||||
'definition-not-hireable': 'its role is on the no-hire list',
|
||||
'starter-pack-proposal-stale': 'the pack changed since it was applied; apply it again',
|
||||
'human-required': 'only a person can hire',
|
||||
'organization-busy': 'another pack hire on this organization was running',
|
||||
'outcome-unknown': 'the bus did not say why',
|
||||
};
|
||||
const whyText = code => HIRE_WHY[code] ?? code;
|
||||
const OPEN_STATE = { 'awaiting-owner': 'waiting for the owner in the inbox', proposed: 'proposed, not hired yet' };
|
||||
const plainObj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
const MARKS = {
|
||||
add: 'will be added',
|
||||
same: 'already the same',
|
||||
@@ -43,10 +63,11 @@
|
||||
// pack and the last receipt. A kept preview applies by its digest, so a stale one is refused by the bus.
|
||||
async function load(org) {
|
||||
const prev = states.get(org);
|
||||
const s = { packs: null, writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
|
||||
const s = { packs: null, applied: [], writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
|
||||
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.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
|
||||
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
|
||||
@@ -72,7 +93,11 @@
|
||||
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 hasCreds = Array.isArray(h.credentialLines) && h.credentialLines.length > 0;
|
||||
const owner = (Array.isArray(h.flagged) && h.flagged.length) || h.flagged === null || hasCreds;
|
||||
// The binding sentence only where the hire has a credential line to bind.
|
||||
const mark = h.mark === 'dropped' ? 'Not proposed: an agent or open hire decision already has this name.'
|
||||
: `Hired when you apply: applying is the hire decision${owner ? ', and approves the flagged and credential lines below' : ''}.${hasCreds ? ' A credential line is approved, not bound: the agent waits for a binding before it launches.' : ''}`;
|
||||
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>`;
|
||||
}
|
||||
@@ -87,6 +112,23 @@
|
||||
const apply = s.writable ? `<button class="btn" type="button" data-pack-apply data-focus-key="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>`;
|
||||
}
|
||||
// The pack's applied entries (one per project for a project pack): the agents it hired and its open proposals.
|
||||
function appliedBlock(org, s, entry) {
|
||||
const mine = s.applied.filter(a => a.id === entry.id && (a.origin ?? null) === (entry.origin ?? null));
|
||||
if (!mine.length) return '';
|
||||
return mine.map(a => {
|
||||
const where = a.project ? ` <span class="muted">in project ${esc(a.project)}</span>` : '';
|
||||
const n = a.hired.length;
|
||||
const hired = `<p data-pack-hired="${esc(a.project ?? '')}"><strong>${n === 0 ? 'No agents hired yet' : `${n} ${n === 1 ? 'agent' : 'agents'} hired`}</strong>${where}${n ? `: ${a.hired.map(x => `<code>${esc(x)}</code>`).join(', ')}` : ''}</p>`;
|
||||
const open = a.open.filter(plainObj);
|
||||
const lines = open.length ? `<ul class="pack-open" data-pack-open>${open.map(o => `<li data-pack-open-hire="${esc(o.name)}" data-pack-open-state="${esc(o.state)}"><code>${esc(o.name)}</code>: ${esc(o.reason || 'No reason given.')} <span class="muted">${esc(o.state === 'refused' ? `not hired: ${whyText(o.code)}` : OPEN_STATE[o.state] ?? o.state)}</span></li>`).join('')}</ul>` : '';
|
||||
// The page is the owner's, and the owner's pack hire also approves a line this pack's own hire
|
||||
// left in the inbox (fromPack). A decision raised some other way stays the inbox's.
|
||||
const hireable = open.filter(o => o.state !== 'awaiting-owner' || o.fromPack === true).length;
|
||||
const button = hireable && s.writable ? `<button class="btn" type="button" data-pack-hire-button data-pack-hire-project="${esc(a.project ?? '')}" data-focus-key="${esc(`pack-hire:${org}:${entry.id}:${a.project ?? ''}`)}">Hire the ${hireable} proposed ${hireable === 1 ? 'agent' : 'agents'}</button>` : '';
|
||||
return `<div class="pack-applied">${hired}${lines}${button}</div>`;
|
||||
}).join('');
|
||||
}
|
||||
function packRow(org, s, entry) {
|
||||
const pack = entry.pack;
|
||||
const project = pack.scope === 'project'
|
||||
@@ -96,13 +138,13 @@
|
||||
: '';
|
||||
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 data-focus-key="${esc(`pack-preview:${org}:${entry.id}`)}">Preview</button>` : ''}</li>`;
|
||||
<p>${esc(pack.description)}</p>${appliedBlock(org, s, entry)}${project}${canPreview ? `<button class="btn" type="button" data-pack-preview-button data-focus-key="${esc(`pack-preview:${org}:${entry.id}`)}">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)}" data-live-key="${esc(`packs:${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)}" data-live-key="${esc(`packs:${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>`;
|
||||
return `<section class="panel" data-packs data-packs-org="${esc(org)}" data-live-key="${esc(`packs:${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 hires the agents it proposes. Applying is the hire 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);
|
||||
@@ -114,14 +156,19 @@
|
||||
if (s) s.picks[select.closest('[data-pack]').dataset.pack] = select.value;
|
||||
});
|
||||
document.addEventListener('click', async e => {
|
||||
const button = e.target.closest('[data-pack-preview-button],[data-pack-apply]');
|
||||
const button = e.target.closest('[data-pack-preview-button],[data-pack-apply],[data-pack-hire-button]');
|
||||
if (!button) return;
|
||||
const root = button.closest('[data-packs-org]'), org = root?.dataset.packsOrg, s = states.get(org);
|
||||
if (!s) return;
|
||||
button.disabled = true;
|
||||
let applied = false;
|
||||
try {
|
||||
if (button.hasAttribute('data-pack-preview-button')) {
|
||||
if (button.hasAttribute('data-pack-hire-button')) {
|
||||
const pack = button.closest('[data-pack]').dataset.pack, project = button.dataset.packHireProject;
|
||||
const r = await call(`${base(org)}/packs/hire`, { pack, ...(project ? { project } : {}) });
|
||||
s.status = hireSummary(r.hires);
|
||||
applied = true;
|
||||
} else 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) };
|
||||
@@ -131,15 +178,31 @@
|
||||
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.`;
|
||||
s.status = `Applied. Added ${added}. ${typeof r.hireError === 'string' ? `The hires did not run: ${whyText(r.hireError)}. Use Hire on the pack card to run them.` : hireSummary(r.hires)}`;
|
||||
applied = true;
|
||||
}
|
||||
} catch (error) { s.status = error.message; }
|
||||
// An apply or a hire reads the packs again, so the card's hired count and open proposals are the bus's now.
|
||||
if (applied) await load(org);
|
||||
// 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); }
|
||||
// An apply changes the workflows, the board and the roles too: the page and any pane showing this
|
||||
// organization read every section again. The receipt above is kept in state, so it survives that read.
|
||||
if (applied) document.dispatchEvent(new CustomEvent('mosaic-org-changed', { detail: { org } }));
|
||||
});
|
||||
// One line for the hires an apply or a hire made, from the bus's answer.
|
||||
function hireSummary(hires) {
|
||||
const list = Array.isArray(hires) ? hires.filter(plainObj) : [];
|
||||
if (!list.length) return 'The pack proposes no hires.';
|
||||
const names = state => list.filter(h => h.state === state).map(h => h.name);
|
||||
const parts = [];
|
||||
const hired = names('hired'), waiting = names('awaiting-owner'), exists = names('exists'), open = names('open');
|
||||
if (hired.length) parts.push(`Hired ${hired.join(', ')}.`);
|
||||
if (waiting.length) parts.push(`Sent to the owner's inbox: ${waiting.join(', ')}.`);
|
||||
if (open.length) parts.push(`Already waiting as a decision: ${open.join(', ')}.`);
|
||||
if (exists.length) parts.push(`Already hired: ${exists.join(', ')}.`);
|
||||
for (const h of list.filter(h => h.state === 'refused')) parts.push(`Not hired: ${h.name}, ${whyText(h.code)}.`);
|
||||
return parts.join(' ');
|
||||
}
|
||||
window.MosaicPacks = { load, section };
|
||||
})();
|
||||
@@ -27,10 +27,14 @@
|
||||
}
|
||||
document.addEventListener('focusin',e=>{const tab=e.target.closest?.('.project-tabs a'); if(tab) revealTab(tab.parentElement,tab);});
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const storageKey=window.MosaicOrg ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree';
|
||||
// #1873 SP1: the tree and its open/closed state belong to the open organization; a switch drops both.
|
||||
const storageKey=()=>window.MosaicOrg?.id ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree';
|
||||
let treeRows=[], treeThreads=[], treeGeneration=0, treeState, treeRead=null, treeReadAt=0;
|
||||
const treeFocus = new WeakMap();
|
||||
try { treeState=JSON.parse(localStorage.getItem(storageKey) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; }
|
||||
const loadTreeState=()=>{ try { treeState=JSON.parse(localStorage.getItem(storageKey()) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; } };
|
||||
loadTreeState();
|
||||
window.MosaicOrg?.ready?.then(loadTreeState);
|
||||
document.addEventListener('mosaic-org-switch',()=>{ treeGeneration++; treeRows=[]; treeThreads=[]; treeRead=null; treeReadAt=0; loadTreeState(); });
|
||||
// A side-by-side pane reads its own organization: its reads name that organization explicitly.
|
||||
const at=(org,url)=>org && url.startsWith('/api/') ? `/api/orgs/${encodeURIComponent(org)}/${url.slice(5)}` : url;
|
||||
async function read(url) {
|
||||
@@ -76,7 +80,7 @@
|
||||
target?.focus({preventScroll:true});
|
||||
}
|
||||
treeFocus.delete(container);
|
||||
container.onclick=e=>{const button=e.target.closest('[data-project-disclosure]');if(!button)return;const id=button.dataset.projectDisclosure;treeState[id]=button.getAttribute('aria-expanded')!=='true';try{localStorage.setItem(storageKey,JSON.stringify(treeState));}catch{}drawTree(container,route);container.querySelector(`[data-project-disclosure="${id}"]`)?.focus();};
|
||||
container.onclick=e=>{const button=e.target.closest('[data-project-disclosure]');if(!button)return;const id=button.dataset.projectDisclosure;treeState[id]=button.getAttribute('aria-expanded')!=='true';try{localStorage.setItem(storageKey(),JSON.stringify(treeState));}catch{}drawTree(container,route);container.querySelector(`[data-project-disclosure="${id}"]`)?.focus();};
|
||||
} catch { if(generation===treeGeneration && container.isConnected && !document.body.classList.contains('signed-out')) {
|
||||
treeRead=null;
|
||||
const active=document.activeElement;
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
const txt = value => esc(inert(value));
|
||||
const enc = encodeURIComponent;
|
||||
const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
|
||||
const STORE = window.MosaicOrg ? `mosaic-request-answer:${window.MosaicOrg.id}:` : 'mosaic-request-answer:';
|
||||
// #1873 SP1: read per call, so answers stay with the organization open when they were written.
|
||||
const storeOf = () => window.MosaicOrg?.id ? `mosaic-request-answer:${window.MosaicOrg.id}:` : 'mosaic-request-answer:';
|
||||
const QUESTION_PHASES = ['discovery', 'prd-review', 'planning'];
|
||||
const MODE_PHASES = [...QUESTION_PHASES, 'implementation', 'review', 'delivery'];
|
||||
const PICKER_CODES = ['request-existing-project', 'request-attachment-selected'];
|
||||
@@ -55,15 +56,15 @@
|
||||
// removed once the bus has answered either way, so only a lost response leaves one behind.
|
||||
const load = id => {
|
||||
try {
|
||||
const v = JSON.parse(sessionStorage.getItem(STORE + id));
|
||||
const v = JSON.parse(sessionStorage.getItem(storeOf() + id));
|
||||
return v && text(v.op) && ID.test(v.op) && text(v.text) && text(v.question) && ID.test(v.question) && positive(v.revision)
|
||||
? { op: v.op, text: v.text, question: v.question, revision: v.revision } : null;
|
||||
} catch { return null; }
|
||||
};
|
||||
const save = (id, record) => { try { sessionStorage.setItem(STORE + id, JSON.stringify(record)); } catch { /* kept in memory only */ } };
|
||||
const drop = id => { try { sessionStorage.removeItem(STORE + id); } catch { /* nothing stored */ } };
|
||||
const save = (id, record) => { try { sessionStorage.setItem(storeOf() + id, JSON.stringify(record)); } catch { /* kept in memory only */ } };
|
||||
const drop = id => { try { sessionStorage.removeItem(storeOf() + id); } catch { /* nothing stored */ } };
|
||||
const dropAll = () => {
|
||||
try { for (const key of Object.keys(sessionStorage)) if (key.startsWith(STORE)) sessionStorage.removeItem(key); } catch { /* nothing stored */ }
|
||||
try { for (const key of Object.keys(sessionStorage)) if (key.startsWith(storeOf())) sessionStorage.removeItem(key); } catch { /* nothing stored */ }
|
||||
};
|
||||
|
||||
function forget() {
|
||||
|
||||
@@ -550,6 +550,11 @@ html[data-organizations] .ws-levels .mlabel{display:none;align-items:center;gap:
|
||||
html[data-organizations] .ws-agent{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:2px 10px 2px 8px;font-size:12.5px;font-weight:600;background:var(--canvas);margin:2px 4px 2px 0;color:var(--strong)}
|
||||
html[data-organizations] .ws-agent small{color:var(--muted);font-weight:500;font-size:11px}
|
||||
html[data-organizations] .ws-agent .ws-dot b{font-size:11px;width:10px}
|
||||
html[data-organizations] .ws-agent{flex-wrap:wrap}
|
||||
html[data-organizations] .ws-agent .btn{min-height:24px;padding:0 10px;font-size:11.5px;border-radius:999px}
|
||||
html[data-organizations] .ws-fire-confirm{display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px;font-weight:500}
|
||||
html[data-organizations] [data-agents-receipt]:empty{display:none}
|
||||
html[data-organizations] [data-agents-receipt] .receipt{margin:0 0 12px}
|
||||
html[data-organizations] .ws-rules{display:grid;gap:10px;font-size:13px}
|
||||
html[data-organizations] .ws-rules p{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;margin:0}
|
||||
html[data-organizations] .ws-psel{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:0 0 0 8px;font-size:13px;color:var(--strong);white-space:nowrap;max-width:100%}
|
||||
@@ -586,6 +591,18 @@ html[data-organizations] .ws-bar i{display:block;background:var(--org,var(--acti
|
||||
html[data-organizations] .ws-by{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:12px;color:var(--text)}
|
||||
html[data-organizations] .ws-by>span{display:inline-flex;align-items:center;gap:4px;white-space:nowrap;font-variant-numeric:tabular-nums}
|
||||
html[data-organizations] .ws-by .ws-av{width:14px;height:14px;border-radius:3px;font-size:7px}
|
||||
html[data-organizations] .ws-orgtbl td{vertical-align:top}
|
||||
html[data-organizations] .ws-orgtbl .who{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;min-width:0}
|
||||
html[data-organizations] .ws-orgtbl .who a{display:inline-flex;align-items:center;gap:8px;min-width:0;color:var(--strong);font-weight:700;text-decoration:none}
|
||||
html[data-organizations] .ws-orgtbl .who a:hover .nm{text-decoration:underline}
|
||||
html[data-organizations] .ws-orgtbl .who .ws-dot{font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-orgtbl .who .ws-dot.s-working b{color:var(--success)}
|
||||
html[data-organizations] .ws-orgtbl .who .why{flex:1 0 100%;font-size:12px;color:var(--danger);overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-orgtbl tr.off .ws-dot{color:var(--danger)}
|
||||
/* #1873 SP2: a figure keeps its words on one line ("4 agents (0 working)", "none waiting"); the organization cell takes the wrap. */
|
||||
html[data-organizations] .ws-orgtbl td:not(.who){white-space:nowrap}
|
||||
html[data-organizations] .ws-dash [data-org-down]{margin:0 0 14px}
|
||||
html[data-organizations] .ws-dash [data-org-down] .why{display:block;margin-top:4px;color:var(--muted)}
|
||||
html[data-organizations] .ws-orgcards{list-style:none;margin:0;padding:0;display:grid;gap:8px;grid-template-columns:repeat(auto-fill,minmax(220px,1fr))}
|
||||
html[data-organizations] .ws-orgcard a{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 10px;align-items:center;padding:9px 12px;border:1px solid var(--line);border-radius:8px;background:var(--surface);box-shadow:inset 3px 0 0 var(--org);color:var(--text);text-decoration:none;font-size:13px;height:100%}
|
||||
html[data-organizations] .ws-orgcard a:hover{background:var(--raised)}
|
||||
@@ -623,7 +640,7 @@ html[data-organizations] .ws-needs .ws-chip{grid-row:1/3;grid-column:3}
|
||||
html[data-organizations] .ws-more-line{margin:6px 0 0}
|
||||
html[data-organizations] .ws-sess td.who{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:0;width:100%}
|
||||
html[data-organizations] .ws-sess td.who .ws-orgref{vertical-align:middle}
|
||||
html[data-organizations] .ws-sess td.st{white-space:nowrap}
|
||||
html[data-organizations] .ws-sess td.ws-st{white-space:nowrap}
|
||||
/* Filters and tables on Projects and Inbox. */
|
||||
html[data-organizations] .ws-toolbar{display:flex;flex-wrap:wrap;gap:8px 10px;align-items:center;margin-bottom:12px}
|
||||
html[data-organizations] .ws-toolbar .ws-right{align-items:center}
|
||||
|
||||
@@ -104,7 +104,8 @@
|
||||
const root = document.getElementById('workspace-nav'); if (!root) return;
|
||||
const key = focusKey(root);
|
||||
if (orgError || !orgs) { root.innerHTML = `<hr class="ws-hr"><p class="ws-line">${orgError ? 'Organizations unavailable' : 'Reading organizations…'}</p>`; return; }
|
||||
const here = route(), selected = window.MosaicOrg?.id;
|
||||
// SP1: a system route (the dashboard) marks no organization; an organization route marks its own.
|
||||
const here = route(), selected = /^#\/orgs\//.test(location.hash) ? window.MosaicOrg?.id : null;
|
||||
const rows = orgs.map(org => {
|
||||
const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization';
|
||||
return `<li data-workspace-org="${esc(org.id)}"><a class="ws-nav ws-org-row${mine && !current ? ' sel' : ''}" href="${esc(orgHref(org.id))}/organization" data-focus-key="${esc(`org:${org.id}`)}"${current ? ' aria-current="page"' : ''}>${av(org)}<span class="t">${esc(label(org))}</span>${dot(cls, glyph, word, cls !== 's-working')}</a></li>`;
|
||||
@@ -227,6 +228,24 @@
|
||||
return Boolean(a && a.el.isConnected);
|
||||
}
|
||||
|
||||
// SP1: the reason an organization's bus can't be read, for its pages. `row` is its GET /api/workspace
|
||||
// status (state, reason, boot), or null when that read gave none.
|
||||
// A reason that only restates the heading ("the bus is not running", the server's fallback) is not
|
||||
// repeated; the last start time, when read, still shows.
|
||||
const restates = reason => /^the bus is not (running|answering)\.?$/i.test(reason.trim());
|
||||
const downWhy = row => (row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason ? `${row.reason}${row.boot?.at ? `, last start ${when(row.boot.at)}` : ''}` : '');
|
||||
// #1873 SP2: this is the page's only bus banner (the shell's "Bus unavailable" hides on this page), so
|
||||
// it carries the restart action where the Console allows it. A side-by-side pane has no restart.
|
||||
function downBanner(org, row, pane = false) {
|
||||
const stopped = org.busStopped === true;
|
||||
const plain = row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason && restates(row.reason);
|
||||
const why = plain ? '' : downWhy(row);
|
||||
const tail = plain
|
||||
? (row.boot?.at ? ` <span class="why">Last start ${esc(when(row.boot.at))}.</span>` : '')
|
||||
: why ? ` <span class="why">Reason: ${esc(why)}.</span>` : ' <span class="why">No reason was read.</span>';
|
||||
const restart = pane ? '' : window.MosaicConsole?.busButton?.('Restart the bus') || '';
|
||||
return `<div class="banner err" role="status" data-org-down><div><b>${stopped ? 'The bus is not running.' : 'The bus is not answering.'}</b> Nothing about ${esc(label(org))}'s agents or packs can be read until it ${stopped ? 'starts' : 'answers'}.${tail}</div>${restart ? `<div class="actions">${restart}</div>` : ''}</div>`;
|
||||
}
|
||||
// A side-by-side pane passes its own organization and { pane: true, idPrefix }: the pane has no bus
|
||||
// restart (that stays in the organization's full view) and its ids carry the pane's prefix.
|
||||
async function dashboard(id = window.MosaicOrg.id, opts = {}) {
|
||||
@@ -244,6 +263,8 @@
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
|
||||
const agents = rowsOf(value(6)), claims = rowsOf(value(7));
|
||||
const docRead = business?.business ? await docs(id, business.business.projects).catch(() => ({ rows: [], failed: true })) : null;
|
||||
// SP1: a bus that is down says so above everything else, with the reason the workspace read gives.
|
||||
const downRow = org.busHealthy ? null : await data.workspace({ org: id, sections: 'projects' }).then(b => arr(b?.orgs).find(r => r?.org === id) ?? null).catch(() => null);
|
||||
await window.MosaicConsole?.ready;
|
||||
const name = esc(label(org));
|
||||
const tracker = business?.business?.vars?.['tracker.kind'];
|
||||
@@ -290,8 +311,9 @@
|
||||
const stoppedPanel = (attr, title) => `<section class="panel" ${attr} data-bus-stopped><h3>${title}</h3><p class="note">Not read: the bus is stopped.</p></section>`;
|
||||
|
||||
return `<article class="ws ws-dash" data-org-dashboard>
|
||||
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/settings/organizations">Organizations</a><span aria-hidden="true">›</span><span>${name}</span></nav>
|
||||
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/dashboard">Dashboard</a><span aria-hidden="true">›</span><span>${name}</span></nav>
|
||||
<div class="ws-orghead ws-o" style="${colours(org)}">${av(org, 'lg')}<h1 tabindex="-1">${name}</h1><div class="ws-right">${bus}${reload}</div>${meta}</div>
|
||||
${org.busHealthy ? '' : downBanner(org, downRow, pane)}
|
||||
${docrow}
|
||||
<div class="ws-split">
|
||||
<section aria-label="Measures and sessions">
|
||||
@@ -320,6 +342,8 @@
|
||||
// only). Every status comes from the organization's bus: its instances, and since A3 the root and
|
||||
// project agent copies it booted with. Nothing here invents a status, a model or a memory.
|
||||
const NOT_RUNNING = ['s-idle', '–', 'not running'];
|
||||
// SP1: why a bus-backed read gave nothing, in the membership list's words.
|
||||
const busWord = org => (org?.busStopped === true ? 'the bus is stopped' : 'the bus is not answering');
|
||||
// A copy's status: running or not as the bus reports its runs, or why it can't launch.
|
||||
const CANT = ['s-error', '▲', "can't launch"];
|
||||
// #1873 CB5: the bus adds `binding` to a copy that needs a credential binding: its status code and
|
||||
@@ -364,10 +388,10 @@
|
||||
} else if (inst) {
|
||||
rows.push(...Object.entries(inst).map(([name, v]) => ({ name, level: 'org', definition: v?.definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] })));
|
||||
}
|
||||
if (!set && inst === null) return '<p class="ws-panel tight note">Agents unavailable. The bus did not answer the instance read.</p>';
|
||||
if (!set && inst === null) return `<p class="ws-panel tight note" data-agents-why>${selOrg?.busHealthy === false ? `Agents not read: ${busWord(selOrg)}.` : 'Agents unavailable. The bus did not answer the instance read.'}</p>`;
|
||||
if (!rows.length) return '<p class="ws-panel tight note">No agents configured</p>';
|
||||
const where = a => (a.level === 'root' ? 'Your root configuration' : a.level === 'org' ? `${label(selOrg)} file` : `${names(a.project)} project`);
|
||||
const sub = a => [a.definition && a.definition !== a.name ? a.definition : '', a.overrides?.length ? `replaces the ${a.overrides.map(o => (o.level === 'org' ? 'organization' : o.level)).join(' and ')} ${a.overrides.length > 1 ? 'definitions' : 'definition'}` : '', a.narrowed?.length ? `narrowed here: ${a.narrowed.join(', ')}` : ''].filter(Boolean).join(' · ');
|
||||
const sub = a => [a.definition && a.definition !== a.name ? a.definition : '', a.level === 'org' && typeof inst?.[a.name]?.pack?.id === 'string' ? `from pack ${inst[a.name].pack.id}` : '', a.overrides?.length ? `replaces the ${a.overrides.map(o => (o.level === 'org' ? 'organization' : o.level)).join(' and ')} ${a.overrides.length > 1 ? 'definitions' : 'definition'}` : '', a.narrowed?.length ? `narrowed here: ${a.narrowed.join(', ')}` : ''].filter(Boolean).join(' · ');
|
||||
const status = a => {
|
||||
if (a.assistant) return dot('s-unknown', '?', 'status not reported', true);
|
||||
if (a.level !== 'org') {
|
||||
@@ -417,7 +441,16 @@
|
||||
const n = Math.max(valid.length, 1);
|
||||
const cell = (org, inner, cls = '') => `<div class="ws-o${cls}" style="${colours(org)}" data-org="${esc(org.id)}"><span class="mlabel">${av(org, 'xs')}${esc(label(org))}</span>${inner}</div>`;
|
||||
const endc = i => (i === results.length - 1 ? ' endc' : '');
|
||||
const pill = (name, item, agents) => { const cos = item?.definition === 'chief-of-staff' || name === 'chief'; const [acls, aglyph, aword] = activity(name, item, agents); return `<span class="ws-agent${cos ? ' cos' : ''}">${dot(acls, aglyph, aword)}${esc(name)}${cos && name !== 'chief' ? ' <small>chief</small>' : ''}</span>`; };
|
||||
// Ruling 2026-11-14: a card names the pack that hired its agent, and the page's own organization
|
||||
// offers Fire on every card but the chief's and the assistant's (bus.js draws the control and its confirmation).
|
||||
const pill = (org, name, item, agents) => {
|
||||
const cos = item?.definition === 'chief-of-staff' || name === 'chief';
|
||||
const [acls, aglyph, aword] = activity(name, item, agents);
|
||||
const from = typeof item?.pack?.id === 'string' ? ` <small data-agent-pack="${esc(item.pack.id)}">from pack ${esc(item.pack.id)}</small>` : '';
|
||||
// No Fire the bus would refuse: the assistant (and any end-protected instance) is never fired.
|
||||
const fire = cos || item?.definition === 'assistant' || item?.endProtected === true ? '' : window.MosaicDecide?.fireControl(org.id, name) ?? '';
|
||||
return `<span class="ws-agent${cos ? ' cos' : ''}" data-agent-card="${esc(name)}">${dot(acls, aglyph, aword)}${esc(name)}${cos && name !== 'chief' ? ' <small>chief</small>' : ''}${from}${fire}</span>`;
|
||||
};
|
||||
// A root or project copy in one organization's cell: its status from that organization's bus, and
|
||||
// why it can't launch when it can't. No answer from the bus reads as unavailable, never as idle.
|
||||
const copyPill = (copies, agents, name, project, small) => {
|
||||
@@ -439,7 +472,7 @@
|
||||
const on = kept.filter(a => !own(a)), replaced = kept.filter(own);
|
||||
return cell(org, `${on.map(a => copyPill(copies, agents, a.name, null, 'copy')).join('') || '<span class="muted">none</span>'}${replaced.length ? `<span class="note ws-off">${esc(replaced.map(a => a.name).join(', '))} replaced by ${esc(label(org))}'s own</span>` : ''}${off.length ? `<span class="note ws-off">${esc(off.map(a => a.name).join(', '))} turned off for ${esc(label(org))}</span>` : ''}`, endc(i));
|
||||
}).join('');
|
||||
const orgRow = results.map(({ org, inst, agents }, i) => cell(org, inst === null ? '<span class="muted">Agents unavailable</span>' : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(k, v, agents)).join('') : '<span class="muted">No agents configured</span>', endc(i))).join('');
|
||||
const orgRow = results.map(({ org, inst, agents }, i) => cell(org, inst === null ? `<span class="muted" data-agents-why>${org.busHealthy === false ? `Agents not read: ${busWord(org)}` : 'Agents unavailable'}</span>` : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(org, k, v, agents)).join('') : '<span class="muted">No agents configured</span>', endc(i))).join('');
|
||||
// Project: the agents a project defines itself. Narrowing and exclusion show in the table.
|
||||
const projRow = results.map(({ org, lv, rows, copies, agents }, i) => {
|
||||
if (lv?.state !== 'ok') return cell(org, `<span class="muted">${lv?.state === 'invalid' ? 'Project agents unavailable: the organization file was refused' : 'Project agents unavailable'}</span>`, ` last${endc(i)}`);
|
||||
@@ -464,8 +497,9 @@
|
||||
const title = projectIds.length ? 'Available in a project' : `Agents in ${esc(label(selOrg))}`;
|
||||
const table = !mine ? '<p class="ws-panel tight note">The selected organization is not on the list.</p>' : levelsTable(ctx, pick);
|
||||
const rules = `<div class="ws-panel tight ws-rules"><p><span class="ws-lvl root">root</span>You define root agents in agents.json in your configuration directory. The chief cannot change them.</p><p><span class="ws-lvl org">org</span>Agents come from the organization file. Add, change or remove them under Settings, Agents.</p><p><span class="ws-lvl proj">project</span>A project in the organization file can add an agent, narrow an inherited agent's limits or exclude one. It never widens them.</p><p><span class="ws-lvl proj">override</span>The most specific level wins. A row says which definition it replaces.</p><p class="muted">An agent's harness, model and thinking are set under Settings, Routing.</p></div>`;
|
||||
return `<section class="ws ws-agents" data-org-agents>${head}${band}${levelsGrid}
|
||||
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available>${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
|
||||
const receipt = selected === window.MosaicOrg?.id ? `<div data-agents-receipt role="status">${window.MosaicDecide?.fireNote() ?? ''}</div>` : '';
|
||||
return `<section class="ws ws-agents" data-org-agents>${head}${receipt}${band}${levelsGrid}
|
||||
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available data-agents-org="${esc(selected)}">${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
|
||||
</section>`;
|
||||
}
|
||||
document.addEventListener('change', e => {
|
||||
@@ -539,7 +573,11 @@
|
||||
// ---- main dashboard (sample 02) ----
|
||||
async function home() {
|
||||
let body;
|
||||
try { [body] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), ensureThemes()]); took(body); }
|
||||
let levels = null, listed = null;
|
||||
// SP1: the agent counts come from the organization files (GET /api/agents/levels, owner only), so a
|
||||
// stopped bus still has one; the bus state words come from the membership list. Either read may
|
||||
// fail or be absent, and its column then shows no figure.
|
||||
try { [body, levels, listed] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), data.agentLevels().catch(() => null), data.organizations().catch(() => null), ensureThemes()]); took(body); }
|
||||
catch (err) { return failedPage('ws-home', 'data-ws-home', 'Dashboard', err); }
|
||||
const o = orgsOf(body), m = body.metrics, t = m?.totals, per = arr(m?.orgs);
|
||||
const inbox = arr(body.inbox), sessions = arr(body.sessions), projectRows = arr(body.projects), tasks = arr(body.tasks);
|
||||
@@ -563,11 +601,29 @@
|
||||
<div class="ws-tile quiet" data-ws-tile="spend"><span class="ws-label">Model spend</span><span class="ws-empty-t">No spend figures yet</span><span class="ws-delta">No model prices are read yet, so today's use has no cost figure.</span></div>
|
||||
</div>` : '<p class="ws-panel tight note" data-ws-tiles>No organization answered, so there are no totals yet.</p>';
|
||||
|
||||
const cards = o.rows.map(r => {
|
||||
const [cls, glyph, word] = orgState(r), id = r.org;
|
||||
const extra = r.state === 'ok' ? '' : `<span class="why">${esc(r.reason || '')}${r.boot?.at ? `${r.reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}</span>`;
|
||||
return `<li class="ws-orgcard ws-o${r.state === 'ok' ? '' : ' off'}" style="${o.style(id)}" data-ws-orgcard="${esc(id)}" data-state="${esc(r.state)}"><a href="${esc(orgHref(id))}/organization" data-focus-key="${esc(`orgcard:${id}`)}">${av(o.meta(id), 'md')}<span class="nm">${esc(o.name(id))}</span>${dot(cls, glyph, word, true)}<span class="at">read ${esc(hm(r.at))}</span>${extra}</a></li>`;
|
||||
// SP1 (sample r2-01): one row per organization. A figure shows only when its read gave it; an
|
||||
// organization that did not answer shows its state and reason instead of figures.
|
||||
const listRow = id => (Array.isArray(listed) ? listed.find(x => x?.id === id) : null);
|
||||
const projectsRead = readers(o, SRC.projects), inboxRead = readers(o, SRC.needs), sessionsRead = readers(o, SRC.sessions);
|
||||
const none = '<span class="muted" title="not read">–</span>';
|
||||
// The bus state as the workspace read found it; "stopped" only when the membership list says the owner stopped it.
|
||||
const ROW_STATE = { ok: ['s-working', '●', 'bus running'], starting: ['s-waiting', '◐', 'bus starting'], timeout: ['s-error', '▲', 'bus not answering'], invalid: ['s-error', '▲', 'invalid'] };
|
||||
const rowState = (r, fromList) => (r.state === 'down' ? ['s-offline', '○', fromList?.busStopped === true ? 'bus stopped' : 'bus down'] : ROW_STATE[r.state] || orgState(r));
|
||||
const orgTable = o.rows.map(r => {
|
||||
const id = r.org, fromList = listRow(id), x = per.find(p => p.org === id);
|
||||
const [cls, glyph, word] = rowState(r, fromList);
|
||||
const lv = levels?.orgs?.find(v => v?.id === id);
|
||||
const count = lv?.state === 'ok' && Array.isArray(lv.base?.agents) ? lv.base.agents.length : null;
|
||||
const working = x && sessionsRead.has(id) ? num(x.sessions?.working) : null;
|
||||
const agentsCell = count === null ? none : `${plural(count, 'agent')}${working === null ? '' : ` <small class="muted">(${working} working)</small>`}`;
|
||||
const projectsCell = x && projectsRead.has(id) ? plural(num(x.projects?.active), 'project') : none;
|
||||
const needsCell = x && inboxRead.has(id) ? (num(x.needsYou) ? `${num(x.needsYou)} needs you` : 'none waiting') : none;
|
||||
// #1873 SP2: a reason that only restates the state word ("the bus is not running" beside "bus stopped") is said once.
|
||||
const reason = r.state !== 'ok' && typeof r.reason === 'string' && r.reason && !restates(r.reason) ? r.reason : '';
|
||||
const why = r.state === 'ok' || !(reason || r.boot?.at) ? '' : `<span class="why">${esc(reason)}${r.boot?.at ? `${reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}</span>`;
|
||||
return `<tr class="ws-o${r.state === 'ok' ? '' : ' off'}" style="${o.style(id)}" data-ws-orgrow="${esc(id)}" data-state="${esc(r.state)}"><td class="who"><a href="${esc(orgHref(id))}/organization" data-focus-key="${esc(`orgrow:${id}`)}">${av(o.meta(id))}<span class="nm">${esc(o.name(id))}</span></a>${dot(cls, glyph, word, true)}${why}</td><td>${agentsCell}</td><td class="hide-m">${projectsCell}</td><td>${needsCell}</td></tr>`;
|
||||
}).join('');
|
||||
const orgList = o.rows.length ? `<div class="ws-tbl"><table class="ws-orgtbl" data-ws-orgs><thead><tr><th scope="col">Organization</th><th scope="col">Agents</th><th scope="col" class="hide-m">Projects</th><th scope="col">Needs you</th></tr></thead><tbody>${orgTable}</tbody></table></div>` : '<p class="ws-panel tight note" data-ws-orgs>No organizations yet</p>';
|
||||
|
||||
const recent = projectRows.filter(p => p.lastActivity).slice(0, 6);
|
||||
const STATE_WORD = { working: 'has a session working', waiting: 'is waiting on you', idle: 'has an idle session', none: 'no live session' };
|
||||
@@ -590,7 +646,7 @@
|
||||
const who = s => (s.kind === 'thread' ? s.instance || s.thread || 'thread' : s.role || 'agent');
|
||||
const what = s => s.project?.name || s.task?.title || '';
|
||||
const st = s => { const [cls, glyph, word] = s.kind === 'thread' ? ['s-working', '●', 'live'] : ACTIVITY[s.state] || ['s-unknown', '?', s.state || 'not reported']; return `${dot(cls, glyph, word === 'waiting on you' ? 'waiting' : word, true)}${s.state === 'waiting' ? ' <span class="muted">on you</span>' : s.since ? ` <span class="muted">${esc(span(s.since))}</span>` : ''}`; };
|
||||
const sessTable = now.length ? `<div class="ws-tbl"><table class="ws-sess" data-ws-sessions><thead><tr><th scope="col">Agent and project</th><th scope="col">Status</th></tr></thead><tbody>${now.slice(0, 8).map(s => `<tr><td class="who"><span class="ws-orgref">${av(o.meta(s.org), 'xs')}<span class="ws-sr">${esc(o.name(s.org))}: </span>${esc(who(s))}</span>${what(s) ? `<span class="muted"> · ${esc(what(s))}</span>` : ''}</td><td class="st">${st(s)}</td></tr>`).join('')}</tbody></table></div>${now.length > 8 ? `<p class="note ws-more-line">${now.length - 8} more on Agents</p>` : ''}` : `<p class="ws-panel tight note" data-ws-sessions>${noneRead(o, ['agents', 'claims']) ? 'Sessions not read' : `No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}`}</p>`;
|
||||
const sessTable = now.length ? `<div class="ws-tbl"><table class="ws-sess" data-ws-sessions><thead><tr><th scope="col">Agent and project</th><th scope="col">Status</th></tr></thead><tbody>${now.slice(0, 8).map(s => `<tr><td class="who"><span class="ws-orgref">${av(o.meta(s.org), 'xs')}<span class="ws-sr">${esc(o.name(s.org))}: </span>${esc(who(s))}</span>${what(s) ? `<span class="muted"> · ${esc(what(s))}</span>` : ''}</td><td class="ws-st">${st(s)}</td></tr>`).join('')}</tbody></table></div>${now.length > 8 ? `<p class="note ws-more-line">${now.length - 8} more on Agents</p>` : ''}` : `<p class="ws-panel tight note" data-ws-sessions>${noneRead(o, ['agents', 'claims']) ? 'Sessions not read' : `No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}`}</p>`;
|
||||
|
||||
const total = t ? num(t.projects?.active) + num(t.projects?.archived) : null;
|
||||
const allRead = !o.unread.length;
|
||||
@@ -600,10 +656,10 @@
|
||||
return `<article class="ws ws-home" data-ws-home>
|
||||
<div class="ws-vh"><h1 tabindex="-1">Dashboard</h1><p class="sub">${sub}</p></div>
|
||||
${tiles}
|
||||
${secH('Organizations', `read ${esc(hm(body.readAt))}`)}
|
||||
<ul class="ws-orgcards" data-ws-orgs>${cards || '<li class="ws-line">No organizations yet</li>'}</ul>
|
||||
<div class="ws-split ws-home-split">
|
||||
<section aria-label="Projects and tasks">
|
||||
<section aria-label="Organizations, projects and tasks">
|
||||
${secH('Organizations', `read ${esc(hm(body.readAt))}`)}
|
||||
${orgList}
|
||||
${secH('Recent project activity', 'latest change per project; there is no activity feed yet', `<a href="${esc(selHref('/projects'))}" data-focus-key="home-projects">All projects</a>`)}
|
||||
${trail}${missLine(o, ['projects'], 'recent')}
|
||||
${secH('Tasks by state', 'open tasks, every tracker', `<a href="${esc(selHref('/tasks'))}" data-focus-key="home-tasks">Open tasks</a>`)}
|
||||
@@ -612,7 +668,7 @@
|
||||
<section aria-label="Needs you and sessions">
|
||||
${secH('Needs you', '', `<a href="${esc(selHref('/inbox'))}" data-focus-key="home-inbox">Inbox</a>`)}
|
||||
${needsList}${missLine(o, ['inbox'], 'needs')}
|
||||
${secH('Sessions now', '', `<a href="${esc(selHref('/agents'))}" data-focus-key="home-agents">Agents</a>`)}
|
||||
${secH('Active agents', 'sessions now', `<a href="${esc(selHref('/agents'))}" data-focus-key="home-agents">Agents</a>`)}
|
||||
${sessTable}${missLine(o, ['agents', 'claims'], 'sessions')}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@ const LIMIT = 4096;
|
||||
const codes = {
|
||||
'invalid-request': 400, 'template-secret-suspected': 400, 'starter-pack-invalid': 400,
|
||||
'project-not-found': 404,
|
||||
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409,
|
||||
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409, 'template-exists': 409,
|
||||
'human-required': 403, 'read-only': 403,
|
||||
'not-configured': 503, 'no-bus-host': 503,
|
||||
};
|
||||
|
||||
@@ -81,7 +81,8 @@ test('archive does not announce success for an unexpected response', { timeout:
|
||||
test('archiving the current organization switches to the remaining one', { timeout: 45000 }, async t => {
|
||||
const f = await fixture(t); await f.open('alpha');
|
||||
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
|
||||
await f.wait(`window.MosaicOrg?.id === 'beta' && document.querySelector('header')?.textContent.includes('beta')`);
|
||||
// #1873 SP1: the breadcrumb, not the header, names the open organization.
|
||||
await f.wait(`window.MosaicOrg?.id === 'beta' && /beta/i.test(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent ?? '')`);
|
||||
assert.equal((await registry.listOrgs(f.ctx)).find(e => e.id === 'alpha').state, 'archived');
|
||||
});
|
||||
|
||||
@@ -188,6 +189,8 @@ test('fresh archived organization page offers owner restore while writes stay re
|
||||
const f = await fixture(t); await f.open('beta');
|
||||
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
|
||||
await f.wait(`!document.querySelector('#org-archived').hidden`);
|
||||
// #1873 SP1: another organization's address no longer reloads the page, so a fresh page is loaded on purpose.
|
||||
await f.b.navigate('about:blank');
|
||||
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/beta/settings/organizations?org=beta`);
|
||||
await f.wait(`document.querySelector('#org-archived') && !document.querySelector('#org-archived').hidden`);
|
||||
assert.equal(await f.b.evaluate(`document.querySelector('#org-restore').disabled`), false);
|
||||
@@ -200,6 +203,16 @@ test('fresh archived organization page offers owner restore while writes stay re
|
||||
assert.equal((await registry.listOrgs(f.ctx)).find(e => e.id === 'beta').state, 'active');
|
||||
});
|
||||
|
||||
// #1873 SP1: opening the archived organization's page in place (no reload) shows its restore command.
|
||||
test('an archived organization opened in place shows its restore command', { timeout: 45000 }, async t => {
|
||||
const f = await fixture(t); await f.open('beta');
|
||||
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
|
||||
await f.wait(`!document.querySelector('#org-archived').hidden`);
|
||||
await f.b.evaluate(`window.__sameDocument = true; location.hash = '#/orgs/beta/settings/organizations?org=beta'`);
|
||||
await f.wait(`window.MosaicOrg?.id === 'beta' && /mosaic org restore beta --if-revision \\d+/.test(document.querySelector('#org-archived')?.innerText ?? '')`);
|
||||
assert.equal(await f.b.evaluate(`window.__sameDocument`), true);
|
||||
});
|
||||
|
||||
test('owner can start a down bus after setup recorded done and sees recovery guidance on refusal', { timeout: 45000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
await f.b.evaluate(`(()=>{const old=window.fetch;window.fetch=async (input,init={})=>{const u=String(input);if(u.endsWith('/setup') && (!init.method || init.method==='GET'))return new Response(JSON.stringify({notifications:{state:'done'},queue:{state:'done'},projects:[],bus:{state:'done',verb:'mosaic bus start alpha'}}),{status:200});if(u.endsWith('/setup/bus') && init.method==='POST')return new Response(JSON.stringify({error:'stale-lock',message:'stale bus host lock'}),{status:409});return old(input,init)}})()`);
|
||||
@@ -233,6 +246,8 @@ for (const capability of [{ user:true, orgSetup:false }, { tester:true, orgSetup
|
||||
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
|
||||
await f.wait(`!document.querySelector('#org-archived').hidden`);
|
||||
await f.b.call('Page.addScriptToEvaluateOnNewDocument', {source:`{const old=window.fetch;window.fetch=(input,init)=>input instanceof URL && input.pathname==='/api/config'?Promise.resolve(new Response(JSON.stringify(${JSON.stringify(capability)}),{status:200})):old(input,init)}`});
|
||||
// #1873 SP1: the stub applies to a new document; another organization's address alone no longer reloads.
|
||||
await f.b.navigate('about:blank');
|
||||
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/beta/settings/organizations?org=beta`);
|
||||
await f.wait(`document.querySelector('#org-archived') && !document.querySelector('#org-archived').hidden`);
|
||||
assert.equal(await f.b.evaluate(`document.querySelector('#org-restore').disabled`),true);
|
||||
|
||||
@@ -78,8 +78,9 @@ test('deleting the current organization switches the Console to a remaining orga
|
||||
await b.evaluate(`document.querySelector('#org-open-form button').click()`);
|
||||
await wait(`document.querySelector('#org-delete') && !document.querySelector('#org-delete').hidden`);
|
||||
await b.evaluate(`document.querySelector('#org-delete-open').click();document.querySelector('#org-delete-continue').click();const i=document.querySelector('#org-delete-confirm');i.value='alpha';i.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('#org-delete-final').click()`);
|
||||
// #1873 SP1: the breadcrumb, not the header, names the open organization.
|
||||
let switched = false;
|
||||
for (let i = 0; i < 300 && !switched; i++) { try { switched = await b.evaluate(`window.MosaicOrg?.id === 'beta' && document.querySelector('header')?.textContent.includes('beta')`); } catch {} if (!switched) await new Promise(r => setTimeout(r, 30)); }
|
||||
for (let i = 0; i < 300 && !switched; i++) { try { switched = await b.evaluate(`window.MosaicOrg?.id === 'beta' && (document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent ?? '').includes('beta')`); } catch {} if (!switched) await new Promise(r => setTimeout(r, 30)); }
|
||||
assert.equal(switched, true); assert.deepEqual((await registry.listOrgs(ctx)).map(e => e.id), ['beta']);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// On a selected org's page, the header shows why the org list failed or which org is broken,
|
||||
// and Retry re-reads the list and clears the banner once it recovers (polish review F3, P19 #868).
|
||||
// #1873 SP1: the breadcrumb names the open organization; the header no longer does.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as fs from 'node:fs/promises';
|
||||
@@ -35,9 +36,9 @@ test('a registry error shows on a selected org page and Retry recovers', async t
|
||||
await wait(f.b, `(${bannerText}).includes('Organization registry could not be read') && document.querySelector('#held [data-retry]')`);
|
||||
const before = f.requests(); await fs.writeFile(file, original);
|
||||
await f.b.evaluate("document.querySelector('#held [data-retry]').click()");
|
||||
await wait(f.b, "!!document.querySelector('#current-organization') && !document.getElementById('org-list-banner')");
|
||||
await wait(f.b, "!!document.querySelector('#breadcrumbs [data-crumb-org]') && !document.getElementById('org-list-banner')");
|
||||
assert.ok(f.requests() > before, 'Retry re-read the organization list');
|
||||
assert.equal(await f.b.evaluate("document.querySelectorAll('#current-organization').length"), 1);
|
||||
assert.equal(await f.b.evaluate("document.querySelectorAll('#breadcrumbs [data-crumb-org]').length"), 1);
|
||||
});
|
||||
|
||||
test('a broken org banner is replaced, not stacked, and clears after repair', async t => {
|
||||
@@ -52,5 +53,5 @@ test('a broken org banner is replaced, not stacked, and clears after repair', as
|
||||
await fs.writeFile(file, original);
|
||||
await f.b.evaluate("document.querySelector('#held [data-retry]').click()");
|
||||
await wait(f.b, "!document.getElementById('org-list-banner')");
|
||||
assert.equal(await f.b.evaluate("document.querySelectorAll('#current-organization').length"), 1);
|
||||
assert.equal(await f.b.evaluate("document.querySelectorAll('#breadcrumbs [data-crumb-org]').length"), 1);
|
||||
});
|
||||
@@ -92,7 +92,8 @@ test('creating another organization opens its setup, receipt, header and theme',
|
||||
assert.ok(switched, 'new organization setup loaded after the switch');
|
||||
await b.evaluate('window.MosaicAppearance.ready');
|
||||
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/beta\/settings\/organizations\?org=beta&step=setup/);
|
||||
assert.match(await b.evaluate('document.querySelector("header").textContent'), /beta/);
|
||||
// SP1: the shell no longer names the organization in its header; the breadcrumb does.
|
||||
assert.match(await b.evaluate('document.querySelector("#breadcrumbs [data-crumb-org]").textContent'), /beta/);
|
||||
assert.equal(await b.evaluate('document.documentElement.dataset.palette'), 'cobalt');
|
||||
assert.match(await b.evaluate('document.querySelector("#org-receipt").textContent'), /Organization created.*beta/s);
|
||||
});
|
||||
@@ -142,18 +143,28 @@ test('sidebar lists organizations and navigating changes the route and header',
|
||||
await b.viewport(390, 900);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/settings/business`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelectorAll('[data-workspace-org]').length===2 && document.querySelector('#settings-page-title'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organizations did not appear')})()`);
|
||||
assert.match(await b.evaluate(`document.querySelector('header').textContent`), /Alpha/);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent==='Alpha')return;await new Promise(r=>setTimeout(r,30))}throw Error('organization crumb missing')})()`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#current-organization')`), null, 'the header does not name an organization');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization');
|
||||
await b.evaluate('window.__sameDocument = true');
|
||||
assert.equal(await b.evaluate(`!!document.querySelector('#org-picker')`), false);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(o=>o.dataset.workspaceOrg)`), ['alpha', 'beta']);
|
||||
await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`);
|
||||
let switched = false;
|
||||
for (let i = 0; i < 150 && !switched; i++) {
|
||||
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('header')?.textContent.includes('Beta')`); } catch { /* reload replaced the page */ }
|
||||
// The sidebar opens the organization's own page: its breadcrumb is Dashboard / Beta.
|
||||
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs')?.textContent === 'Dashboard/Beta'`); } catch { /* not ready */ }
|
||||
if (!switched) await new Promise(r => setTimeout(r, 30));
|
||||
}
|
||||
assert.equal(switched, true, 'switch completed after reload');
|
||||
assert.match(await b.evaluate(`document.querySelector('body').textContent`), /Bus unavailable/);
|
||||
assert.equal(switched, true, 'switch completed in place');
|
||||
assert.equal(await b.evaluate('window.__sameDocument'), true, 'the switch did not reload the page');
|
||||
// #1873 SP2: the organization's own page says the bus is down once, in its own banner; the shell's banner gives way there.
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-down]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('down banner missing')})()`);
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(await b.evaluate(`document.querySelector('#bus-down').hidden`), true, 'the organization page shows one bus banner');
|
||||
// On the organization's other pages the shell's banner still says it, and stays after the boot-status read.
|
||||
await b.evaluate(`location.hash = '#/orgs/beta/tasks'`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(!document.querySelector('#bus-down').hidden)return;await new Promise(r=>setTimeout(r,30))}throw Error('offline banner missing')})()`);
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(await b.evaluate(`document.querySelector('#bus-down').hidden`), false, 'offline banner remains visible after the boot-status read');
|
||||
assert.match(await b.evaluate(`document.querySelector('#bus-down').textContent`), /Bus unavailable/);
|
||||
@@ -193,7 +204,7 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy
|
||||
await b.evaluate(`document.querySelector('[data-discard]').click()`).catch(() => {});
|
||||
let switched = false;
|
||||
for (let i = 0; i < 150 && !switched; i++) {
|
||||
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('header')?.textContent.includes('Beta')`); } catch {}
|
||||
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {}
|
||||
if (!switched) await new Promise(r => setTimeout(r, 30));
|
||||
}
|
||||
assert.equal(switched, true);
|
||||
@@ -212,15 +223,9 @@ test('organization switch isolates browser board preferences', async t => {
|
||||
await b.navigate(base + '#/orgs/alpha/');
|
||||
await b.evaluate(`document.querySelector('#show-machine').click()`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), true);
|
||||
// The switch reloads the page. The navigate helper's load checks can be in flight when that
|
||||
// reload commits, so set the hash in the page and poll one short check at a time.
|
||||
// #1873 SP1: the switch happens in place, with no reload, and beta's own board setting applies.
|
||||
await b.evaluate(`location.hash = '#/orgs/beta/'`);
|
||||
let loaded = false;
|
||||
for (let i = 0; i < 150 && !loaded; i++) {
|
||||
try { loaded = await b.evaluate(`window.MosaicOrg?.id === 'beta' && !!document.querySelector('#show-machine')`); } catch {}
|
||||
if (!loaded) await new Promise(r => setTimeout(r, 30));
|
||||
}
|
||||
assert.equal(loaded, true, 'beta did not load');
|
||||
await b.evaluate(`(async () => { for (let i = 0; i < 150; i++) { if (window.MosaicOrg?.id === 'beta' && !!document.querySelector('#show-machine')) return; await new Promise(r => setTimeout(r, 30)); } throw Error('beta did not load'); })()`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), false);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" Driven in Chromium
|
||||
// against stand-in pack, instance and decision verbs: the owner's apply hires the pack's proposals, the
|
||||
// pack card says how many agents it hired and lists the open proposals with their reasons, and "Hire the
|
||||
// N proposed agents" runs the hire again. The Agents page shows the new cards, each naming its pack, in
|
||||
// the same response cycle as the write, and Fire removes a card at once with a receipt. Each wait is
|
||||
// at most three seconds, well inside the page's ten-second poll, so the write's own redraw shows them.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const REV = n => String(n).repeat(64);
|
||||
const waitFor = (b, expression, what, tries = 100) => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(what)}+': '+document.body.innerText.slice(0,2000))})()`);
|
||||
const PACKS = [{ id: 'software-team', origin: 'shipped', pack: { label: 'Software team', description: 'Roles, a board and a review workflow.', version: '1.0.0', scope: 'organization' } }];
|
||||
const FROM = { id: 'software-team', origin: 'shipped', project: null }; // the bus's instances read shape (pack-hire.test.mjs)
|
||||
const PREVIEW = {
|
||||
pack: { id: 'software-team', version: '1.0.0', label: 'Software team', origin: 'shipped', scope: 'organization' },
|
||||
project: null, revision: REV('c'),
|
||||
items: [{ item: 'board', name: 'board', target: 'board', path: 'board', mark: 'add' }],
|
||||
hires: [
|
||||
{ name: 'coder-1', definition: 'coder', mark: 'propose', pin: null, flagged: [{ field: 'tools', value: 'bash', reasons: ['above-chief'] }], credentialLines: [{ service: 'gitea', scope: 'repo:write' }], noHire: false },
|
||||
{ name: 'reviewer-1', definition: 'reviewer', mark: 'propose', pin: null, flagged: [], credentialLines: [], noHire: false },
|
||||
{ name: 'scout-1', definition: 'scout', mark: 'propose', pin: null, flagged: [], credentialLines: [], noHire: false },
|
||||
],
|
||||
skills: { notEnabled: [] }, chief: true, plan: {}, digest: REV('d'),
|
||||
};
|
||||
|
||||
// busy: the bus's apply committed but its hire loop did not run (hireError), and the packs read lists one line a
|
||||
// member's pack hire left in the owner's inbox (fromPack), one raised some other way and one refused.
|
||||
async function fixture(t, { busy = false } = {}) {
|
||||
const verbs = [], decisions = [];
|
||||
const hired = new Map(); // name -> its pack provenance, as the bus's instances read reports it
|
||||
let applied = null, route = false, instanceReads = 0;
|
||||
const instances = () => ({ chief: { definition: 'chief-of-staff', running: [] }, assistant: { definition: 'assistant', running: [], protected: true, endProtected: true }, ...Object.fromEntries([...hired].map(([n, pack]) => [n, { definition: n.split('-')[0], running: [], pack }])) });
|
||||
// The bus's hire loop, stood in: with a route every open proposal is hired; without one scout-1 is refused.
|
||||
const hireLoop = () => PREVIEW.hires.map(h => {
|
||||
if (hired.has(h.name)) return { name: h.name, state: 'exists' };
|
||||
if (!route && h.name === 'scout-1') return { name: h.name, state: 'refused', code: 'pack-hire-route-missing' };
|
||||
hired.set(h.name, FROM); const decision = `d-${hired.size}`; decisions.push(decision);
|
||||
return { name: h.name, state: 'hired', decision };
|
||||
});
|
||||
const listed = () => applied ? [{ id: 'software-team', origin: 'shipped', project: null, hired: [...hired.keys()],
|
||||
open: PREVIEW.hires.filter(h => !hired.has(h.name)).map(h => ({ name: h.name, reason: `Proposed by starter pack software-team for ${h.definition} work.`,
|
||||
...(!busy || h.name === 'scout-1' ? { state: 'refused', code: 'pack-hire-route-missing' } : { state: 'awaiting-owner', decision: `inbox-${h.name}`, ...(h.name === 'coder-1' ? { fromPack: true } : {}) }) })) }] : [];
|
||||
const read = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'packs.console') return { packs: PACKS, applied: listed() };
|
||||
if (verb === 'pack.preview.console') return PREVIEW;
|
||||
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const write = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'pack.apply.console') { applied = true; return { revision: REV('f'), added: ['board'], pack: { id: args.pack, version: '1.0.0' }, ...(busy ? { hires: [], hireError: 'organization-busy' } : { hires: hireLoop() }) }; }
|
||||
if (verb === 'pack.hire.console') return { pack: args.pack, hires: hireLoop() };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const decisionWrite = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'hire.start.console' && args.op === 'fire' && hired.has(args.name)) { hired.delete(args.name); return { id: 'fire-1', op: 'resolved', choice: 'yes' }; }
|
||||
throw Object.assign(new Error('invalid-request'), { code: 'invalid-request' });
|
||||
};
|
||||
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, requestRead: read, requestWrite: read, packsWrite: write,
|
||||
workflowsRead: async () => ({ revision: REV('a'), document: { workflows: {}, projects: {}, definitions: {} }, templates: [] }), send: async () => ({}),
|
||||
reads: { business: async () => ({ business: { id: 'acme', projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
|
||||
bus: { instances: async () => { instanceReads++; return { revision: REV('b'), instances: instances(), definitions: {} }; }, 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);
|
||||
return { b, verbs, decisions, port: server.address().port, reads: () => instanceReads, setRoute: v => { route = v; } };
|
||||
}
|
||||
|
||||
const shot = async (b, name, selector) => {
|
||||
if (!process.env.MOSAIC_UX_SHOTS) return;
|
||||
await mkdir(process.env.MOSAIC_UX_SHOTS, { recursive: true });
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(selector)})?.scrollIntoView({block:'start'});true`);
|
||||
await b.screenshot(join(process.env.MOSAIC_UX_SHOTS, `${name}.png`));
|
||||
};
|
||||
|
||||
test('PD apply hires the proposals, the pack card counts them, Hire the N proposed agents hires the rest, Agents shows and fires them without a poll', { timeout: 90000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const { b, verbs } = f;
|
||||
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/agents`);
|
||||
await waitFor(b, `document.querySelector('[data-org-agents] [data-agent-card="chief"]')`, 'agents before');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-card]').length`), 2);
|
||||
// Fire is offered on neither the chief nor the assistant: the bus would refuse both.
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-fire]').length`), 0);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agent-card="chief"] [data-agent-fire]')`), null, 'the chief has no Fire');
|
||||
await shot(b, 'agents-before-1440', '[data-org-agents]');
|
||||
|
||||
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
|
||||
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"] [data-pack-hired]')`), null, 'nothing applied yet');
|
||||
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-pack-preview]')`, 'preview');
|
||||
// The preview says the apply is the hire decision and that the owner's apply approves the flagged and credential lines.
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-pack-hire="coder-1"]').textContent`), /Hired when you apply: applying is the hire decision, and approves the flagged and credential lines below\. A credential line is approved, not bound/);
|
||||
// A hire with no credential line says nothing about binding one.
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-pack-hire="reviewer-1"] p').textContent`), /^Hired when you apply: applying is the hire decision\.$/);
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelector('[data-pack-hire="reviewer-1"]').textContent`), /flagged and credential lines/);
|
||||
await shot(b, 'pack-card-before-1440', '[data-pack="software-team"]');
|
||||
|
||||
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. Hired coder-1, reviewer-1. Not hired: scout-1, neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing.');
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-hired]')`, 'hired count');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hired]').textContent`), '2 agents hired: coder-1, reviewer-1');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-open-hire]')].map(l=>[l.dataset.packOpenHire,l.dataset.packOpenState,l.textContent])`),
|
||||
[['scout-1', 'refused', 'scout-1: Proposed by starter pack software-team for scout work. not hired: neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing']]);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 1 proposed agent');
|
||||
await shot(b, 'pack-card-after-1440', '[data-pack="software-team"]');
|
||||
|
||||
// The route is set; the card's action hires the remaining proposal, the same loop, and nothing twice.
|
||||
f.setRoute(true);
|
||||
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-packs-status]').textContent.startsWith('Hired scout-1.')`, 'hire status');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Hired scout-1. Already hired: coder-1, reviewer-1.');
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
|
||||
await waitFor(b, `document.querySelector('[data-pack-hired]').textContent.startsWith('3 agents hired')`, 'hired count 3');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]')`), null, 'nothing left to hire');
|
||||
assert.equal(f.decisions.length, 3);
|
||||
|
||||
// The Agents page: three new cards, each naming its pack.
|
||||
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/agents`);
|
||||
await waitFor(b, `document.querySelectorAll('[data-org-agents] [data-agent-card]').length===5`, 'agents after');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-org-agents] [data-agent-card] [data-agent-pack]')].map(s=>[s.closest('[data-agent-card]').dataset.agentCard,s.textContent])`),
|
||||
[['coder-1', 'from pack software-team'], ['reviewer-1', 'from pack software-team'], ['scout-1', 'from pack software-team']]);
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-agents-available] tr[data-agent="coder-1"]')?.textContent ?? ''`), /from pack software-team/);
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true);
|
||||
await shot(b, 'agents-after-1440', '[data-org-agents]');
|
||||
|
||||
// Fire asks first; Cancel fires nothing.
|
||||
const card = `[data-org-agents] [data-agent-card="reviewer-1"]`;
|
||||
await b.evaluate(`document.querySelector('${card} [data-agent-fire]').click();true`);
|
||||
await waitFor(b, `document.querySelector('${card} [data-agent-fire-no]')`, 'fire confirm');
|
||||
await b.evaluate(`document.querySelector('${card} [data-agent-fire-no]').click();true`);
|
||||
await waitFor(b, `document.querySelector('${card} [data-agent-fire]')`, 'kept');
|
||||
assert.equal(verbs.filter(([v]) => v === 'hire.start.console').length, 0);
|
||||
// Confirm: the card goes at once, the receipt names the decision, and the page reads the bus again.
|
||||
await b.evaluate(`document.querySelector('${card} [data-agent-fire]').click();true`);
|
||||
await waitFor(b, `document.querySelector('${card} [data-agent-fire-yes]')`, 'fire confirm again');
|
||||
const before = f.reads();
|
||||
await b.evaluate(`document.querySelector('${card} [data-agent-fire-yes]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-agents-receipt]')?.textContent.includes('Fired reviewer-1')`, 'fire receipt');
|
||||
assert.equal(await b.evaluate(`document.querySelector('${card}')`), null);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agents-available] tr[data-agent="reviewer-1"]')`), null);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agents-receipt]').textContent`), 'Fired reviewer-1. Recorded decision fire-1.');
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'hire.start.console').map(([, a]) => a), [{ op: 'fire', level: 'org', name: 'reviewer-1', reason: 'Fired from the Agents page.' }]);
|
||||
// The redraw the fire asked for reads the instances again and keeps the receipt.
|
||||
for (let i = 0; i < 100 && f.reads() <= before; i++) await new Promise(r => setTimeout(r, 30));
|
||||
assert.ok(f.reads() > before, 'the fire redraws the page from a fresh read');
|
||||
await waitFor(b, `document.querySelector('[data-agents-receipt]')?.textContent.includes('Fired reviewer-1')&&document.querySelectorAll('[data-org-agents] [data-agent-card]').length===4`, 'redrawn');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-card]').length`), 4);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agents-receipt]').textContent`), 'Fired reviewer-1. Recorded decision fire-1.');
|
||||
});
|
||||
|
||||
test('PD an apply whose hire loop did not run says so; the owner card counts a pack-raised inbox line as hireable and leaves the inbox its own', { timeout: 90000 }, async t => {
|
||||
const f = await fixture(t, { busy: true });
|
||||
const { b } = f;
|
||||
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
|
||||
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-apply]')`, 'preview');
|
||||
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. The hires did not run: another pack hire on this organization was running. Use Hire on the pack card to run them.');
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-open]')`, 'open lines');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-open-hire]')].map(l=>[l.dataset.packOpenHire,l.dataset.packOpenState])`),
|
||||
[['coder-1', 'awaiting-owner'], ['reviewer-1', 'awaiting-owner'], ['scout-1', 'refused']]);
|
||||
// coder-1 was left in the inbox by a pack hire, so the owner's pack hire approves it; reviewer-1 is the inbox's.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 2 proposed agents');
|
||||
});
|
||||
@@ -25,12 +25,14 @@ 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 } = {}) {
|
||||
async function fixture(t, { send = true, workflows = true, route = false, tap = null } = {}) {
|
||||
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'] };
|
||||
// Ruling 2026-11-14: a hire runs as the chief's harness and model, else the assistant's (lane pr2); this fixture has no assistant, so without a chief route it refuses pack-hire-route-missing.
|
||||
if (route) doc.roles.chief.vars = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
const file = writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const business = loadBusiness('demo', { dir: root, rolesDir });
|
||||
@@ -55,7 +57,9 @@ async function fixture(t, { send = true, workflows = true } = {}) {
|
||||
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'));
|
||||
// tap: a test's view of each write's bus result before the route shapes it.
|
||||
const writer = packsCaller(consoleCall('write'));
|
||||
const packsWrite = tap ? async (verb, args, ctx) => tap(verb, await writer(verb, args, ctx)) : writer;
|
||||
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: () => ({}) };
|
||||
@@ -69,7 +73,7 @@ async function fixture(t, { send = true, workflows = true } = {}) {
|
||||
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'; } };
|
||||
return { base, file, root, calls, onDisk, broker: runtime.broker, flowReads, boardHits, failFlows: () => { flowFails = true; }, signOut: () => { active = false; }, revokeOwner: () => { session.rootOwner = false; session.user = 'legacy-user'; } };
|
||||
}
|
||||
|
||||
function call(f, path, method = 'GET', body, headers = {}) {
|
||||
@@ -166,8 +170,8 @@ test('SP4 the admission checks refuse before any bus call; a read-only Console s
|
||||
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']);
|
||||
// The fenced writer calls nothing but the four write verbs.
|
||||
assert.deepEqual(PACK_WRITE_VERBS, ['pack.apply.console', 'pack.hire.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);
|
||||
@@ -372,3 +376,73 @@ test('SP6 the pack picker and workflow files are the owner\'s: the tester listen
|
||||
assert.ok((await res.text()).length > 100, path);
|
||||
}
|
||||
});
|
||||
|
||||
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" The owner's apply
|
||||
// hires the proposals in the same act; the packs read names the agents hired and the open proposals;
|
||||
// the hire route runs the same loop on the recorded entry and hires nothing twice.
|
||||
test('PD the owner apply hires the proposals; the packs read lists them; the hire route hires nothing twice', async t => {
|
||||
const f = await fixture(t, { route: true });
|
||||
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
|
||||
const [applied, receipt] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
|
||||
assert.equal(applied, 200, JSON.stringify(receipt));
|
||||
assert.deepEqual(receipt.hires.map(h => [h.name, h.state, h.routeFrom]), [['pm-1', 'hired', 'chief'], ['coder-1', 'hired', 'chief'], ['reviewer-1', 'hired', 'chief']]);
|
||||
for (const h of receipt.hires) assert.match(h.decision, /^[0-9a-f-]{36}$/);
|
||||
const disk = f.onDisk();
|
||||
for (const h of receipt.hires) { assert.equal(disk.roles[h.name].hireDecision, h.decision); assert.ok(disk.launch.instances.includes(h.name)); }
|
||||
|
||||
const [, list] = await call(f, `${ORG}/packs`);
|
||||
assert.deepEqual(list.applied.map(a => [a.id, a.origin, a.project, a.hired.sort(), a.open]), [['coding', 'shipped', null, ['coder-1', 'pm-1', 'reviewer-1'], []]]);
|
||||
|
||||
const [hired, again] = await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding' });
|
||||
assert.equal(hired, 200, JSON.stringify(again));
|
||||
assert.deepEqual(again, { pack: 'coding', hires: [{ name: 'pm-1', state: 'exists' }, { name: 'coder-1', state: 'exists' }, { name: 'reviewer-1', state: 'exists' }] });
|
||||
assert.deepEqual(f.calls.at(-1), ['write', 'pack.hire.console', ['pack']]);
|
||||
const asked = f.calls.length;
|
||||
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding', as: [] })).map((x, i) => i ? x.error : x), [400, 'invalid-request']);
|
||||
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'GET')).map((x, i) => i ? x.error : x), [405, 'method-not-allowed']);
|
||||
assert.equal(f.calls.length, asked);
|
||||
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'research' })).map((x, i) => i ? x.error : x), [404, 'pack-not-applied']);
|
||||
});
|
||||
|
||||
test('PD with no chief route the apply records the pack and each hire says pack-hire-route-missing', async t => {
|
||||
const f = await fixture(t);
|
||||
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
|
||||
const [applied, receipt] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
|
||||
assert.equal(applied, 200, JSON.stringify(receipt));
|
||||
assert.deepEqual(receipt.hires.map(h => [h.name, h.state, h.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
const [, list] = await call(f, `${ORG}/packs`);
|
||||
assert.deepEqual(list.applied[0].hired, []);
|
||||
assert.deepEqual(list.applied[0].open.map(o => [o.name, o.state, o.code, typeof o.reason]), [['pm-1', 'refused', 'pack-hire-route-missing', 'string'], ['coder-1', 'refused', 'pack-hire-route-missing', 'string'], ['reviewer-1', 'refused', 'pack-hire-route-missing', 'string']]);
|
||||
});
|
||||
|
||||
test('PD a member-raised awaiting-owner line reads fromPack; the owner hire route approves it; an apply whose hire loop did not run says hireError', async t => {
|
||||
const f = await fixture(t);
|
||||
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
|
||||
await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
|
||||
const doc = f.onDisk();
|
||||
doc.roles.chief.vars = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
writeFileSync(f.file, JSON.stringify(doc, null, 2) + '\n');
|
||||
// A member with org.hire runs the pack hire on the bus (no WebUI route serves a member yet).
|
||||
const member = f.broker.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
|
||||
const out = await f.broker.request(member, { verb: 'pack.hire.console', args: { pack: 'coding' } });
|
||||
const waiting = out.hires.filter(x => x.state === 'awaiting-owner').map(x => x.name);
|
||||
assert.ok(waiting.length > 0, JSON.stringify(out));
|
||||
const [, list] = await call(f, `${ORG}/packs`);
|
||||
const open = list.applied[0].open.filter(o => o.state === 'awaiting-owner');
|
||||
assert.deepEqual(open.map(o => [o.name, o.fromPack]), waiting.map(n => [n, true]));
|
||||
const [status, hired] = await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding' });
|
||||
assert.equal(status, 200, JSON.stringify(hired));
|
||||
assert.deepEqual(hired.hires.filter(x => waiting.includes(x.name)).map(x => [x.name, x.state]), waiting.map(n => [n, 'hired']));
|
||||
assert.deepEqual((await call(f, `${ORG}/packs`))[1].applied[0].open, []);
|
||||
|
||||
// The bus answers an apply whose hire loop did not run with hireError; the route passes a code through
|
||||
// and drops anything that is not one.
|
||||
for (const [given, shown] of [['organization-busy', 'organization-busy'], ['Not A Code!', undefined], [7, undefined]]) {
|
||||
const g = await fixture(t, { tap: (verb, result) => verb === 'pack.apply.console' ? { ...result, hires: [], hireError: given } : result });
|
||||
const [, p] = await call(g, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
|
||||
const [code, receipt] = await call(g, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: p.digest });
|
||||
assert.equal(code, 200, JSON.stringify(receipt));
|
||||
assert.equal(receipt.hireError, shown);
|
||||
assert.deepEqual(receipt.hires, []);
|
||||
}
|
||||
});
|
||||
@@ -56,7 +56,7 @@ async function fixture(t, { send = true } = {}) {
|
||||
};
|
||||
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 === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' }, hires: [{ name: 'lead-reviewer', state: 'refused', code: 'definition-not-hireable' }] };
|
||||
if (verb === 'workflow.set.console') {
|
||||
assert.equal(args.revision, flows.revision);
|
||||
const doc = structuredClone(flows.document);
|
||||
@@ -118,7 +118,7 @@ test('SP6 pack picker: list, preview with marks, flagged, credential and noHire
|
||||
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.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board, definitions.reviewer. Not hired: lead-reviewer, its role is on the no-hire list.');
|
||||
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.
|
||||
|
||||
@@ -67,7 +67,8 @@ test('shipped strings are unchanged, and the web keeps its write boundary', () =
|
||||
const writes = read('bus.js').toString().match(/fetch\([^;]*method:\s*['"](POST|PUT|PATCH|DELETE)[^;]*;/g) ?? [];
|
||||
assert.deepEqual(writes, ["fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });", "fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', redirect: 'manual' });", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});", "fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});", "fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});", "fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/project-file', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(sent), cache: 'no-store', redirect: 'manual' });", "fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });"]);
|
||||
assert.equal(read('bus.js').toString().split(/method:/).length - 1, 11);
|
||||
assert.deepEqual([...read('bus.js').toString().matchAll(/decidePost\(([^,]*),/g)].map(m => m[1]), ["`/api/decisions/hire/${templatesOnly?'templates':'start'}`", 'url', '`/api/decisions/${enc(a.id)}/confirmation`', '`/api/decisions/${enc(a.id)}/resolve`']);
|
||||
// Ruling 2026-11-14 (#1873): Fire on an Agents card is a second hire.start caller, {op:'fire'}.
|
||||
assert.deepEqual([...read('bus.js').toString().matchAll(/decidePost\(([^,]*),/g)].map(m => m[1]), ["`/api/decisions/hire/${templatesOnly?'templates':'start'}`", "'/api/decisions/hire/start'", 'url', '`/api/decisions/${enc(a.id)}/confirmation`', '`/api/decisions/${enc(a.id)}/resolve`']);
|
||||
// Row 155 (#1649): the one fetch(url, ...) posts only to these three routes, each a literal.
|
||||
// Row 176 (#1674): the tester name form adds a second /api/name caller.
|
||||
assert.deepEqual([...read('bus.js').toString().matchAll(/assistantPost\(([^,]*),/g)].map(m => m[1]), ['url', "'/api/settings'", "'/api/name'", "'/api/assistant-stop'", "'/api/name'"]);
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
// SP1 (#1873, single pane slice 1): #/dashboard is the system landing route, an organization page is a
|
||||
// drill-in route inside the same shell (no reload, the sidebar and top bar stay), and an organization
|
||||
// whose bus is down says so with its reason. Every bus is a fake: acme and beta answer, gamma's bus is
|
||||
// stopped. The real GET /api/orgs, /api/workspace and /api/agents/levels serve the page.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
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<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
|
||||
async function fixture({ empty = false, bootless = false } = {}) {
|
||||
const { checkRootAgents } = await import('../../organization/src/index.mjs');
|
||||
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
|
||||
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
|
||||
];
|
||||
const ROLES = {
|
||||
acme: { chief: { definition: 'chief-of-staff' }, coder: { definition: 'coder' }, reviewer: { definition: 'reviewer' } },
|
||||
beta: { chief: { definition: 'chief-of-staff' } },
|
||||
gamma: { chief: { definition: 'chief-of-staff' }, researcher: { definition: 'research' } },
|
||||
};
|
||||
const DATA = {
|
||||
acme: {
|
||||
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }, { id: 'p-zeta', repo: 'zeta', name: 'Zeta API', archived: false, at: at(300) }],
|
||||
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40) } }],
|
||||
inbox: [{ id: 'dec-acme-1', question: 'Ship the hero?', class: 'gated', blocking: true, raised_by_role: 'coder', at: at(10), options: [{ key: 'yes', text: 'Ship it' }] }],
|
||||
},
|
||||
beta: { projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }], agents: [], inbox: [] },
|
||||
};
|
||||
// Launch settings differ per organization so a value carried from one to the other shows.
|
||||
const LAUNCH = id => ({ business: id, revision: (id === 'acme' ? 'a' : 'b').repeat(64), models: { opus: { provider: 'anthropic', model: 'claude-opus-5-5' } }, limits: { total: id === 'acme' ? 4 : 7 }, instances: {}, usage: { total: 0, providers: {}, models: {} } });
|
||||
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
|
||||
const opts = id => ({
|
||||
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
|
||||
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
|
||||
});
|
||||
const member = org => ({
|
||||
id: org.id, doc: { appearance: { theme: org.theme }, roles: ROLES[org.id], projects: {} },
|
||||
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : bootless ? { healthy: false, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
|
||||
options: () => opts(org.id),
|
||||
});
|
||||
const instances = id => Object.fromEntries(Object.entries(ROLES[id]).map(([n, r]) => [n, { definition: r.definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: n === 'coder' ? ['run-1'] : [], alive: [] }]));
|
||||
const organizations = {
|
||||
list: async () => (empty ? [] : LIST),
|
||||
members: async () => (empty ? [] : LIST.map(member)),
|
||||
resolve: async id => {
|
||||
const org = LIST.find(o => o.id === id); if (!org) return null;
|
||||
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
|
||||
return {
|
||||
busHealthy: true,
|
||||
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {}, launch: LAUNCH(id) }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => DATA[id].agents, 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', routed_to: 'human' })), tasks: async () => [], instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: instances(id) }) },
|
||||
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
|
||||
};
|
||||
},
|
||||
};
|
||||
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
|
||||
}
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], path = '/', empty = false, init = null, bootless = false } = {}) {
|
||||
const { organizations, agentLevels } = await fixture({ empty, bootless });
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
// `init` runs before the page's own scripts, under the display.js fetch wrapper, so it sees the scoped URL.
|
||||
if (init) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init });
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
await b.navigate(`${base}${path}`);
|
||||
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
|
||||
}
|
||||
|
||||
const rowText = org => `document.querySelector("[data-ws-orgrow=${org}]")?.innerText.replace(/\\s+/g, " ").trim() ?? ""`;
|
||||
|
||||
test('the bare address lands on #/dashboard without a reload and lists every organization with only the figures read', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
// One page load: the landing route is set in place, never by location.reload().
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation")[0].type'), 'navigate');
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/dashboard');
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgrow]")].map(r => r.dataset.wsOrgrow)'), ['acme', 'beta', 'gamma']);
|
||||
// Agents from the levels read, projects and needs-you from the workspace read.
|
||||
await wait(`${rowText('acme')}.includes("3 agents")`);
|
||||
const acme = await b.evaluate(rowText('acme'));
|
||||
assert.match(acme, /Acme Studio/);
|
||||
assert.match(acme, /bus running/);
|
||||
assert.match(acme, /2 projects/);
|
||||
assert.match(acme, /1 needs you/);
|
||||
assert.match(await b.evaluate(rowText('beta')), /1 agent\b/);
|
||||
// gamma: down with its reason; its agent count comes from its file, the bus figures are not read.
|
||||
const gamma = await b.evaluate(rowText('gamma'));
|
||||
assert.match(gamma, /bus stopped/);
|
||||
assert.match(gamma, /stopped by the owner/);
|
||||
assert.match(gamma, /2 agents/);
|
||||
assert.doesNotMatch(gamma, /\d+ projects?|\d+ needs you/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a")?.getAttribute("href")'), '#/orgs/beta/organization');
|
||||
// A system route marks no organization in the sidebar and shows no breadcrumb.
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("#workspace-nav .sel, #workspace-nav [aria-current]").length'), 0);
|
||||
assert.equal(await b.evaluate('document.querySelector(".ws-crumb")'), null);
|
||||
// The top bar names no organization.
|
||||
assert.equal(await b.evaluate('document.getElementById("current-organization")'), null);
|
||||
});
|
||||
|
||||
test('an organization opens inside the same shell with a breadcrumb, and its pages keep reading that organization', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
await b.evaluate('window.__marker = 1; window.__bar = document.querySelector(".cmdbar"); window.__side = document.getElementById("workspace-nav")');
|
||||
await b.evaluate('document.querySelector("[data-ws-orgrow=acme] a").click()');
|
||||
await wait('location.hash === "#/orgs/acme/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
|
||||
assert.equal(await b.evaluate('window.__marker'), 1);
|
||||
assert.equal(await b.evaluate('window.__bar === document.querySelector(".cmdbar") && window.__side === document.getElementById("workspace-nav")'), true);
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
|
||||
assert.equal(await b.evaluate('document.querySelector(".ws-crumb")?.innerText.replace(/\\s+/g, " ").trim()'), 'Dashboard › Acme Studio');
|
||||
assert.equal(await b.evaluate('document.querySelector(".ws-crumb a")?.getAttribute("href")'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('document.getElementById("current-organization")'), null);
|
||||
// The sidebar marks the open organization.
|
||||
await wait('document.querySelector("#workspace-nav a[aria-current=page]")?.getAttribute("href") === "#/orgs/acme/organization"');
|
||||
|
||||
// The sidebar opens another organization in place; its page reads that organization's routes.
|
||||
await b.evaluate('performance.clearResourceTimings(); document.querySelector("#workspace-nav a[href=\'#/orgs/beta/organization\']").click()');
|
||||
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
|
||||
assert.equal(await b.evaluate('window.__marker'), 1);
|
||||
// A page inside beta scopes its reads to beta.
|
||||
await b.evaluate('location.hash = "#/agents"');
|
||||
await wait('location.hash === "#/orgs/beta/agents" && document.querySelector("[data-org-agents]")');
|
||||
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
|
||||
assert.equal(await b.evaluate('window.__marker'), 1);
|
||||
// The organization's control board is named as such after the organization, not as a second Dashboard.
|
||||
await b.evaluate('location.hash = "#/orgs/beta/board"');
|
||||
await wait('/^Dashboard\\/.+\\/Control board$/.test(document.getElementById("breadcrumbs")?.textContent ?? "")');
|
||||
assert.equal(await b.evaluate('document.querySelector("#breadcrumbs [data-crumb-org]")?.getAttribute("href")'), '#/orgs/beta/organization');
|
||||
|
||||
// The breadcrumb goes back to the system dashboard, still without a reload.
|
||||
await b.evaluate('location.hash = "#/orgs/beta/organization"');
|
||||
await wait('document.querySelector(".ws-crumb a")');
|
||||
await b.evaluate('document.querySelector(".ws-crumb a").click()');
|
||||
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
assert.equal(await b.evaluate('window.__marker'), 1);
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
});
|
||||
|
||||
test('an old #/orgs/<id>/... link still opens that page', async t => {
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/beta/agents' });
|
||||
await wait('document.querySelector("[data-org-agents]")');
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/agents');
|
||||
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
|
||||
});
|
||||
|
||||
test('a stopped organization says so on its page and on its agents, with the reason', async t => {
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization' });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-down]")');
|
||||
const down = await b.evaluate('document.querySelector("[data-org-down]").innerText.replace(/\\s+/g, " ")');
|
||||
assert.match(down, /The bus is not running/);
|
||||
assert.match(down, /stopped by the owner/);
|
||||
await b.evaluate('location.hash = "#/orgs/gamma/agents"');
|
||||
await wait('document.querySelector("[data-org-agents] [data-org=gamma] [data-agents-why]")');
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org=gamma] [data-agents-why]").innerText.trim()'), 'Agents not read: the bus is stopped');
|
||||
const agents = await b.evaluate('document.querySelector("[data-org-agents]").innerText.replace(/\\s+/g, " ")');
|
||||
assert.doesNotMatch(agents, /Agents unavailable/);
|
||||
});
|
||||
|
||||
test('at 390 px the dashboard lists the organizations without a horizontal scroll', async t => {
|
||||
const { b, wait } = await setup(t, { viewport: [390, 844] });
|
||||
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= window.innerWidth'), true);
|
||||
});
|
||||
|
||||
// Review round finding 1: with no organization yet the page keeps its first-run addresses, so the
|
||||
// wordmark (href "#/") opens the first-run board, not a #/dashboard the first-run page has no view for.
|
||||
test('first run: the wordmark opens the first-run board, not a Not found page', async t => {
|
||||
const { b, wait } = await setup(t, { path: '/#/settings/appearance', empty: true });
|
||||
await wait('document.querySelector("#bus-view h1")');
|
||||
await b.evaluate('document.querySelector(".wordmark").click()');
|
||||
// The board route empties the page view; give the router and render time to settle before checking.
|
||||
await wait('location.hash !== "#/settings/appearance"');
|
||||
await new Promise(r => setTimeout(r, 800));
|
||||
assert.equal(await b.evaluate('location.hash'), '#/');
|
||||
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .nf")'), false);
|
||||
assert.equal(await b.evaluate('window.MosaicOrg'), undefined);
|
||||
});
|
||||
|
||||
test('a switch stops following an agent request: no poll reaches the next organization and its page shows no receipt', async t => {
|
||||
const ID = '11111111-2222-4333-8444-555555555555';
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
const init = `window.__reads = []; window.__posts = []; const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true }; return ${json}; }
|
||||
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __posts.push(s); x = { request: '${ID}', at: 'x' }; return ${json}; }
|
||||
if (/\\/agent\\/request\\?/.test(s)) { __reads.push(s); x = { request: '${ID}', action: 'launch', instance: 'reviewer', state: 'open', done: null, cancelled: null }; return ${json}; }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/agents', init });
|
||||
const launch = '#agents-section [data-agent-action=launch][data-agent-name=reviewer]';
|
||||
await wait(`document.querySelector(${JSON.stringify(launch)}) && !document.querySelector(${JSON.stringify(launch)}).disabled`);
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(launch)}).click()`);
|
||||
await wait('window.__reads.length >= 1');
|
||||
assert.deepEqual(await b.evaluate('window.__posts'), ['/api/orgs/acme/agent/launch']);
|
||||
assert.match(await b.evaluate('window.__reads[0]'), /^\/api\/orgs\/acme\/agent\/request\?id=/);
|
||||
await b.evaluate('location.hash = "#/orgs/beta/settings/agents"');
|
||||
await wait('location.hash === "#/orgs/beta/settings/agents" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")');
|
||||
const seen = await b.evaluate('window.__reads.length');
|
||||
// Two poll periods pass on beta's page.
|
||||
await new Promise(r => setTimeout(r, 4500));
|
||||
const reads = await b.evaluate('window.__reads');
|
||||
assert.equal(reads.filter(u => u.includes('/orgs/beta/')).length, 0, reads.join(' '));
|
||||
assert.equal(reads.length, seen, 'the poll stopped at the switch');
|
||||
assert.equal(await b.evaluate('document.querySelector("#agents-receipt")?.textContent.trim() ?? ""'), '');
|
||||
assert.equal(await b.evaluate('document.querySelector("#agents-section [data-agent-action=launch][data-agent-name=chief]")?.disabled'), false);
|
||||
});
|
||||
|
||||
test('a save still in flight at a switch: its answer is not drawn on the next organization and its Save is not held', async t => {
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
// acme's settings POST is held until the test releases it, then answers with acme's saved values.
|
||||
const init = `window.__posts = []; const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true }; return ${json}; }
|
||||
if (options.method === 'POST' && s === '/api/orgs/acme/settings') { __posts.push(JSON.parse(options.body)); await new Promise(r => { window.__release = r; });
|
||||
x = { business: 'acme', revision: 'c'.repeat(64), models: { opus: { provider: 'anthropic', model: 'claude-opus-5-5' } }, limits: { total: 5 }, instances: {}, usage: { total: 0, providers: {}, models: {} } }; return ${json}; }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/limits', init });
|
||||
const total = '#launch-settings-form input[data-setting=\'["total"]\']';
|
||||
const submit = '#launch-settings-form button[type=submit]';
|
||||
await wait(`document.querySelector(${JSON.stringify(total)})?.value === "4" && !document.querySelector(${JSON.stringify(submit)}).disabled`);
|
||||
await b.evaluate(`(() => { const i = document.querySelector(${JSON.stringify(total)}); i.value = "5"; i.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector(${JSON.stringify(submit)}).click(); })()`);
|
||||
await wait('typeof window.__release === "function"');
|
||||
assert.equal(await b.evaluate('window.__posts[0]?.revision'), 'a'.repeat(64));
|
||||
await b.evaluate('location.hash = "#/orgs/beta/settings/limits"');
|
||||
await wait(`location.hash === "#/orgs/beta/settings/limits" && document.querySelector(${JSON.stringify(total)})?.value === "7"`);
|
||||
// beta's Save is its own: not held by acme's write.
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
|
||||
await b.evaluate('window.__release()');
|
||||
await new Promise(r => setTimeout(r, 700));
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value`), '7');
|
||||
assert.equal(await b.evaluate('document.getElementById("launch-settings-receipt")?.textContent.trim() ?? ""'), '');
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
|
||||
});
|
||||
|
||||
test('a down banner does not repeat its heading as the reason', async t => {
|
||||
// No boot record: the server's reason is its fallback, "the bus is not running", the heading's own words.
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization', bootless: true });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-down]")');
|
||||
const down = await b.evaluate('document.querySelector("[data-org-down]").innerText.replace(/\\s+/g, " ")');
|
||||
assert.match(down, /The bus is not running\./);
|
||||
assert.equal((down.match(/the bus is not running/gi) || []).length, 1, down);
|
||||
assert.doesNotMatch(down, /Reason:|No reason was read/);
|
||||
});
|
||||
|
||||
test('a restart started on one organization finishes on that organization after a switch', { timeout: 60000 }, async t => {
|
||||
const END = '11111111-2222-4333-8444-5555555555e1', LAUNCHED = '11111111-2222-4333-8444-5555555555a1';
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
// Every agent request read and write is recorded, whichever organization it names; the bus answers
|
||||
// are stubs (terminate, closed requests, one launch). Only acme's instances read is stubbed and
|
||||
// recorded (the session gone): beta's own page reads beta's instances, which is not the chain.
|
||||
const init = `window.__chain = []; const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); x = { request: '${END}' }; return ${json}; }
|
||||
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __chain.push(s); x = { request: '${LAUNCHED}' }; return ${json}; }
|
||||
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id');
|
||||
x = { request: id, instance: 'coder', action: id === '${END}' ? 'end' : 'launch', state: 'closed', done: { run: id === '${END}' ? null : 'run-9' }, cancelled: null }; return ${json}; }
|
||||
if (s === '/api/orgs/acme/bus/instances' && window.__restarting) { __chain.push(s); x = { rows: [{ instances: { coder: { running: [] } } }] }; return ${json}; }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/acme/organization', init });
|
||||
await wait('window.MosaicAgents && document.querySelector("[data-org-dashboard] h1")');
|
||||
// The button the Routing receipt offers (agents.js restartMarkup), placed on acme's page.
|
||||
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); document.querySelector("[data-agent-restart=coder]").click()');
|
||||
await wait('window.__chain.length >= 1');
|
||||
await b.evaluate('location.hash = "#/orgs/beta/organization"');
|
||||
await wait('location.hash === "#/orgs/beta/organization"');
|
||||
// Done when the chain has launched and read the launch request back, or as soon as any of it names beta.
|
||||
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || (window.__chain.some(u => /\\/agent\\/launch$/.test(u)) && window.__chain.filter(u => /\\/agent\\/request$/.test(u)).length >= 2)', 30000);
|
||||
const chain = await b.evaluate('window.__chain');
|
||||
assert.deepEqual([...new Set(chain)], ['/api/orgs/acme/agent/terminate', '/api/orgs/acme/agent/request', '/api/orgs/acme/bus/instances', '/api/orgs/acme/agent/launch'], chain.join(' '));
|
||||
// beta's page draws nothing of acme's chain.
|
||||
assert.equal(await b.evaluate('!!document.querySelector("[data-agent-restart-status=coder]")'), false);
|
||||
});
|
||||
|
||||
test('a file save still in flight at a switch: its outcome is not announced on the next organization', async t => {
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
// acme's file reads are stubbed; its save POST is held until the test releases it, then answers with a commit.
|
||||
const init = `window.__posts = []; const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true, edit: true }; return ${json}; }
|
||||
if (s.startsWith('/api/orgs/acme/project-file?')) { x = { path: 'docs/a.md', commit: 'a'.repeat(40), content: '# A\\n', at: new Date().toISOString() }; return ${json}; }
|
||||
if (options.method === 'POST' && s === '/api/orgs/acme/project-file') { __posts.push(JSON.parse(options.body)); await new Promise(r => { window.__release = r; });
|
||||
x = { path: 'docs/a.md', commit: 'c'.repeat(40) }; return ${json}; }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: `/#/orgs/acme/docs/site/${encodeURIComponent('docs/a.md')}`, init });
|
||||
await wait('document.querySelector("#doc-form")');
|
||||
if (!await b.evaluate('!!document.querySelector("#doc-text")')) await b.evaluate('document.querySelector("#doc-mode-source").click(), true');
|
||||
await wait('document.querySelector("#doc-text")?.value === "# A\\n"');
|
||||
await b.evaluate('(() => { const a = document.querySelector("#doc-text"); a.value = "# A\\n\\nmore\\n"; a.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector("#doc-form").requestSubmit(); })()');
|
||||
await wait('typeof window.__release === "function"');
|
||||
assert.equal(await b.evaluate('window.__posts[0]?.base'), 'a'.repeat(40));
|
||||
await b.evaluate('location.hash = "#/orgs/beta/organization"');
|
||||
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
|
||||
await b.evaluate('window.__release()');
|
||||
await new Promise(r => setTimeout(r, 700));
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/organization');
|
||||
assert.doesNotMatch(await b.evaluate('document.getElementById("announce")?.textContent ?? ""'), /Saved as commit|Draft kept/);
|
||||
});
|
||||
|
||||
// SP2 item 1: an organization's own bare address is its page, not the system dashboard.
|
||||
test('a bare #/orgs/<id> opens that organization\'s page', async t => {
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/beta' });
|
||||
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
|
||||
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
|
||||
// In place too, from another organization's page.
|
||||
await b.evaluate('location.hash = "#/orgs/acme"');
|
||||
await wait('location.hash === "#/orgs/acme/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
|
||||
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
|
||||
// The old per-organization dashboard address is still the system dashboard.
|
||||
await b.evaluate('location.hash = "#/orgs/acme/dashboard"');
|
||||
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
});
|
||||
|
||||
// SP2 item 2: the system dashboard shows the system theme, never the organization opened last.
|
||||
test('the dashboard keeps the system theme after an organization with its own theme was opened', async t => {
|
||||
const { b, base, wait } = await setup(t, { path: '/#/orgs/acme/organization' });
|
||||
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio" && document.documentElement.dataset.palette === "cobalt"');
|
||||
await b.evaluate('location.hash = "#/dashboard"');
|
||||
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
await wait('document.documentElement.dataset.palette === "harbor"');
|
||||
assert.equal(await b.evaluate('window.MosaicAppearance.state().organization'), null);
|
||||
assert.equal(await b.evaluate('document.getElementById("org-cue").hidden'), true);
|
||||
// A fresh load of the bare address, with acme stored as the last organization shown, starts on the system theme.
|
||||
await b.navigate(`${base}/`);
|
||||
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
assert.equal(await b.evaluate('document.documentElement.dataset.palette'), 'harbor');
|
||||
// A choice made on the dashboard is the system's own: acme keeps its theme, and the dashboard keeps the choice.
|
||||
await b.evaluate('window.MosaicAppearance.set({ mode: "light" })');
|
||||
assert.equal(await b.evaluate('document.documentElement.dataset.mode'), 'light');
|
||||
await b.evaluate('location.hash = "#/orgs/acme/organization"');
|
||||
await wait('document.documentElement.dataset.palette === "cobalt"');
|
||||
assert.equal(await b.evaluate('document.documentElement.dataset.mode'), 'dark');
|
||||
await b.evaluate('location.hash = "#/dashboard"');
|
||||
await wait('document.documentElement.dataset.palette === "harbor" && document.documentElement.dataset.mode === "light"');
|
||||
});
|
||||
|
||||
// SP2 item 3: a stopped organization's page shows one bus banner, with the restart action and what can't be read.
|
||||
test('a stopped organization\'s page shows one bus banner, with the restart action', async t => {
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
const init = `const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (/^\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, orgSetup: true }; return ${json}; }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization', init });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-down] [data-bus-restart]")');
|
||||
// Both shell painters (display.js on the list read, app.js on its own read) have had their turn.
|
||||
await b.evaluate('window.MosaicOrg.list');
|
||||
await new Promise(r => setTimeout(r, 800));
|
||||
const banners = 'Array.from(document.querySelectorAll(".banner")).filter(e => !e.hidden && e.getClientRects().length && /bus/i.test(e.textContent)).map(e => e.innerText.replace(/\\s+/g, " ").trim())';
|
||||
const shown = await b.evaluate(banners);
|
||||
assert.equal(shown.length, 1, shown.join(' | '));
|
||||
assert.match(shown[0], /The bus is not running\. Nothing about Gamma Home's agents or packs can be read until it starts\./);
|
||||
assert.match(shown[0], /Restart the bus/);
|
||||
assert.equal(await b.evaluate('document.getElementById("bus-down").hidden'), true);
|
||||
// The organization's other pages keep the shell's banner, with its restart.
|
||||
await b.evaluate('location.hash = "#/orgs/gamma/agents"');
|
||||
await wait('!document.getElementById("bus-down").hidden && /Bus unavailable/.test(document.getElementById("bus-down").textContent)');
|
||||
// And back on the organization page it gives way again.
|
||||
await b.evaluate('location.hash = "#/orgs/gamma/organization"');
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-down]") && document.getElementById("bus-down").hidden');
|
||||
});
|
||||
|
||||
// SP2 item 4: the dashboard row for a stopped organization says it once.
|
||||
test('a stopped organization\'s dashboard row does not repeat its state as the reason', async t => {
|
||||
const { b, wait } = await setup(t, { bootless: true });
|
||||
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
await wait(`${rowText('gamma')}.includes("bus stopped")`);
|
||||
const gamma = await b.evaluate(rowText('gamma'));
|
||||
assert.doesNotMatch(gamma, /the bus is not running/i, gamma);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=gamma] .why")'), null);
|
||||
});
|
||||
|
||||
// SP2 item 6: no status-badge glyph ("?") is drawn before the live dot in the dashboard's Active agents.
|
||||
test('the dashboard\'s active agents draw no stray glyph before the status dot', async t => {
|
||||
const { b, wait } = await setup(t);
|
||||
await wait('document.querySelector("[data-ws-sessions] tbody tr")');
|
||||
const cells = await b.evaluate('Array.from(document.querySelectorAll("[data-ws-sessions] tbody td")).map(td => getComputedStyle(td, "::before").content)');
|
||||
assert.ok(cells.length >= 2, String(cells));
|
||||
for (const c of cells) assert.ok(c === 'none' || c === 'normal', `generated content ${c}`);
|
||||
});
|
||||
|
||||
// SP2 item 7 (the test SP1 lacks): a read still in flight when the organization switches keeps nothing.
|
||||
// acme's settings read is held across a switch to beta and then answers with a figure only it has (99);
|
||||
// beta's own read then fails, so beta's page draws from what was kept. Nothing of acme's may be there.
|
||||
test('a read still in flight at a switch: its answer is not kept for the next organization', async t => {
|
||||
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
|
||||
const init = `window.__acme = []; window.__beta = []; const original = window.fetch;
|
||||
window.fetch = async (url, options = {}) => { const s = String(url); let x;
|
||||
if (s === '/api/orgs/acme/settings' && !options.method && window.__holdAcme) { await new Promise(r => window.__acme.push(r));
|
||||
const r = await original(url, options), body = await r.json(); x = { ...body, launch: { ...body.launch, limits: { total: 99 } } }; return ${json}; }
|
||||
if (s === '/api/orgs/beta/settings' && !options.method && window.__holdBeta) { await new Promise(r => window.__beta.push(r));
|
||||
return new Response(JSON.stringify({ error: 'unavailable', message: 'beta settings read failed' }), { status: 500, headers: { 'content-type': 'application/json' } }); }
|
||||
return original(url, options); };`;
|
||||
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/limits', init });
|
||||
const total = '#launch-settings-form input[data-setting=\'["total"]\']';
|
||||
await wait(`document.querySelector(${JSON.stringify(total)})?.value === "4"`);
|
||||
// A fresh read of acme's settings starts and is held.
|
||||
await b.evaluate('window.__holdAcme = true; location.hash = "#/orgs/acme/settings/tokens"');
|
||||
await wait('window.__acme.length >= 1');
|
||||
await b.evaluate('window.__holdBeta = true; location.hash = "#/orgs/beta/settings/limits"');
|
||||
await wait('location.hash === "#/orgs/beta/settings/limits" && window.__beta.length >= 1');
|
||||
// acme answers after the switch; then beta's read fails.
|
||||
await b.evaluate('window.__acme.forEach(r => r())');
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
await b.evaluate('window.__beta.forEach(r => r())');
|
||||
await wait('document.querySelector("#bus-view .banner")');
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value ?? null`), null, 'acme\'s held answer was drawn on beta');
|
||||
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .s1-stale")'), false);
|
||||
assert.match(await b.evaluate('document.getElementById("bus-view").innerText'), /beta settings read failed/);
|
||||
});
|
||||
@@ -85,7 +85,7 @@ test('SP8 the owner previews a template (nothing written), saves it with the dig
|
||||
assert.equal(readFileSync(f.saved('demo-shape'), 'utf8'), preview.json);
|
||||
assert.deepEqual(readFileSync(f.file), before, 'the organization file is unchanged');
|
||||
const [again, againBody] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: preview.digest });
|
||||
assert.deepEqual([again, againBody.error], [400, 'invalid-request']);
|
||||
assert.deepEqual([again, againBody.error], [409, 'template-exists']);
|
||||
const [, list] = await call(f, `${ORG}/templates`);
|
||||
assert.deepEqual(list.templates.map(x => [x.name, x.scope]), [['demo-shape', 'org']]);
|
||||
// The preview and the list went over the read; only the saves used the fenced writer.
|
||||
|
||||
@@ -370,7 +370,7 @@ test('an unavailable selected bus does not hide other organizations on Agents',
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/beta/agents`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-agents]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('organization agent grid missing')})()`);
|
||||
const text=await b.evaluate('document.querySelector("[data-org-agents]").innerText');
|
||||
assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); assert.match(text,/Agents unavailable/);
|
||||
assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); assert.match(text,/Agents not read: the bus is not answering/); assert.doesNotMatch(text,/Agents unavailable/);
|
||||
});
|
||||
|
||||
test('a failed conversation read says unavailable, never that none exists', async t => {
|
||||
|
||||
@@ -81,10 +81,10 @@ async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs
|
||||
|
||||
test('Dashboard renders every section across organizations, and a stopped one shows its state while the others render', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait('document.querySelector("[data-ws-home] [data-ws-tiles]") && document.querySelectorAll("[data-ws-orgcard]").length === 3');
|
||||
await wait('document.querySelector("[data-ws-home] [data-ws-tiles]") && document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
// The Dashboard nav item is this page.
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/dashboard');
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
// Tiles: needs you, sessions, open tasks, projects, and an honest line for spend.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile)'), ['needs', 'sessions', 'tasks', 'projects', 'spend']);
|
||||
@@ -92,12 +92,12 @@ test('Dashboard renders every section across organizations, and a stopped one sh
|
||||
assert.match(await text('[data-ws-tile=projects]'), /Projects\s*4\s*3 active/i);
|
||||
assert.match(await text('[data-ws-tile=spend]'), /No spend figures yet/);
|
||||
assert.doesNotMatch(await text('[data-ws-tile=spend]'), /\$|\d/);
|
||||
// Organization cards: two running with their read, the stopped one with its state and the time it was read.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgcard]")].map(e => [e.dataset.wsOrgcard, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]);
|
||||
assert.match(await text('[data-ws-orgcard=gamma]'), /Gamma Home/);
|
||||
assert.match(await text('[data-ws-orgcard=gamma]'), /down/);
|
||||
assert.match(await text('[data-ws-orgcard=gamma]'), /stopped by the owner/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").getAttribute("href")'), '#/orgs/beta/organization');
|
||||
// SP1: one organization row each: two running, the stopped one with its state and reason.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgrow]")].map(e => [e.dataset.wsOrgrow, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]);
|
||||
assert.match(await text('[data-ws-orgrow=gamma]'), /Gamma Home/);
|
||||
assert.match(await text('[data-ws-orgrow=gamma]'), /bus down/);
|
||||
assert.match(await text('[data-ws-orgrow=gamma]'), /stopped by the owner/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a").getAttribute("href")'), '#/orgs/beta/organization');
|
||||
assert.match(await text('[data-ws-home] .sub'), /2 of 3 organizations answered/);
|
||||
assert.match(await text('[data-ws-home] .sub'), /Gamma Home down, read \d\d:\d\d/);
|
||||
// Recent project activity across both running organizations, newest first, each linking into its org.
|
||||
@@ -243,18 +243,18 @@ test('A poll repaints in place: focus, caret and scroll stay where they were', a
|
||||
assert.deepEqual(await b.evaluate('[document.activeElement?.dataset.focusKey, document.activeElement.selectionStart]'), ['proj-name', 2]);
|
||||
// The Dashboard and the Inbox repaint the same way.
|
||||
await b.evaluate('location.hash = "#/orgs/acme/"');
|
||||
await wait('document.querySelectorAll("[data-ws-orgcard]").length === 3');
|
||||
await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").focus()');
|
||||
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
|
||||
await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a").focus()');
|
||||
await b.evaluate('window.__marker = document.querySelector("[data-ws-orgs]"); document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
|
||||
await wait('document.querySelector("[data-ws-orgs]") !== window.__marker');
|
||||
assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'orgcard:beta');
|
||||
assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'orgrow:beta');
|
||||
// No loading view replaced the page during that repaint.
|
||||
assert.equal(await b.evaluate('document.querySelector("#bus-view .loading")'), null);
|
||||
});
|
||||
|
||||
test('Phone width: no horizontal scroll on any of the three pages, and the drawer opens and closes', async t => {
|
||||
const { b, wait } = await setup(t, { viewport: [390, 844] });
|
||||
for (const [hash, ready] of [['/', '[data-ws-orgcard]'], ['/projects', '[data-ws-project]'], ['/inbox', '[data-ws-item]']]) {
|
||||
for (const [hash, ready] of [['/', '[data-ws-orgrow]'], ['/projects', '[data-ws-project]'], ['/inbox', '[data-ws-item]']]) {
|
||||
await b.evaluate(`location.hash = "#/orgs/acme${hash}"`);
|
||||
await wait(`document.querySelector(${JSON.stringify(ready)})`);
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, hash);
|
||||
|
||||
Reference in new issue
Block a user