fix(admin): reconcile bounded PREPARE backend contracts
This commit is contained in:
1 parent
56b6696ca3
commit
f29ba4ab8b
7 files changed
+127
-31
No files matched your search
@@ -3,12 +3,14 @@ import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import CreateOrchestrationTask from './CreateOrchestrationTask';
|
||||
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
|
||||
it('submits explicit bounded scope and acceptance criteria, only after valid input',async()=>{
|
||||
it('submits exact bounded PREPARE contract only after valid commit and budget',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
|
||||
expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Bounded scope':'Staging schema audit only','Acceptance criteria (one per line)':'Report all failures','Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Commit SHA (40 lowercase hex)':'a'.repeat(40),'Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value}});expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();}
|
||||
fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value:'500'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
|
||||
await screen.findByText('Task created by backend.');
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{commitSha:'a'.repeat(40)}}));
|
||||
expect(done).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -1,14 +1,15 @@
|
||||
import {useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import {orchestration,proposalError} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',scope:'',criteria:'',budget:''});
|
||||
const [mode,setMode]=useState<CreateTaskInput['operationMode']>('PREPARE');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&Number.isSafeInteger(Number(fields.budget))&&Number(fields.budget)>=0;
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — Refresh and reconcile the task key before resubmitting.':'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy||!!success} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision. Production proposals are disabled. After an ambiguous failure, refresh and reconcile the unique task key before resubmitting.</p>
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',commitSha:'',budget:''});
|
||||
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const input:CreateTaskInput={key:fields.key,title:fields.title,department:fields.department,operationMode:'PREPARE',budgetLimitCents:Number(fields.budget),metadata:{commitSha:fields.commitSha}};
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&!proposalError(input);
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — Refresh and reconcile the task key before resubmitting.':'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['commitSha','Commit SHA (40 lowercase hex)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<p>Operation mode: PREPARE · Scope: STAGE_PREPARE · Environment: staging. Budget: 20..10000 cents. Backend does not persist free-form scope or acceptance criteria.</p><p>Creation does not authorize work. Gate1 is a separate immutable decision. Production proposals are disabled. After an ambiguous failure, refresh and reconcile the unique task key before resubmitting.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>Create bounded task</Button>
|
||||
</form></details>;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ vi.mock('../services/api', () => ({ default: {get:vi.fn(),post:vi.fn(),put:vi.fn
|
||||
const task={id:'t1',key:'bounded-1',title:'Bounded SEO audit',department:'SEO',state:'GATE1_PENDING',version:4,operationMode:'PREPARE',budgetLimitCents:500,availableActions:[{id:'g1',label:'Approve bounded work',gate:1,decision:'APPROVED'}],runs:[],metadata:{scope:'Only staging',acceptanceCriteria:['Audit schema']}};
|
||||
describe('command center', () => {
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => {
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,chat:true,runtime:false}}};
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,killSwitch:true,chat:true,runtime:false}}};
|
||||
if(url.endsWith('/tasks')) return {data:[task]};
|
||||
if(url.endsWith('/tasks/t1')) return {data:task};
|
||||
throw new Error('Unavailable: '+url);
|
||||
@@ -114,3 +114,10 @@ describe('command center', () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
it('requires explicit kill capability rather than generic mutations',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -13,7 +13,7 @@ function Json({value}:{value:unknown}) {return <pre className="text-xs whitespac
|
||||
export default function OrchestrationCommandCenter() {
|
||||
const detailEpoch=useRef(0);
|
||||
const [section,setSection]=useState<Section>('Overview');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false});
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false});
|
||||
const [tasks,setTasks]=useState<Task[]>([]);
|
||||
const [selected,setSelected]=useState<Task|null>(null);
|
||||
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
|
||||
@@ -32,7 +32,7 @@ export default function OrchestrationCommandCenter() {
|
||||
const [messages,setMessages]=useState<ChatMessage[]>([]);
|
||||
const [chatKey,setChatKey]=useState(()=>crypto.randomUUID());
|
||||
const loadTasks=async()=> {setLoading(true);setError(''); try {setTasks(await orchestration.tasks())} catch(e){setTasks([]);setSelected(null);setError(errorText(e))} finally {setLoading(false)}};
|
||||
useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false}));},[]);
|
||||
useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true,killSwitch:s.capabilities?.killSwitch===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false,killSwitch:false}));},[]);
|
||||
useEffect(()=> {
|
||||
const resource=resources[section]; setSnapshot(null);setError('');
|
||||
if(!resource)return;
|
||||
@@ -71,8 +71,8 @@ export default function OrchestrationCommandCenter() {
|
||||
<h3>Budget ledger (cents; not inferred usage)</h3><Json value={selected.budgetLedger??[]}/><h3>Ordered audit events</h3><Json value={selected.events??[]}/>
|
||||
</section>}
|
||||
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>Measured at: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>No records returned by backend.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3>{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{k}</dt><dd>{String(v??'Unknown')}</dd></div>)}</dl></article>)}</div><p>Configuration mutations require backend-advertised commands; none are inferred by this client.</p></section>}
|
||||
{section==='Kill switch'&&!capabilities.mutations&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.mutations&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
|
||||
{section==='Kill switch'&&!capabilities.killSwitch&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
|
||||
{section==='9router usage & quota'&&<RouterUsagePanel/>}
|
||||
{section==='Runtime health & sessions'&&<RuntimeReadPanel/>}
|
||||
{section==='Chat'&&!capabilities.chat&&<p>Chat unsupported: trusted runtime bridge unavailable.</p>}
|
||||
@@ -82,7 +82,7 @@ export default function OrchestrationCommandCenter() {
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</option>{pending.task.runs?.filter(r=>r.status==='SUCCEEDED').flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
|
||||
<label className="block">Reason<input aria-label="Reason" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>I reviewed the immutable scope and binding</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
|
||||
</div></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -2,23 +2,24 @@ import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
const action={id:'g1',label:'Review Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const task={id:'t',key:'t',title:'Safe proposal',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[action],runs:[]};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[task]:task}));});
|
||||
it('refuses Production creation even when called outside form',async()=>{
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{scope:'x',acceptanceCriteria:['x']}})).rejects.toThrow(/Production/);
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|advertised/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects ambiguous advertised action rather than selecting a mutation path',async()=>{
|
||||
const ambiguous={...action,toState:'READY'};
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Unsupported/);
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/advertised/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks release transitions even when advertised by server',async()=>{
|
||||
const release={id:'release',label:'Release',toState:'RELEASING'};
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/Production/);
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|advertised/);
|
||||
expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects Gate2 evidence from failed runs',async()=>{
|
||||
|
||||
@@ -46,9 +46,57 @@ describe('orchestration adapter', () => {
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',{sessionId:'session',message:'Review task',idempotencyKey:'key'});
|
||||
});
|
||||
it('creates bounded work without permitting invalid caps or client-supplied state',async()=>{
|
||||
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{scope:'staging',acceptanceCriteria:['report']}})).rejects.toThrow(/budget/);
|
||||
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{commitSha:'a'.repeat(40)}})).rejects.toThrow(/budget/);
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
|
||||
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
|
||||
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40)}});
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40)}});
|
||||
});
|
||||
});
|
||||
|
||||
describe('actual PREPARE backend contract',()=>{
|
||||
beforeEach(()=>vi.resetAllMocks());
|
||||
it('normalizes strings by fixed mapping, drops unknown and tampered objects, never infers from state',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE','RELEASE_AUTHORIZE',{id:'SUBMIT_GATE1',label:'bad',toState:'RELEASING'},null]}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
expect(detail.availableActions.map(a=>a.id)).toEqual(['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE']);
|
||||
vi.mocked(api.put).mockResolvedValue({data:{}});
|
||||
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'submit'});
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1/transition',{toState:'GATE1_PENDING',expectedVersion:7,idempotencyKey:'submit',reason:undefined});
|
||||
vi.mocked(api.get).mockResolvedValue({data:[{...task,state:'DRAFT',availableActions:[]}]});
|
||||
expect((await orchestration.tasks())[0].availableActions).toEqual([]);
|
||||
});
|
||||
it('rejects arbitrary object transitions and conflicting known mappings',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:[{id:'evil',label:'go',toState:'RUNNING'},{id:'SUBMIT_GATE1',label:'go',toState:'READY'}]}});
|
||||
expect((await orchestration.task('t/1')).availableActions).toEqual([]);
|
||||
});
|
||||
it.each([0,19,10001,20.5])('rejects invalid budget %s',async budget=>{
|
||||
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40)}})).rejects.toThrow(/budget/i);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['abc','A'.repeat(40),'a'.repeat(64),''])('rejects invalid commit %s',async commitSha=>{
|
||||
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha}})).rejects.toThrow(/commit/i);
|
||||
});
|
||||
it.each([20,10000])('posts exact DTO at boundary %s',async budget=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{}});
|
||||
const dto={key:'k',title:'t',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40)}};
|
||||
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['APPROVE_GATE1','post','/gates/1/decide',{decision:'APPROVED'}],
|
||||
['REJECT_GATE1','post','/gates/1/decide',{decision:'REJECTED'}],
|
||||
['QUEUE_PREPARE','put','/transition',{toState:'READY'}],
|
||||
])('routes actual advertised %s regardless of state',async(id,method,path,payload)=>{
|
||||
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:[id]}});
|
||||
vi.mocked(api.post).mockResolvedValue({data:{}});vi.mocked(api.put).mockResolvedValue({data:{}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:new Date(Date.now()+3600000).toISOString()});
|
||||
expect(method==='post'?api.post:api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1'+path,expect.objectContaining({...payload,expectedVersion:7,idempotencyKey:'k'}));
|
||||
});
|
||||
it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
|
||||
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:['APPROVE_GATE1']}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/24 hours/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,5 +1,36 @@
|
||||
import api from './api';
|
||||
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
|
||||
// Only advertised IDs select commands; task state never manufactures authorization.
|
||||
const actionCommands: Record<string, ServerAction> = {
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'Submit Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'Approve Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'Reject Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'Queue PREPARE',toState:'READY'},
|
||||
};
|
||||
export function normalizeActions(value:unknown):ServerAction[] {
|
||||
if(!Array.isArray(value))return [];
|
||||
const result:ServerAction[]=[];
|
||||
for(const raw of value){
|
||||
let action:ServerAction|undefined;
|
||||
if(typeof raw==='string')action=Object.hasOwn(actionCommands,raw)?actionCommands[raw]:undefined;
|
||||
else if(raw&&typeof raw==='object'&&typeof raw.id==='string'){
|
||||
const fixed=Object.hasOwn(actionCommands,raw.id)?actionCommands[raw.id]:undefined;
|
||||
if(fixed){
|
||||
if(['toState','gate','decision'].some(k=>raw[k]!==undefined&&raw[k]!==fixed[k as keyof ServerAction]))continue;
|
||||
action={...fixed};
|
||||
}else if(!raw.toState&&[1,2].includes(raw.gate)&&['APPROVED','REJECTED'].includes(raw.decision)){
|
||||
// Legacy object format may describe only dedicated gate decisions, never arbitrary transitions.
|
||||
action={id:raw.id,label:raw.id,gate:raw.gate,decision:raw.decision};
|
||||
}
|
||||
if(action){
|
||||
if(typeof raw.label==='string'&&raw.label.trim())action={...action,label:raw.label};
|
||||
if(typeof raw.disabledReason==='string')action={...action,disabledReason:raw.disabledReason};
|
||||
}
|
||||
}
|
||||
if(action&&!result.some(a=>a.id===action.id))result.push({...action});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export interface Artifact { id: string; sha256: string; kind?: string; uri?: string }
|
||||
export interface Run { id: string; commitSha: string; environment: string; status: string; artifacts: Artifact[] }
|
||||
export interface Task { id: string; key: string; title: string; department: string; state: string; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
|
||||
@@ -22,23 +53,28 @@ export function commandFailure(error:unknown):{message:string;retryable:boolean}
|
||||
return {message:(error instanceof Error?error.message:'Backend request unavailable')+' — Outcome unknown. Retry only the identical payload/key, or refresh to reconcile.',retryable:true};
|
||||
}
|
||||
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean;killSwitch?:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
|
||||
export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const;
|
||||
export type KillLevel = typeof killLevels[number];
|
||||
export interface ChatMessage {id:string;role:'assistant'|'user';content:string}
|
||||
function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof data === 'object' && 'success' in data) {if (!data.success) throw new Error('Orchestration request failed'); return data.data;} return data as T; }
|
||||
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'OBSERVE'|'PREPARE'|'MUTATE_PRODUCTION';budgetLimitCents:number;metadata:{scope:string;acceptanceCriteria:string[]}}
|
||||
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string}}
|
||||
export function proposalError(input:CreateTaskInput):string|undefined {
|
||||
if(input.operationMode!=='PREPARE')return 'Only bounded Stage PREPARE proposals are available';
|
||||
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<20||input.budgetLimitCents>10000)return 'PREPARE budget must be an integer 20..10000 cents';
|
||||
if(!/^[a-f0-9]{40}$/.test(input.metadata?.commitSha??''))return 'Immutable commit must be 40 lowercase hex characters';
|
||||
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'Proposal requires key (1..120), title (1..255), department (1..50)';
|
||||
}
|
||||
export const orchestration = {
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
if(input.operationMode==='MUTATE_PRODUCTION')throw new Error('Production proposals are unavailable in this panel');
|
||||
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<0)throw new Error('Nonnegative integer budget required');
|
||||
if(!input.key.trim()||!input.title.trim()||!input.department.trim()||!input.metadata.scope.trim()||!input.metadata.acceptanceCriteria.length)throw new Error('Bounded scope and acceptance criteria required');
|
||||
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:input.operationMode,budgetLimitCents:input.budgetLimitCents,metadata:input.metadata})).data;
|
||||
const error=proposalError(input);if(error)throw new Error(error);
|
||||
// Backend fixes scope/environment and does not persist free-form acceptance fields.
|
||||
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:'PREPARE',budgetLimitCents:input.budgetLimitCents,metadata:{commitSha:input.metadata.commitSha}})).data;
|
||||
},
|
||||
async task(id:string):Promise<Task> {
|
||||
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);
|
||||
if (!data?.id || !Number.isInteger(data.version)) throw new Error('Invalid task detail');
|
||||
return {...data,availableActions:data.availableActions??[]};
|
||||
return {...data,availableActions:normalizeActions(data.availableActions)};
|
||||
},
|
||||
async resource(name:Resource):Promise<ResourceSnapshot> {
|
||||
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
|
||||
@@ -56,13 +92,14 @@ export const orchestration = {
|
||||
return data;
|
||||
},
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
const action = task.availableActions.find(a => a.id === requested.id);
|
||||
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
||||
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
|
||||
if (action.gate && action.decision) {
|
||||
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('Future expiry required');
|
||||
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('Gate1 expiry must be within 24 hours');
|
||||
let binding = {};
|
||||
if (action.gate === 2 && action.decision === 'APPROVED') {
|
||||
const run = task.runs?.find(r => r.id === input.runId);
|
||||
@@ -79,6 +116,6 @@ export const orchestration = {
|
||||
const { data } = await api.get('/admin/orchestration/tasks');
|
||||
const rows = Array.isArray(data) ? data : data.data;
|
||||
if (!Array.isArray(rows)) throw new Error('Invalid orchestration task response');
|
||||
return rows.map(row => ({ ...row, availableActions: row.availableActions ?? [] }));
|
||||
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user