fix(admin): restore immutable PREPARE scope contract

Match d43aa02 metadata validation and exact DTO; distinguish missing safe-projection workflow scope from human review evidence. Preserve action normalization and explicit kill-switch capability. TDD regression RED verified; disposable admin 61 files / 381 tests, app+node TypeScript and build pass.
This commit is contained in:
devops committed 2026-10-23 13:13:41 +00:00
1 parent f29ba4ab8b
commit 0bed6e0313
6 files changed
+59 -17

No files matched your search

@@ -6,11 +6,11 @@ vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
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','Commit SHA (40 lowercase hex)':'a'.repeat(40),'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','Scope':'Audit staging only','Acceptance criteria (one per line)':'Schema checked\nEvidence attached'}))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:{commitSha:'a'.repeat(40)}}));
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'audit-1',title:'Audit schema',department:'SEO',operationMode:'PREPARE',budgetLimitCents:500,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked','Evidence attached']}});
expect(done).toHaveBeenCalledOnce();
});
@@ -3,13 +3,13 @@ import Button from './ui/Button';
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:'',commitSha:'',budget:''});
const [fields,setFields]=useState({key:'',title:'',department:'',commitSha:'',budget:'',scope:'',criteria:''});
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 input:CreateTaskInput={key:fields.key,title:fields.title,department:fields.department,operationMode:'PREPARE',budgetLimitCents:Number(fields.budget),metadata:{commitSha:fields.commitSha,scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n')}};
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>
{([['key','Task key'],['title','Title'],['department','Department'],['commitSha','Commit SHA (40 lowercase hex)'],['budget','Budget cap in cents'],['scope','Scope'],['criteria','Acceptance criteria (one per line)']] 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 · Environment: staging. Budget: 20..10000 cents. Scope: nonblank, at most 2000 characters. Acceptance criteria: 1..20 nonblank lines, at most 500 characters each. Human scope and criteria are persisted unchanged; the workflow restriction is server-owned.</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>;
}
@@ -121,3 +121,16 @@ it('requires explicit kill capability rather than generic mutations',async()=>{
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
});
it.each([{}, {scope:'STAGE_PREPARE'}, {scope:'Human scope',acceptanceCriteria:[]}])('does not claim incomplete or legacy metadata is scope evidence: %j',async metadata=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[{...task,metadata}]:{...task,metadata}}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText(/Scope \/ acceptance criteria unavailable/)).toBeInTheDocument();
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
});
it('separates human evidence from server workflow scope without inventing a marker',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:task}));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText('Backend-reported scope / acceptance criteria')).toBeInTheDocument();
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
});
@@ -64,7 +64,7 @@ export default function OrchestrationCommandCenter() {
{!loading&&!error&&!tasks.length&&<p>No tasks returned by backend.</p>}
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{t.department}</td><td>{t.state}</td><td>{t.operationMode}</td><td>{t.budgetLimitCents??'Unknown'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
</section>}
{selected&&<section aria-label="Task detail" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{selected.metadata?<h3>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend projection.</p>}<Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
{selected&&<section aria-label="Task detail" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?<h3>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend projection.</p>}<p>Server workflow scope: unavailable in safe projection.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'Backend mutations unavailable':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
<h3>Immutable approval decisions</h3><Json value={selected.decisions??[]}/>
<h3>Runs & registered artifacts</h3>{!selected.runs?.length&&<p>No registered runs.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {r.status}</h4><p>Commit: {r.commitSha} · Environment: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
@@ -46,10 +46,10 @@ 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:{commitSha:'a'.repeat(40)}})).rejects.toThrow(/budget/);
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/budget/);
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
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)}});
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
});
});
@@ -70,15 +70,15 @@ describe('actual PREPARE backend contract',()=>{
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);
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).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);
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha,scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).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)}};
const dto={key:'k',title:'t',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}};
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
});
});
@@ -100,3 +100,30 @@ it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
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();
});
const validProposal={key:'scope-1',title:'Review staging',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:' Human scope ',acceptanceCriteria:[' Evidence reviewed ']}};
it('preserves immutable human metadata exactly and strips server-owned fields from exact DTO',async()=>{
vi.resetAllMocks();
const projected={id:'new',...validProposal,state:'DRAFT',version:1,metadata:{...validProposal.metadata,environment:'staging'},availableActions:['SUBMIT_GATE1']};
vi.mocked(api.post).mockResolvedValue({data:projected});
await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,workflowScope:'PRODUCTION',createdBy:'forged'}} as unknown as import('./orchestration').CreateTaskInput)).resolves.toEqual(projected);
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',validProposal);
vi.mocked(api.get).mockResolvedValue({data:projected});
expect((await orchestration.task('new')).metadata).toEqual(projected.metadata);
vi.mocked(api.get).mockResolvedValue({data:[projected]});
expect((await orchestration.tasks())[0].metadata).toEqual(projected.metadata);
});
it.each(['', ' ', 'x'.repeat(2001),undefined,42])('rejects invalid human scope %s before HTTP',async scope=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,scope}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/scope/i);expect(api.post).not.toHaveBeenCalled();
});
it.each([[],Array(21).fill('x'),[''],[' '],['x'.repeat(501)],undefined,'criterion',[42]])('rejects invalid acceptance criteria %s before HTTP',async acceptanceCriteria=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,acceptanceCriteria}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/criteria/i);expect(api.post).not.toHaveBeenCalled();
});
it('rejects array-coerced commit hashes',async()=>{
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,commitSha:['a'.repeat(40)]}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/commit/i);expect(api.post).not.toHaveBeenCalled();
});
it('accepts scope and criteria at exact backend limits',async()=>{
vi.resetAllMocks();vi.mocked(api.post).mockResolvedValue({data:{}});
const dto={...validProposal,metadata:{...validProposal.metadata,scope:'x'.repeat(2000),acceptanceCriteria:Array(20).fill('x'.repeat(500))}};
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
});
@@ -58,18 +58,20 @@ export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','
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:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string}}
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string;scope:string;acceptanceCriteria: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(typeof input.metadata?.commitSha!=='string'||!/^[a-f0-9]{40}$/.test(input.metadata.commitSha))return 'Immutable commit must be 40 lowercase hex characters';
if(typeof input.metadata?.scope!=='string'||!input.metadata.scope.trim()||input.metadata.scope.length>2000)return 'Scope must be nonblank and at most 2000 characters';
if(!Array.isArray(input.metadata?.acceptanceCriteria)||input.metadata.acceptanceCriteria.length<1||input.metadata.acceptanceCriteria.length>20||input.metadata.acceptanceCriteria.some(value=>typeof value!=='string'||!value.trim()||value.length>500))return 'Acceptance criteria must contain 1..20 nonblank strings of at most 500 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> {
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;
// Preserve human evidence exactly; workflowScope/environment/identity remain server-owned.
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,scope:input.metadata.scope,acceptanceCriteria:[...input.metadata.acceptanceCriteria]}})).data;
},
async task(id:string):Promise<Task> {
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);