fix(org): enforce autonomy budgets and durable inverse boundaries (#1873)
This commit is contained in:
1 parent
0ef6326084
commit
e3232b814f
20 files changed
+352
-78
No files matched your search
@@ -14,10 +14,20 @@ export function autonomyHost({writer,dataRoot,business,hires,reload,processing,e
|
|||||||
const live=reload(id);return {...result,restart:live===false};
|
const live=reload(id);return {...result,restart:live===false};
|
||||||
},
|
},
|
||||||
reversible:cls=>['cross-role','merge'].includes(cls) || cls==='authority' && typeof hires?.reverse==='function',
|
reversible:cls=>['cross-role','merge'].includes(cls) || cls==='authority' && typeof hires?.reverse==='function',
|
||||||
async reverse({business:id,decision,decisionClass,raised,effects,actor,beforeWrite,fire,stop,relaunch,record}) {
|
async reverse({business:id,decision,decisionClass,raised,effects,actor,beforeWrite,beforePublish,fire,stop,complete,relaunch,record}) {
|
||||||
if(decisionClass==='authority') {
|
if(decisionClass==='authority') {
|
||||||
if(!hires?.reverse)refuse('reversal-unavailable');
|
if(!hires?.reverse)refuse('reversal-unavailable');
|
||||||
const result=await hires.reverse(id,decision,{actor,beforeWrite,fire,stop,relaunch,record});reload(id);if(result.relaunch){beforeWrite();await relaunch(result.relaunch);}return {transaction:result.transaction??null};
|
let stopped;
|
||||||
|
const result=await hires.reverse(id,decision,{actor,beforeWrite,beforePublish,fire,stop:async p=>{const r=await stop(p);stopped=p;return r;},relaunch,record});
|
||||||
|
if(stopped)complete?.(stopped,result);
|
||||||
|
// The writer admitted publication within the window. Reload and relaunch
|
||||||
|
// complete that committed inverse; crossing the deadline here cannot undo it.
|
||||||
|
const receipt={committed:true,transaction:result.transaction??null,relaunch:result.relaunch?'pending':'not-needed'};
|
||||||
|
try {
|
||||||
|
if(reload(id)===false)receipt.restart=true;
|
||||||
|
if(result.relaunch && !receipt.restart){await relaunch(result.relaunch);receipt.relaunch='requested';}
|
||||||
|
} catch {receipt.restart=true;if(result.relaunch)receipt.relaunch='failed';}
|
||||||
|
record(receipt);return receipt;
|
||||||
}
|
}
|
||||||
const used=effects.filter(e=>e.operation!=='decision.raise' && !String(e.operation??'').startsWith('autonomy.'));
|
const used=effects.filter(e=>e.operation!=='decision.raise' && !String(e.operation??'').startsWith('autonomy.'));
|
||||||
// An unused approval has changed no task or policy. Reversing it revokes that permission.
|
// An unused approval has changed no task or policy. Reversing it revokes that permission.
|
||||||
@@ -44,3 +54,35 @@ export function autonomyHost({writer,dataRoot,business,hires,reload,processing,e
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The runtime adapter is shared with integration tests, including key revocation order.
|
||||||
|
export function authorityHost(service,{modelKeys,reload,proxyOrganization}) {
|
||||||
|
return {
|
||||||
|
...service,
|
||||||
|
reverse:async(id,decision,caller)=>{
|
||||||
|
const proposal=service.read(decision);
|
||||||
|
if(!modelKeys || (proposal.level==='org' && proposal.op==='hire'))return service.reverse(id,decision,caller);
|
||||||
|
const instance=`${id}/${proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name}`;
|
||||||
|
let prepared=false;
|
||||||
|
return service.reverse(id,decision,{
|
||||||
|
...caller,
|
||||||
|
beforeWrite:()=>{caller.beforeWrite();if(prepared){modelKeys.completeRevoke(instance);prepared=false;}caller.beforeWrite();},
|
||||||
|
stop:async(p,guard)=>{await modelKeys.prepareRevoke(instance,guard);prepared=true;return caller.stop(p);},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
apply:async(id,decision,caller)=>{
|
||||||
|
const proposal=service.read(decision);
|
||||||
|
const publish=async()=>{
|
||||||
|
let approved=caller;
|
||||||
|
if(modelKeys && proposal.op==='fire' && proposal.level!=='org') {
|
||||||
|
const instance=`${id}/${proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name}`;
|
||||||
|
await modelKeys.prepareRevoke(instance,()=>caller.beforeWrite?.());
|
||||||
|
approved={...caller,beforeWrite:()=>{caller.beforeWrite?.();modelKeys.completeRevoke(instance);caller.beforeWrite?.();}};
|
||||||
|
}
|
||||||
|
const result=await service.apply(id,decision,approved);reload(id);return result;
|
||||||
|
};
|
||||||
|
if(proxyOrganization && proposal.level==='org' && proposal.op==='hire')return proxyOrganization.hire(id,proposal.name,()=>service.check(id,decision,caller),publish);
|
||||||
|
return publish();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ export function autonomyEvent(q, business, decision, operations) {
|
|||||||
return row?{...row,body:JSON.parse(row.body)}:null;
|
return row?{...row,body:JSON.parse(row.body)}:null;
|
||||||
}
|
}
|
||||||
export function decisionResolution(q, business, decision) {
|
export function decisionResolution(q, business, decision) {
|
||||||
|
const terminal=q.get("SELECT * FROM decision_events WHERE decision=? AND op IN ('withdrawn','expired') ORDER BY seq DESC LIMIT 1",decision);
|
||||||
|
if(terminal)return terminal;
|
||||||
const overlay=autonomyEvent(q,business,decision,['autonomy.resolved','autonomy.declined']);
|
const overlay=autonomyEvent(q,business,decision,['autonomy.resolved','autonomy.declined']);
|
||||||
if(overlay)return overlay.body.operation==='autonomy.declined'?null:{...overlay.body.resolution,seq:overlay.seq};
|
if(overlay)return overlay.body.operation==='autonomy.declined'?null:{...overlay.body.resolution,seq:overlay.seq};
|
||||||
return q.get("SELECT * FROM decision_events WHERE decision=? AND op IN ('resolved','withdrawn','expired') ORDER BY seq DESC LIMIT 1",decision);
|
return q.get("SELECT * FROM decision_events WHERE decision=? AND op IN ('resolved','withdrawn','expired') ORDER BY seq DESC LIMIT 1",decision);
|
||||||
|
|||||||
+34
-13
@@ -1,5 +1,5 @@
|
|||||||
import { autonomyEvent, decisionResolution } from './autonomy-state.mjs';
|
import { autonomyEvent, decisionResolution } from './autonomy-state.mjs';
|
||||||
import { autonomyClass, checkAutonomy, decisionAutonomy, resolverSubject } from '../../organization/src/autonomy.mjs';
|
import { autonomyClass, authorityBudgetCovered, checkAutonomy, decisionAutonomy, resolverSubject } from '../../organization/src/autonomy.mjs';
|
||||||
import { ownRails } from '../../organization/src/rails.mjs';
|
import { ownRails } from '../../organization/src/rails.mjs';
|
||||||
import { refusalGuidance } from './refusals.mjs';
|
import { refusalGuidance } from './refusals.mjs';
|
||||||
import { PROXY_PAGE_VERBS, PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
|
import { PROXY_PAGE_VERBS, PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
|
||||||
@@ -3348,24 +3348,26 @@ export class Broker {
|
|||||||
const job = (async () => {
|
const job = (async () => {
|
||||||
try {
|
try {
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
await run();
|
return await run();
|
||||||
} finally {
|
} finally {
|
||||||
this.#revoking.delete(key);
|
this.#revoking.delete(key);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
this.#grantJobs.add(job);
|
this.#grantJobs.add(job);
|
||||||
job.catch(() => {}).finally(() => this.#grantJobs.delete(job));
|
job.catch(() => {}).finally(() => this.#grantJobs.delete(job));
|
||||||
|
return job;
|
||||||
}
|
}
|
||||||
// Section 2, the fire's job: step G, then step B and step C. A step G refusal is section 4's record. A
|
// Section 2, the fire's job: step G, then step B and step C. A step G refusal is section 4's record. A
|
||||||
// step B or C failure is fire.failed (d6, C1). Step C records the authority the verb checked, with no
|
// step B or C failure is fire.failed (d6, C1). Step C records the authority the verb checked, with no
|
||||||
// holder check, since the chief's run may have ended since.
|
// holder check, since the chief's run may have ended since.
|
||||||
async #fireJob(sc, args, authority, write, job, set) {
|
async #fireJob(sc, args, authority, write, job, set,propagate=false) {
|
||||||
const name = args.name;
|
const name = args.name;
|
||||||
let out;
|
let out;
|
||||||
try {
|
try {
|
||||||
out = await this.#stepG(sc.business, name, set, { job, reason: args.reason, by: sc.role, flag: { fire: true } });
|
out = await this.#stepG(sc.business, name, set, { job, reason: args.reason, by: sc.role, flag: { fire: true } });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.#store.transaction(() => this.#grantRefused(sc.business, name, 'instance.fire', job, e.grantRefusal, sc.role));
|
this.#store.transaction(() => this.#grantRefused(sc.business, name, 'instance.fire', job, e.grantRefusal, sc.role));
|
||||||
|
if(propagate)throw e;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let step = 'B';
|
let step = 'B';
|
||||||
@@ -3377,6 +3379,7 @@ export class Broker {
|
|||||||
else this.#recordAuthority(sc, 'role.fire', authority, { reason: args.reason, transaction: result.transaction ?? null });
|
else this.#recordAuthority(sc, 'role.fire', authority, { reason: args.reason, transaction: result.transaction ?? null });
|
||||||
this.#event(sc, 'action.allowed', { action: 'fire.done', transaction: result.transaction ?? null, job, grants: out.grants, grantsLeft: out.grantsLeft }, name);
|
this.#event(sc, 'action.allowed', { action: 'fire.done', transaction: result.transaction ?? null, job, grants: out.grants, grantsLeft: out.grantsLeft }, name);
|
||||||
});
|
});
|
||||||
|
return result;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const code = e instanceof BusError ? e.code : 'outcome-unknown';
|
const code = e instanceof BusError ? e.code : 'outcome-unknown';
|
||||||
const list = out.grants.map((g) => g.grant).join(', ') || 'none';
|
const list = out.grants.map((g) => g.grant).join(', ') || 'none';
|
||||||
@@ -3389,6 +3392,7 @@ export class Broker {
|
|||||||
`Fire of ${name}: job ${job} revoked its grants (${list}) but stopped at step ${step} (${code}).${tokens} The instance is still firing. Run the fire again once ${code} is cleared.`,
|
`Fire of ${name}: job ${job} revoked its grants (${list}) but stopped at step ${step} (${code}).${tokens} The instance is still firing. Run the fire again once ${code} is cleared.`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
if(propagate)throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Section 2, the delete's job: step G, then grants.revoked.done and the end message.
|
// Section 2, the delete's job: step G, then grants.revoked.done and the end message.
|
||||||
@@ -6402,6 +6406,7 @@ export class Broker {
|
|||||||
// Lead ruling: policy has no effect executor. Its existing out and in levels
|
// Lead ruling: policy has no effect executor. Its existing out and in levels
|
||||||
// remain usable; near refuses in checkAutonomy until an inverse exists.
|
// remain usable; near refuses in checkAutonomy until an inverse exists.
|
||||||
if(cls==='policy')continue;
|
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(['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 || !this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition');
|
||||||
const resolvers=cls==='authority'?[a.autonomy.authorityResolver]:cls==='merge'?[b.arbiters.technical]:cls==='policy'?[b.arbiters.delivery]:Object.values(b.arbiters);
|
const resolvers=cls==='authority'?[a.autonomy.authorityResolver]:cls==='merge'?[b.arbiters.technical]:cls==='policy'?[b.arbiters.delivery]:Object.values(b.arbiters);
|
||||||
@@ -6410,13 +6415,15 @@ export class Broker {
|
|||||||
if(!role?.authority?.withinRole.includes(right) || (cls==='authority' && name===b.launch?.by))fail('autonomy-precondition');
|
if(!role?.authority?.withinRole.includes(right) || (cls==='authority' && name===b.launch?.by))fail('autonomy-precondition');
|
||||||
}
|
}
|
||||||
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition');
|
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition');
|
||||||
if(cls==='authority' && !b.launch?.limits?.tokens)fail('autonomy-precondition');
|
if(cls==='authority' && !authorityBudgetCovered(b))fail('autonomy-precondition');
|
||||||
if(after==='out of the loop') {
|
if(after==='out of the loop') {
|
||||||
if(before!=='near the loop')fail('autonomy-precondition');
|
if(before!=='near the loop')fail('autonomy-precondition');
|
||||||
const review=this.#store.get("SELECT 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 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);
|
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');
|
||||||
if(cls==='authority' && Object.keys(b.roles).some(name=>!b.launch?.limits?.tokens?.instances?.[name]?.limit))fail('autonomy-precondition');
|
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');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'autonomy.set.requested',autonomy:a.autonomy,subject:s.console},null));
|
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'autonomy.set.requested',autonomy:a.autonomy,subject:s.console},null));
|
||||||
@@ -6450,7 +6457,12 @@ export class Broker {
|
|||||||
const effects=this.#store.all("SELECT body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.decision')=? ORDER BY seq",s.business,d.id).map(e=>JSON.parse(e.body));
|
const effects=this.#store.all("SELECT body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.decision')=? ORDER BY seq",s.business,d.id).map(e=>JSON.parse(e.body));
|
||||||
let recorded=false;
|
let recorded=false;
|
||||||
const result=await this.#autonomyHost.reverse({business:s.business,decision:d.id,decisionClass:autonomyClass(d.action),action:d.action,raised:this.#raised(s.business,d.id),effects,actor:s.human,
|
const result=await this.#autonomyHost.reverse({business:s.business,decision:d.id,decisionClass:autonomyClass(d.action),action:d.action,raised:this.#raised(s.business,d.id),effects,actor:s.human,
|
||||||
beforeWrite:()=>{this.#autonomyOwner(s);windowOpen();},fire:proposal=>this.#fireApproved(s,proposal,windowOpen),stop:proposal=>this.#stopCopyApproved(s,proposal),relaunch:proposal=>this.#dispatch(s,'instance.launch',{instance:proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name}),record:result=>this.#store.transaction(()=>{windowOpen();recorded=true;this.#event(s,'action.allowed',{operation:'autonomy.reverse',decision:d.id,result},d.id);})});
|
beforeWrite:()=>{this.#autonomyOwner(s);windowOpen();},beforePublish:()=>{this.#autonomyOwner(s);windowOpen();},fire:proposal=>this.#fireApproved(s,proposal,()=>{this.#autonomyOwner(s);windowOpen();},true),stop:proposal=>this.#stopCopyApproved(s,proposal),complete:(proposal,result)=>this.#store.transaction(()=>this.#event(s,'action.allowed',{action:'fire.done',decision:d.id,transaction:result.transaction??null},proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name)),relaunch:proposal=>{
|
||||||
|
this.#autonomyOwner(s);
|
||||||
|
const instance=proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name;
|
||||||
|
this.#mayHuman(s,'instance.launch',instance);this.#launchable(s,instance,'not-thread-launch');
|
||||||
|
return this.#store.transaction(()=>({request:this.#lifecycleRecord(s,'lifecycle.launch',instance,{decision:d.id})}));
|
||||||
|
},record:result=>this.#store.transaction(()=>{if(!(autonomyClass(d.action)==='authority' && result.committed===true))windowOpen();recorded=true;this.#event(s,'action.allowed',{operation:'autonomy.reverse',decision:d.id,result},d.id);})});
|
||||||
if(!recorded)this.#store.transaction(()=>{windowOpen();this.#event(s,'action.allowed',{operation:'autonomy.reverse',decision:d.id,result},d.id);});
|
if(!recorded)this.#store.transaction(()=>{windowOpen();this.#event(s,'action.allowed',{operation:'autonomy.reverse',decision:d.id,result},d.id);});
|
||||||
return {id:d.id,reversed:true,...result};
|
return {id:d.id,reversed:true,...result};
|
||||||
} catch(error) {
|
} catch(error) {
|
||||||
@@ -6488,6 +6500,8 @@ export class Broker {
|
|||||||
const level=decisionAutonomy('authority',b.autonomy);
|
const level=decisionAutonomy('authority',b.autonomy);
|
||||||
let route='human';
|
let route='human';
|
||||||
if(!immediate && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
if(!immediate && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||||
|
if(level==='out of the loop')fail('authority-limits-unavailable');
|
||||||
|
if(!authorityBudgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||||
route=b.autonomy?.authorityResolver;
|
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');
|
||||||
if(route===s.role || resolverSubject(b,route,p.name))route='human';
|
if(route===s.role || resolverSubject(b,route,p.name))route='human';
|
||||||
@@ -6516,6 +6530,8 @@ export class Broker {
|
|||||||
if(this.#closed(d.id))fail('decision-closed');
|
if(this.#closed(d.id))fail('decision-closed');
|
||||||
if(this.#expireHire(s,d,p))fail('decision-expired');
|
if(this.#expireHire(s,d,p))fail('decision-expired');
|
||||||
if(this.#autonomyLevel(d)==='in the loop')fail('hire-resolution-required');
|
if(this.#autonomyLevel(d)==='in the loop')fail('hire-resolution-required');
|
||||||
|
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||||
|
if(!authorityBudgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||||
if(!this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority'))fail('not-resolver');
|
if(!this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority'))fail('not-resolver');
|
||||||
};
|
};
|
||||||
validate();
|
validate();
|
||||||
@@ -6534,13 +6550,15 @@ export class Broker {
|
|||||||
// No caller-provided human identity: the trusted writer receives the resolving instance.
|
// No caller-provided human identity: the trusted writer receives the resolving instance.
|
||||||
const recheck=()=>{
|
const recheck=()=>{
|
||||||
this.#agent(s);
|
this.#agent(s);
|
||||||
|
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||||
|
if(!authorityBudgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||||
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');
|
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();
|
recheck();
|
||||||
try {
|
try {
|
||||||
if(p.op==='fire' && p.level!=='org')await this.#stopCopyApproved(s,p);
|
if(p.op==='fire' && p.level!=='org')await this.#stopCopyApproved(s,p);
|
||||||
recheck();
|
recheck();
|
||||||
const result=p.op==='fire' && p.level==='org'?await this.#fireApproved(s,p,recheck):await this.#hires.apply(s.business,d.id,{...caller,beforeWrite:recheck});
|
const result=p.op==='fire' && p.level==='org'?await this.#fireApproved(s,p,recheck):await this.#hires.apply(s.business,d.id,{...caller,beforeWrite:recheck,beforePublish:recheck});
|
||||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'hire.apply',decision:d.id,transaction:result.transaction??null,revision:result.revision??null},d.id));
|
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'hire.apply',decision:d.id,transaction:result.transaction??null,revision:result.revision??null},d.id));
|
||||||
return {...result,id:d.id,op:'resolved',choice:a.choice};
|
return {...result,id:d.id,op:'resolved',choice:a.choice};
|
||||||
} catch(error) {
|
} catch(error) {
|
||||||
@@ -6621,13 +6639,14 @@ export class Broker {
|
|||||||
return {running};
|
return {running};
|
||||||
}
|
}
|
||||||
// The existing row-281 fire executor, now entered only after a consumed human decision.
|
// The existing row-281 fire executor, now entered only after a consumed human decision.
|
||||||
#fireApproved(s,p,beforeWrite=()=>{}) {
|
#fireApproved(s,p,beforeWrite=()=>{},waitForCommit=false) {
|
||||||
const args={name:p.name,reason:'Approved fire decision'},verb='instance.fire',action='role.fire';
|
const args={name:p.name,reason:'Approved fire decision'},verb='instance.fire',action='role.fire';
|
||||||
const b=this.#business(s.business),authority={target:p.name};
|
const b=this.#business(s.business),authority={target:p.name};
|
||||||
|
const refused=e=>{if(['reverse-window-closed','autonomy-precondition','not-resolver'].includes(e.code))throw e;return this.#organizationFail(e,verb);};
|
||||||
const write=op=>{
|
const write=op=>{
|
||||||
try {beforeWrite();const result=this.#organization(s.business,op,{name:p.name,revision:p.revision},s.human??s.role,{decision:p.id,digest:p.digest,beforeWrite});
|
try {beforeWrite();const result=this.#organization(s.business,op,{name:p.name,revision:p.revision},s.human??s.role,{decision:p.id,digest:p.digest,beforeWrite,beforePublish:beforeWrite});
|
||||||
return result?.then?result.catch(e=>this.#organizationFail(e,verb)):result;
|
return result?.then?result.catch(refused):result;
|
||||||
} catch(e) {this.#organizationFail(e,verb);}
|
} catch(e) {refused(e);}
|
||||||
};
|
};
|
||||||
if (!Object.hasOwn(b.roles, args.name)) fail('unknown-role');
|
if (!Object.hasOwn(b.roles, args.name)) fail('unknown-role');
|
||||||
if (END_PROTECTED.includes(b.roles[args.name].definition)) fail('organization-definition-refused');
|
if (END_PROTECTED.includes(b.roles[args.name].definition)) fail('organization-definition-refused');
|
||||||
@@ -6671,7 +6690,8 @@ export class Broker {
|
|||||||
if (stopped.job) {
|
if (stopped.job) {
|
||||||
const { job, set, ...rest } = stopped;
|
const { job, set, ...rest } = stopped;
|
||||||
const sc = { business: s.business, role: s.role, run: s.run, thread: s.thread, human: s.human };
|
const sc = { business: s.business, role: s.role, run: s.run, thread: s.thread, human: s.human };
|
||||||
this.#startGrantJob(s.business, args.name, verb, () => this.#fireJob(sc, args, authority, write, job, set));
|
const pending=this.#startGrantJob(s.business, args.name, verb, () => this.#fireJob(sc, args, authority, write, job, set,waitForCommit));
|
||||||
|
if(waitForCommit)return pending;
|
||||||
return { ...rest, job, revoking: set.map((g) => g.label), done: false };
|
return { ...rest, job, revoking: set.map((g) => g.label), done: false };
|
||||||
}
|
}
|
||||||
// Step B: the delist. An instance already delisted counts as done.
|
// Step B: the delist. An instance already delisted counts as done.
|
||||||
@@ -7312,6 +7332,7 @@ export class Broker {
|
|||||||
if(d.route_to==='human' || d.action==='prd.approve' || d.class==='within-role')fail('decision-not-eligible');
|
if(d.route_to==='human' || d.action==='prd.approve' || d.class==='within-role')fail('decision-not-eligible');
|
||||||
const pending=autonomyEvent(this.#store,s.business,d.id,['autonomy.pending','autonomy.declined','autonomy.confirmed']);
|
const pending=autonomyEvent(this.#store,s.business,d.id,['autonomy.pending','autonomy.declined','autonomy.confirmed']);
|
||||||
const closed=this.#closed(d.id);
|
const closed=this.#closed(d.id);
|
||||||
|
if(closed && ['withdrawn','expired'].includes(closed.op))fail('decision-closed');
|
||||||
if(pending?.body.operation!=='autonomy.pending')fail('decision-not-eligible');
|
if(pending?.body.operation!=='autonomy.pending')fail('decision-not-eligible');
|
||||||
const resolution=pending.body.resolution;
|
const resolution=pending.body.resolution;
|
||||||
if(!resolution || resolution.op!=='resolved' || this.#autonomyLevel(d)!=='in the loop')fail('decision-not-eligible');
|
if(!resolution || resolution.op!=='resolved' || this.#autonomyLevel(d)!=='in the loop')fail('decision-not-eligible');
|
||||||
|
|||||||
@@ -9,8 +9,9 @@ const group = (codes, rail, nextStep) => {
|
|||||||
entries.push([code, guidance]);
|
entries.push([code, guidance]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
group("authority-limits-unavailable", "R3/R12: future authority spend coverage", "Use authority near the loop with an enforced organization budget. Out of the loop waits for enforceable per-agent limits in every approvable definition; current-instance limits do not cover future hires.");
|
||||||
group("policy-reverse-unavailable", "R3/R12: policy inverse unavailable", "Choose policy in the loop or out of the loop. Near the loop waits for a policy effect executor and a tested reverse.");
|
group("policy-reverse-unavailable", "R3/R12: policy inverse unavailable", "Choose policy in the loop or out of the loop. Near the loop waits for a policy effect executor and a tested reverse.");
|
||||||
group("invalid-autonomy autonomy-precondition reversal-unavailable", "R3/R12: validated owner autonomy and reversible effects", "Use only the four decision classes and three levels. Keep work in the loop until the class has a distinct resolver, tested inverse, notices, review and spend prerequisites; an unsupported effect needs an ordinary new decision.");
|
group("invalid-autonomy autonomy-precondition reversal-unavailable", "R3/R12: validated owner autonomy and reversible effects", "Use only the four decision classes and three levels. Keep work in the loop until the class has a distinct resolver, tested inverse, notices, review and spend prerequisites; an unsupported effect needs an ordinary new decision. Authority near needs enabled limit checks and aggregate coverage of new agents. Moving out needs a near-loop resolution followed by the owner’s trail review. A failed inverse may have stopped an agent; inspect its writer receipt and use the normal launch or decision path.");
|
||||||
group("confirmation-required", "R5/R12: person confirms the arbiter resolution", "The arbiter remains the resolver. Confirm its pending resolution in the owner Console, or return it with a reason for a fresh resolution.");
|
group("confirmation-required", "R5/R12: person confirms the arbiter resolution", "The arbiter remains the resolver. Confirm its pending resolution in the owner Console, or return it with a reason for a fresh resolution.");
|
||||||
group("decision-reversed reverse-window-closed", "R2/R12: one-use reverse within the owner's window", "Inspect the reversal trail. After the window, raise an ordinary new decision through the normal approval path; never replay the old approval.");
|
group("decision-reversed reverse-window-closed", "R2/R12: one-use reverse within the owner's window", "Inspect the reversal trail. After the window, raise an ordinary new decision through the normal approval path; never replay the old approval.");
|
||||||
group("definition-shared hire-resolution-required hire-owner-required decision-expired right-required", "R5/R8/R9: digest-bound hire approval by a permitted person", "Use the hire Console path with org.hire. Flagged, credential and root decisions need their owner; expired decisions need a fresh proposal.");
|
group("definition-shared hire-resolution-required hire-owner-required decision-expired right-required", "R5/R8/R9: digest-bound hire approval by a permitted person", "Use the hire Console path with org.hire. Flagged, credential and root decisions need their owner; expired decisions need a fresh proposal.");
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { autonomyHost } from './autonomy-host.mjs';
|
import { autonomyHost, authorityHost } from './autonomy-host.mjs';
|
||||||
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
||||||
import { organizationPlugins } from '../../plugins/src/organization.mjs';
|
import { organizationPlugins } from '../../plugins/src/organization.mjs';
|
||||||
import { pluginService } from '../../plugins/src/tools.mjs';
|
import { pluginService } from '../../plugins/src/tools.mjs';
|
||||||
@@ -895,29 +895,7 @@ export async function startBroker({
|
|||||||
hires: organization ? (()=>{
|
hires: organization ? (()=>{
|
||||||
const service=hireDecisions({writer:organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir,dataRoot:instanceRoot??dataRoot}),rolesDir:organization.rolesDir,configDir:organization.dir,dataRoot,
|
const service=hireDecisions({writer:organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir,dataRoot:instanceRoot??dataRoot}),rolesDir:organization.rolesDir,configDir:organization.dir,dataRoot,
|
||||||
system:organization.system,levels,catalogueFor:async(id,doc)=>doc.plugins?.['model-provider']?.length?catalogueFor(id,{fresh:true}):null,assertClean:value=>credentials.assertClean(value),scanDefinition:(name,entry)=>scanDefinitions({[name]:entry},value=>credentials.assertClean(value)),registryFor:doc=>organizationPlugins(instanceRoot??dataRoot,doc.plugins).registry});
|
system:organization.system,levels,catalogueFor:async(id,doc)=>doc.plugins?.['model-provider']?.length?catalogueFor(id,{fresh:true}):null,assertClean:value=>credentials.assertClean(value),scanDefinition:(name,entry)=>scanDefinitions({[name]:entry},value=>credentials.assertClean(value)),registryFor:doc=>organizationPlugins(instanceRoot??dataRoot,doc.plugins).registry});
|
||||||
return {...service,reverse:async(id,decision,caller)=>{
|
return authorityHost(service,{modelKeys,reload,proxyOrganization});
|
||||||
const proposal=service.read(decision);
|
|
||||||
if(!modelKeys || (proposal.level==='org' && proposal.op==='hire'))return service.reverse(id,decision,caller);
|
|
||||||
const instance=`${id}/${proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name}`;
|
|
||||||
let prepared=false;
|
|
||||||
return service.reverse(id,decision,{...caller,
|
|
||||||
beforeWrite:()=>{caller.beforeWrite();if(prepared){modelKeys.completeRevoke(instance);prepared=false;}caller.beforeWrite();},
|
|
||||||
stop:async(p,guard)=>{await modelKeys.prepareRevoke(instance,guard);prepared=true;return caller.stop(p);},
|
|
||||||
});
|
|
||||||
},apply:async(id,decision,caller)=>{
|
|
||||||
const proposal=service.read(decision);
|
|
||||||
const publish=async()=>{
|
|
||||||
let approved=caller;
|
|
||||||
if(modelKeys && proposal.op==='fire' && proposal.level!=='org') {
|
|
||||||
const instance=`${id}/${proposal.level==='project'?`${proposal.name}.${proposal.project}`:proposal.name}`;
|
|
||||||
await modelKeys.prepareRevoke(instance,()=>caller.beforeWrite?.());
|
|
||||||
approved={...caller,beforeWrite:()=>{caller.beforeWrite?.();modelKeys.completeRevoke(instance);caller.beforeWrite?.();}};
|
|
||||||
}
|
|
||||||
const result=await service.apply(id,decision,approved);reload(id);return result;
|
|
||||||
};
|
|
||||||
if(proxyOrganization && proposal.level==='org' && proposal.op==='hire')return proxyOrganization.hire(id,proposal.name,()=>service.check(id,decision,caller),publish);
|
|
||||||
return publish();
|
|
||||||
}};
|
|
||||||
})() : null,
|
})() : null,
|
||||||
roleFile: organization ? (name) => loadRole(organization.rolesDir, name) : null,
|
roleFile: organization ? (name) => loadRole(organization.rolesDir, name) : null,
|
||||||
secretCheck: (value) => credentials.assertClean(value),
|
secretCheck: (value) => credentials.assertClean(value),
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {mkdtempSync,mkdirSync,rmSync} from 'node:fs';
|
||||||
|
import {tmpdir} from 'node:os';
|
||||||
|
import {join} from 'node:path';
|
||||||
|
import {Broker} from '../src/broker.mjs';
|
||||||
|
import {Store} from '../src/store.mjs';
|
||||||
|
import {autonomyHost,authorityHost} from '../src/autonomy-host.mjs';
|
||||||
|
import {organizationWriter} from '../../organization/src/organization.mjs';
|
||||||
|
import {instanceSettings} from '../../organization/src/instance-settings.mjs';
|
||||||
|
import {hireDecisions} from '../../organization/src/hire-decisions.mjs';
|
||||||
|
import {loadBusiness} from '../../organization/src/organization-config.mjs';
|
||||||
|
import {businessDoc,rolesCopy,writeJson} from '../../organization/tests/helpers.mjs';
|
||||||
|
const inline={tools:['read'],network:'none',authority:{withinRole:[],crossRole:[]},credentials:[],instructions:'Changed role'};
|
||||||
|
const cap={limit:100000,since:'2026-01-01T00:00:00.000Z'};
|
||||||
|
function world(t,options={}) {
|
||||||
|
const root=mkdtempSync(join(tmpdir(),'au-authority-')),rolesDir=rolesCopy(root),dataRoot=join(root,'data');mkdirSync(dataRoot,{mode:0o700});
|
||||||
|
const doc=businessDoc(root,'demo');doc.plugins={harness:['pi'],'limit-check':['token-limit']};
|
||||||
|
doc.launch.limits.tokens={providers:{zai:cap}};
|
||||||
|
doc.definitions={judge:{rev:1,role:{...inline,authority:{withinRole:['decision.resolve.authority'],crossRole:[]}},instructions:'Judge'},scout:{rev:3,role:structuredClone(inline),instructions:'Prior role'}};
|
||||||
|
// Definition instructions live beside the role composition.
|
||||||
|
for(const d of Object.values(doc.definitions))delete d.role.instructions;
|
||||||
|
doc.roles.judge={definition:'org:judge',vars:{harness:'pi',model:'claude-opus-5-5'}};
|
||||||
|
doc.roles.scout={definition:'org:scout',vars:{harness:'pi',model:'claude-opus-5-5'}};
|
||||||
|
doc.launch.instances.push('scout');doc.autonomy={authority:'near the loop',authorityResolver:'judge',notices:true,reverseWindowHours:1};
|
||||||
|
writeJson(join(root,'businesses/demo.json'),doc);
|
||||||
|
let reversing=false,broker,now=Date.now;
|
||||||
|
const writer=organizationWriter({dir:root,rolesDir,barrier:point=>{if(reversing && point==='prepared' && options.expirePrepared)Date.now=()=>now()+3600001;if(!reversing && point==='prepared' && options.removeResolverPrepared){const b=structuredClone(loaded());b.roles.judge.authority.withinRole=[];broker.reloadBusiness('demo',b);}}});
|
||||||
|
const store=new Store(dataRoot),order=[];
|
||||||
|
const loaded=()=>{const b=loadBusiness('demo',{dir:root,rolesDir});return {...b,roles:Object.fromEntries(Object.entries(b.roles).map(([n,e])=>[n,{...b.definitions[e.definition],...e}]))};};
|
||||||
|
const reload=id=>{if(reversing && options.crossAfterCommit)Date.now=()=>now()+3600001;if(reversing && options.reloadRefused)return false;broker.reloadBusiness(id,loaded());return true;};
|
||||||
|
const service=hireDecisions({writer,rolesDir,configDir:root,dataRoot,assertClean:()=>{}});
|
||||||
|
const hires=authorityHost(service,{reload,modelKeys:{prepareRevoke:async(instance,guard)=>{guard();assert.equal(instance,'demo/scout');order.push('prepare');},completeRevoke:instance=>{assert.equal(instance,'demo/scout');assert.ok(store.get("SELECT 1 FROM events WHERE json_extract(body,'$.action')='fire.stopped'"));assert.equal(writer.read('demo').document.definitions.scout.instructions,'Changed role');order.push('complete');}}});
|
||||||
|
const host=autonomyHost({writer,dataRoot,business:()=>loaded(),hires,reload});
|
||||||
|
const instances=instanceSettings({dir:root,rolesDir,writer,revoke:()=>{order.push('fire-revoke');}});
|
||||||
|
broker=new Broker({store,businesses:{demo:loaded()},hires,autonomy:host,organization:(id,verb,args,actor,context)=>{if(verb==='instance.fireCheck'){instances.checkFire(id,args.name);return {};}if(verb==='instance.fire')return instances.fire(id,args,{actor,context});throw Error('unexpected organization verb');}});
|
||||||
|
const caps={};const call=(who,verb,args={})=>broker.request(caps[who],{verb,args});
|
||||||
|
for(const role of ['chief','judge','scout']){caps[role]=broker.bindLaunch({business:'demo',role,run:role+'-run',harness:'pi'});call(role,'role.claim');}
|
||||||
|
caps.owner=broker.bindConsole({business:'demo',human:'jason',subject:{provider:'test',iss:'test',sub:'owner'}});
|
||||||
|
t.after(()=>{Date.now=now;store.close();rmSync(root,{recursive:true,force:true});});
|
||||||
|
const raise=(extra={})=>call('chief','hire.raise',{op:'change',level:'org',name:'scout',role:{inline},route:{harness:'pi',model:'claude-opus-5-5'},reason:'Change the task',...extra});
|
||||||
|
const reverse=id=>{reversing=true;return call('owner','decision.reverse.console',{id});};
|
||||||
|
return {writer,store,order,broker,call,raise,reverse,loaded};
|
||||||
|
}
|
||||||
|
for(const crossAfterCommit of [false,true])test(`AU authority reverse uses runtime key wrapper and relaunches after commit (deadline crossed: ${crossAfterCommit})`,async t=>{
|
||||||
|
const f=world(t,{crossAfterCommit}),d=await f.raise();assert.deepEqual(d.hire.flagged,[]);assert.equal(d.route_to,'judge');
|
||||||
|
await f.call('judge','decision.resolve',{id:d.id,choice:'yes'});assert.equal(f.writer.read('demo').document.definitions.scout.rev,4);
|
||||||
|
const r=await f.reverse(d.id);assert.equal(r.committed,true);assert.equal(r.relaunch,'requested');assert.deepEqual(f.order,['prepare','complete']);
|
||||||
|
const restored=f.writer.read('demo').document.definitions.scout;assert.equal(restored.rev,5);assert.equal(restored.instructions,'Prior role');
|
||||||
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse'").n,1);
|
||||||
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse.failed'").n,0);
|
||||||
|
assert.ok(f.store.get("SELECT 1 FROM events WHERE json_extract(body,'$.action')='lifecycle.launch' AND subject='scout'"));
|
||||||
|
});
|
||||||
|
test('AU a committed authority reverse reports pending recovery when reload refuses',async t=>{
|
||||||
|
const f=world(t,{reloadRefused:true}),d=await f.raise();await f.call('judge','decision.resolve',{id:d.id,choice:'yes'});
|
||||||
|
const r=await f.reverse(d.id);assert.equal(r.committed,true);assert.equal(r.restart,true);assert.equal(r.relaunch,'pending');assert.equal(f.writer.read('demo').document.definitions.scout.instructions,'Prior role');
|
||||||
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse.failed'").n,0);
|
||||||
|
});
|
||||||
|
test('AU authority reverse crossing deadline in prepared IO never publishes',async t=>{
|
||||||
|
const f=world(t,{expirePrepared:true}),d=await f.raise();await f.call('judge','decision.resolve',{id:d.id,choice:'yes'});const prior=f.writer.read('demo').revision;
|
||||||
|
await assert.rejects(f.reverse(d.id),{code:'reverse-window-closed'});assert.equal(f.writer.read('demo').revision,prior);f.writer.recover('demo');assert.equal(f.writer.read('demo').revision,prior);
|
||||||
|
});
|
||||||
|
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'});
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('AU authority apply rechecks a removed resolve right at publication',async t=>{
|
||||||
|
const f=world(t,{removeResolverPrepared:true}),d=await f.raise(),before=f.writer.read('demo').revision;
|
||||||
|
await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'not-resolver'});
|
||||||
|
assert.equal(f.writer.read('demo').revision,before);f.writer.recover('demo');assert.equal(f.writer.read('demo').revision,before);
|
||||||
|
});
|
||||||
|
test('AU authority hire reverse runs normal fire/revoke and records committed delisting',async t=>{
|
||||||
|
const f=world(t),d=await f.raise({op:'hire',name:'helper'});await f.call('judge','decision.resolve',{id:d.id,choice:'yes'});
|
||||||
|
assert.ok(f.writer.read('demo').document.launch.instances.includes('helper'));
|
||||||
|
const r=await f.reverse(d.id);assert.equal(r.committed,true);assert.ok(!f.writer.read('demo').document.launch.instances.includes('helper'));assert.deepEqual(f.order,['fire-revoke']);
|
||||||
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse'").n,1);
|
||||||
|
});
|
||||||
@@ -39,10 +39,10 @@ test('AU revoked resolver right refuses when an approved decision is consumed',a
|
|||||||
assert.throws(()=>f.broker.authorize(f.coder,'task.scope.change',{decision:d.id,target:'vikunja:1/2'}),{code:'not-resolver'});
|
assert.throws(()=>f.broker.authorize(f.coder,'task.scope.change',{decision:d.id,target:'vikunja:1/2'}),{code:'not-resolver'});
|
||||||
});
|
});
|
||||||
test('AU member, agent and dev tester cannot change settings',async t=>{
|
test('AU member, agent and dev tester cannot change settings',async t=>{
|
||||||
const f=await setup(t);
|
const revision='a'.repeat(64),f=await setup(t,null,{get:()=>({revision,autonomy:{}})});
|
||||||
const member=f.broker.bindHireConsole({business:'demo',actor:'member',subject:{...SUBJECT,sub:'member'},rights:['org.hire']});
|
const member=f.broker.bindHireConsole({business:'demo',actor:'member',subject:{...SUBJECT,sub:'member'},rights:['org.hire']});
|
||||||
for(const cap of [f.coder,member])assert.throws(()=>f.call(cap,'autonomy.set.console',{revision:'0'.repeat(64),autonomy:{merge:'near the loop'}}));
|
for(const cap of [f.coder,member])assert.throws(()=>f.call(cap,'autonomy.set.console',{revision,autonomy:{merge:'near the loop'}}),{code:'human-required'});
|
||||||
assert.throws(()=>f.call(f.human,'autonomy.set.console',{revision:'0'.repeat(64),autonomy:{merge:'near the loop'}}));
|
assert.throws(()=>f.call(f.human,'autonomy.set.console',{revision,autonomy:{merge:'near the loop'}}),{code:'human-required'});
|
||||||
});
|
});
|
||||||
test('AU near-loop merge sends owner a bounded notice; expired reverse names ordinary path',async t=>{
|
test('AU near-loop merge sends owner a bounded notice; expired reverse names ordinary path',async t=>{
|
||||||
const f=await setup(t,{merge:'near the loop',notices:true,reverseWindowHours:1}),d=f.raise({action:'git.merge.protected'});
|
const f=await setup(t,{merge:'near the loop',notices:true,reverseWindowHours:1}),d=f.raise({action:'git.merge.protected'});
|
||||||
@@ -109,3 +109,56 @@ test('AU near cross-role authorization without a trusted inverse fails closed be
|
|||||||
assert.throws(()=>f.broker.authorize(f.coder,'task.scope.change',{decision:d.id,target:'vikunja:1/2'}),{code:'reversal-unavailable'});
|
assert.throws(()=>f.broker.authorize(f.coder,'task.scope.change',{decision:d.id,target:'vikunja:1/2'}),{code:'reversal-unavailable'});
|
||||||
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.decision')=? AND json_extract(body,'$.action')='task.scope.change' AND json_extract(body,'$.operation') IS NOT 'decision.raise'",d.id).n,0);
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.decision')=? AND json_extract(body,'$.action')='task.scope.change' AND json_extract(body,'$.operation') IS NOT 'decision.raise'",d.id).n,0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test('AU a withdrawal after decline is terminal for resolver, owner and confirmation',async t=>{
|
||||||
|
const f=await setup(t,{merge:'in the loop'}),d=f.raise({action:'git.merge.protected'});
|
||||||
|
f.call(f.chief,'decision.resolve',{id:d.id,choice:'yes'});
|
||||||
|
f.call(f.owner,'decision.confirm.console',{id:d.id,confirm:false,reason:'Revise'});
|
||||||
|
f.call(f.coder,'decision.withdraw',{id:d.id});
|
||||||
|
assert.throws(()=>f.call(f.chief,'decision.resolve',{id:d.id,choice:'yes'}),{code:'decision-closed'});
|
||||||
|
for(const cap of [f.chief,f.human])assert.ok(!f.call(cap,'inbox').some(x=>x.id===d.id));
|
||||||
|
assert.throws(()=>f.call(f.owner,'decision.confirm.console',{id:d.id,confirm:true}),e=>['decision-closed','decision-not-eligible'].includes(e.code));
|
||||||
|
});
|
||||||
|
async function settingsFixture(t) {
|
||||||
|
let f,autonomy={},revision='a'.repeat(64),writes=0;
|
||||||
|
const host={get:()=>({autonomy,revision}),set:(_b,a)=>{writes++;autonomy=a.autonomy;revision='b'.repeat(64);f.business.autonomy=autonomy;f.broker.reloadBusiness('demo',f.business);return {revision,transaction:'setting-test'};},reversible:()=>true};
|
||||||
|
f=await setup(t,null,host);
|
||||||
|
f.business.roles.judge={definition:'judge',authority:{withinRole:['decision.resolve.authority'],crossRole:[]}};
|
||||||
|
f.business.roles.reviewer.authority.withinRole.push('review.verdict');
|
||||||
|
f.business.launch={by:'chief',models:{model:{provider:'anthropic',model:'test-model'}},limits:{tokens:{}}};
|
||||||
|
f.business.plugins={'limit-check':['token-limit']};
|
||||||
|
f.broker.reloadBusiness('demo',f.business);
|
||||||
|
return {...f,set:value=>f.call(f.owner,'autonomy.set.console',{revision,autonomy:value}),writes:()=>writes};
|
||||||
|
}
|
||||||
|
const authorityNear={authority:'near the loop',authorityResolver:'judge',notices:true};
|
||||||
|
const tokenCap={limit:1000,since:'2026-01-01T00:00:00.000Z'};
|
||||||
|
test('AU authority near requires an enforced organization budget covering every allowed model, including zero caps',async t=>{
|
||||||
|
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'});
|
||||||
|
}
|
||||||
|
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'});
|
||||||
|
f.business.plugins={'limit-check':['token-limit']};f.broker.reloadBusiness('demo',f.business);
|
||||||
|
await f.set(authorityNear);assert.equal(f.writes(),1);
|
||||||
|
});
|
||||||
|
test('AU authority out refuses until per-definition agent limits exist, even with current agents capped',async t=>{
|
||||||
|
const f=await settingsFixture(t);
|
||||||
|
f.business.launch.limits.tokens={providers:{anthropic:tokenCap},instances:Object.fromEntries(Object.keys(f.business.roles).map(n=>[n,tokenCap]))};
|
||||||
|
f.broker.reloadBusiness('demo',f.business);await f.set(authorityNear);
|
||||||
|
f.call(f.owner,'autonomy.review.console',{decisionClass:'authority'});
|
||||||
|
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 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});
|
||||||
|
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||||
|
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
|
||||||
|
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'});
|
||||||
|
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||||
|
await f.set({merge:'out of the loop',notices:true});
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
// keys are real local ssh-keygen pairs in the scratch store, and no ssh connection is made. Decisions a
|
// keys are real local ssh-keygen pairs in the scratch store, and no ssh connection is made. Decisions a
|
||||||
// test needs outside the human's yes go in by SQL as fixtures.
|
// test needs outside the human's yes go in by SQL as fixtures.
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
|
import {autonomyHost} from '../src/autonomy-host.mjs';
|
||||||
import { hireServiceFixture, fixtureConsole, approveFixtureFire } from './hire-fixtures.mjs';
|
import { hireServiceFixture, fixtureConsole, approveFixtureFire } from './hire-fixtures.mjs';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
@@ -75,7 +76,7 @@ function makeBusiness(url) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setup(t) {
|
async function setup(t,autonomy=null) {
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'g281-'));
|
const dir = mkdtempSync(join(tmpdir(), 'g281-'));
|
||||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||||
const gitea = await fakeGiteaApi(t, join(dir, 'tls'));
|
const gitea = await fakeGiteaApi(t, join(dir, 'tls'));
|
||||||
@@ -157,7 +158,7 @@ async function setup(t) {
|
|||||||
return { revision: REV };
|
return { revision: REV };
|
||||||
};
|
};
|
||||||
const make = () =>
|
const make = () =>
|
||||||
new Broker({hires:hireServiceFixture,
|
new Broker({hires:hireServiceFixture,autonomy,
|
||||||
store,
|
store,
|
||||||
businesses: { demo: structuredClone(doc) },
|
businesses: { demo: structuredClone(doc) },
|
||||||
secretCheck: (value) => credentials.assertClean(value),
|
secretCheck: (value) => credentials.assertClean(value),
|
||||||
@@ -997,3 +998,24 @@ test("row 239 T4b: an unmarked step B refusal keeps its code, and the notice say
|
|||||||
assert.ok(message.includes('(revision-conflict). The instance is still firing.'), message);
|
assert.ok(message.includes('(revision-conflict). The instance is still firing.'), message);
|
||||||
assert.ok(!message.includes('may already be revoked'), message);
|
assert.ok(!message.includes('may already be revoked'), message);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for(const expired of [false,true])test(`AU hire inverse waits for grant removal and refuses late publication (expired: ${expired})`,async t=>{
|
||||||
|
const host=autonomyHost({hires:{reverse:async(id,decision,caller)=>caller.fire({id:decision,level:'org',name:'coder',revision:REV,digest:'a'.repeat(64)})},reload:()=>true});
|
||||||
|
const f=await setup(t,host);await f.approveHost('coder','web1');
|
||||||
|
const decision=grantDecision(f.store,{action:'role.hire',route:'pm',close:{op:'resolved',by:'pm-run',choice:'yes',via:'broker'}});
|
||||||
|
const at=new Date().toISOString(),deadline=new Date(Date.now()+3600000).toISOString();
|
||||||
|
f.store.run("INSERT INTO events(id,at,business,kind,subject,body) VALUES(?,?,?,'action.allowed',?,?)",decision,at,'demo',decision,JSON.stringify({operation:'autonomy.notice',decision,decisionClass:'authority',reverseUntil:deadline}));
|
||||||
|
f.held.add('web1:remove');
|
||||||
|
const owner=fixtureConsole(f.broker),pending=f.broker.request(owner,{verb:'decision.reverse.console',args:{id:decision}});
|
||||||
|
// Attach the rejection handler before letting the asynchronous revoke complete.
|
||||||
|
const outcome=pending.then(value=>({value}),error=>({error}));
|
||||||
|
await until(()=>f.sent.some(s=>s.startsWith('remove web1')));
|
||||||
|
assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse'").n,0);assert.ok(f.doc.launch.instances.includes('coder'));
|
||||||
|
const clock=Date.now;
|
||||||
|
try {
|
||||||
|
if(expired)Date.now=()=>Date.parse(deadline)+1;
|
||||||
|
f.held.delete('web1:remove');const result=await outcome;await f.broker.grantsIdle();
|
||||||
|
if(expired){assert.equal(result.error?.code,'reverse-window-closed');assert.ok(f.doc.launch.instances.includes('coder'));}
|
||||||
|
else{assert.equal(result.error,undefined);assert.equal(result.value.committed,true);assert.match(result.value.transaction,/^t-/);assert.equal(f.store.get("SELECT count(*) n FROM events WHERE json_extract(body,'$.operation')='autonomy.reverse'").n,1);assert.ok(!f.doc.launch.instances.includes('coder'));}
|
||||||
|
}finally{Date.now=clock;f.held.clear();}
|
||||||
|
});
|
||||||
@@ -209,6 +209,7 @@ test('AU a distinct authority resolver applies a plain near-loop hire, while fla
|
|||||||
const f=fixture(t),doc=JSON.parse(readFileSync(f.file,'utf8'));
|
const f=fixture(t),doc=JSON.parse(readFileSync(f.file,'utf8'));
|
||||||
doc.definitions={resolver:{rev:1,role:{tools:['read'],network:'none',authority:{withinRole:['decision.resolve.technical','decision.resolve.authority'],crossRole:[]},credentials:[]},instructions:'Resolve independent decisions.'}};
|
doc.definitions={resolver:{rev:1,role:{tools:['read'],network:'none',authority:{withinRole:['decision.resolve.technical','decision.resolve.authority'],crossRole:[]},credentials:[]},instructions:'Resolve independent decisions.'}};
|
||||||
doc.roles.cto={definition:'org:resolver'};
|
doc.roles.cto={definition:'org:resolver'};
|
||||||
|
doc.plugins['limit-check']=['token-limit'];doc.launch.limits={tokens:{providers:{zai:{limit:100000,since:'2026-01-01T00:00:00.000Z'}}}};
|
||||||
doc.autonomy={authority:'near the loop',authorityResolver:'cto',notices:true};writeJson(f.file,doc);
|
doc.autonomy={authority:'near the loop',authorityResolver:'cto',notices:true};writeJson(f.file,doc);
|
||||||
const live=loadBusiness('demo',{dir:f.root,rolesDir:f.rolesDir});
|
const live=loadBusiness('demo',{dir:f.root,rolesDir:f.rolesDir});
|
||||||
const business={...live,roles:Object.fromEntries(Object.entries(live.roles).map(([n,e])=>[n,{...live.definitions[e.definition],...e}]))};
|
const business={...live,roles:Object.fromEntries(Object.entries(live.roles).map(([n,e])=>[n,{...live.definitions[e.definition],...e}]))};
|
||||||
@@ -227,12 +228,13 @@ test('AU R5 a change naming the authority resolver stays with a person; no agent
|
|||||||
const f=fixture(t),doc=JSON.parse(readFileSync(f.file,'utf8'));
|
const f=fixture(t),doc=JSON.parse(readFileSync(f.file,'utf8'));
|
||||||
doc.definitions={judge:{rev:1,role:{tools:['read'],network:'none',authority:{withinRole:['decision.resolve.authority'],crossRole:[]},credentials:[]},instructions:'Resolve independent authority decisions.'}};
|
doc.definitions={judge:{rev:1,role:{tools:['read'],network:'none',authority:{withinRole:['decision.resolve.authority'],crossRole:[]},credentials:[]},instructions:'Resolve independent authority decisions.'}};
|
||||||
doc.roles.judge={definition:'org:judge',vars:{harness:'pi',model:'claude-opus-5-5'}};
|
doc.roles.judge={definition:'org:judge',vars:{harness:'pi',model:'claude-opus-5-5'}};
|
||||||
doc.autonomy={authority:'near the loop',authorityResolver:'judge',notices:true};writeJson(f.file,doc);
|
doc.plugins['limit-check']=['token-limit'];doc.launch.limits={tokens:{providers:{zai:{limit:100000,since:'2026-01-01T00:00:00.000Z'}}}};
|
||||||
|
doc.autonomy={authority:'near the loop',authorityResolver:'judge',notices:true};writeJson(f.file,doc);
|
||||||
const loaded=loadBusiness('demo',{dir:f.root,rolesDir:f.rolesDir});
|
const loaded=loadBusiness('demo',{dir:f.root,rolesDir:f.rolesDir});
|
||||||
f.b.reloadBusiness('demo',{...loaded,roles:Object.fromEntries(Object.entries(loaded.roles).map(([n,e])=>[n,{...loaded.definitions[e.definition],...e}]))});
|
f.b.reloadBusiness('demo',{...loaded,roles:Object.fromEntries(Object.entries(loaded.roles).map(([n,e])=>[n,{...loaded.definitions[e.definition],...e}]))});
|
||||||
const judge=f.b.bindLaunch({business:'demo',role:'judge',run:'judge-run',harness:'pi'});f.call(judge,'role.claim');
|
const judge=f.b.bindLaunch({business:'demo',role:'judge',run:'judge-run',harness:'pi'});f.call(judge,'role.claim');
|
||||||
const d=await f.raise({op:'change',name:'judge',role:{definition:'judge',rev:1}});
|
const d=await f.raise({op:'change',name:'judge',role:{inline:{...INLINE,authority:{withinRole:['decision.resolve.authority'],crossRole:[]},instructions:'Narrow this resolver'}}});
|
||||||
assert.ok(d.hire.flagged.some(line=>line.value==='decision.resolve.authority'));assert.equal(d.route_to,'human');
|
assert.ok(d.hire.flagged.some(x=>x.value==='decision.resolve.authority'));assert.equal(d.route_to,'human');
|
||||||
await assert.rejects(Promise.resolve().then(()=>f.call(judge,'decision.resolve',{id:d.id,choice:'yes'})));
|
await assert.rejects(Promise.resolve().then(()=>f.call(judge,'decision.resolve',{id:d.id,choice:'yes'})));
|
||||||
assert.equal(f.writes(),0);
|
assert.equal(f.writes(),0);
|
||||||
});
|
});
|
||||||
@@ -644,10 +644,10 @@ owner approval. No setting changes hard waits or the PRD request-mode switch.
|
|||||||
|
|
||||||
Moving toward the loop needs no prerequisites. Moving away requires the class's
|
Moving toward the loop needs no prerequisites. Moving away requires the class's
|
||||||
resolver, inverse, notices and review/limit prerequisites. Moving from near to
|
resolver, inverse, notices and review/limit prerequisites. Moving from near to
|
||||||
out also requires an owner trail review. A task inverse restores its prior
|
out also requires an actual near-loop resolution and a later owner trail review. Authority near requires an enabled limit check and an aggregate quota covering every selectable model (or the shared account when every enabled harness uses it). Empty budgets and existing-instance caps do not cover future hires. Authority out refuses `authority-limits-unavailable` until per-definition limits exist. A task inverse restores its prior
|
||||||
stored fields if no later edit intervened; a merge inverse lands a gated revert
|
stored fields if no later edit intervened; a merge inverse lands a gated revert
|
||||||
commit. Hire/fire/change inverses reuse the existing lifecycle and writer paths,
|
commit. Hire/fire/change inverses reuse the existing lifecycle and writer paths,
|
||||||
never restore credential bindings, and refuse stale targets. External task
|
never restore credential bindings, and refuse stale targets. Authority inverses check the window immediately before file publication. After a durable commit, reload or relaunch failures are reported as recovery metadata, with the inverse recorded as committed. A refusal after stop/revoke leaves the agent stopped; inspect its trail before relaunching. External task
|
||||||
adapters without host-owned inverse evidence refuse near-loop consumption.
|
adapters without host-owned inverse evidence refuse near-loop consumption.
|
||||||
After the pinned window, use an ordinary new decision.
|
After the pinned window, use an ordinary new decision.
|
||||||
|
|
||||||
|
|||||||
@@ -28,3 +28,17 @@ export function resolverSubject(business, resolver, target) {
|
|||||||
const definition=business.roles?.[resolver]?.definition;
|
const definition=business.roles?.[resolver]?.definition;
|
||||||
return target===resolver || target===definition || target===definition?.replace(/^org:/,'') || (definition!==undefined && business.roles?.[target]?.definition===definition);
|
return target===resolver || target===definition || target===definition?.replace(/^org:/,'') || (definition!==undefined && business.roles?.[target]?.definition===definition);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Aggregate provider/model limits cover names that do not exist yet. An account
|
||||||
|
// quota covers every future launch only when every enabled harness uses that account.
|
||||||
|
export function authorityBudgetCovered(business) {
|
||||||
|
const launch=business.launch, tokens=launch?.limits?.tokens, checks=business.plugins?.['limit-check']??[];
|
||||||
|
const quota=x=>Number.isSafeInteger(x?.limit) && x.limit>=0 && typeof x.since==='string' && !Number.isNaN(Date.parse(x.since));
|
||||||
|
const account=launch?.account?.name, harnesses=business.plugins?.harness??[];
|
||||||
|
if(account && harnesses.length && harnesses.every(h=>h==='claude-code') &&
|
||||||
|
(checks.includes('daily-quota') && quota(tokens?.daily?.[account]) ||
|
||||||
|
checks.includes('token-limit') && quota(tokens?.keys?.[account]) && tokens.keys[account].reset===undefined))return true;
|
||||||
|
const models=Object.values(launch?.models??{});
|
||||||
|
return checks.includes('token-limit') && models.length>0 && models.every(({provider,model})=>
|
||||||
|
quota(tokens?.providers?.[provider]) || quota(tokens?.models?.[provider]?.[model]));
|
||||||
|
}
|
||||||
@@ -244,8 +244,8 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
|||||||
return publish();
|
return publish();
|
||||||
}
|
}
|
||||||
if(r.level==='project') return writer.setProjectAgent(business,{revision:p.revision,project:r.project,name:r.name,entry},caller.actor,
|
if(r.level==='project') return writer.setProjectAgent(business,{revision:p.revision,project:r.project,name:r.name,entry},caller.actor,
|
||||||
{approvedDefinition:p.entry?{name:p.definition,entry:approvedEntry}:null,decision:p.id,assertClean,beforeWrite:caller.beforeWrite,authorityDecision:caller.authorityDecision});
|
{approvedDefinition:p.entry?{name:p.definition,entry:approvedEntry}:null,decision:p.id,assertClean,beforeWrite:caller.beforeWrite,beforePublish:caller.beforePublish,authorityDecision:caller.authorityDecision});
|
||||||
return writer.applyHireDecision(business,p,{actor:caller.actor,assertClean,beforeWrite:caller.beforeWrite,authorityDecision:caller.authorityDecision});
|
return writer.applyHireDecision(business,p,{actor:caller.actor,assertClean,beforeWrite:caller.beforeWrite,beforePublish:caller.beforePublish,authorityDecision:caller.authorityDecision});
|
||||||
}
|
}
|
||||||
async function reverse(business,decision,caller) {
|
async function reverse(business,decision,caller) {
|
||||||
const p=read(decision);if(p.business!==business || !p.prior || p.request.level==='root')fail('decision-stale');
|
const p=read(decision);if(p.business!==business || !p.prior || p.request.level==='root')fail('decision-stale');
|
||||||
@@ -259,15 +259,16 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
|||||||
}
|
}
|
||||||
if(p.prior.definition && canonicalJson(old.document.definitions?.[p.prior.instance.definition.slice(4)])!==canonicalJson(p.prior.definition))fail('decision-stale');
|
if(p.prior.definition && canonicalJson(old.document.definitions?.[p.prior.instance.definition.slice(4)])!==canonicalJson(p.prior.definition))fail('decision-stale');
|
||||||
} else if(current?.hireDecision!==decision)fail('decision-stale');
|
} else if(current?.hireDecision!==decision)fail('decision-stale');
|
||||||
const guard=()=>{caller.beforeWrite();if(p.prior.definition)scanEntry(p.prior.instance.definition.slice(4),p.prior.definition);if(writer.read(business).revision!==old.revision)fail('decision-stale');};
|
const publicationGuard=()=>{(caller.beforePublish??caller.beforeWrite)();if(p.prior.definition)scanEntry(p.prior.instance.definition.slice(4),p.prior.definition);if(writer.read(business).revision!==old.revision)fail('decision-stale');};
|
||||||
|
const guard=()=>{caller.beforeWrite();publicationGuard();};
|
||||||
guard();
|
guard();
|
||||||
if(r.op==='hire') {
|
if(r.op==='hire') {
|
||||||
if(r.level==='org')return caller.fire({...publicOf(p),revision:old.revision});
|
if(r.level==='org')return caller.fire({...publicOf(p),revision:old.revision});
|
||||||
await caller.stop(publicOf(p),guard);guard();
|
await caller.stop(publicOf(p),guard);guard();
|
||||||
return writer.setProjectAgent(business,{revision:old.revision,project:r.project,name:r.name,entry:null},caller.actor,{beforeWrite:guard});
|
return writer.setProjectAgent(business,{revision:old.revision,project:r.project,name:r.name,entry:null},caller.actor,{beforeWrite:guard,beforePublish:publicationGuard});
|
||||||
}
|
}
|
||||||
const stopped=await caller.stop(publicOf(p),guard);guard();
|
const stopped=await caller.stop(publicOf(p),guard);guard();
|
||||||
const result=writer.reverseHireDecision(business,p,{...caller,beforeWrite:guard});
|
const result=writer.reverseHireDecision(business,p,{...caller,beforeWrite:guard,beforePublish:publicationGuard});
|
||||||
return {...result,...(r.op==='change' && stopped?.running?{relaunch:publicOf(p)}:{})};
|
return {...result,...(r.op==='change' && stopped?.running?{relaunch:publicOf(p)}:{})};
|
||||||
}
|
}
|
||||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||||
|
|||||||
@@ -423,7 +423,7 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
|||||||
// writer checks again under its lock, before the revoke (row 239), and that check is what keeps
|
// writer checks again under its lock, before the revoke (row 239), and that check is what keeps
|
||||||
// a stale fire or delete from revoking.
|
// a stale fire or delete from revoking.
|
||||||
if (writer.read(business).revision !== revision) throw new OrganizationError("revision-conflict", "organization revision changed; read again");
|
if (writer.read(business).revision !== revision) throw new OrganizationError("revision-conflict", "organization revision changed; read again");
|
||||||
const receipt = writer.write(business, next, { revision, actor, context, beforeWrite });
|
const receipt = writer.write(business, next, { revision, actor, context, beforeWrite, beforePublish:context?.beforePublish });
|
||||||
return { ...read(business, actor), transaction: receipt.transaction, restart: false };
|
return { ...read(business, actor), transaction: receipt.transaction, restart: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -282,7 +282,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
// the old document, for a writer that builds what it publishes from what it read under the lock.
|
// the old document, for a writer that builds what it publishes from what it read under the lock.
|
||||||
// #1873 A2: `pathsOnly` logs each change's path and presence without its values, for a verb whose
|
// #1873 A2: `pathsOnly` logs each change's path and presence without its values, for a verb whose
|
||||||
// values can hold a var a person typed (a secret pasted in the wrong place must not reach evidence).
|
// values can hold a var a person typed (a secret pasted in the wrong place must not reach evidence).
|
||||||
function commit(id, document, { revision, actor, detail, context, beforeWrite = null, guard, pathsOnly = false }) {
|
function commit(id, document, { revision, actor, detail, context, beforeWrite = null, beforePublish = null, guard, pathsOnly = false }) {
|
||||||
requireId(actor, "authenticated actor");
|
requireId(actor, "authenticated actor");
|
||||||
requireId(id, "organization id");
|
requireId(id, "organization id");
|
||||||
let revoked = false;
|
let revoked = false;
|
||||||
@@ -343,6 +343,13 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
rmSync(candidate);
|
rmSync(candidate);
|
||||||
fail("revision-conflict", "organization revision changed before publication");
|
fail("revision-conflict", "organization revision changed before publication");
|
||||||
}
|
}
|
||||||
|
// Pure admission check after candidate IO, immediately before publication.
|
||||||
|
// A refused prepared candidate is never rolled forward by recovery.
|
||||||
|
try { beforePublish?.(); } catch (error) {
|
||||||
|
log(id, { ...event, state: 'aborted' });
|
||||||
|
rmSync(candidate);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
renameSync(candidate, file);
|
renameSync(candidate, file);
|
||||||
syncDir(parent);
|
syncDir(parent);
|
||||||
if (entry) { entry.digest = after; entry.revision++; publishRegistry(); }
|
if (entry) { entry.digest = after; entry.revision++; publishRegistry(); }
|
||||||
@@ -484,12 +491,12 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
if (entry === null) delete agents[name]; else agents[name] = entry;
|
if (entry === null) delete agents[name]; else agents[name] = entry;
|
||||||
const { agents: _drop, ...rest } = target;
|
const { agents: _drop, ...rest } = target;
|
||||||
return { ...old, ...(approval?.approvedDefinition ? {definitions:{...(old.definitions??{}),[approval.approvedDefinition.name]:approval.approvedDefinition.entry}} : {}), projects: { ...old.projects, [project]: Object.keys(agents).length ? { ...rest, agents } : rest } };
|
return { ...old, ...(approval?.approvedDefinition ? {definitions:{...(old.definitions??{}),[approval.approvedDefinition.name]:approval.approvedDefinition.entry}} : {}), projects: { ...old.projects, [project]: Object.keys(agents).length ? { ...rest, agents } : rest } };
|
||||||
}, { revision, actor, guard, beforeWrite:approval?.beforeWrite, pathsOnly: true, detail: { verb: "project.agents.set", project, agent: name, form: entryForm(entry), ...(approval?.decision ? {decision:approval.decision}: {}) } });
|
}, { revision, actor, guard, beforeWrite:approval?.beforeWrite, beforePublish:approval?.beforePublish, pathsOnly: true, detail: { verb: "project.agents.set", project, agent: name, form: entryForm(entry), ...(approval?.decision ? {decision:approval.decision}: {}) } });
|
||||||
}
|
}
|
||||||
|
|
||||||
// A4 trusted decision executor: one locked publication of the role, route and definition.
|
// A4 trusted decision executor: one locked publication of the role, route and definition.
|
||||||
// The broker has consumed the matching digest before entering this host-only writer.
|
// The broker has consumed the matching digest before entering this host-only writer.
|
||||||
function applyHireDecision(id, proposal, { actor, assertClean, beforeWrite = null, authorityDecision = null }) {
|
function applyHireDecision(id, proposal, { actor, assertClean, beforeWrite = null, beforePublish = null, authorityDecision = null }) {
|
||||||
const { request: r, definition, entry, revision } = proposal;
|
const { request: r, definition, entry, revision } = proposal;
|
||||||
if (!proposal.id || r.level !== 'org') fail('invalid-request');
|
if (!proposal.id || r.level !== 'org') fail('invalid-request');
|
||||||
const build = old => {
|
const build = old => {
|
||||||
@@ -519,7 +526,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
};
|
};
|
||||||
return commit(id, build, {revision,actor,beforeWrite,pathsOnly:true,guard:(old,next)=>{
|
return commit(id, build, {revision,actor,beforeWrite,beforePublish,pathsOnly:true,guard:(old,next)=>{
|
||||||
if(canonicalJson(next)!==canonicalJson(build(old)))fail('organization-definitions-only');
|
if(canonicalJson(next)!==canonicalJson(build(old)))fail('organization-definitions-only');
|
||||||
projectsProtected(old,next);
|
projectsProtected(old,next);
|
||||||
},context:{decision:proposal.id,digest:proposal.digest??null},detail:{verb:'hire.apply',decision:proposal.id,op:r.op,agent:r.name}});
|
},context:{decision:proposal.id,digest:proposal.digest??null},detail:{verb:'hire.apply',decision:proposal.id,op:r.op,agent:r.name}});
|
||||||
@@ -527,7 +534,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
|
|
||||||
// AU inverse, from an immutable private proposal. It touches only the named instance and
|
// AU inverse, from an immutable private proposal. It touches only the named instance and
|
||||||
// definition; writer validation, fresh revision and owner fence still apply. Bindings never restore.
|
// definition; writer validation, fresh revision and owner fence still apply. Bindings never restore.
|
||||||
function reverseHireDecision(id,p,{actor,beforeWrite}) {
|
function reverseHireDecision(id,p,{actor,beforeWrite,beforePublish}) {
|
||||||
const {document:old,revision}=read(id),r=p.request,prior=p.prior;
|
const {document:old,revision}=read(id),r=p.request,prior=p.prior;
|
||||||
if(actor!==old.human || !prior || r.level==='root')fail('human-required');
|
if(actor!==old.human || !prior || r.level==='root')fail('human-required');
|
||||||
if(r.op==='hire')fail('invalid-request'); // Hire reverses through the stop/revoke/fire executor.
|
if(r.op==='hire')fail('invalid-request'); // Hire reverses through the stop/revoke/fire executor.
|
||||||
@@ -560,7 +567,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
|||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
};
|
};
|
||||||
return commit(id,build,{revision,actor,beforeWrite,pathsOnly:true,guard:(current,next)=>{if(actor!==current.human || canonicalJson(build(current))!==canonicalJson(next))fail('human-required');},detail:{verb:'hire.reverse',decision:p.id,agent:r.name}});
|
return commit(id,build,{revision,actor,beforeWrite,beforePublish,pathsOnly:true,guard:(current,next)=>{if(actor!==current.human || canonicalJson(build(current))!==canonicalJson(next))fail('human-required');},detail:{verb:'hire.reverse',decision:p.id,agent:r.name}});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Runs `fn({ revision, document })` under the writer lock, after recovery, and nothing else may
|
// Runs `fn({ revision, document })` under the writer lock, after recovery, and nothing else may
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ import {organizationWriter} from '../src/organization.mjs';
|
|||||||
import {hireDecisions} from '../src/hire-decisions.mjs';
|
import {hireDecisions} from '../src/hire-decisions.mjs';
|
||||||
import {instanceSettings} from '../src/instance-settings.mjs';
|
import {instanceSettings} from '../src/instance-settings.mjs';
|
||||||
const role={tools:['read'],network:'none',authority:{withinRole:[],crossRole:[]},credentials:[],instructions:'Prior role'};
|
const role={tools:['read'],network:'none',authority:{withinRole:[],crossRole:[]},credentials:[],instructions:'Prior role'};
|
||||||
function setup(t, scanDefinition) {
|
function setup(t, scanDefinition, barrier) {
|
||||||
const root=tmp();t.after(()=>rmSync(root,{recursive:true,force:true}));const rolesDir=rolesCopy(root),doc=businessDoc(root);
|
const root=tmp();t.after(()=>rmSync(root,{recursive:true,force:true}));const rolesDir=rolesCopy(root),doc=businessDoc(root);
|
||||||
doc.plugins={harness:['pi']};
|
doc.plugins={harness:['pi']};
|
||||||
doc.definitions={scout:{rev:3,role:{tools:role.tools,network:role.network,authority:role.authority,credentials:[]},instructions:role.instructions}};
|
doc.definitions={scout:{rev:3,role:{tools:role.tools,network:role.network,authority:role.authority,credentials:[]},instructions:role.instructions}};
|
||||||
doc.roles.scout={definition:'org:scout',vars:{harness:'pi',model:'claude-opus-5-5'}};doc.launch.instances.push('scout');
|
doc.roles.scout={definition:'org:scout',vars:{harness:'pi',model:'claude-opus-5-5'}};doc.launch.instances.push('scout');
|
||||||
writeJson(join(root,'businesses/acme.json'),doc);
|
writeJson(join(root,'businesses/acme.json'),doc);
|
||||||
const writer=organizationWriter({dir:root,rolesDir}),service=hireDecisions({writer,rolesDir,configDir:root,dataRoot:join(root,'data'),assertClean:()=>{},scanDefinition});
|
const writer=organizationWriter({dir:root,rolesDir,barrier}),service=hireDecisions({writer,rolesDir,configDir:root,dataRoot:join(root,'data'),assertClean:()=>{},scanDefinition});
|
||||||
let stopped=0,revoked=0;const instances=instanceSettings({dir:root,rolesDir,writer,revoke:()=>{revoked++;}});
|
let stopped=0,revoked=0;const instances=instanceSettings({dir:root,rolesDir,writer,revoke:()=>{revoked++;}});
|
||||||
const prepare=async request=>{const p=await service.prepare('acme',Object.fromEntries(Object.entries({op:'change',level:'org',name:'scout',role:{inline:{...role,instructions:'Changed role'}},route:{harness:'pi',model:'claude-opus-5-5'},reason:'Test',...request}).filter(([,v])=>v!==undefined)),{id:randomUUID(),expiresAt:'2099-01-01T00:00:00Z'});return p;};
|
const prepare=async request=>{const p=await service.prepare('acme',Object.fromEntries(Object.entries({op:'change',level:'org',name:'scout',role:{inline:{...role,instructions:'Changed role'}},route:{harness:'pi',model:'claude-opus-5-5'},reason:'Test',...request}).filter(([,v])=>v!==undefined)),{id:randomUUID(),expiresAt:'2099-01-01T00:00:00Z'});return p;};
|
||||||
const caller=p=>({agent:false,rights:['org.hire'],owner:true,instanceOwner:true,actor:'jason',digest:p.digest,subject:{provider:'test',iss:'test',sub:'owner'}});
|
const caller=p=>({agent:false,rights:['org.hire'],owner:true,instanceOwner:true,actor:'jason',digest:p.digest,subject:{provider:'test',iss:'test',sub:'owner'}});
|
||||||
@@ -53,3 +53,13 @@ test('AU inverse scans prior definition against current held credentials before
|
|||||||
await assert.rejects(f.reverse(p),{code:'definition-holds-credential'});
|
await assert.rejects(f.reverse(p),{code:'definition-holds-credential'});
|
||||||
assert.equal(f.stopped(),0);assert.equal(f.writer.read('acme').revision,before);
|
assert.equal(f.stopped(),0);assert.equal(f.writer.read('acme').revision,before);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('AU inverse crossing its window during candidate IO never publishes or recovers forward',async t=>{
|
||||||
|
let reversing=false,expired=false;
|
||||||
|
const f=setup(t,undefined,point=>{if(reversing && point==='prepared')expired=true;});
|
||||||
|
const p=await f.prepare({});await f.service.apply('acme',p.id,f.caller(p));
|
||||||
|
const prior=f.writer.read('acme');reversing=true;
|
||||||
|
await assert.rejects(f.service.reverse('acme',p.id,{actor:'jason',beforeWrite(){if(expired)throw Object.assign(new Error('reverse-window-closed'),{code:'reverse-window-closed'});},stop:async()=>({running:true})}),{code:'reverse-window-closed'});
|
||||||
|
assert.equal(f.writer.read('acme').revision,prior.revision);
|
||||||
|
f.writer.recover('acme');assert.equal(f.writer.read('acme').revision,prior.revision);
|
||||||
|
});
|
||||||
@@ -29,3 +29,17 @@ test('AU setting validates in the organization file; every writer refuses non-ow
|
|||||||
const writer=organizationWriter({dir:root,rolesDir}),old=writer.read('acme');
|
const writer=organizationWriter({dir:root,rolesDir}),old=writer.read('acme');
|
||||||
for(const actor of ['coder','tester','member'])assert.throws(()=>writer.write('acme',{...doc,autonomy:{merge:'out of the loop'}},{revision:old.revision,actor}),{code:'human-required'});
|
for(const actor of ['coder','tester','member'])assert.throws(()=>writer.write('acme',{...doc,autonomy:{merge:'out of the loop'}},{revision:old.revision,actor}),{code:'human-required'});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
import {authorityBudgetCovered} from '../src/autonomy.mjs';
|
||||||
|
test('AU authority budgets cover all selectable models and only enforced account harnesses',()=>{
|
||||||
|
const cap={limit:0,since:'2026-01-01T00:00:00.000Z'};
|
||||||
|
const b={plugins:{harness:['pi'],'limit-check':['token-limit']},launch:{models:{one:{provider:'one',model:'m'},two:{provider:'two',model:'n'}},limits:{tokens:{providers:{one:cap}}}}};
|
||||||
|
assert.equal(authorityBudgetCovered(b),false);
|
||||||
|
b.launch.limits.tokens.models={two:{n:cap}};assert.equal(authorityBudgetCovered(b),true);
|
||||||
|
b.plugins['limit-check']=[];assert.equal(authorityBudgetCovered(b),false);
|
||||||
|
b.launch.account={name:'shared'};b.launch.limits.tokens={keys:{shared:cap}};b.plugins['limit-check']=['token-limit'];
|
||||||
|
assert.equal(authorityBudgetCovered(b),false);
|
||||||
|
b.plugins.harness=['claude-code'];assert.equal(authorityBudgetCovered(b),true);
|
||||||
|
b.plugins.harness.push('pi');assert.equal(authorityBudgetCovered(b),false);
|
||||||
|
b.plugins.harness=['claude-code'];b.plugins['limit-check']=['daily-quota'];b.launch.limits.tokens={daily:{shared:{...cap,reset:'00:00',timeZone:'UTC'}}};assert.equal(authorityBudgetCovered(b),true);
|
||||||
|
});
|
||||||
@@ -24,5 +24,5 @@ export async function autonomyHTTP(req,res,{path,read,write,session,live,origin}
|
|||||||
const subject={provider:session.provider,iss:session.iss,sub:session.sub};
|
const subject={provider:session.provider,iss:session.iss,sub:session.sub};
|
||||||
const verb=step==='confirm'?'decision.confirm.console':step==='reverse'?'decision.reverse.console':step==='review'?'autonomy.review.console':post?'autonomy.set.console':'autonomy.get.console';
|
const verb=step==='confirm'?'decision.confirm.console':step==='reverse'?'decision.reverse.console':step==='review'?'autonomy.review.console':post?'autonomy.set.console':'autonomy.get.console';
|
||||||
try{return json(res,200,{...await(post?write:read)(verb,args,{subject}),writable:!!write});}
|
try{return json(res,200,{...await(post?write:read)(verb,args,{subject}),writable:!!write});}
|
||||||
catch(e){const allowed=['human-required','invalid-request','invalid-autonomy','policy-reverse-unavailable','autonomy-precondition','revision-conflict','decision-not-eligible','decision-stale','decision-reversed','reverse-window-closed','reversal-unavailable','not-resolver','gate-missing','gate-failed','base-conflict','not-configured'];const code=allowed.includes(e?.code)?e.code:'outcome-unknown';return json(res,code==='human-required'?403:code==='invalid-request'||code==='invalid-autonomy'?400:409,{error:code});}
|
catch(e){const allowed=['authority-limits-unavailable','decision-closed','confirmation-required','not-found','storage-refused','human-required','invalid-request','invalid-autonomy','policy-reverse-unavailable','autonomy-precondition','revision-conflict','decision-not-eligible','decision-stale','decision-reversed','reverse-window-closed','reversal-unavailable','not-resolver','gate-missing','gate-failed','base-conflict','not-configured'];const code=allowed.includes(e?.code)?e.code:'outcome-unknown';return json(res,code==='human-required'?403:code==='invalid-request'||code==='invalid-autonomy'?400:409,{error:code});}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,12 @@
|
|||||||
const states=new Map(),path=(org,step='')=>`${org?`/api/orgs/${encodeURIComponent(org)}`:'/api'}/autonomy${step?`/${step}`:''}`;
|
const states=new Map(),path=(org,step='')=>`${org?`/api/orgs/${encodeURIComponent(org)}`:'/api'}/autonomy${step?`/${step}`:''}`;
|
||||||
const guidance={
|
const guidance={
|
||||||
'policy-reverse-unavailable':'Policy has no effect executor or reverse yet. Choose in the loop or out of the loop.',
|
'policy-reverse-unavailable':'Policy has no effect executor or reverse yet. Choose in the loop or out of the loop.',
|
||||||
'autonomy-precondition':'This move needs a separate resolver, a tested reverse, owner notices and the class prerequisites. Out of the loop also needs time near the loop and your review of its trail.',
|
'autonomy-precondition':'This move needs a separate resolver, a tested reverse, owner notices and an enforced budget covering new agents for authority. Out of the loop needs an actual near-loop decision followed by your review of its trail. If a reverse stopped an agent, inspect the trail before relaunching it.',
|
||||||
|
'authority-limits-unavailable':'Choose near the loop with a budget covering new agents. Authority out of the loop waits for per-definition agent limits.',
|
||||||
|
'decision-closed':'This decision is closed. Refresh the inbox; raise a new decision if needed.',
|
||||||
|
'confirmation-required':'Confirm the arbiter resolution in the Console before using the decision.',
|
||||||
|
'not-found':'This decision could not be found. Refresh the inbox.',
|
||||||
|
'storage-refused':'The trail write was refused. Inspect the decision trail before retrying.',
|
||||||
'reverse-window-closed':'The reverse window has closed. Raise an ordinary new decision.',
|
'reverse-window-closed':'The reverse window has closed. Raise an ordinary new decision.',
|
||||||
'revision-conflict':'The organization changed. Reload before saving.',
|
'revision-conflict':'The organization changed. Reload before saving.',
|
||||||
'not-resolver':'The resolver no longer holds the required right. Withdraw and raise a fresh decision under current policy.',
|
'not-resolver':'The resolver no longer holds the required right. Withdraw and raise a fresh decision under current policy.',
|
||||||
@@ -53,7 +58,7 @@
|
|||||||
const review=button.dataset.autonomyReview,reverse=button.hasAttribute('data-autonomy-reverse');
|
const review=button.dataset.autonomyReview,reverse=button.hasAttribute('data-autonomy-reverse');
|
||||||
const body=review?{decisionClass:review}:reverse?{id:section.dataset.autonomyDecision}:{id:section.dataset.autonomyDecision,confirm:button.dataset.autonomyConfirm==='yes',...(button.dataset.autonomyConfirm==='no'?{reason:section.querySelector('[data-autonomy-reason]').value}:{})};
|
const body=review?{decisionClass:review}:reverse?{id:section.dataset.autonomyDecision}:{id:section.dataset.autonomyDecision,confirm:button.dataset.autonomyConfirm==='yes',...(button.dataset.autonomyConfirm==='no'?{reason:section.querySelector('[data-autonomy-reason]').value}:{})};
|
||||||
button.disabled=true;
|
button.disabled=true;
|
||||||
try{await call(org,review?'review':reverse?'reverse':'confirm',body);status.textContent=review?'Trail review recorded.':reverse?'Reversal recorded.':'Confirmation recorded. Refresh the inbox for current state.';}
|
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);status.textContent=review?'Trail review recorded.':reverse?(r.restart?'Reversal committed. Reload or restart the organization and inspect the trail before relaunching the agent.':'Reversal recorded.'):(body.confirm?'Confirmation recorded. Refresh the inbox for current state.':'Returned to arbiter. Refresh the inbox for current state.');}
|
||||||
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
|
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
|
||||||
});
|
});
|
||||||
window.MosaicAutonomy={load,section,notice};
|
window.MosaicAutonomy={load,section,notice};
|
||||||
|
|||||||
@@ -2,23 +2,27 @@ import test from 'node:test';
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import {mkdirSync} from 'node:fs';
|
import {mkdirSync} from 'node:fs';
|
||||||
import {join} from 'node:path';
|
import {join} from 'node:path';
|
||||||
|
import {tmpdir} from 'node:os';
|
||||||
import {startServer} from '../src/serve.mjs';
|
import {startServer} from '../src/serve.mjs';
|
||||||
import {createDevOwner} from '../src/dev-owner.mjs';
|
import {createDevOwner} from '../src/dev-owner.mjs';
|
||||||
import {browser} from './browser.mjs';
|
import {browser} from './browser.mjs';
|
||||||
import {close} from './fixture.mjs';
|
import {close} from './fixture.mjs';
|
||||||
const shots='/mnt/storage/scratch/mosaic-lead/reports/org-au-shots';
|
const shots=join(tmpdir(),'autonomy-shots');
|
||||||
const waitFor=(b,expression)=>b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error('autonomy view unavailable '+document.querySelector('[data-autonomy]')?.innerText)})()`);
|
const waitFor=(b,expression)=>b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error('autonomy view unavailable '+document.body.innerText)})()`);
|
||||||
for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','dark'])test(`AU owner settings ${width}x${height} ${theme}`,{timeout:60000},async t=>{
|
for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','dark'])test(`AU owner settings ${width}x${height} ${theme}`,{timeout:60000},async t=>{
|
||||||
let writes=0,confirms=0,reverses=0,setting={merge:'out of the loop'},revision='a'.repeat(64);
|
let writes=0,confirms=0,declines=0,reverses=0,setting={merge:'out of the loop'},revision='a'.repeat(64);
|
||||||
const call=async(verb,args)=>{
|
const call=async(verb,args)=>{
|
||||||
if(verb==='autonomy.get.console')return {revision,autonomy:setting,levels:{'cross-role':'out of the loop',merge:setting.merge,policy:'out of the loop',authority:'in the loop'}};
|
if(verb==='autonomy.get.console')return {revision,autonomy:setting,levels:{'cross-role':'out of the loop',merge:setting.merge,policy:'out of the loop',authority:'in the loop'}};
|
||||||
if(verb==='autonomy.set.console'){assert.equal(args.revision,revision);writes++;setting=args.autonomy;revision='b'.repeat(64);return {revision,transaction:'10000000-0000-4000-8000-000000000001'};}
|
if(verb==='autonomy.set.console'){assert.equal(args.revision,revision);writes++;setting=args.autonomy;revision='b'.repeat(64);return {revision,transaction:'10000000-0000-4000-8000-000000000001'};}
|
||||||
if(verb==='decision.confirm.console'){confirms++;assert.equal(args.confirm,true);return {op:'confirmed'};}
|
if(verb==='decision.confirm.console'){if(args.confirm)confirms++;else{declines++;assert.equal(args.reason,'Revise the plan');}return {op:args.confirm?'confirmed':'declined'};}
|
||||||
if(verb==='decision.reverse.console'){reverses++;return {reversed:true};}
|
if(verb==='decision.reverse.console'){reverses++;return {reversed:true};}
|
||||||
if(verb==='system-types.console')return {installed:[],enabled:[],project:null};
|
if(verb==='system-types.console')return {installed:[],enabled:[],project:null};
|
||||||
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
|
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
|
||||||
};
|
};
|
||||||
const server=await startServer({port:0,sso:createDevOwner(),send:async()=>({}),organizations:{list:async()=>[{id:'acme',label:'Acme',busHealthy:true}],resolve:async()=>({busHealthy:true,requestRead:call,requestWrite:call,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()=>[]}})},log:()=>{}});
|
const ids=['10000000-0000-4000-8000-000000000001','10000000-0000-4000-8000-000000000002','10000000-0000-4000-8000-000000000003'];
|
||||||
|
const rows=ids.map((id,i)=>({id,business:'acme',at:'2026-11-11T12:00:00.000Z',class:'gated',action:'git.merge.protected',route_to:'cto',raised_by_role:'coder',raised_by_run:'coder-run',question:'Land the reviewed change?',options:[{key:'yes',text:'Land'},{key:'no',text:'Revise'}],recommendation:'yes',blocking:false,autonomy:i===2?{notice:true,reverseUntil:'2099-01-01T00:00:00Z'}:{pending:true}}));
|
||||||
|
const trail=async id=>[{...rows.find(r=>r.id===id),table:'decisions'},{table:'events',kind:'action.allowed',body:{operation:'decision.raise',decision:id,approvalChoice:'yes',target:'vikunja:1/2'}}];
|
||||||
|
const server=await startServer({port:0,sso:createDevOwner(),send:async()=>({}),organizations:{list:async()=>[{id:'acme',label:'Acme',busHealthy:true}],resolve:async()=>({busHealthy:true,decisionWrite:async()=>({}),requestRead:call,requestWrite:call,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()=>rows,trail,messages:async()=>({messages:[]})},chat:{projects:async()=>[],threads:async()=>[]}})},log:()=>{}});
|
||||||
t.after(()=>close(server));const b=await browser({machine:false});t.after(()=>b.close());await b.viewport(width,height);
|
t.after(()=>close(server));const b=await browser({machine:false});t.after(()=>b.close());await b.viewport(width,height);
|
||||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`);
|
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`);
|
||||||
await waitFor(b,`document.querySelector('[data-autonomy-form]')`);
|
await waitFor(b,`document.querySelector('[data-autonomy-form]')`);
|
||||||
@@ -28,10 +32,23 @@ for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','d
|
|||||||
await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value='in the loop';document.querySelector('[data-autonomy-form]').requestSubmit();true`);
|
await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value='in the loop';document.querySelector('[data-autonomy-form]').requestSubmit();true`);
|
||||||
await waitFor(b,`/Saved/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(writes,1);assert.equal(setting.merge,'in the loop');
|
await waitFor(b,`/Saved/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(writes,1);assert.equal(setting.merge,'in the loop');
|
||||||
mkdirSync(shots,{recursive:true});await b.evaluate(`document.querySelector('[data-autonomy]').scrollIntoView();true`);await b.screenshot(join(shots,`autonomy-${width}-${theme}.png`));
|
mkdirSync(shots,{recursive:true});await b.evaluate(`document.querySelector('[data-autonomy]').scrollIntoView();true`);await b.screenshot(join(shots,`autonomy-${width}-${theme}.png`));
|
||||||
await b.evaluate(`document.querySelector('[data-autonomy]').innerHTML=MosaicAutonomy.notice({id:'decision-1',business:'acme',autonomy:{pending:true}});document.querySelector('[data-autonomy-confirm=yes]').click();true`);
|
const detail=async(id,selector)=>{
|
||||||
|
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/inbox/${id}`);
|
||||||
|
await waitFor(b,`document.querySelector(${JSON.stringify(selector)})`);
|
||||||
|
await b.evaluate(`document.documentElement.dataset.mode=${JSON.stringify(theme)};document.querySelector('[data-autonomy-decision]').scrollIntoView();true`);
|
||||||
|
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`),true);
|
||||||
|
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-decision]').dataset.autonomyDecision`),id);
|
||||||
|
};
|
||||||
|
await detail(ids[0],'[data-autonomy-confirm=yes]');
|
||||||
|
await b.evaluate(`document.querySelector('[data-autonomy-confirm=yes]').click();true`);
|
||||||
await waitFor(b,`/Confirmation recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(confirms,1);
|
await waitFor(b,`/Confirmation recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(confirms,1);
|
||||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`),true);await b.screenshot(join(shots,`confirm-${width}-${theme}.png`));
|
await b.screenshot(join(shots,`confirm-${width}-${theme}.png`));
|
||||||
await b.evaluate(`document.querySelector('[data-autonomy]').innerHTML=MosaicAutonomy.notice({id:'decision-2',business:'acme',autonomy:{notice:true,reverseUntil:'2099-01-01T00:00:00Z'}});document.querySelector('[data-autonomy-reverse]').click();true`);
|
await detail(ids[1],'[data-autonomy-confirm=no]');
|
||||||
|
await b.evaluate(`document.querySelector('[data-autonomy-reason]').value='Revise the plan';document.querySelector('[data-autonomy-confirm=no]').click();true`);
|
||||||
|
await waitFor(b,`/Returned to arbiter/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(declines,1);
|
||||||
|
await b.screenshot(join(shots,`decline-${width}-${theme}.png`));
|
||||||
|
await detail(ids[2],'[data-autonomy-reverse]');
|
||||||
|
await b.evaluate(`document.querySelector('[data-autonomy-reverse]').click();true`);
|
||||||
await waitFor(b,`/Reversal recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(reverses,1);
|
await waitFor(b,`/Reversal recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(reverses,1);
|
||||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`),true);await b.screenshot(join(shots,`reverse-${width}-${theme}.png`));
|
await b.screenshot(join(shots,`reverse-${width}-${theme}.png`));
|
||||||
});
|
});
|
||||||
@@ -3,10 +3,10 @@ import assert from 'node:assert/strict';
|
|||||||
import {Readable} from 'node:stream';
|
import {Readable} from 'node:stream';
|
||||||
import {autonomyHTTP} from '../src/autonomy-http.mjs';
|
import {autonomyHTTP} from '../src/autonomy-http.mjs';
|
||||||
const owner={provider:'test',iss:'https://issuer.test',sub:'owner'};
|
const owner={provider:'test',iss:'https://issuer.test',sub:'owner'};
|
||||||
async function request({method='POST',path='/api/autonomy',body={revision:'a'.repeat(64),autonomy:{merge:'in the loop'}},headers={},session=owner,writable=true,live=()=>session}={}) {
|
async function request({method='POST',path='/api/autonomy',body={revision:'a'.repeat(64),autonomy:{merge:'in the loop'}},headers={},session=owner,writable=true,live=()=>session,error=null}={}) {
|
||||||
const req=Readable.from([Buffer.from(JSON.stringify(body))]);req.method=method;req.headersDistinct={origin:['http://console.test'],'sec-fetch-site':['same-origin'],'content-type':['application/json'],...headers};
|
const req=Readable.from([Buffer.from(JSON.stringify(body))]);req.method=method;req.headersDistinct={origin:['http://console.test'],'sec-fetch-site':['same-origin'],'content-type':['application/json'],...headers};
|
||||||
let status,result,calls=[];const res={writeHead:s=>status=s,end:text=>result=JSON.parse(text)};
|
let status,result,calls=[];const res={writeHead:s=>status=s,end:text=>result=JSON.parse(text)};
|
||||||
const invoke=async(...args)=>{calls.push(args);return {revision:'b'.repeat(64)};};
|
const invoke=async(...args)=>{calls.push(args);if(error)throw Object.assign(new Error('unsafe detail'),{code:error});return {revision:'b'.repeat(64)};};
|
||||||
await autonomyHTTP(req,res,{path,session,live,read:invoke,write:writable?invoke:null,origin:'http://console.test'});
|
await autonomyHTTP(req,res,{path,session,live,read:invoke,write:writable?invoke:null,origin:'http://console.test'});
|
||||||
return {status,result,calls};
|
return {status,result,calls};
|
||||||
}
|
}
|
||||||
@@ -26,3 +26,9 @@ test('AU HTTP sign-in, cross-origin and stale session refuse without bus effects
|
|||||||
test('AU HTTP refuses caller-selected identity or organization',async()=>{
|
test('AU HTTP refuses caller-selected identity or organization',async()=>{
|
||||||
for(const extra of [{actor:'owner'},{business:'other'},{subject:owner}]){const r=await request({body:{revision:'a'.repeat(64),autonomy:{},...extra}});assert.equal(r.status,400);assert.deepEqual(r.calls,[]);}
|
for(const extra of [{actor:'owner'},{business:'other'},{subject:owner}]){const r=await request({body:{revision:'a'.repeat(64),autonomy:{},...extra}});assert.equal(r.status,400);assert.deepEqual(r.calls,[]);}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('AU HTTP preserves named state and authority refusals without raw details',async()=>{
|
||||||
|
for(const code of ['authority-limits-unavailable','decision-closed','confirmation-required','not-found','storage-refused']){
|
||||||
|
const r=await request({error:code});assert.equal(r.status,409);assert.deepEqual(r.result,{error:code});
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user