Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65f7288cea | ||
|
|
211b32ef1a | ||
|
|
163972e08e | ||
|
|
23e504f331 | ||
|
|
23b5e24ebc | ||
|
|
266f3a45ff | ||
|
|
0c35eeed9d |
No files matched your search
@@ -348,6 +348,8 @@ The hire form and the autonomy panel from a terminal (E2, #1873, P1-3). `mosaic
|
||||
|
||||
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
|
||||
|
||||
+26
-21
@@ -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
|
||||
@@ -6262,7 +6265,7 @@ 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(request.verb==='decision.resolve' && !s.human) {
|
||||
@@ -6271,7 +6274,7 @@ export class Broker {
|
||||
}
|
||||
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,12 +6288,12 @@ 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(()=>this.#raiseHire(s,this.#proposalHire(s,args),false)).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));
|
||||
// #1873 SP4: the owner's starter packs, board and workflows. Only the organization's owner calls
|
||||
@@ -6628,7 +6631,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 +6640,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));
|
||||
@@ -6785,9 +6790,9 @@ export class Broker {
|
||||
// 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(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(()=>{
|
||||
@@ -6818,7 +6823,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 +6843,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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -225,6 +225,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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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') {
|
||||
|
||||
+21
-14
@@ -63,7 +63,22 @@ 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',
|
||||
};
|
||||
// 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++) {
|
||||
@@ -105,13 +120,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 +129,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 +157,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,36 @@ 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));
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// rechecks everything in the resolve transaction. Nothing here retries.
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { BusReadError, subjectOk } from './bus.mjs';
|
||||
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
export const DECISION_ROUTE = /^\/api\/decisions\/([^/]*)\/(confirmation|resolve|start|templates)$/;
|
||||
// The endpoint contract, design section 4. Each refusal is one of these, never a 200.
|
||||
@@ -42,21 +43,117 @@ const BUS_CODES = {
|
||||
'decision-closed': 'decision-closed', 'decision-stale': 'decision-stale', 'invalid-choice': 'decision-stale',
|
||||
'invalid-request': 'invalid-request', 'hire-owner-required':'hire-owner-required','right-required':'right-required','decision-expired':'decision-expired','hire-resolution-required':'hire-resolution-required',
|
||||
};
|
||||
// D4 (#1873, P1-2): a hire, fire or change start the bus definitely refused keeps its own code,
|
||||
// but only for codes the broker raises before it records the decision: the proposal checks in
|
||||
// hire-decisions.mjs prepare(), which #raiseHire runs before its INSERT. hire.start.console then
|
||||
// resolves the decision and applies it in #hireConsole, and those steps can raise other codes (and
|
||||
// some of the same generic ones) after the decision exists or is consumed, so every code not listed
|
||||
// here stays outcome-unknown. Review P3: an allowlist, not a pass-through of any well-formed code.
|
||||
// D4 (#1873, P1-2) and E2E6 P1-2: a hire, fire or change start the bus definitely refused keeps its
|
||||
// own code and a next step. hire.start.console runs prepare() (hire-decisions.mjs) before it records
|
||||
// the decision, then #hireConsole checks it, consumes it, and applies it. apply() runs check() again
|
||||
// and the writers, authorityHost and #fireApproved run after the consume, so most codes can come from
|
||||
// either side of it; for a fire the agent's runs may already be stopped. The code alone does not say
|
||||
// which, and the inbox cannot tell either: it lists no closed decision (broker inbox verb), so a
|
||||
// consumed one simply drops out of it. Those codes therefore say part of the change may already be
|
||||
// applied and send the user to the Agents page (re-check finding 1). Only codes
|
||||
// that prepare() alone raises say "Nothing was applied.": the route checks (checkRoutes runs in
|
||||
// prepare(), and in adjusted() only for an adjust, which a start never carries), definition-shared,
|
||||
// definition-not-hireable and no-chief-of-staff. organization-uncertain, a lost reply and the
|
||||
// bus server's own request codes (request-timeout and invalid-envelope can fire while the request is
|
||||
// processing) stay outcome-unknown.
|
||||
const NONE = ' Nothing was applied.';
|
||||
const EITHER = ' Part of it may already be applied: check the Agents page before trying again.';
|
||||
const CHECK = ' Check the Agents page and the inbox before trying again.';
|
||||
const HIRE_START_REFUSALS = {
|
||||
'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy. Nothing was applied.'],
|
||||
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again. Nothing was applied.'],
|
||||
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness. Nothing was applied.'],
|
||||
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies. Nothing was applied.'],
|
||||
'definition-not-hireable': [409, 'This organization does not hire agents from this role template. Pick another template. Nothing was applied.'],
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it. Nothing was applied.'],
|
||||
'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it. Nothing was applied.'],
|
||||
'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy.' + NONE],
|
||||
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again.' + NONE],
|
||||
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness.' + NONE],
|
||||
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies.' + NONE],
|
||||
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Model proxy.' + NONE],
|
||||
'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Routing, or ask the owner to switch it on.' + NONE],
|
||||
'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Routing.' + NONE],
|
||||
'definition-not-hireable': [409, 'This organization does not hire agents from this role template. Pick another template.' + NONE],
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it.' + NONE],
|
||||
'definition-rev-conflict': [409, 'The role definition changed since it was read. Reload the page and propose again.' + EITHER],
|
||||
'definition-missing': [409, 'The agent\'s role definition is missing from the organization file. Check the Agents page.' + EITHER],
|
||||
'definition-secret-check-required': [503, 'The bus cannot check role text for secrets right now. Ask the owner to check the organization bus.' + EITHER],
|
||||
'credential-leak': [409, 'The proposal carries a value the credential store holds. Remove it from the role text or the reason.' + EITHER],
|
||||
'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it.' + NONE],
|
||||
'project-agents-invalid': [409, 'That project is not a code project of this organization. Pick a code project from Projects; a library project has no agents.' + EITHER],
|
||||
'organization-unknown-instance': [409, 'No agent has that name at this level. Check the name on the Agents page.' + EITHER],
|
||||
'organization-instance-exists': [409, 'An agent already has that name at this level. Pick another name, or propose a change to that agent.' + EITHER],
|
||||
'organization-instance-retired': [409, 'That name belonged to a fired agent and cannot be reused. Pick another name.' + EITHER],
|
||||
'organization-instance-referenced': [409, 'Another part of the organization still names this agent. Remove those references first.' + EITHER],
|
||||
'instance-kept': [409, 'This agent is kept by the organization and cannot be fired or replaced this way.' + EITHER],
|
||||
'root-fire-shared': [409, 'This root agent is shared with other organizations, so it cannot be fired from here.' + EITHER],
|
||||
'decision-stale': [409, 'The role template or the organization changed since it was read. Reload the templates and propose again.' + EITHER],
|
||||
'organization-refused': [409, 'The organization file refused this change. Check the role and route against the organization checks.' + EITHER],
|
||||
'not-configured': [503, 'This Console\'s bus has no hire support configured. Ask the owner to check the organization bus.' + EITHER],
|
||||
'organization-busy': [409, 'The organization is busy with another write.' + CHECK],
|
||||
'fire-in-progress': [409, 'A fire of this agent is already in progress.' + CHECK],
|
||||
'instance-fired': [409, 'This agent was fired.' + CHECK],
|
||||
'copy-unavailable': [409, 'This copy is not available for credentials.' + CHECK],
|
||||
'copy-refused': [409, 'The copy refused this credential change.' + CHECK],
|
||||
'copy-stale': [409, 'The copy changed since it was read. Reload the Agents page.' + CHECK],
|
||||
'root-policy-unreadable': [503, 'The root policy could not be read.' + CHECK],
|
||||
'credential-definition-unpinned': [409, 'The copy\'s role definition is not pinned, so credentials cannot be bound to it.' + CHECK],
|
||||
'credential-binding-changed': [409, 'The copy\'s credential binding changed since it was read.' + CHECK],
|
||||
'credential-role-changed': [409, 'The copy\'s role changed since it was read.' + CHECK],
|
||||
'credential-unbound': [409, 'The copy has no credential binding to remove.' + CHECK],
|
||||
'credential-revoking': [409, 'The copy\'s credential is being revoked.' + CHECK],
|
||||
'credential-scope-exceeded': [409, 'The requested credential scope is wider than the role allows.' + CHECK],
|
||||
// The fields passed the shape check below, so a malformed answer here is a value the organization
|
||||
// checks refused: most often a model that is not a launch.models key.
|
||||
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Model proxy and a role the organization checks accept.' + EITHER],
|
||||
};
|
||||
// A reply the endpoint cannot read as a definite answer: no answer, or the bus server's request
|
||||
// codes. Anything else that reads as a code is a definite refusal.
|
||||
const NO_ANSWER = new Set(['outcome-unknown', 'invalid-response', 'response-too-large', 'organization-uncertain', 'request-timeout', 'invalid-envelope', 'incomplete-request', 'revision-conflict-revoked']);
|
||||
const CODE = /^[a-z][a-z-]{0,63}$/;
|
||||
const definiteStart = err => err instanceof BusReadError && typeof err.code === 'string' && CODE.test(err.code) &&
|
||||
!NO_ANSWER.has(err.code) && !err.code.startsWith('outcome-unknown') ? err.code : null;
|
||||
// E2E6 P2-4: the start's own shape check, the structural rules prepare() applies, so a malformed
|
||||
// proposal names its field and rule before anything leaves for the bus. A binding request keeps the
|
||||
// bus's own check (its shape lives in copy-bindings.mjs).
|
||||
const HIRE_KEYS = ['op', 'level', 'project', 'name', 'role', 'credentials', 'personality', 'route', 'reason', 'binding'];
|
||||
const plain = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
const idOk = x => typeof x === 'string' && ID_PATTERN.test(x) && !['human', 'tester', 'user'].includes(x);
|
||||
const ID_RULE = 'lowercase letters, digits, dot, dash or underscore, starting with a letter or digit, at most 64 characters, and not human, tester or user';
|
||||
export function hireProblem(hire) {
|
||||
if (!plain(hire)) return { field: 'hire', rule: 'must be an object' };
|
||||
const extra = Object.keys(hire).find(k => !HIRE_KEYS.includes(k));
|
||||
if (extra) return { field: extra, rule: 'is not a hire field' };
|
||||
if ('binding' in hire) return null;
|
||||
for (const k of ['op', 'level', 'name', 'reason']) if (!Object.hasOwn(hire, k)) return { field: k, rule: 'is required' };
|
||||
if (!['hire', 'fire', 'change'].includes(hire.op)) return { field: 'op', rule: 'must be hire, fire or change' };
|
||||
if (!['org', 'project', 'root'].includes(hire.level)) return { field: 'level', rule: 'must be org, project or root' };
|
||||
if (!idOk(hire.name)) return { field: 'name', rule: `must be ${ID_RULE}` };
|
||||
if (typeof hire.reason !== 'string' || !hire.reason.trim()) return { field: 'reason', rule: 'must not be blank' };
|
||||
if (hire.reason.length > 500) return { field: 'reason', rule: 'must be at most 500 characters' };
|
||||
if (hire.level === 'project' && !idOk(hire.project)) return { field: 'project', rule: 'must name a code project at project level' };
|
||||
if (hire.level !== 'project' && 'project' in hire) return { field: 'project', rule: 'is only for project level' };
|
||||
if (hire.op === 'fire') {
|
||||
const k = ['role', 'route', 'credentials', 'personality'].find(x => x in hire);
|
||||
return k ? { field: k, rule: 'is not used by fire' } : null;
|
||||
}
|
||||
const route = hire.route;
|
||||
if (!plain(route)) return { field: 'route', rule: 'must name a harness and a model' };
|
||||
const rk = Object.keys(route).find(k => !['harness', 'model', 'thinking'].includes(k));
|
||||
if (rk) return { field: `route.${rk}`, rule: 'is not a route field' };
|
||||
for (const k of ['harness', 'model']) if (!Object.hasOwn(route, k)) return { field: `route.${k}`, rule: 'is required' };
|
||||
for (const [k, v] of Object.entries(route)) if (typeof v !== 'string' || !v || v.length > 200) return { field: `route.${k}`, rule: 'must be text of 1 to 200 characters' };
|
||||
const role = hire.role;
|
||||
if (!plain(role)) return { field: 'role', rule: 'must name a role template' };
|
||||
const kinds = ['template', 'definition', 'inline'].filter(k => k in role);
|
||||
if (kinds.length !== 1) return { field: 'role', rule: 'must name exactly one of a template, a definition or an inline role' };
|
||||
const ok = { template: ['template', 'sha256'], definition: ['definition', 'rev'], inline: ['inline'] }[kinds[0]];
|
||||
const rx = Object.keys(role).find(k => !ok.includes(k));
|
||||
if (rx) return { field: `role.${rx}`, rule: `is not used with role.${kinds[0]}` };
|
||||
if (kinds[0] === 'template') {
|
||||
if (!idOk(role.template)) return { field: 'role.template', rule: `must be ${ID_RULE}` };
|
||||
if (!DIGEST.test(role.sha256 ?? '')) return { field: 'role.sha256', rule: 'must be the template\'s 64-character digest; read the templates again' };
|
||||
}
|
||||
if (kinds[0] === 'definition') {
|
||||
if (!idOk(role.definition)) return { field: 'role.definition', rule: `must be ${ID_RULE}` };
|
||||
if (!Number.isSafeInteger(role.rev)) return { field: 'role.rev', rule: 'must be a whole number' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// #1873 CB5: the owner's next step once a copy credential binding decision is approved, fixed text
|
||||
// (design section 6 and its three steps). Nothing in it comes from the decision, the bus or a token.
|
||||
export const BINDING_NEXT = Object.freeze({
|
||||
@@ -156,6 +253,14 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
if(step==='start' || step==='templates') {
|
||||
const allowed=step==='start'?['business','hire']:['business'];
|
||||
if(id!=='hire' || Object.keys(value).length!==allowed.length || Object.keys(value).some(k=>!allowed.includes(k)) || !subjectOk(value.business))return refuse('invalid-request');
|
||||
if(step==='start') {
|
||||
const problem=hireProblem(value.hire);
|
||||
if(problem) {
|
||||
const label=problem.field[0].toUpperCase()+problem.field.slice(1);
|
||||
line(`error=invalid-request field=${problem.field}`);
|
||||
return json(res,400,{error:'invalid-request',field:problem.field,rule:problem.rule,message:`${label} ${problem.rule}. Nothing was sent to the bus.`});
|
||||
}
|
||||
}
|
||||
if(live()!==session)return refuse('sign-in-required');
|
||||
try {
|
||||
const result=await decide.call(step==='start'?'hire.start.console':'hire.templates.console',step==='start'?value.hire:{},{subject,business:value.business});
|
||||
@@ -167,11 +272,18 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
? (value.hire.binding.services===null?'unbind':'bind') : null;
|
||||
return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice,...(change?{next:BINDING_NEXT[change]}:{})}:result);
|
||||
} catch(err) {
|
||||
if(step!=='start' || !(err instanceof BusReadError) || !Object.hasOwn(HIRE_START_REFUSALS,err.code))
|
||||
return refuse(busCode(err,step==='start'?'outcome-unknown':'confirmation-unavailable'));
|
||||
const [status,message]=HIRE_START_REFUSALS[err.code];
|
||||
line(`error=${err.code}`);
|
||||
return json(res,status,{error:err.code,message});
|
||||
if(step!=='start')return refuse(busCode(err,'confirmation-unavailable'));
|
||||
const code=definiteStart(err);
|
||||
if(!code)return refuse('outcome-unknown');
|
||||
if(Object.hasOwn(HIRE_START_REFUSALS,code)) {
|
||||
const [status,message]=HIRE_START_REFUSALS[code];
|
||||
line(`error=${code}`);
|
||||
return json(res,status,{error:code,message});
|
||||
}
|
||||
if(Object.hasOwn(BUS_CODES,code))return refuse(BUS_CODES[code]);
|
||||
// A definite refusal this page has no wording for keeps its code, with a safe next step.
|
||||
line(`error=${code}`);
|
||||
return json(res,409,{error:code,message:'The bus refused this proposal.'+CHECK});
|
||||
}
|
||||
}
|
||||
if (step === 'confirmation') {
|
||||
|
||||
@@ -29,9 +29,11 @@ export function organizationConsole({ ctx, listOrgs, showOrg, resolveOrg, orgPat
|
||||
result.push({ id: entry.id, label: entry.id, invalid: true, reason: publicReason(ctx, error) });
|
||||
continue;
|
||||
}
|
||||
let busHealthy = false;
|
||||
try { busHealthy = (await busStatus(ctx, entry.id)).healthy === true; } catch { /* offline metadata remains visible */ }
|
||||
result.push({ id: entry.id, label: entry.id, theme: verified.shown.doc?.appearance?.theme ?? null, busHealthy });
|
||||
// E2E6 P2-8: a bus with no host recorded (stopped by its owner, or never started) is "stopped",
|
||||
// not a failure. A host that is recorded but does not answer stays plain unavailable.
|
||||
let busHealthy = false, busStopped = false;
|
||||
try { const s = await busStatus(ctx, entry.id); busHealthy = s?.healthy === true; busStopped = !busHealthy && s?.pid == null; } catch { /* offline metadata remains visible */ }
|
||||
result.push({ id: entry.id, label: entry.id, theme: verified.shown.doc?.appearance?.theme ?? null, busHealthy, ...(busStopped ? { busStopped: true } : {}) });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -22,19 +22,25 @@
|
||||
const r=await fetch(path(org,step),body===undefined?{cache:'no-store'}:{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
|
||||
const value=await r.json();if(!r.ok)throw Error(guidance[value.error]??`The bus refused: ${value.error??'outcome unknown'}. Refresh before retrying.`);return value;
|
||||
}
|
||||
async function load(org) {try{states.set(org,await call(org,''));}catch(error){states.set(org,{error:error.message});}}
|
||||
// E2E6 P1-1: a poll reloads this state; the last save's receipt and the open review list stay.
|
||||
// A failed poll keeps the last good read only while the page holds the form (dirty, or a field has
|
||||
// focus), so the held form is not dropped (review P3). A clean form shows the read error (re-check P3).
|
||||
const held=org=>{const form=[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
|
||||
async function load(org) {const prev=states.get(org),keep={status:prev?.status??'',reviewOpen:prev?.reviewOpen===true};try{states.set(org,{...await call(org,''),...keep});}catch(error){states.set(org,prev&&!prev.error&&held(org)?{...prev,...keep}:{error:error.message,...keep});}}
|
||||
function section(org) {
|
||||
const s=states.get(org);
|
||||
if(!s || s.error)return `<section class="panel" data-autonomy><h3>Autonomy</h3><p>${esc(s?.error??'Autonomy could not be read.')}</p></section>`;
|
||||
const v=s.autonomy??{};
|
||||
return `<section class="panel" data-autonomy data-autonomy-org="${esc(org)}"><h3>Autonomy</h3><p>Choose how closely you follow each class of decision. Hard waits, flagged grants and credentials always need a person.</p><form data-autonomy-form>
|
||||
const v=s.autonomy??{},fk=k=>` data-focus-key="${esc(`autonomy-${k}:${org}`)}"`;
|
||||
// The form carries the revision it was drawn from: a form a poll kept (workspace holdLive) saves
|
||||
// against that revision, so it cannot overwrite a change it never showed.
|
||||
return `<section class="panel" data-autonomy data-autonomy-org="${esc(org)}" data-live-key="${esc(`autonomy:${org}`)}"><h3>Autonomy</h3><p>Choose how closely you follow each class of decision. Hard waits, flagged grants and credentials always need a person.</p><form data-autonomy-form data-revision="${esc(JSON.stringify(s.revision??null))}">
|
||||
<div class="autonomy-fields">${classes.map(k=>`<label>${labels[k]}<select name="${k}"${s.writable?'':' disabled'}>${levels.map(l=>`<option${s.levels[k]===l?' selected':''}>${l}</option>`).join('')}</select></label>`).join('')}</div>
|
||||
<div class="autonomy-fields"><label>Reverse window (hours)<input type="number" name="reverseWindowHours" min="1" max="168" value="${v.reverseWindowHours??24}"${s.writable?'':' disabled'}></label><label>Authority resolver<input name="authorityResolver" maxlength="64" value="${esc(v.authorityResolver??'')}" autocomplete="off"${s.writable?'':' disabled'}></label></div>
|
||||
<label class="autonomy-checkbox"><input name="notices" type="checkbox"${v.notices===true?' checked':''}${s.writable?'':' disabled'}> Console notices for decisions near the loop</label>
|
||||
<label class="autonomy-checkbox"><input name="notices" type="checkbox"${fk('notices')}${v.notices===true?' checked':''}${s.writable?'':' disabled'}> Console notices for decisions near the loop</label>
|
||||
<p>In the loop, the arbiter resolves and you confirm before work takes effect. Near the loop, work takes effect and you can reverse it within the window. Out of the loop, the trail records it without a notice.</p>
|
||||
${s.writable?'<button class="btn" type="submit">Save autonomy</button>':'<p>Only the owner can change autonomy.</p>'}
|
||||
<p data-autonomy-status role="status"></p></form>
|
||||
${s.writable?`<details><summary>Review reversals before moving out of the loop</summary><p>Read the decision trail and its reversals before recording your review.</p>${classes.map(k=>`<button class="btn" type="button" data-autonomy-review="${k}">Record review: ${labels[k]}</button>`).join('')}</details>`:''}</section>`;
|
||||
${s.writable?`<p><button class="btn" type="submit"${fk('save')}>Save autonomy</button> <button class="btn" type="button" data-autonomy-discard${fk('discard')}>Discard changes</button></p>`:'<p>Only the owner can change autonomy.</p>'}
|
||||
<p data-autonomy-status role="status">${esc(s.status)}</p></form>
|
||||
${s.writable?`<details data-autonomy-review-list${s.reviewOpen?' open':''}><summary${fk('review-list')}>Review reversals before moving out of the loop</summary><p>Read the decision trail and its reversals before recording your review.</p>${classes.map(k=>`<button class="btn" type="button" data-autonomy-review="${k}"${fk(`review-${k}`)}>Record review: ${labels[k]}</button>`).join('')}</details>`:''}</section>`;
|
||||
}
|
||||
function notice(d) {
|
||||
if(!d?.autonomy)return '';
|
||||
@@ -49,9 +55,16 @@
|
||||
const autonomy=Object.fromEntries(classes.map(k=>[k,fields.get(k)]));autonomy.notices=fields.has('notices');autonomy.reverseWindowHours=Number(fields.get('reverseWindowHours'));
|
||||
if(fields.get('authorityResolver'))autonomy.authorityResolver=fields.get('authorityResolver');
|
||||
const button=form.querySelector('button[type="submit"]'),status=form.querySelector('[data-autonomy-status]');button.disabled=true;
|
||||
try{const r=await call(org,'',{revision:s.revision,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));status.textContent=`Saved. Receipt ${r.transaction}.`;}
|
||||
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
|
||||
let base=s.revision;try{if(form.dataset.revision)base=JSON.parse(form.dataset.revision);}catch{/* drawn without one */}
|
||||
try{const r=await call(org,'',{revision:base,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));s.status=`Saved. Receipt ${r.transaction}.`;form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;status.textContent=s.status;}
|
||||
catch(error){s.status=error.message;status.textContent=s.status;}finally{button.disabled=false;}
|
||||
});
|
||||
// An edited form is dirty until it saves: holdLive keeps a dirty form through every poll.
|
||||
const dirty=e=>{const form=e.target.closest?.('[data-autonomy-form]');if(form)form.dataset.liveDirty='1';};
|
||||
document.addEventListener('input',dirty);document.addEventListener('change',dirty);
|
||||
// Review P3: Discard drops the held form and draws the last read in its place.
|
||||
document.addEventListener('click',e=>{const b=e.target.closest?.('[data-autonomy-discard]');const el=b?.closest('[data-autonomy-org]');if(!el||!states.get(el.dataset.autonomyOrg))return;const org=el.dataset.autonomyOrg;el.outerHTML=section(org);[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-discard]')?.focus();});
|
||||
document.addEventListener('toggle',e=>{if(!e.target.matches?.('[data-autonomy-review-list]'))return;const s=states.get(e.target.closest('[data-autonomy-org]')?.dataset.autonomyOrg);if(s)s.reviewOpen=e.target.open;},true);
|
||||
document.addEventListener('click',async e=>{
|
||||
const button=e.target.closest('[data-autonomy-confirm],[data-autonomy-reverse],[data-autonomy-review]');if(!button)return;
|
||||
const section=button.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,status=section.querySelector('[data-autonomy-status]');
|
||||
|
||||
@@ -1743,8 +1743,11 @@
|
||||
// A route edit after the markup was prepared must win over that pending redraw.
|
||||
if(path==='/settings/routing' && routeVersion!==routesEditVersion){render(false);return;}
|
||||
const k = !navigated && (shown === route || samePage) ? keep() : null;
|
||||
// E2E6 P1-1: an org-page editor in use keeps its node, draft and focus across the repaint.
|
||||
const heldLive = k ? window.MosaicWorkspace?.holdLive?.($('bus-view')) : null;
|
||||
unmountEditor();
|
||||
$('bus-view').innerHTML = html; shown = route;
|
||||
if (heldLive) window.MosaicWorkspace.graftLive($('bus-view'), heldLive);
|
||||
syncAppearance(true);
|
||||
if (path.startsWith('/docs/')) paintDoc();
|
||||
if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]'));
|
||||
@@ -1929,6 +1932,9 @@
|
||||
};
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {});
|
||||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line 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); });
|
||||
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.
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
const inert = value => String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g,
|
||||
c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
|
||||
const txt = value => esc(inert(value));
|
||||
// E2E6 P2-15: a message's `inline code` spans show as code, not as raw backticks. The text is escaped
|
||||
// first; a pair of single backticks on one line then wraps its already-escaped contents in <code>.
|
||||
const prose = value => txt(value).replace(/`([^`\n]+)`/g, '<code>$1</code>');
|
||||
const states = new Map(), forms = new Map(), knownRequests = new Map();
|
||||
const pinnedScrolls = new WeakMap(), settlingPins = new WeakMap();
|
||||
const pageFlow = log => log.closest('.project-chat') && matchMedia('(max-width: 319px), (max-height: 540px)').matches;
|
||||
@@ -161,12 +164,12 @@
|
||||
function messageBody(m) {
|
||||
if (m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ')) return `<div class="chat-body">The assistant couldn't reply. Try again, or check Agents.<div class="small">Details: ${txt(m.body.slice('The turn failed: '.length))}</div></div>`;
|
||||
const r = renderReply?.(m.body, { check: m.check ?? null, name: m.from_role, changed: changedBy(m.check) });
|
||||
if (r?.kind === 'reply') return `<div class="chat-body">${txt(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
|
||||
if (r?.kind === 'reply') return `<div class="chat-body">${prose(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
|
||||
if (r?.kind === 'notice') {
|
||||
const v = reverts.get(r.commit) ?? {};
|
||||
return `<div class="chat-body chat-notice"><span>${txt(r.text)}</span> ${current.archiveUnknown || current.projectArchived || window.MosaicOrg ? '' : `<button class="btn" type="button" data-revert="${esc(r.commit)}"${disabled(v.pending)}>Revert</button>`} <span class="chat-revert-receipt" role="status">${txt(v.receipt ?? '')}</span></div>`;
|
||||
}
|
||||
return `<div class="chat-body">${txt(m.body)}</div>`;
|
||||
return `<div class="chat-body">${prose(m.body)}</div>`;
|
||||
}
|
||||
const ago = iso => {
|
||||
const minutes = Math.floor((Date.now() - Date.parse(iso)) / 60000);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
.org-field-err{display:block;font-size:13px;color:var(--danger);margin:4px 0 0}
|
||||
.org-field-err code,.org-errors code{overflow-wrap:anywhere}
|
||||
.org-verb code{overflow-wrap:normal;word-break:normal}
|
||||
.cmd-word{display:inline-block;max-width:100%;overflow-wrap:anywhere}
|
||||
.org-start-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:24px;align-items:start}
|
||||
.org-inline{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 8px;align-items:center}
|
||||
.org-inline label{grid-column:1/-1;font-size:14px;font-weight:600;color:var(--strong)}
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
(() => {
|
||||
const $ = id => document.getElementById(id);
|
||||
const txt = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
// E2E6 minor: a command shown as "Same as" wraps between words, never inside a flag such as
|
||||
// --if-revision. Each word is an inline-block; one longer than the line still breaks inside itself.
|
||||
const cmd = v => `<code>${String(v ?? '').split(' ').map(w => `<span class="cmd-word">${txt(w)}</span>`).join(' ')}</code>`;
|
||||
// #1873 P1-6: the remote check a repository receipt records, in one plain line.
|
||||
const CHECKED = { reachable: 'reachable', 'needs-credential': 'needs a credential', unreachable: 'unreachable' };
|
||||
const checkLine = r => `Remote check: ${CHECKED[r.check.result] ?? 'unknown'}, ${r.check.message}. Origin: ${r.origin ?? 'none'}.`;
|
||||
@@ -253,7 +256,7 @@
|
||||
$('org-archive').hidden = mode !== 'edit' || state !== 'active'; $('org-archived').hidden = mode !== 'edit' || state !== 'archived';
|
||||
$('org-restore-verb').textContent = state === 'archived' ? `Same as mosaic org restore ${id} --if-revision ${revision}` : '';
|
||||
$('org-editor-title').textContent = mode === 'create' ? `New organization: ${id}` : `Organization: ${id}`;
|
||||
$('org-editor-verb').innerHTML = verb ? `Same as <code>${txt(verb)}</code>` : '';
|
||||
$('org-editor-verb').innerHTML = verb ? `Same as ${cmd(verb)}` : '';
|
||||
$('org-save').textContent = mode === 'create' ? 'Save organization' : 'Save changes';
|
||||
$('org-errors').hidden = true;
|
||||
renderForm(); renderJSON(true);
|
||||
@@ -318,7 +321,7 @@
|
||||
{ title: 'Initialize project records', verb: `mosaic project init ${id} ${project}` },
|
||||
];
|
||||
const list = $('org-quick-steps');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as <code>${txt(s.verb)}</code></p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as ${cmd(s.verb)}</p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
const run = $('org-quick-run'); run.disabled = true; $('org-quick-open').disabled = true; $('org-advanced-open').disabled = true; $('org-preset').disabled = true; $('org-thinking').disabled = true; banner('');
|
||||
let current = 0;
|
||||
try {
|
||||
@@ -404,7 +407,7 @@
|
||||
}
|
||||
function showReceipt(title, body) {
|
||||
const box = $('org-receipt');
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as <code>${txt(body.verb)}</code></p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as ${cmd(body.verb)}</p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.hidden = false; status(`${title}. Receipt shown.`);
|
||||
}
|
||||
async function refreshList() {
|
||||
@@ -454,7 +457,7 @@
|
||||
const c = st.choice.get(key) || {}, remote = c.mode === 'remote';
|
||||
return `<li class="panel org-step org-step-${cls}" data-step="${txt(key)}" aria-labelledby="org-step-${i}-title">
|
||||
<div class="org-step-head"><h4 id="org-step-${i}-title"><span class="org-step-n">${i + 1}</span> ${txt(title)}</h4><span class="org-pill ${cls}">${txt(stateLabel)}</span></div>
|
||||
<p class="org-verb">Same as <code>${txt(s.verb || '')}</code></p>
|
||||
<p class="org-verb">Same as ${cmd(s.verb || '')}</p>
|
||||
${s.message ? `<p class="org-help">${txt(s.message)}</p>` : ''}
|
||||
${key.startsWith('project:') && s.receipt?.check ? `<p class="org-help" data-remote-check>${txt(checkLine(s.receipt))}</p>` : ''}
|
||||
${s.lastError ? `<p class="org-field-err" role="alert">${txt(s.lastError)}</p>` : ''}
|
||||
@@ -570,7 +573,7 @@
|
||||
: `The bus did not start: ${bus.message || 'no reason was given.'}`;
|
||||
const offer = (!known || bus.outcome !== 'done') && canWrite;
|
||||
const box = $('org-archive-success');
|
||||
box.innerHTML = `<p>Organization restored. ${txt(line)}</p>${known && bus.verb ? `<p class="org-verb">Same as <code>${txt(bus.verb)}</code></p>` : ''}${offer ? `<p><button type="button" data-restore-bus="${txt(id)}">Restart bus</button> <span role="status" data-restore-bus-receipt></span></p>` : ''}`;
|
||||
box.innerHTML = `<p>Organization restored. ${txt(line)}</p>${known && bus.verb ? `<p class="org-verb">Same as ${cmd(bus.verb)}</p>` : ''}${offer ? `<p><button type="button" data-restore-bus="${txt(id)}">Restart bus</button> <span role="status" data-restore-bus-receipt></span></p>` : ''}`;
|
||||
box.hidden = false; box.focus();
|
||||
}
|
||||
// Restart bus for the restored organization, the same route as the dashboard's (console-restart.js).
|
||||
@@ -620,13 +623,13 @@
|
||||
if (r.status !== 200) {
|
||||
$('org-delete-error').textContent = `The outcome is unknown. ${r.body.message || `Deletion stopped (${r.body.error || r.status}).`} Inspect the receipt and resume with the CLI.`;
|
||||
const receipt = r.body.receipt;
|
||||
$('org-delete-progress').innerHTML = `<p>Same as <code>${txt(r.body.verb || `mosaic org delete ${id} --confirm ${id}`)}</code></p><ol class="org-steps"><li class="panel org-step">Bus: ${receipt?.bus ? 'Done' : r.body.step === 'bus' ? 'Stopped' : 'Not started'}</li><li class="panel org-step">Local files: ${receipt?.moves?.length || 0} moved; ${txt(r.body.step || 'deletion')} stopped</li><li class="panel org-step">Registry: ${receipt?.registry === 'removed' ? 'Done' : 'Not complete'}</li></ol>`;
|
||||
$('org-delete-progress').innerHTML = `<p>Same as ${cmd(r.body.verb || `mosaic org delete ${id} --confirm ${id}`)}</p><ol class="org-steps"><li class="panel org-step">Bus: ${receipt?.bus ? 'Done' : r.body.step === 'bus' ? 'Stopped' : 'Not started'}</li><li class="panel org-step">Local files: ${receipt?.moves?.length || 0} moved; ${txt(r.body.step || 'deletion')} stopped</li><li class="panel org-step">Registry: ${receipt?.registry === 'removed' ? 'Done' : 'Not complete'}</li></ol>`;
|
||||
status('Deletion stopped.'); return;
|
||||
}
|
||||
if (!verifiedReply(r, 'delete')) throw Error('unknown deletion outcome');
|
||||
editorDirty = false; setupDirty.clear(); $('org-editor').hidden = true; $('org-setup').hidden = true; $('org-delete').hidden = true; $('org-archive').hidden = true; $('org-archived').hidden = true;
|
||||
const box = $('org-delete-success');
|
||||
box.innerHTML = `<h3>Organization deleted</h3><p>Same as <code>${txt(r.body.verb)}</code></p><ol class="org-steps"><li class="panel org-step org-step-done">Bus stopped or was already stopped: Done</li><li class="panel org-step org-step-done">Local files moved to the deleted folder: Done</li><li class="panel org-step org-step-done">Organization removed from the list: Done</li></ol><details><summary>Receipt</summary><pre class="org-pre">${txt(JSON.stringify(r.body.receipt, null, 2))}</pre></details>`;
|
||||
box.innerHTML = `<h3>Organization deleted</h3><p>Same as ${cmd(r.body.verb)}</p><ol class="org-steps"><li class="panel org-step org-step-done">Bus stopped or was already stopped: Done</li><li class="panel org-step org-step-done">Local files moved to the deleted folder: Done</li><li class="panel org-step org-step-done">Organization removed from the list: Done</li></ol><details><summary>Receipt</summary><pre class="org-pre">${txt(JSON.stringify(r.body.receipt, null, 2))}</pre></details>`;
|
||||
const rows = await refreshOrganizations(); box.hidden = false; box.focus(); status('Organization deleted.');
|
||||
switchIfCurrentRemoved(id, rows);
|
||||
} catch { $('org-delete-error').textContent = 'The outcome is unknown. Inspect the receipt and resume with the CLI.'; $('org-delete-progress').innerHTML = `<p>Resume with <code>${txt(`mosaic org delete ${id} --confirm ${id}`)}</code></p>`; }
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
:is(.pack-row,.pack-hire,.wf-item){border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere}
|
||||
.pack-preview{border:1px solid var(--border);border-radius:var(--r);padding:12px;margin:12px 0;overflow-wrap:anywhere}
|
||||
.pack-preview .ws-tbl{overflow-x:auto}
|
||||
/* E2E6 P2-3: the preview's overflow-wrap:anywhere let the table squeeze words ("Workfl ow"). Cells wrap
|
||||
at word breaks; only a path, which has none, may break anywhere. */
|
||||
.pack-preview .ws-tbl :is(td,th){overflow-wrap:normal;word-break:normal}
|
||||
.pack-preview .ws-tbl td code{overflow-wrap:anywhere}
|
||||
.pack-nohire,.wf-missing,.wf-note{color:var(--danger)}
|
||||
.wf-missing{font-size:.9em}
|
||||
.wf-steps{margin:6px 0;padding-left:22px}.wf-steps li{margin:4px 0}
|
||||
|
||||
@@ -39,8 +39,11 @@
|
||||
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
|
||||
return value;
|
||||
}
|
||||
// E2E6 P1-1, P2-2: a poll reloads the list but keeps the open preview, the project picked for each
|
||||
// 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 s = { packs: null, writable: false, error: null, projects: null, preview: null, status: '' };
|
||||
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 ?? {} };
|
||||
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') : [];
|
||||
@@ -81,36 +84,42 @@
|
||||
const hires = Array.isArray(v.hires) && v.hires.length ? `<h4>Hires</h4><ul class="pack-hires">${v.hires.map(hireBlock).join('')}</ul>` : '<p class="note">The pack proposes no hires.</p>';
|
||||
const skills = v.skills?.notEnabled?.length ? `<p data-pack-skills>Skills this machine has not enabled: ${v.skills.notEnabled.map(n => `<code>${esc(n)}</code>`).join(', ')}</p>` : '';
|
||||
const chief = v.chief === false ? '<p class="note">The organization has no chief, so no line is compared against one.</p>' : '';
|
||||
const apply = s.writable ? `<button class="btn" type="button" data-pack-apply>Apply this plan</button>` : '<p class="note">This Console was started without send. Packs can be previewed, not applied.</p>';
|
||||
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>`;
|
||||
}
|
||||
function packRow(org, s, entry) {
|
||||
const pack = entry.pack;
|
||||
const project = pack.scope === 'project'
|
||||
? s.projects === null ? '<p class="note">The project list could not be read.</p>' : s.projects.length
|
||||
? `<label>Project<select data-pack-project>${s.projects.map(id => `<option value="${esc(id)}">${esc(id)}</option>`).join('')}</select></label>`
|
||||
? `<label>Project<select data-pack-project data-focus-key="${esc(`pack-project:${org}:${entry.id}`)}">${s.projects.map(id => `<option value="${esc(id)}"${s.picks[entry.id] === id ? ' selected' : ''}>${esc(id)}</option>`).join('')}</select></label>`
|
||||
: '<p class="note">No code project to apply this pack to.</p>'
|
||||
: '';
|
||||
const canPreview = pack.scope !== 'project' || (s.projects && s.projects.length);
|
||||
return `<li class="pack-row" data-pack="${esc(entry.id)}"><strong>${esc(pack.label ?? entry.id)}</strong> <span class="muted"><code>${esc(entry.id)}</code> ${esc(pack.version)} · ${esc(entry.origin)} · ${pack.scope === 'project' ? 'project pack' : 'organization pack'}</span>
|
||||
<p>${esc(pack.description)}</p>${project}${canPreview ? '<button class="btn" type="button" data-pack-preview-button>Preview</button>' : ''}</li>`;
|
||||
<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>`;
|
||||
}
|
||||
function section(org) {
|
||||
const s = states.get(org);
|
||||
if (!s || s.error) return `<section class="panel" data-packs data-packs-org="${esc(org)}"><h3>Starter packs</h3><p>${esc(s?.error ?? 'Starter packs could not be read.')}</p></section>`;
|
||||
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)}"><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 a hire it proposes is only raised by the chief, as a decision.</p>${list}${previewBlock(s)}<p role="status" data-packs-status>${esc(s.status)}</p></section>`;
|
||||
}
|
||||
function redraw(org) {
|
||||
const el = [...document.querySelectorAll('[data-packs-org]')].find(n => n.dataset.packsOrg === org);
|
||||
if (el) el.outerHTML = section(org);
|
||||
}
|
||||
document.addEventListener('change', e => {
|
||||
const select = e.target.closest?.('[data-pack-project]');
|
||||
const s = select && states.get(select.closest('[data-packs-org]')?.dataset.packsOrg);
|
||||
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]');
|
||||
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')) {
|
||||
const row = button.closest('[data-pack]'), pack = row.dataset.pack, project = row.querySelector('[data-pack-project]')?.value;
|
||||
@@ -123,10 +132,14 @@
|
||||
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.`;
|
||||
applied = true;
|
||||
}
|
||||
} catch (error) { s.status = error.message; }
|
||||
// A preview the page cannot draw says so, instead of leaving the button disabled with nothing shown.
|
||||
try { redraw(org); } catch { s.preview = null; s.status = 'The preview could not be shown.'; redraw(org); }
|
||||
// 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 } }));
|
||||
});
|
||||
window.MosaicPacks = { load, section };
|
||||
})();
|
||||
@@ -60,6 +60,16 @@ html[data-organizations] .pane-body .project-columns .project-section-title h2,h
|
||||
html[data-organizations] .pane-body .project-metrics{grid-template-columns:repeat(4,minmax(0,1fr))}
|
||||
html[data-organizations] .pane-body .project-metrics a:not(:nth-child(4)){border-right:1px solid var(--line)}
|
||||
}
|
||||
/* E2E6 P2-9: a dashboard in a pane sizes from the pane, not the window. Half a 1440 window left the
|
||||
Settings column too narrow for its values (clipped to 1-2 characters): the split stacks below 900px
|
||||
of pane, and a narrow Settings list puts each value on its own line, as at phone width. */
|
||||
@container (max-width:899px){
|
||||
html[data-organizations] .pane-body .ws-split{grid-template-columns:minmax(0,1fr)}
|
||||
}
|
||||
@container (max-width:559px){
|
||||
html[data-organizations] .pane-body .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .pane-body .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
}
|
||||
/* The side-by-side page has its own bar; the page breadcrumb would name only one pane. */
|
||||
body:has(#bus-view > .sbs) #breadcrumbs{display:none}
|
||||
html[data-organizations] .content:has(> #bus-view > .sbs) > .org-cue{margin:8px 14px}
|
||||
|
||||
@@ -176,9 +176,11 @@
|
||||
function paintBody(p, html) {
|
||||
const { body } = els(p);
|
||||
if (p.html === html && body.childElementCount) return;
|
||||
const kept = capture(p, body);
|
||||
const kept = capture(p, body), live = window.MosaicWorkspace?.holdLive?.(body);
|
||||
body.innerHTML = html; p.html = html; p.project = null;
|
||||
rewrite(p, body);
|
||||
// E2E6 P1-1: an editor in use keeps its node, draft and focus; its ids were rewritten when first painted.
|
||||
if (live && window.MosaicWorkspace.graftLive(body, live)) kept.focus = null;
|
||||
restore(p, body, kept);
|
||||
}
|
||||
|
||||
@@ -470,6 +472,11 @@
|
||||
void orgList(true).then(rows => { if (rows) listCache = rows; });
|
||||
for (const p of mounted.panes) void drawPane(p, { fresh: true });
|
||||
}
|
||||
// E2E6 P2-2: a pane showing the organization a write changed reads it again.
|
||||
document.addEventListener('mosaic-org-changed', e => {
|
||||
if (!mounted) return;
|
||||
for (const p of mounted.panes) if (p.org === e.detail?.org) void drawPane(p, { fresh: true });
|
||||
});
|
||||
// The list the tabs draw from follows each fresh read of the organization list.
|
||||
document.addEventListener('mosaic-org-list', e => { if (Array.isArray(e.detail?.rows)) listCache = e.detail.rows; });
|
||||
|
||||
|
||||
@@ -86,7 +86,17 @@
|
||||
.breadcrumbs:has(.project-crumb-current) a::after { content:''; position:absolute; top:0; bottom:0; left:50%; width:max(100%,44px); transform:translateX(-50%); }
|
||||
.chat-area:has(.project-header),.chat-area:has(.project-list-head) { max-width:none; margin-inline:0; }
|
||||
.project-tabs { scrollbar-width:none; } .project-tabs::-webkit-scrollbar { display:none; }
|
||||
@media (max-width:699px) { .project-tabs { mask-image:linear-gradient(to right, #000 calc(100% - 22px), transparent 100%); } }
|
||||
/* E2E6 P2-12: a strip wider than the screen fades out over its last 48px, so a cut tab reads as "more
|
||||
this way". Where scroll timelines exist the fade runs only while there is more to scroll: a strip that
|
||||
fits has an inactive timeline and keeps the 0px initial value (review P3), and the fade goes once the
|
||||
strip is scrolled to its end. Without scroll timelines the 48px fade is static. */
|
||||
@property --tabs-fade { syntax:'<length>'; inherits:false; initial-value:0px; }
|
||||
@keyframes project-tabs-cue { 0%, 92% { --tabs-fade:48px; } 100% { --tabs-fade:0px; } }
|
||||
@media (max-width:699px) {
|
||||
.project-tabs { mask-image:linear-gradient(to right, #000 calc(100% - var(--tabs-fade)), transparent 100%); }
|
||||
@supports (animation-timeline: scroll()) { .project-tabs { animation:project-tabs-cue linear both; animation-timeline:scroll(self inline); } }
|
||||
@supports not (animation-timeline: scroll()) { .project-tabs { --tabs-fade:48px; } }
|
||||
}
|
||||
.project-chip { white-space:nowrap; flex:none; }
|
||||
@media(max-width:699px) { .project-stepper span { white-space:nowrap; font-size:10.5px; padding:4px 1px; }.project-work-head { align-items:flex-start; } }
|
||||
|
||||
@@ -336,7 +346,8 @@ body:has(.chat-area .project-header):has(.project-chat) .breadcrumbs { margin-bo
|
||||
/* Header actions use the specified compact widths while retaining 44px targets. */
|
||||
.project-primary-action { box-sizing:border-box; flex:none; }
|
||||
@media (min-width:1200px) {
|
||||
.project-header:not([data-project-conversation="true"]) { width:calc(100vw - 270px); }
|
||||
/* E2E6 P2-11: 100vw counts the page scrollbar; max-width keeps the header inside its column. */
|
||||
.project-header:not([data-project-conversation="true"]) { width:calc(100vw - 270px); max-width:100%; box-sizing:border-box; }
|
||||
.project-header:not([data-project-conversation="true"]) .project-actions { align-self:flex-start; margin-top:4px; }
|
||||
.project-primary-action:nth-of-type(1) { width:130px; }
|
||||
.project-primary-action:nth-of-type(2) { width:88px; }
|
||||
@@ -504,3 +515,5 @@ body:has(.chat-area .project-header):has(.project-chat) .breadcrumbs { margin-bo
|
||||
|
||||
/* Keep the action in flow when a read error occupies the top of the page. */
|
||||
@media (min-width:700px) { .chat-area:has(.chat-error) .project-create:not([open]) { position:static; margin:12px 0; } }
|
||||
/* E2E6 P2-15: inline code in a chat bubble keeps the bubble's text colour on a light tint. */
|
||||
.project-chat .chat-body code { font-size:.92em; padding:0 .3em; border-radius:4px; background:color-mix(in srgb, currentColor 12%, transparent); color:inherit; }
|
||||
@@ -301,6 +301,11 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
|
||||
#agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)}
|
||||
@media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}}
|
||||
.settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px}
|
||||
/* E2E6 minor: the harness checkboxes sit side by side, each keeping its 44px target, instead of one per
|
||||
50px row. Save and the receipt keep their own full-width rows. */
|
||||
.settings-content fieldset.harness-control{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px}
|
||||
.settings-content fieldset.harness-control>legend{flex-basis:100%}
|
||||
.settings-content fieldset.harness-control>:is(button,p){flex-basis:100%}
|
||||
.settings-content :is(.instance-form,.level-form) textarea,.settings-content .assistant-form textarea{display:block;width:100%}
|
||||
.route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}}
|
||||
@media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}}
|
||||
@@ -444,6 +449,9 @@ html[data-organizations] .ws-btn:disabled,html[data-organizations] .ws-busctl [d
|
||||
html[data-organizations] .ws-btn svg.i{width:15px;height:15px}
|
||||
/* The live bus restart is console-restart.js's own button; it carries its icon through repaints,
|
||||
so the icon stays on the button however wide the receipt below it is. */
|
||||
/* E2E6 P2-13: the disabled pair (a pane, or a Console without the trail) sits in a flex row too. As two
|
||||
inline-flex boxes on one line, Restart bus took its baseline from its glyph and sat 2.6px above Stop bus. */
|
||||
html[data-organizations] [data-dashboard-bus]:not(.ws-busctl){display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px}
|
||||
html[data-organizations] .ws-busctl{display:inline-flex;flex-direction:column;align-items:flex-end}
|
||||
html[data-organizations] .ws-busctl .bus-restart{display:inline-flex;flex-direction:column;align-items:flex-end;gap:4px}
|
||||
html[data-organizations] .ws-busctl .bus-buttons{display:inline-flex;flex-wrap:wrap;gap:6px;justify-content:flex-end}
|
||||
@@ -477,6 +485,10 @@ html[data-organizations] .ws-panel.tight{padding:12px 14px}
|
||||
html[data-organizations] .ws-split{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:16px;align-items:start}
|
||||
html[data-organizations] .ws-split{margin-top:22px}
|
||||
html[data-organizations] .ws-split>section>.ws-sec-h:first-child{margin-top:0}
|
||||
/* E2E6 P1-3: the long editors (Autonomy, Packs, Workflows) span the page below the split, so neither
|
||||
column runs screens past the other at 1440. */
|
||||
html[data-organizations] .ws-wide{display:grid;grid-template-columns:minmax(0,1fr);gap:16px;margin-top:22px}
|
||||
html[data-organizations] .ws-wide>.panel{margin:0}
|
||||
|
||||
/* Organization dashboard (sample 03). */
|
||||
html[data-organizations] .ws-orghead{display:flex;flex-wrap:wrap;align-items:center;gap:14px;margin-bottom:14px}
|
||||
|
||||
@@ -43,9 +43,17 @@
|
||||
s.data = value;
|
||||
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
|
||||
}
|
||||
// E2E6 P1-1: a poll reloads the data but keeps the page's own state: an open editor and its draft,
|
||||
// a pending delete confirmation and the last receipt.
|
||||
async function load(org) {
|
||||
const s = { data: null, known: new Set(), error: null, editing: null, confirm: null, status: '' };
|
||||
try { await read(org, s); } catch (error) { s.error = error.message; }
|
||||
const prev = states.get(org);
|
||||
const s = { data: null, known: new Set(), error: null, editing: prev?.editing ?? null, confirm: prev?.confirm ?? null, status: prev?.status ?? '' };
|
||||
try { await read(org, s); } catch (error) {
|
||||
// Review P3: a failed poll while an editor is open keeps the last good read, so the fresh section
|
||||
// still carries its data-live-key and graftLive puts the held section, editor and focus back.
|
||||
if (prev?.editing && prev.data) Object.assign(s, { data: prev.data, known: prev.known });
|
||||
else s.error = error.message;
|
||||
}
|
||||
states.set(org, s);
|
||||
}
|
||||
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
|
||||
@@ -60,8 +68,8 @@
|
||||
const steps = Array.isArray(w?.steps) ? w.steps : [];
|
||||
const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name;
|
||||
const actions = !s.data.writable ? '' : confirm
|
||||
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes>Delete</button> <button class="btn" type="button" data-wf-delete-no>Keep</button></p>`
|
||||
: `<p><button class="btn" type="button" data-wf-edit>Edit</button> <button class="btn" type="button" data-wf-delete>Delete</button></p>`;
|
||||
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes data-focus-key="${esc(`wf-yes:${scope}:${name}`)}">Delete</button> <button class="btn" type="button" data-wf-delete-no data-focus-key="${esc(`wf-no:${scope}:${name}`)}">Keep</button></p>`
|
||||
: `<p><button class="btn" type="button" data-wf-edit data-focus-key="${esc(`wf-edit:${scope}:${name}`)}">Edit</button> <button class="btn" type="button" data-wf-delete data-focus-key="${esc(`wf-delete:${scope}:${name}`)}">Delete</button></p>`;
|
||||
return `<li class="wf-item" data-wf="${esc(name)}" data-wf-scope="${esc(scope)}"><strong data-wf-title>${esc(w?.title || name)}</strong> <span class="muted"><code>${esc(name)}</code></span>
|
||||
${w?.description ? `<p>${esc(w.description)}</p>` : ''}<ol class="wf-steps">${steps.map(st => stepItem(s, st)).join('')}</ol>${actions}</li>`;
|
||||
}
|
||||
@@ -81,7 +89,7 @@
|
||||
const scopeField = e.isNew
|
||||
? `<label>Where<select name="scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${e.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label><label>Name<input name="name" maxlength="64" value="${esc(e.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes"></label>`
|
||||
: `<p>${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, <code>${esc(e.name)}</code></p>`;
|
||||
return `<form class="wf-editor" data-wf-editor><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
|
||||
return `<form class="wf-editor" data-wf-editor data-live-hold><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(e.draft.title)}" autocomplete="off"></label>
|
||||
<label>Description<textarea name="description" maxlength="1000" rows="2">${esc(e.draft.description)}</textarea></label>
|
||||
${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}
|
||||
@@ -95,8 +103,8 @@
|
||||
const names = Object.keys(flows || {}).sort();
|
||||
return `<div class="wf-scope" data-wf-scope-list="${esc(scope)}"><h4>${esc(label)}</h4>${names.length ? `<ul class="wf-list">${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}</ul>` : '<p class="note">No workflows.</p>'}</div>`;
|
||||
}).join('');
|
||||
const add = s.data.writable ? (s.editing ? '' : '<p><button class="btn" type="button" data-wf-new>New workflow</button></p>') : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
|
||||
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
|
||||
const add = s.data.writable ? (s.editing ? '' : `<p><button class="btn" type="button" data-wf-new data-focus-key="${esc(`wf-new:${org}`)}">New workflow</button></p>`) : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
|
||||
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}" data-live-key="${esc(`workflows:${org}`)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
|
||||
}
|
||||
function redraw(org) {
|
||||
const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org);
|
||||
@@ -124,10 +132,10 @@
|
||||
if (!s?.data) return;
|
||||
const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf;
|
||||
if (button.hasAttribute('data-wf-new')) {
|
||||
s.editing = { isNew: true, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
|
||||
s.editing = { isNew: true, revision: s.data.revision, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
|
||||
} else if (button.hasAttribute('data-wf-edit')) {
|
||||
const w = flowsIn(s, scope)?.[name];
|
||||
s.editing = { isNew: false, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
|
||||
s.editing = { isNew: false, revision: s.data.revision, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
|
||||
} else if (button.hasAttribute('data-wf-cancel')) {
|
||||
s.editing = null;
|
||||
} else if (button.hasAttribute('data-wf-step-add')) {
|
||||
@@ -148,7 +156,10 @@
|
||||
}
|
||||
redraw(org);
|
||||
});
|
||||
// Every keystroke goes back into the draft, so any repaint draws what was typed.
|
||||
document.addEventListener('input', ev => {
|
||||
const form = ev.target.closest('[data-wf-editor]'), root = form?.closest('[data-workflows-org]');
|
||||
if (form && root) { const st = states.get(root.dataset.workflowsOrg); if (st?.editing) capture(root, st); }
|
||||
const field = ev.target.closest('[data-wf-edit-step] [name="roles"]');
|
||||
if (!field) return;
|
||||
const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg);
|
||||
@@ -168,6 +179,9 @@
|
||||
if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; }
|
||||
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
|
||||
if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; }
|
||||
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
|
||||
const unknown = e.draft.steps.flatMap((st, i) => st.roles.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r)).map(r => [i + 1, r]));
|
||||
if (unknown.length) { s.status = `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`; redraw(org); return; }
|
||||
const workflow = {
|
||||
...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}),
|
||||
...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}),
|
||||
@@ -176,7 +190,8 @@
|
||||
const button = ev.target.querySelector('button[type="submit"]');
|
||||
button.disabled = true;
|
||||
try {
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: s.data.revision, workflow, ...target(s, e.scope) });
|
||||
// The revision the editor opened on: a change made since then is a revision-conflict, not overwritten.
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: e.revision ?? s.data.revision, workflow, ...target(s, e.scope) });
|
||||
s.editing = null;
|
||||
await reload(org, s, `Saved ${e.name}.`);
|
||||
} catch (error) { s.status = error.message; }
|
||||
|
||||
@@ -5,7 +5,12 @@
|
||||
const read = async path => {
|
||||
const response = await fetch(path, { cache: 'no-store', redirect: 'manual' });
|
||||
// The status travels with the failure, so a caller can tell a refusal (403) from a bus that is down.
|
||||
if (!response.ok || response.type === 'opaqueredirect') { const error = new Error('Read unavailable'); error.status = response.type === 'opaqueredirect' ? 0 : response.status; throw error; }
|
||||
// E2E6 P2-6: the server's refusal code and its redacted message travel too, so a section can say why.
|
||||
if (!response.ok || response.type === 'opaqueredirect') {
|
||||
const error = new Error('Read unavailable'); error.status = response.type === 'opaqueredirect' ? 0 : response.status;
|
||||
if (response.type !== 'opaqueredirect') try { const body = await response.json(); if (typeof body?.error === 'string') error.code = body.error; if (typeof body?.message === 'string') error.detail = body.message; } catch { /* no JSON body */ }
|
||||
throw error;
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
const orgPath = (id, path) => `/api/orgs/${encodeURIComponent(id)}/${path}`;
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
}
|
||||
const av = (org, size = '') => `<span class="ws-av ws-o${size ? ` ${size}` : ''}" style="${colours(org)}" aria-hidden="true">${esc(initials(org))}</span>`;
|
||||
const label = org => org.label || org.id;
|
||||
const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : ['s-offline', '○', 'bus unavailable']);
|
||||
const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']);
|
||||
// A status mark: a glyph plus its word, shown or read aloud only.
|
||||
const dot = (cls, glyph, word, shown = false) => `<span class="ws-dot ${cls}" title="${esc(word)}"><b aria-hidden="true">${glyph}</b>${shown ? esc(word) : `<span class="ws-sr">${esc(word)}</span>`}</span>`;
|
||||
const orgHref = id => `#/orgs/${enc(id)}`;
|
||||
@@ -183,7 +183,7 @@
|
||||
['business', 'Organizations', orgCount === null ? unread : plural(orgCount, 'organization'), 'system', 'organizations'],
|
||||
['flag', 'About', typeof s?.release === 'string' ? `Release ${s.release}` : 'Address, release and notifier', 'system', 'about'],
|
||||
['people', 'Members and invites', 'Not built yet', 'not built', null],
|
||||
['restart', 'Bus', `${org.busHealthy ? 'Running' : 'Unavailable'} · restart from this page's header`, 'system', null],
|
||||
['restart', 'Bus', `${org.busHealthy ? 'Running' : org.busStopped ? 'Stopped' : 'Unavailable'} · restart from this page's header`, 'system', null],
|
||||
['close', 'Archive or delete', "Archive or delete this organization's file", 'danger', 'organizations'],
|
||||
];
|
||||
return `<ul class="ws-cfg one" data-org-settings>${rows.map(([ic, name, value, tag, page]) => {
|
||||
@@ -193,6 +193,40 @@
|
||||
}).join('')}</ul>`;
|
||||
}
|
||||
|
||||
// E2E6 P1-1: a poll repaints the whole page, which would drop an editor's draft and its focus. A
|
||||
// section marked data-live-key that is being edited (it holds [data-live-hold] or [data-live-dirty])
|
||||
// or holds focus is kept: holdLive takes it before the repaint and graftLive puts that same node, with
|
||||
// its typed values, caret and focus, in place of its fresh counterpart. Each editor saves against the
|
||||
// revision it started from, so a kept node cannot overwrite a change it never saw.
|
||||
const TYPING = 'input:not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio]),select,textarea';
|
||||
function holdLive(root) {
|
||||
const held = new Map(), a = document.activeElement;
|
||||
if (!root) return { held, active: null };
|
||||
// Focus alone holds a section only while it sits in a field being typed in. A focused button or link
|
||||
// is rebuilt with fresh data and gets its focus back through data-focus-key (review P3), so a section
|
||||
// never stays stale just because its Apply button kept focus.
|
||||
const typing = a?.matches?.(TYPING) ?? false;
|
||||
for (const el of root.querySelectorAll('[data-live-key]')) {
|
||||
if (el.matches('[data-live-hold]') || el.querySelector('[data-live-hold],[data-live-dirty]') || (typing && el.contains(a))) held.set(el.dataset.liveKey, el);
|
||||
}
|
||||
const active = a && [...held.values()].some(el => el.contains(a))
|
||||
? { el: a, caret: typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null } : null;
|
||||
return { held, active };
|
||||
}
|
||||
function graftLive(root, kept) {
|
||||
if (!root || !kept?.held?.size) return false;
|
||||
for (const el of root.querySelectorAll('[data-live-key]')) {
|
||||
const old = kept.held.get(el.dataset.liveKey);
|
||||
if (old && old !== el) el.replaceWith(old);
|
||||
}
|
||||
const a = kept.active;
|
||||
if (a && a.el.isConnected) {
|
||||
a.el.focus({ preventScroll: true });
|
||||
if (a.caret && typeof a.el.setSelectionRange === 'function') try { a.el.setSelectionRange(a.caret[0], a.caret[1]); a.el.scrollTop = a.caret[2]; } catch { /* not a text field */ }
|
||||
}
|
||||
return Boolean(a && a.el.isConnected);
|
||||
}
|
||||
|
||||
// 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 = {}) {
|
||||
@@ -202,7 +236,9 @@
|
||||
const list = Array.isArray(listRead) ? listRead : null;
|
||||
const org = list?.find(o => o.id === id && !o.invalid);
|
||||
if (!org) return `<article class="ws ws-dash" data-org-dashboard data-org-unavailable><div class="ws-vh"><h1 tabindex="-1">Organization unavailable</h1><p class="sub">${list ? 'This organization is not on your list.' : 'The organization list could not be read.'}</p></div></article>`;
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)]);
|
||||
// E2E6 P2-8: a stopped bus is not read for the bus-backed editors; each says the bus is stopped.
|
||||
const stopped = !org.busHealthy && org.busStopped === true;
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), ...(stopped ? [] : [window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)])]);
|
||||
const value = i => (reads[i].status === 'fulfilled' ? reads[i].value : null);
|
||||
const business = value(0), settings = value(1), instances = instancesOf(value(2));
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
|
||||
@@ -220,7 +256,7 @@
|
||||
const bus = restart ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
|
||||
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reload arrives with the cross-org update">${icon('doc')}Reload organization file</button>`;
|
||||
const [bcls, bglyph] = state(org);
|
||||
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
|
||||
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : org.busStopped ? `bus stopped, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
|
||||
|
||||
const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid;
|
||||
const docChips = !docRead ? '<span class="note">Docs unavailable</span>' : docRead.failed ? '<span class="note">Docs unavailable</span>' : docRead.rows.length ? docRead.rows.slice(0, 6).map(d => `<a class="ws-doc" href="#/docs/${enc(d.project)}/${enc(d.path)}" data-focus-key="${esc(`doc:${d.project}:${d.path}`)}" title="${esc(`${d.project}/${d.path}`)}">${icon('doc')}${esc(docName(d.path))}<small>${esc(projectName(d.project))}</small></a>`).join('') : '<span class="note">No docs yet</span>';
|
||||
@@ -242,9 +278,16 @@
|
||||
: threads ? `<span class="muted">Conversation</span><span class="t2">${esc(first.thread)}${more}</span>` : '<span class="muted">Conversation unavailable</span>';
|
||||
return `<tr><td>${esc(agent)}</td><td>${where}</td><td class="hide-m mono">${modelCell(agent, model)}</td><td>${dot(acls, aglyph, aword, true)}${count > 1 ? ` <span class="muted">${count} sessions</span>` : ''}</td></tr>`;
|
||||
}).join('');
|
||||
const sessions = live === null ? '<p class="ws-panel tight note">Sessions unavailable. The bus did not answer the instance read.</p>' : live.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Project and task</th><th scope="col" class="hide-m">Model</th><th scope="col">Status</th></tr></thead><tbody>${sessionRows}</tbody></table></div>` : '<p class="ws-panel tight note">No active agent sessions</p>';
|
||||
const sessions = live === null ? (stopped ? '<p class="ws-panel tight note" data-bus-stopped>Sessions not read: the bus is stopped.</p>' : '<p class="ws-panel tight note">Sessions unavailable. The bus did not answer the instance read.</p>') : live.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Project and task</th><th scope="col" class="hide-m">Model</th><th scope="col">Status</th></tr></thead><tbody>${sessionRows}</tbody></table></div>` : '<p class="ws-panel tight note">No active agent sessions</p>';
|
||||
const open = queue ? queue.filter(r => r?.state !== 'done').length : null;
|
||||
const queueNote = queue === null ? 'unavailable' : queue.length ? `${plural(queue.length, 'row')}, ${open} not done` : 'no rows';
|
||||
// E2E6 P2-6: a failed queue read says why, in the words the Queue page uses (server-redacted).
|
||||
const qerr = queue === null && reads[5].status === 'rejected' ? reads[5].reason : null;
|
||||
const queueWhy = queue !== null ? '' : `<p class="ws-panel tight note" data-org-queue-why>${qerr?.code === 'queue-refused' ? `The queue refused the read.${qerr.detail ? ` ${esc(qerr.detail.replace(/<path>/g, 'This checkout'))}` : ''}`
|
||||
: qerr?.status === 0 ? 'You are signed out. Reload the page to sign in again.'
|
||||
: qerr?.code === 'not-configured' ? 'This Console has no queue to read for this organization.'
|
||||
: `The queue read did not answer${qerr?.code ? ` (${esc(qerr.code)})` : ''}.`}</p>`;
|
||||
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>
|
||||
@@ -257,15 +300,18 @@
|
||||
${secH('Active agent sessions', live ? (live.length ? `${live.length} running` : 'none running') : '', '<a href="#/agents" data-focus-key="agents-all">All agents</a>')}
|
||||
${sessions}
|
||||
${secH('Queue', queueNote, '<a href="#/queue" data-org-queue data-focus-key="queue-open">Open queue</a>')}
|
||||
${queueWhy}
|
||||
</section>
|
||||
<section aria-label="Settings">
|
||||
${secH('Settings', 'every setting, with where its value comes from')}
|
||||
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null })}
|
||||
${window.MosaicAutonomy?.section(id)??''}
|
||||
${window.MosaicPacks?.section(id) ?? ''}
|
||||
${window.MosaicWorkflows?.section(id) ?? ''}
|
||||
</section>
|
||||
</div>
|
||||
<div class="ws-wide">
|
||||
${stopped ? stoppedPanel('data-autonomy', 'Autonomy') : window.MosaicAutonomy?.section(id) ?? ''}
|
||||
${stopped ? stoppedPanel('data-packs', 'Starter packs') : window.MosaicPacks?.section(id) ?? ''}
|
||||
${stopped ? stoppedPanel('data-workflows', 'Workflows') : window.MosaicWorkflows?.section(id) ?? ''}
|
||||
</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
@@ -514,7 +560,7 @@
|
||||
${tile('sessions', 'Sessions', sessN(t.sessions), `${num(t.sessions?.working)} working`, parts('sessions', x => sessN(x.sessions)), `${num(t.sessions?.waiting)} waiting on you · ${num(t.sessions?.idle)} idle${num(t.sessions?.live) ? ` · ${num(t.sessions.live)} live ${t.sessions.live === 1 ? 'thread' : 'threads'}` : ''}`)}
|
||||
${tile('tasks', 'Open tasks', num(t.openTasks), '', parts('tasks', x => x.openTasks), `<b>${num(t.doneThisWeek)}</b> done this week`)}
|
||||
${tile('projects', 'Projects', num(t.projects?.active) + num(t.projects?.archived), `${num(t.projects?.active)} active`, parts('projects', x => num(x.projects?.active) + num(x.projects?.archived)), `${num(t.projects?.archived)} archived`)}
|
||||
<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 read prices model use today.</span></div>
|
||||
<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 => {
|
||||
@@ -783,6 +829,6 @@
|
||||
|
||||
// U4b: the org mark (colour and initials) for the task board (tasks-board.js).
|
||||
const orgMark = Object.freeze({ ready: ensureThemes, av, colours, initials });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, setGrouping, get pollMs() { return pollMs; } });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, setGrouping, get pollMs() { return pollMs; } });
|
||||
refresh();
|
||||
})();
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -30,6 +30,8 @@ const ROWS = [
|
||||
row(3, reply('Unchecked.', [cite('Notes/Eyes.md', [1, 1], HOSTILE)])),
|
||||
row(4, JSON.stringify({ notice: 'library-write', op: 'write', path: 'Notes/Eyes.md', commit: C4 }), undefined, 'scribe'),
|
||||
row(5, JSON.stringify({ notice: 'library-write', op: 'delete', path: 'Fake/Claim.md', commit: C4 }), { citations: [] }, 'forger'),
|
||||
// E2E6 P2-15: a human message with inline code, a hostile span and an unpaired backtick.
|
||||
row(6, `Approve with \`mosaic project north-star work\`. Not \`${HOSTILE}\`, a lone \` stays.`, undefined, 'human'),
|
||||
];
|
||||
const STATUS = { project: 'books', version: 1, branch: 'main', served: C3, lastFetch: 'FIVE-MINUTES-AGO',
|
||||
lastError: { code: 'library-fetch-failed', at: '2026-10-23T18:00:00.000Z' }, diverged: { commit: C2, at: '2026-10-23T18:00:00.000Z' },
|
||||
@@ -83,6 +85,10 @@ test('chat replies: free text, cites with badges, the agent label, changed since
|
||||
const { b, text, message } = await setup(t);
|
||||
assert.equal(await text(`${message(1)} .chat-body`), 'Plain text answer.');
|
||||
assert.equal(await text(`${message(2)} .chat-body`), "Mara's eyes are grey.");
|
||||
// E2E6 P2-15: backtick pairs render as code and their contents stay text.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(message(6) + ' .chat-body code')})].map(c => c.textContent)`), ['mosaic project north-star work', HOSTILE]);
|
||||
assert.equal(await text(`${message(6)} .chat-body`), `Approve with mosaic project north-star work. Not ${HOSTILE}, a lone \` stays.`);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('.chat-log img').length`), 0);
|
||||
const cites = await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(message(2) + ' .chat-cites > li')})].map(li => ({
|
||||
badge: li.querySelector('.chat-scope')?.textContent ?? null, ref: (li.querySelector('a') ?? li.querySelector('code'))?.textContent,
|
||||
href: li.querySelector('a')?.getAttribute('href') ?? null, rel: li.querySelector('a')?.getAttribute('rel') ?? null,
|
||||
|
||||
@@ -326,12 +326,84 @@ test('D4 hire start: the other proposal checks that run before the decision inse
|
||||
assert.doesNotMatch(r.json().message,/\bhire was\b/,'worded for hire, fire and change alike');
|
||||
}
|
||||
});
|
||||
// Review P3: a code the broker can raise after the decision exists or is consumed, or one the bus
|
||||
// server raises about the request itself, is not a definite refusal of the start.
|
||||
test('D4 hire start: a code that can follow the decision insert, or a transport code, stays outcome-unknown',async()=>{
|
||||
for(const code of ['revision-conflict-revoked','request-timeout','invalid-envelope','incomplete-request','instance-kept','organization-instance-exists','organization-unknown-instance','root-fire-shared','fire-in-progress','some-future-code'])
|
||||
// E2E6 P1-2: every definite refusal of a start keeps its own code and a next step. Only a reply that
|
||||
// never came, could not be read, or the bus server's request codes stay outcome-unknown.
|
||||
test('E2E6 hire start: an unknown project, an unknown agent on fire and an unknown harness keep their code',async()=>{
|
||||
for(const [code,re] of [['project-agents-invalid',/code project/],['organization-unknown-instance',/Agents page/],['harness-off',/Settings > Routing/]]) {
|
||||
const {r,s}=await startWith(new BusReadError(code));
|
||||
assert.equal(r.status,409,`${code}: ${r.text}`);
|
||||
assert.equal(r.json().error,code);assert.match(r.json().message,re);
|
||||
// harness-off comes only from prepare()'s route check; the other two can also come from apply().
|
||||
if(code==='harness-off')assert.match(r.json().message,/ Nothing was applied\.$/);
|
||||
else {assert.match(r.json().message,/ Part of it may already be applied: check the Agents page before trying again\.$/);assert.doesNotMatch(r.json().message,/nothing was applied/i);}
|
||||
assert.match(s.lines.at(-1),new RegExp(`step=start error=${code}$`));
|
||||
}
|
||||
});
|
||||
test('E2E6 hire start: the other proposal and apply codes keep their code; apply-phase ones do not claim nothing changed',async()=>{
|
||||
for(const code of ['unknown-model','harness-refused']) {
|
||||
const {r}=await startWith(new BusReadError(code));
|
||||
assert.equal(r.json().error,code,`${code}: ${r.text}`);assert.match(r.json().message,/ Nothing was applied\.$/);
|
||||
}
|
||||
// Review finding 1: apply() runs check() again and the writers run after the consume, so these
|
||||
// never claim nothing changed, in any case or clause. The inbox lists no closed decision, so they
|
||||
// do not send the user there to tell which side of the consume the refusal came from (re-check).
|
||||
for(const code of ['organization-instance-exists','instance-kept','root-fire-shared','definition-rev-conflict','definition-missing','credential-leak','decision-stale','organization-instance-retired','organization-instance-referenced','organization-refused','definition-secret-check-required','not-configured','invalid-request']) {
|
||||
const {r}=await startWith(new BusReadError(code));
|
||||
assert.equal(r.json().error,code,`${code}: ${r.text}`);
|
||||
assert.doesNotMatch(r.json().message,/nothing was applied/i,`${code} does not claim nothing changed`);
|
||||
assert.doesNotMatch(r.json().message,/inbox/,`${code} does not point at the inbox, which drops a consumed decision`);
|
||||
assert.match(r.json().message,/Part of it may already be applied: check the Agents page/);
|
||||
}
|
||||
for(const code of ['organization-busy','fire-in-progress','credential-revoking']) {
|
||||
const {r}=await startWith(new BusReadError(code));
|
||||
assert.equal(r.status,409);assert.equal(r.json().error,code);
|
||||
assert.doesNotMatch(r.json().message,/Nothing was applied/);assert.match(r.json().message,/Agents page and the inbox/);
|
||||
}
|
||||
const {r}=await startWith(new BusReadError('some-future-code'));
|
||||
assert.equal(r.status,409);assert.equal(r.json().error,'some-future-code');assert.match(r.json().message,/Agents page and the inbox/);
|
||||
});
|
||||
test('E2E6 hire start: an apply-phase decision-stale on a fire does not say nothing was applied',async()=>{
|
||||
// #hireConsole consumes the decision and stops a project agent's runs before apply() checks again.
|
||||
const s=setup({resolve:()=>{throw new BusReadError('decision-stale');}});
|
||||
const r=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:{op:'fire',level:'project',project:'site',name:'coder',reason:'done'}}}));
|
||||
assert.equal(s.calls.length,1);assert.equal(r.status,409,r.text);assert.equal(r.json().error,'decision-stale');
|
||||
assert.doesNotMatch(r.json().message,/nothing was applied/i);
|
||||
assert.doesNotMatch(r.json().message,/inbox|answer it there/,'a consumed decision is gone from the inbox');
|
||||
assert.match(r.json().message,/check the Agents page/);
|
||||
});
|
||||
test('E2E6 hire start: invalid-request from the bus says the values, not the shape, were refused',async()=>{
|
||||
const {r}=await startWith(new BusReadError('invalid-request'));
|
||||
assert.equal(r.status,400);assert.equal(r.json().error,'invalid-request');assert.match(r.json().message,/Settings > Model proxy/);
|
||||
});
|
||||
test('E2E6 hire start: the bus server request codes and organization-uncertain stay outcome-unknown',async()=>{
|
||||
for(const code of ['revision-conflict-revoked','request-timeout','invalid-envelope','incomplete-request','organization-uncertain'])
|
||||
refused((await startWith(new BusReadError(code))).r,'outcome-unknown');
|
||||
});
|
||||
// E2E6 P2-4: a malformed proposal names its field and the rule, and never reaches the bus.
|
||||
test('E2E6 hire start: a malformed proposal names the field and the rule before the bus',async()=>{
|
||||
const cases=[
|
||||
[{...START_HIRE,name:'Bad Name'},'name',/lowercase/],
|
||||
[(({route,...h})=>h)(START_HIRE),'route',/harness and a model/],
|
||||
[{...START_HIRE,route:{harness:'pi'}},'route.model',/required/],
|
||||
[{...START_HIRE,level:'project'},'project',/code project/],
|
||||
[{...START_HIRE,project:'north'},'project',/only for project level/],
|
||||
[{...START_HIRE,reason:' '},'reason',/blank/],
|
||||
[{...START_HIRE,op:'promote'},'op',/hire, fire or change/],
|
||||
[{op:'fire',level:'org',name:'scout',reason:'r',route:START_HIRE.route},'route',/not used by fire/],
|
||||
[{...START_HIRE,role:{template:'coder',sha256:'x'}},'role.sha256',/digest/],
|
||||
[{...START_HIRE,role:{template:'coder',sha256:DIGEST,definition:'x'}},'role',/exactly one/],
|
||||
[{...START_HIRE,colour:'blue'},'colour',/not a hire field/],
|
||||
];
|
||||
for(const [hire,field,rule] of cases) {
|
||||
const s=setup({resolve:()=>{throw new Error('must not be called');}});
|
||||
const r=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire}}));
|
||||
assert.equal(r.status,400,`${field}: ${r.text}`);
|
||||
const body=r.json();
|
||||
assert.equal(body.error,'invalid-request');assert.equal(body.field,field);assert.match(body.rule,rule);
|
||||
assert.match(body.message,/Nothing was sent to the bus/);assert.ok(body.message.toLowerCase().startsWith(field.toLowerCase()),body.message);
|
||||
assert.equal(s.calls.length,0,`${field}: no bus call`);
|
||||
}
|
||||
});
|
||||
test('D4 hire start: a lost or unreadable reply is still outcome-unknown',async()=>{
|
||||
for(const err of [new BusReadError('outcome-unknown'),new BusReadError('invalid-response'),new BusReadError('response-too-large'),new BusReadError('outcome-unknown-revoked'),new BusReadError('Not A Code'),new BusReadError(''),new Error('socket closed'),Object.assign(new Error('x'),{code:'model-provider-unavailable'})])
|
||||
refused((await startWith(err)).r,'outcome-unknown');
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// E2E6 P2-11, P2-12, P2-13 (#1873): layout pins measured in a real browser.
|
||||
// P2-11: a project's header stays inside its column at desktop widths, so its actions are not cut off.
|
||||
// P2-12: at phone width the project tabs fade at the right edge while more tabs lie past it, and the
|
||||
// fade is gone once the row is scrolled to its end or when every tab fits.
|
||||
// P2-13: Restart bus and Stop bus share one top and height, on the organization page and in a pane.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fixture, close } from './fixture.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { P, stub } from './helpers/projects-review-fixture.mjs';
|
||||
|
||||
const until = (b, expression, what) => b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,25))}throw Error(${JSON.stringify(what)})})()`);
|
||||
const frames = b => b.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(()=>r(true))))');
|
||||
|
||||
async function project(t, width) {
|
||||
const f = await fixture(), b = await browser({ machine: false, args: ['--disable-extensions'] });
|
||||
t.after(async () => { await b.close(); await f.close(); });
|
||||
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: stub });
|
||||
await b.viewport(width, 900);
|
||||
await b.navigate(`${f.base}/#/projects/${P}`);
|
||||
await until(b, `document.querySelector('.project-header .project-actions')`, 'project header');
|
||||
await b.evaluate('new Promise(r=>setTimeout(r,400))');
|
||||
return b;
|
||||
}
|
||||
|
||||
for (const width of [1440, 1280]) {
|
||||
test(`E2E6 P2-11: the project header and its actions stay inside the column at ${width}`, { timeout: 60000 }, async t => {
|
||||
const b = await project(t, width);
|
||||
const m = JSON.parse(await b.evaluate(`JSON.stringify((()=>{const h=document.querySelector('.project-header'),p=h.parentElement.getBoundingClientRect(),r=h.getBoundingClientRect();return {right:r.right,parent:p.right,actions:[...h.querySelectorAll('.project-actions > *')].map(a=>a.getBoundingClientRect().right),page:[document.documentElement.scrollWidth,innerWidth]}})())`));
|
||||
assert.ok(m.right <= m.parent + 0.5, `header right ${m.right} inside its column ${m.parent}`);
|
||||
for (const a of m.actions) assert.ok(a <= m.parent + 0.5, `action right ${a} inside ${m.parent}`);
|
||||
assert.ok(m.page[0] <= m.page[1], 'no sideways page scroll');
|
||||
});
|
||||
}
|
||||
|
||||
test('E2E6 P2-12: at 390 the project tabs fade at the edge until scrolled to the end', { timeout: 60000 }, async t => {
|
||||
const b = await project(t, 390);
|
||||
const read = () => b.evaluate(`JSON.stringify((()=>{const e=document.querySelector('.project-tabs'),s=getComputedStyle(e);return {mask:s.maskImage||s.webkitMaskImage,fade:s.getPropertyValue('--tabs-fade').trim(),sw:e.scrollWidth,cw:e.clientWidth}})())`).then(JSON.parse);
|
||||
const start = await read();
|
||||
assert.ok(start.sw > start.cw, `the tabs overflow (${start.sw} > ${start.cw})`);
|
||||
assert.match(start.mask, /linear-gradient/, 'a fade mask is set');
|
||||
assert.equal(start.fade, '48px', 'a 48px fade while more tabs lie past the edge');
|
||||
await b.evaluate(`{const e=document.querySelector('.project-tabs');e.scrollLeft=e.scrollWidth}true`);
|
||||
await frames(b);
|
||||
assert.equal((await read()).fade, '0px', 'no fade once the row is scrolled to its end');
|
||||
// Review P3: a strip whose tabs all fit has nothing past the edge, so it has no fade.
|
||||
await b.evaluate(`{const e=document.querySelector('.project-tabs');[...e.children].slice(1).forEach(c=>c.style.display='none');e.scrollLeft=0}true`);
|
||||
await frames(b);
|
||||
const fits = await read();
|
||||
assert.ok(fits.sw <= fits.cw, `the remaining tab fits (${fits.sw} <= ${fits.cw})`);
|
||||
assert.equal(fits.fade, '0px', 'no fade when nothing is cut off');
|
||||
});
|
||||
|
||||
const org = {
|
||||
busHealthy: true, decisionWrite: async () => ({}), send: async () => ({}),
|
||||
requestRead: async () => { throw Object.assign(new Error('not-configured'), { code: 'not-configured' }); },
|
||||
reads: { business: async () => ({ business: { id: 'acme', projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
|
||||
bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
|
||||
chat: { projects: async () => [], threads: async () => [] },
|
||||
};
|
||||
for (const [width, route, where] of [[1440, 'orgs/acme/organization', 'the organization page'], [390, 'orgs/acme/organization', 'the organization page'], [1440, 'orgs/acme/side-by-side?a=acme/organization&b=acme/agents', 'a pane'], [390, 'orgs/acme/side-by-side?a=acme/agents&b=acme/organization&show=b', 'a pane']]) {
|
||||
test(`E2E6 P2-13: Restart bus and Stop bus line up on ${where} at ${width}`, { timeout: 60000 }, async t => {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: { list: async () => [{ id: 'acme', label: 'Acme', busHealthy: true }], resolve: async () => org } });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] });
|
||||
t.after(() => b.close());
|
||||
await b.viewport(width, 900);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/${route}`);
|
||||
const pair = `[...document.querySelectorAll('[data-bus-restart],[data-bus-restart-off],[data-bus-stop],[data-bus-stop-off]')].filter(e=>e.getClientRects().length)`;
|
||||
await until(b, `${pair}.length===2`, 'the two bus buttons');
|
||||
await b.evaluate('new Promise(r=>setTimeout(r,300))');
|
||||
const [restart, stop] = JSON.parse(await b.evaluate(`JSON.stringify(${pair}.map(e=>{const r=e.getBoundingClientRect();return {text:e.textContent.trim(),top:r.top,height:r.height,left:r.left,right:r.right}}))`));
|
||||
assert.equal(restart.text, 'Restart bus');
|
||||
assert.equal(stop.text, 'Stop bus');
|
||||
assert.ok(Math.abs(restart.top - stop.top) < 0.5, `same top (${restart.top} vs ${stop.top})`);
|
||||
assert.ok(Math.abs(restart.height - stop.height) < 0.5, `same height (${restart.height} vs ${stop.height})`);
|
||||
assert.ok(stop.left - restart.right >= 4, 'a gap between them');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// E2E6 P1-1, P2-2 (#1873): an editor in use on an organization's page survives the page's refresh. The
|
||||
// workflow editor's node, typed draft and focus, the autonomy form's unsaved choice and a pack's picked
|
||||
// project are kept when the page reads every section again. An apply refreshes the other sections.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const waitFor = (b, expression, what) => b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(what)}+': '+document.body.innerText.slice(0,2000))})()`);
|
||||
const REV = n => String(n).repeat(64);
|
||||
|
||||
async function fixture(t) {
|
||||
const counts = { workflows: 0, autonomy: 0, packs: 0 };
|
||||
// ctl lets a test fail the next reads or change what the packs read returns.
|
||||
const ctl = { workflowsFail: false, autonomyFail: false, packLabel: 'Web project' };
|
||||
const flows = {
|
||||
revision: REV('a'),
|
||||
document: {
|
||||
workflows: { intake: { title: 'Intake', steps: [{ title: 'Sort', state: 'todo', roles: ['human'] }] } },
|
||||
projects: { site: { workflows: {} }, docs: { workflows: {} } },
|
||||
definitions: {},
|
||||
},
|
||||
templates: ['coder'],
|
||||
};
|
||||
const read = async verb => {
|
||||
if (verb === 'packs.console') { counts.packs++; return { packs: [{ id: 'web-project', origin: 'installed', pack: { label: ctl.packLabel, description: 'A board.', version: '0.2.0', scope: 'project' } }] }; }
|
||||
if (verb === 'pack.preview.console') return { pack: { id: 'web-project', version: '0.2.0', label: 'Web project', origin: 'installed', scope: 'project' }, project: 'docs', revision: REV('c'), items: [{ item: 'board', name: 'board', target: 'board', path: 'board', mark: 'add' }], hires: [], skills: { notEnabled: [] }, chief: true, plan: {}, digest: REV('d') };
|
||||
if (verb === 'autonomy.get.console') { counts.autonomy++; if (ctl.autonomyFail) throw Object.assign(new Error('bus-unreachable'), { code: 'bus-unreachable' }); return { revision: REV('e'), autonomy: { merge: 'out of the loop' }, levels: { 'cross-role': 'out of the loop', merge: 'out of the loop', policy: 'out of the loop', authority: 'in the loop' } }; }
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const write = async (verb, args) => {
|
||||
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board'], pack: { id: args.pack, version: '0.2.0' } };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const server = await startServer({
|
||||
port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {},
|
||||
organizations: {
|
||||
list: async () => [{ id: 'acme', label: 'Acme', busHealthy: true }],
|
||||
resolve: async () => ({
|
||||
busHealthy: true, decisionWrite: async () => ({}), requestRead: read, requestWrite: read, packsWrite: write,
|
||||
workflowsRead: async () => { counts.workflows++; if (ctl.workflowsFail) throw Object.assign(new Error('bus-unreachable'), { code: 'bus-unreachable' }); return structuredClone(flows); }, send: async () => ({}),
|
||||
reads: { business: async () => ({ business: { id: 'acme', projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
|
||||
bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
|
||||
chat: { projects: async () => [], threads: async () => [] },
|
||||
}),
|
||||
},
|
||||
});
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] });
|
||||
t.after(() => b.close());
|
||||
await b.viewport(1440, 900);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`);
|
||||
// poll: wait for the page's own 10-second poll. Otherwise send the event a write on the page sends,
|
||||
// which repaints /organization the same way.
|
||||
const refresh = async ({ poll = false } = {}) => {
|
||||
const n = counts.workflows;
|
||||
if (!poll) await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
|
||||
for (let i = 0; i < 500 && counts.workflows === n; i++) await new Promise(r => setTimeout(r, 30));
|
||||
assert.ok(counts.workflows > n, 'the refresh read the workflows again');
|
||||
await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),200))`);
|
||||
};
|
||||
return { b, counts, ctl, refresh };
|
||||
}
|
||||
|
||||
test('E2E6 P1-1: an open workflow editor keeps its node, draft and focus across a refresh', { timeout: 60000 }, async t => {
|
||||
const { b, refresh } = await fixture(t);
|
||||
await waitFor(b, `document.querySelector('[data-wf="intake"] [data-wf-edit]')`, 'workflow list');
|
||||
await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor');
|
||||
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');window.__editor=f;const i=f.querySelector('input[name=title]');i.value='Intake, revised';i.focus();i.setSelectionRange(3,3);f.querySelector('[data-wf-edit-step="0"] [name=roles]').value='human, coder'}true`);
|
||||
await refresh({ poll: true });
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true, 'the same editor node');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf-editor]').length`), 1);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Intake, revised');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] [data-wf-edit-step="0"] [name=roles]').value`), 'human, coder');
|
||||
assert.equal(await b.evaluate(`document.activeElement===document.querySelector('[data-wf-editor] input[name=title]')`), true, 'focus stays in the field');
|
||||
assert.equal(await b.evaluate(`document.activeElement.selectionStart`), 3, 'the caret stays put');
|
||||
// A second refresh with focus elsewhere still keeps the open editor: it holds data-live-hold.
|
||||
await b.evaluate(`document.activeElement.blur();true`);
|
||||
await refresh();
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Intake, revised');
|
||||
// Cancel closes it; the next refresh paints the list fresh.
|
||||
await b.evaluate(`document.querySelector('[data-wf-cancel]').click();true`);
|
||||
await waitFor(b, `!document.querySelector('[data-wf-editor]')`, 'cancel');
|
||||
await refresh();
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')`), null);
|
||||
});
|
||||
|
||||
test('E2E6 P1-1, P2-14: an unsaved autonomy choice, a picked pack project and a focused link survive the poll', { timeout: 60000 }, async t => {
|
||||
const { b, refresh } = await fixture(t);
|
||||
await waitFor(b, `document.querySelector('[data-autonomy-form] select[name=merge]')&&document.querySelector('[data-pack-project]')`, 'autonomy and packs');
|
||||
await b.evaluate(`{const s=document.querySelector('[data-autonomy-form] select[name=merge]');s.value='in the loop';s.dispatchEvent(new Event('change',{bubbles:true}));window.__auto=document.querySelector('[data-autonomy-form]')}true`);
|
||||
await b.evaluate(`{const s=document.querySelector('[data-pack-project]');s.value='docs';s.dispatchEvent(new Event('change',{bubbles:true}));s.blur()}true`);
|
||||
// P2-14: a visible Open link outside any editor keeps focus through restore(). (The tester's "Open
|
||||
// Inbox →" is the legacy dashboard card outside #bus-view, hidden on this page, so it never took focus.)
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-focus-key="set:Identity"]').focus();document.activeElement.dataset.focusKey`), 'set:Identity');
|
||||
await refresh({ poll: true });
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey??document.activeElement.tagName`), 'set:Identity', 'focus stays on the link');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]')===window.__auto`), true, 'the dirty form is kept');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`), 'in the loop');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-project]').value`), 'docs', 'the picked project is kept');
|
||||
});
|
||||
|
||||
test('E2E6 P2-2: a pack apply re-reads the other sections and keeps its receipt', { timeout: 60000 }, async t => {
|
||||
const { b, counts } = await fixture(t);
|
||||
await waitFor(b, `document.querySelector('[data-pack="web-project"] [data-pack-preview-button]')`, 'pack list');
|
||||
await b.evaluate(`{const s=document.querySelector('[data-pack-project]');s.value='docs';s.dispatchEvent(new Event('change',{bubbles:true}))}true`);
|
||||
await b.evaluate(`document.querySelector('[data-pack-preview-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-pack-apply]')`, 'preview');
|
||||
const before = { ...counts };
|
||||
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
|
||||
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'')`, 'apply');
|
||||
for (let i = 0; i < 300 && counts.workflows === before.workflows; i++) await new Promise(r => setTimeout(r, 30));
|
||||
assert.ok(counts.workflows > before.workflows, 'workflows read again after the apply');
|
||||
assert.ok(counts.autonomy > before.autonomy, 'autonomy read again after the apply');
|
||||
await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),300))`);
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), /^Applied\. Added board\./, 'the receipt survives the re-read');
|
||||
});
|
||||
|
||||
test('E2E6 review P3: a failed read keeps an open editor, Discard drops a held form, a focused button does not hold its section, and a clean form shows a failed read', { timeout: 60000 }, async t => {
|
||||
const { b, ctl, refresh } = await fixture(t);
|
||||
await waitFor(b, `document.querySelector('[data-wf="intake"] [data-wf-edit]')&&document.querySelector('[data-autonomy-form] select[name=merge]')&&document.querySelector('[data-pack-preview-button]')`, 'sections');
|
||||
// A focused Preview button alone no longer holds the packs section: the next poll shows a changed
|
||||
// pack and focus comes back to the rebuilt button through its data-focus-key.
|
||||
await b.evaluate(`document.querySelector('[data-pack-preview-button]').focus();true`);
|
||||
ctl.packLabel = 'Web project, renamed';
|
||||
await refresh({ poll: true });
|
||||
await waitFor(b, `/Web project, renamed/.test(document.querySelector('[data-packs-org]').textContent)`, 'the renamed pack');
|
||||
assert.match(await b.evaluate(`document.activeElement.dataset.focusKey??document.activeElement.tagName`), /^pack-preview:acme:web-project$/, 'focus returns to the rebuilt button');
|
||||
// One failed workflows read while the editor is open keeps the same editor node, draft and focus.
|
||||
await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor');
|
||||
await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');window.__editor=f;const i=f.querySelector('input[name=title]');i.value='Typed during an outage';i.focus()}true`);
|
||||
// A dirty autonomy form survives a failed autonomy read the same way.
|
||||
await b.evaluate(`{const s=document.querySelector('[data-autonomy-form] select[name=merge]');s.value='in the loop';s.dispatchEvent(new Event('change',{bubbles:true}));window.__auto=document.querySelector('[data-autonomy-form]')}true`);
|
||||
await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').focus();true`);
|
||||
ctl.workflowsFail = true; ctl.autonomyFail = true;
|
||||
await refresh({ poll: true });
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true, 'the same editor node after a failed read');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Typed during an outage');
|
||||
assert.equal(await b.evaluate(`document.activeElement===document.querySelector('[data-wf-editor] input[name=title]')`), true, 'focus stays in the field');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]')===window.__auto`), true, 'the dirty autonomy form is kept after a failed read');
|
||||
// Discard draws the last read in place of the held form.
|
||||
ctl.workflowsFail = false; ctl.autonomyFail = false;
|
||||
await b.evaluate(`document.querySelector('[data-autonomy-discard]').click();true`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]')!==window.__auto`), true, 'a fresh form');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`), 'out of the loop', 'the stored value is back');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').hasAttribute('data-live-dirty')`), false);
|
||||
assert.equal(await b.evaluate(`document.activeElement.hasAttribute('data-autonomy-discard')`), true, 'focus stays on Discard');
|
||||
// Re-check P3: a focused button in a clean form gets its focus back after the poll repaints it.
|
||||
await refresh({ poll: true });
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey??document.activeElement.tagName`), 'autonomy-discard:acme', 'focus returns to Discard after a poll');
|
||||
// Re-check P3: a clean form the page does not hold shows a failed read instead of hiding it.
|
||||
await b.evaluate(`document.activeElement.blur();true`);
|
||||
ctl.autonomyFail = true;
|
||||
await refresh({ poll: true });
|
||||
await waitFor(b, `!document.querySelector('[data-autonomy-form]')&&/bus-unreachable|could not|refused/i.test(document.querySelector('[data-autonomy]')?.textContent??'')`, 'the autonomy read error');
|
||||
ctl.autonomyFail = false;
|
||||
await refresh({ poll: true });
|
||||
await waitFor(b, `document.querySelector('[data-autonomy-form] select[name=merge]')`, 'the form after a good read');
|
||||
});
|
||||
@@ -26,13 +26,18 @@ async function accessibleName(b, selector) {
|
||||
for (const width of [1440,390]) {
|
||||
test(`S8 project action icons, accessible names and positions at ${width}`, async t => {
|
||||
const {b,wait} = await setup(t,width);
|
||||
const expected = width === 1440 ? [[1060,1190],[1202,1290],[1302,1418]] : [[12,132],[140,220],[228,340]];
|
||||
// E2E6 P2-11 (#1873): at 1440 the actions end 22px inside the content edge. A page tall enough to
|
||||
// scroll has a scrollbar (sb wide), so the design's x values move left by its width on that route:
|
||||
// 1418 was 100vw-based and ran under the scrollbar, which clipped Settings.
|
||||
const design = width === 1440 ? [[1060,1190],[1202,1290],[1302,1418]] : [[12,132],[140,220],[228,340]];
|
||||
const y = width === 1440 ? [130,174] : [198,242];
|
||||
for (const route of ['', '/conversations', '/tasks', '/requirements', '/files', '/settings', ...(width === 1440 ? ['/room'] : [])]) {
|
||||
if (route) {
|
||||
await b.evaluate(`location.hash=${JSON.stringify(route === '/room' ? '#/projects/rooms/'+P : '#/projects/'+P+route)}`);
|
||||
await wait(`document.querySelector('.project-header')?.dataset.projectSection===${JSON.stringify(route.slice(1))}`);
|
||||
}
|
||||
const sb = width === 1440 ? await b.evaluate('innerWidth-document.documentElement.clientWidth') : 0;
|
||||
const expected = design.map(x => x.map(v => v - sb));
|
||||
for (const [i,name] of ['North star','PRD','Settings'].entries()) {
|
||||
const selector = `.project-header .project-primary-action:nth-of-type(${i+1})`;
|
||||
const data = await b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(selector)}),r=e.getBoundingClientRect();return {icon:!!e.querySelector('svg[aria-hidden="true"]'),left:r.left,right:r.right,top:r.top,bottom:r.bottom}})()`);
|
||||
|
||||
@@ -65,10 +65,13 @@ for (const zoom of [true,false]) test(`S9 project routes reflow at ${zoom ? 'act
|
||||
});
|
||||
for(const width of [1440,390]) test(`S9 Overview action and S8 header boxes at ${width}`,async t=>{
|
||||
const {b}=await setup(t,width);
|
||||
const data=await b.evaluate(`(()=>{const rect=e=>{const r=e.getBoundingClientRect();return [r.left,r.top,r.right,r.bottom]};return {button:rect(document.querySelector('[data-project-content] .project-section-title .btn')),section:rect(document.querySelector('.project-columns > section')),headers:[...document.querySelectorAll('.project-primary-action')].map(rect)}})()`);
|
||||
const data=await b.evaluate(`(()=>{const rect=e=>{const r=e.getBoundingClientRect();return [r.left,r.top,r.right,r.bottom]};return {sb:innerWidth-document.documentElement.clientWidth,button:rect(document.querySelector('[data-project-content] .project-section-title .btn')),section:rect(document.querySelector('.project-columns > section')),headers:[...document.querySelectorAll('.project-primary-action')].map(rect)}})()`);
|
||||
if(process.env.S9_CAPTURE) await b.screenshot(`${process.env.S9_CAPTURE}/${process.env.S9_PHASE}-overview-${width}.png`);
|
||||
if(process.env.S9_MEASURE) console.log('S9 geometry',width,JSON.stringify(data));
|
||||
const expected=width===1440?[[1060,130,1190,174],[1202,130,1290,174],[1302,130,1418,174]]:[[12,198,132,242],[140,198,220,242],[228,198,340,242]];
|
||||
// E2E6 P2-11 (#1873): at 1440 the header actions end 22px inside the content edge, so the design's
|
||||
// x values move left by the page scrollbar when the page scrolls (1418 was 100vw-based and clipped Settings).
|
||||
const sb=width===1440?data.sb:0;
|
||||
const expected=(width===1440?[[1060,130,1190,174],[1202,130,1290,174],[1302,130,1418,174]]:[[12,198,132,242],[140,198,220,242],[228,198,340,242]]).map(([x0,y0,x1,y1])=>[x0-sb,y0,x1-sb,y1]);
|
||||
for(let i=0;i<3;i++) for(let j=0;j<4;j++) assert.ok(Math.abs(data.headers[i][j]-expected[i][j])<=4,`header ${i}: ${JSON.stringify(data.headers[i])}`);
|
||||
// The accepted shell reserves a scrollbar and narrows the content; the
|
||||
// action must align to its section when that puts the target right edge out of reach.
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user