Compare commits

...
Author SHA1 Message Date
devops 9d3d7f409d fix(admin): distinguish snapshot inventory from live runtime telemetry 2026-10-23 13:34:20 +00:00
devops a26a18b5f2 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.
2026-10-23 13:13:11 +00:00
devops 7479e0ead4 fix(admin): reconcile bounded PREPARE backend contracts 2026-10-23 13:03:23 +00:00
devops c058295f35 Complete safe admin workflow and authenticated runtime read UI 2026-10-23 12:52:09 +00:00
13 changed files with 433 additions and 43 deletions

No files matched your search

@@ -0,0 +1,33 @@
# Admin v4 completion integration contract
Frontend-only slice based on 5507fbc. No deployment or runtime writes. The historical read-only integration document does not authorize enabling routes. Backend policy remains the authority; UI adds deny-only safety restrictions, never permissions.
## Workflow (existing routes retained)
- GET `/admin/orchestration/overview`: ResourceSnapshot with `items`, ISO `measuredAt`, `capabilities:{mutations:boolean,chat:boolean,runtime:boolean}`. Missing/failed capability read defaults false.
- GET `/admin/orchestration/tasks`: Task[] (or `{success:true,data:Task[]}`).
- GET `/admin/orchestration/tasks/:id`: Task. Required identity/version/state/mode/budget and server-computed `availableActions`; optional scope/acceptance metadata, runs/artifacts, immutable decisions, events and budgetLedger. Missing actions means no permission. Include structured redacted scope metadata for a useful Gate1 review; no secrets or arbitrary event payloads.
- POST `/admin/orchestration/tasks`: existing CreateTaskInput `{key,title,department,operationMode,budgetLimitCents,metadata:{scope,acceptanceCriteria:string[]}}`. UI allows OBSERVE/PREPARE only, not Production. Key is unique business identity; after an ambiguous create, reconcile key before resubmission. Success locks the form to prevent accidental duplicate submission.
- PUT `/admin/orchestration/tasks/:id/transition`: TransitionDto `{toState,expectedVersion,idempotencyKey,reason}`.
- POST `/admin/orchestration/tasks/:id/gates/:gate/decide`: GateDecisionDto `{decision:'APPROVED'|'REJECTED',expectedVersion,idempotencyKey,expiresAt,notes}`; Gate2 approval additionally binds `{runId,artifactHash,commitSha,environment}` from a registered SUCCEEDED run, never editable commit/environment. Gate1 is bounded work, not release permission.
- ServerAction `{id,label,toState? ,gate?:1|2,decision?:'APPROVED'|'REJECTED',disabledReason?}`. Exactly one of transition or gate decision. All role/policy/kill/version checks remain backend-side. Browser identity fields are never posted; actor must derive from verified JWT. HOLD/request changes only appear if advertised as supported transitions. EDIT_AND_APPROVE is unavailable without a separately reviewed DTO; no guessed mutation endpoint.
- HTTP409 stale version/idempotency mismatch, 410 expired, 401/403 denied and other 4xx permanently lock that dialog; refresh and review afresh. Network/5xx ambiguous failures allow only identical payload/key. Inputs and navigation are locked after first attempt; authoritative refresh invalidates selection and pending detail reads. No optimistic status update.
- Production task actions and release transitions remain disabled even if advertised. Gate2 evidence inspection is not deployment authorization. Server still enforces TTL; browser time is a usability check, not trusted authorization.
## Runtime read API (aligned by read-only inspection with runtime sibling)
Uses existing JWT Axios client, never upstream Hermes paths or tokens. No automatic runtime mutations. Tab is explicitly selected; failed auth/config/routes show unavailable.
- GET `/admin/orchestration/runtime/health` -> `{ok:boolean,version:string,commit:string,auth_required:true}`. Any false/missing authentication flag is rejected.
- GET `/admin/orchestration/runtime/profiles` -> `{name:string,is_default:boolean,gateway_running:boolean}[]`, already filtered to principal grants.
- GET `/admin/orchestration/runtime/status?profile=<authorized>` -> `{version,gateway_running,overall,active_agents,gateway_state:string|null}`.
- GET `/admin/orchestration/runtime/sessions?profile=<authorized>&limit=20&offset=0` -> `{total:number,sessions:{id,profile,source,is_active}[]}`. UI paginates; profile mismatch is rejected.
- GET `/admin/orchestration/runtime/usage?profile=<authorized>&days=30` -> `{period_days:number,totals:{total_input,total_output,total_sessions,total_estimated_cost}}`.
Runtime client explicitly projects known fields; unknown secret fields are discarded. Numeric zero survives. Cost is labelled **upstream estimate**, unspecified currency, not settled billing and never added to overlapping 9router totals. Client observation time is not server heartbeat/freshness. Profile gateway flags and active agent count are source observations, not invented readiness/department counts. Generic Resources for existing agents/model-policy/schedules/releases remain unchanged; unavailable contracts stay visibly unavailable. Runtime schedules/model-info may exist backend-side but are not guessed into generic Resources.
## Verification
Runner: disposable node:22-bookworm, --userns=host --network none; source and dependency donor read-only, private copies in /work. No donor/source build writes. Required final gates: `tsc --noEmit -p tsconfig.app.json`, `npm run build`, `npm test -- --maxWorkers=2`. Logs under `/opt/services/canina/validation/v4-panel-completion/` (outside discovery). Earlier RED proves 7 workflow failures and 2 selection/idempotency failures; runtime RED is missing new component. Existing test fixtures migrated from invented VERIFIED run status to backend SUCCEEDED status. No tests skipped or permissions inferred.
Not claimed: live backend browser acceptance, real authenticated runtime availability, Stage publication, CI evidence authority or Production execution. Parent owns integration and publication.
@@ -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','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:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
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();
});
@@ -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)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:'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} 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} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE','MUTATE_PRODUCTION'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision.</p>
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy}>Create bounded task</Button>
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,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'],['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>;
}
@@ -0,0 +1,44 @@
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import RuntimeReadPanel from './RuntimeReadPanel';
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:5000,freshness:'stale',liveProcess:'unknown'};
it('labels snapshot inventory without presenting stopped gateway, zero agents or active sessions as live',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'v1',gateway_running:false,overall:'unknown',active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:1,sessions:[{id:'session-1',profile:'dev',source:'cli',is_active:true}],provenance}:{period_days:30,totals:{total_input:1,total_output:2,total_sessions:1,total_estimated_cost:0},provenance}}));
render(<RuntimeReadPanel/>);
expect(await screen.findByText('Inventory service: responsive (not live Hermes health)')).toBeInTheDocument();
screen.getAllByText(/Captured at: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('stale'));
fireEvent.change(screen.getByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
expect(await screen.findByText(/Active agents: unknown/)).toBeInTheDocument();
expect(await screen.findByText(/historical snapshot flag: active; live activity unknown/)).toBeInTheDocument();
expect(screen.queryByText(/Gateway.*stopped/)).not.toBeInTheDocument();
expect(screen.queryByText(/Active agents: 0/)).not.toBeInTheDocument();
expect(screen.queryByText(/runtime health: healthy/)).not.toBeInTheDocument();
});
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/health'))return {data:{ok:true,version:'v1',commit:'abc',auth_required:true}};
if(url.endsWith('/profiles'))return {data:[{name:'dev',is_default:false,gateway_running:false}]};
if(url.endsWith('/status'))return {data:{version:'v1',gateway_running:false,overall:'degraded',active_agents:0,gateway_state:null}};
if(url.endsWith('/sessions'))return {data:{total:0,sessions:[]}};
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
throw new Error('Runtime unavailable');
});});
it('shows actual health identity, explicit stopped gateway, zero usage and profile-bound reads',async()=>{
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).toBeInTheDocument();
fireEvent.change(await screen.findByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('No sessions returned.')).toBeInTheDocument();
expect(screen.getByText('Input tokens: 0')).toBeInTheDocument();expect(screen.getByText(/Upstream estimated cost: 0/)).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/runtime/sessions',{params:{profile:'dev',limit:20,offset:0}});
});
it('shows unavailable rather than healthy when runtime cannot be authenticated',async()=>{
vi.mocked(api.get).mockRejectedValue(new Error('Runtime unavailable'));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText('Authenticated runtime health: healthy')).not.toBeInTheDocument();
});
it('rejects malformed health and never renders unknown secret fields',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:false,password:'secret-value'}:[]}));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
});
it('refreshes the authenticated runtime reads without a browser runtime connection',async()=>{
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'Refresh runtime'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
});
@@ -0,0 +1,35 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {runtime} from '../services/runtime';
import type {RuntimeProvenance,RuntimeHealth,RuntimeProfile,RuntimeStatus,RuntimeSessions,RuntimeUsage} from '../services/runtime';
function Snapshot({value}:{value?:RuntimeProvenance}){return value?<p>Snapshot inventory · Captured at: {value.capturedAt} · Age: {value.ageSeconds} seconds · {value.freshness} · Live process: {value.liveProcess}. Even fresh snapshots are not live readiness.</p>:null}
export default function RuntimeReadPanel(){
const [revision,setRevision]=useState(0);const [profile,setProfile]=useState('');const [offset,setOffset]=useState(0);
const [health,setHealth]=useState<RuntimeHealth|null>(null);const [profiles,setProfiles]=useState<RuntimeProfile[]>([]);const [errors,setErrors]=useState<Record<string,string>>({});
const [status,setStatus]=useState<RuntimeStatus|null>(null);const [sessions,setSessions]=useState<RuntimeSessions|null>(null);const [usage,setUsage]=useState<RuntimeUsage|null>(null);
const [observed,setObserved]=useState('');
useEffect(()=>{let active=true;setHealth(null);setProfiles([]);setErrors({});
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'Health unavailable — authenticated backend runtime read failed.'}))});
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'Profiles unavailable — no authorized runtime identity list.'}))}});
return ()=>{active=false};
},[revision]);
useEffect(()=>{let active=true;setStatus(null);setSessions(null);setUsage(null);setErrors(e=>({health:e.health,profiles:e.profiles}));if(!profile)return;
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:name+' unavailable — no fallback values.'}))};
runtime.status(profile).then(v=>{if(active)setStatus(v)}).catch(()=>fail('Status'));
runtime.sessions(profile,offset).then(v=>{if(active)setSessions(v)}).catch(()=>fail('Sessions'));
runtime.usage(profile).then(v=>{if(active)setUsage(v)}).catch(()=>fail('Usage'));
return ()=>{active=false};
},[profile,offset,revision]);
return <section aria-label="Authenticated runtime" className="bg-white border rounded-2xl p-5 space-y-4">
<div className="flex justify-between"><h2 className="font-bold">Hermes runtime — backend authenticated reads</h2><Button onClick={()=>setRevision(r=>r+1)}>Refresh runtime</Button></div>
<p>No browser runtime credentials or direct Hermes connection. Refresh observations are not heartbeat timestamps.</p>
{Object.entries(errors).filter(([,message])=>message).map(([name,message])=><p key={name} role="alert">{message}</p>)}
{health&&<div><p>Inventory service: {health.ok?'responsive':'not responsive'} (not live Hermes health)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>Client observed at: {observed}. Client receipt time only; not capture time or live heartbeat.</p></div>}
<label>Authorized runtime profile<select aria-label="Authorized runtime profile" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">Select authorized profile</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
{!profiles.length&&!errors.profiles&&<p>No authorized profiles returned.</p>}
{profiles.map(p=><div key={p.name}>{p.name} · Gateway {p.provenance?'unknown (snapshot; not process readiness)':p.gateway_running?'running':'stopped'} · {p.is_default?'default profile':'non-default profile'}<Snapshot value={p.provenance}/></div>)}
{status&&<div><h3>Profile status</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>Gateway: {status.provenance?'unknown':status.gateway_running?'running':'stopped'} · State: {status.provenance?'unknown':status.gateway_state??'Unknown'} · Active agents: {status.provenance?'unknown':status.active_agents}</p></div>}
{usage&&<div><h3>Runtime usage — {usage.period_days} days, selected profile only</h3><Snapshot value={usage.provenance}/><p>Input tokens: {usage.totals.total_input}</p><p>Output tokens: {usage.totals.total_output}</p><p>Sessions: {usage.totals.total_sessions}</p><p>Upstream estimated cost: {usage.totals.total_estimated_cost} (currency unspecified by source; not settled billing)</p><p>Do not add this to 9router totals; attribution overlaps and is not reconciled.</p></div>}
{sessions&&<div><h3>Sessions — {sessions.total} returned total</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>No sessions returned.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`historical snapshot flag: ${s.is_active?'active':'inactive'}; live activity unknown`:s.is_active?'active':'inactive'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>Previous sessions</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>Next sessions</Button></div>}
</section>;
}
@@ -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);
@@ -60,8 +60,8 @@ describe('command center', () => {
expect(screen.getByText('BLOCKED')).toBeInTheDocument();
});
it('binds Gate2 using registered evidence, never editable commit or environment',async()=>{
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'VERIFIED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[release]:release}));
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'SUCCEEDED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
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')?[release]:release}));
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
@@ -114,3 +114,23 @@ 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();
});
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();
});
@@ -1,17 +1,19 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useRef } from 'react';
import Button from '../components/ui/Button';
import RouterUsagePanel from '../components/RouterUsagePanel';
import RuntimeReadPanel from '../components/RuntimeReadPanel';
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
import { orchestration, killLevels } from '../services/orchestration';
import { orchestration, killLevels, actionBlockReason, commandFailure } from '../services/orchestration';
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Chat'] as const;
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Runtime health & sessions','Chat'] as const;
type Section = typeof sections[number];
const resources:Partial<Record<Section,Resource>> = {'Agents & departments':'agents','Models & budgets':'model-policy','Schedules':'schedules','Audit & releases':'releases'};
const errorText=(e:unknown)=> e instanceof Error ? e.message : 'Unknown backend error';
function Json({value}:{value:unknown}) {return <pre className="text-xs whitespace-pre-wrap break-all bg-gray-50 border rounded-xl p-3" dir="ltr">{JSON.stringify(value,null,2)}</pre>}
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);
@@ -22,12 +24,15 @@ export default function OrchestrationCommandCenter() {
const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false);
const [attempted,setAttempted]=useState(false); const [busy,setBusy]=useState(false); const [commandError,setCommandError]=useState('');
const [success,setSuccess]=useState('');
const [blocked,setBlocked]=useState(false);
const [now,setNow]=useState(Date.now());
useEffect(()=>{const timer=setInterval(()=>setNow(Date.now()),1000);return ()=>clearInterval(timer)},[]);
const [kill,setKill]=useState<KillLevel>('FREEZE_NEW_WORK');
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
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;
@@ -35,21 +40,21 @@ export default function OrchestrationCommandCenter() {
orchestration.resource(resource).then(data=>{if(active)setSnapshot(data)}).catch(e=>{if(active)setError(errorText(e))}).finally(()=>{if(active)setLoading(false)});
return ()=>{active=false};
},[section]);
const select=async(task:Task)=>{setSelected(null);setError('');try {setSelected(await orchestration.task(task.id))}catch(e){setError(errorText(e))}};
const open=(task:Task,action:ServerAction)=>{setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
const select=async(task:Task)=>{const epoch=++detailEpoch.current;setSelected(null);setError('');try {const detail=await orchestration.task(task.id);if(epoch===detailEpoch.current)setSelected(detail)}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}};
const open=(task:Task,action:ServerAction)=>{if(!capabilities.mutations||actionBlockReason(task,action))return;setBlocked(false);setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
const execute=async()=> {
if(!pending||busy||!confirmed)return;
if(!pending||busy||!confirmed||blocked||!capabilities.mutations)return;
setAttempted(true);setBusy(true);setCommandError('');
try { const [runId,artifactHash]=binding.split('|');
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,expiresAt:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
setPending(null);setSelected(null);setSuccess('Command accepted by backend; refreshed authoritative state.');await loadTasks();
} catch(e) {setCommandError(errorText(e)+' — Refresh before retrying a version conflict; network retries keep the same key.')} finally {setBusy(false)}
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
};
const refresh=()=>{setSelected(null);setPending(null);void loadTasks()};
const refresh=()=>{detailEpoch.current++;setSelected(null);setPending(null);void loadTasks()};
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
return <div className="space-y-5 font-vazir pb-12">
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">Orchestration command center</h1><p className="text-sm text-gray-600">Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding</p></div><Button onClick={refresh} disabled={busy||loading}>Refresh authoritative state</Button></header>
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
{loading&&<p role="status">Loading measured backend state…</p>}
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">Unknown / unavailable: {error}. No fallback data. <button onClick={refresh}>Reload tasks</button></p>}
{success&&<p role="status">{success}</p>}
@@ -59,24 +64,25 @@ 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}}/>
<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={!!a.disabledReason} title={a.disabledReason} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
{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>)}
<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>}
{section==='Chat'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>Typed backend chat bridge</h2><p>Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.</p><label>Session ID<input value={session} onChange={e=>{setSession(e.target.value);setMessages([])}} className="border p-2"/></label><div role="log">{messages.map(m=><p key={m.id}>{m.role}: {m.content}</p>)}</div><label>Message<textarea value={message} onChange={e=>{setMessage(e.target.value);setChatKey(crypto.randomUUID())}} className="border p-2 block w-full"/></label><Button disabled={busy||!session.trim()||!message.trim()} onClick={async()=>{setBusy(true);setError('');try{const reply=await orchestration.chat(session,message,chatKey);setMessages(prev=>[...prev,{id:chatKey,role:'user',content:message},reply]);setMessage('');setChatKey(crypto.randomUUID())}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Send advisory message</Button></section>}
{pending&&<div role="dialog" aria-modal="true" aria-label="Confirm immutable command" className="fixed inset-0 z-50 bg-black/50 overflow-y-auto p-8"><div className="bg-white rounded-2xl p-6 max-w-2xl mx-auto space-y-4"><h2>{pending.action.label}</h2><Json value={{taskId:pending.task.id,expectedVersion:pending.task.version,idempotencyKey:pending.key,scope:pending.task.metadata,budgetLimitCents:pending.task.budgetLimitCents,operationMode:pending.task.operationMode}}/>
{pending.action.gate&&<label className="block">Expires at<input aria-label="Expires at" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
{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?.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>}
{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||!confirmed||!reason.trim()|| (!!pending.action.gate&&!Number.isFinite(Date.parse(expires))) || (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>;
}
@@ -0,0 +1,19 @@
import {render,screen,fireEvent,within,waitFor,act} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
it('does not restore stale detail after authoritative refresh while detail request is pending',async()=>{
const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[]};
let resolve!:(v:unknown)=>void;
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}};if(url.endsWith('/tasks'))return {data:[t]};return await new Promise<unknown>(r=>{resolve=r}) as never});
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
expect(screen.queryByRole('region',{name:'Task detail'})).not.toBeInTheDocument();
});
it('keeps payload immutable when navigating after an ambiguous network failure',async()=>{
vi.resetAllMocks();const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[{id:'g1',label:'Approve safe work',gate:1,decision:'APPROVED'}]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));vi.mocked(api.post).mockRejectedValue(new Error('network'));
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'Approve safe work'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));fireEvent.click(d.getByRole('button',{name:'Confirm command'}));await d.findByRole('alert');
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));expect(d.getByLabelText('Reason')).toHaveValue('Reviewed');expect(d.getByLabelText('I reviewed the immutable scope and binding')).toBeChecked();
});
@@ -0,0 +1,47 @@
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:{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(/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(/PREPARE|advertised/);
expect(api.put).not.toHaveBeenCalled();
});
it('rejects Gate2 evidence from failed runs',async()=>{
const g2={...action,gate:2 as const};
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/successful/);
expect(api.post).not.toHaveBeenCalled();
});
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'Review Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));return d;}
it('locks stale 409 command until authoritative refresh instead of retrying stale payload',async()=>{
vi.mocked(api.post).mockRejectedValue({response:{status:409,data:{message:'Version conflict'}}});
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'Confirm command'}));
await waitFor(()=>expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled());
expect(await d.findByRole('alert')).toHaveTextContent(/stale/i);
fireEvent.click(d.getByRole('button',{name:'Confirm command'}));expect(api.post).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
});
it('does not expose authorized task mutations when capabilities are unavailable',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))throw new Error('offline');return {data:url.endsWith('/tasks')?[task]:task};});
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'Task detail'});
expect(screen.getByRole('button',{name:'Review Gate1'})).toBeDisabled();
});
it('prevents confirming an already expired approval',async()=>{
const d=await dialog();fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2020-01-01T12:00'}});
expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled();
});
@@ -18,7 +18,7 @@ describe('orchestration adapter', () => {
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
});
it('binds Gate2 to immutable registered run and sends version and retry-stable key', async () => {
const run={id:'r',commitSha:'abc',environment:'staging',status:'VERIFIED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
const input={idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)};
vi.mocked(api.post).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({data:{id:'decision'}});
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],input)).rejects.toThrow('network');
@@ -46,9 +46,84 @@ 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),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: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),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']}});
});
});
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),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,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),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}};
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();
});
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);
});
@@ -1,26 +1,82 @@
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>[] }
export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; runId?: string; artifactHash?: string }
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
if(action.disabledReason)return action.disabledReason;
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'Production actions are unavailable in this panel';
if(task.state==='EXPIRED')return 'Expired proposal: create a fresh proposal';
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'Unsupported server action';
return undefined;
}
export function commandFailure(error:unknown):{message:string;retryable:boolean} {
const status=(error as {response?:{status?:number}})?.response?.status;
if(status===409)return {message:'Stale version or idempotency conflict. Refresh authoritative state and review a fresh decision.',retryable:false};
if(status===410)return {message:'Proposal or approval expired. Refresh; expired proposals require a new proposal.',retryable:false};
if(status===401||status===403)return {message:'Backend denied this action. Refresh permissions before continuing.',retryable:false};
if(status&&status>=400&&status<500)return {message:'Backend rejected this action (HTTP '+status+'). Refresh and review the proposal.',retryable:false};
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;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(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> {
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);
// 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);
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);
@@ -38,15 +94,18 @@ 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);
if(run?.status!=='SUCCEEDED')throw new Error('Registered successful run binding required for Gate2 evidence');
if (!run?.commitSha || !run.environment || !run.artifacts.some(a => a.sha256 === input.artifactHash)) throw new Error('Registered immutable Gate2 binding required');
binding = {runId:run.id, artifactHash:input.artifactHash, commitSha:run.commitSha, environment:run.environment};
}
@@ -59,6 +118,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) }));
},
};
@@ -0,0 +1,21 @@
import {it,expect,vi} from 'vitest';
import api from './api';
import {runtime} from './runtime';
vi.mock('./api',()=>({default:{get:vi.fn()}}));
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:100,freshness:'stale',liveProcess:'unknown'};
it.each([{source:'live'},{capturedAt:'not-a-date'},{capturedAt:'2999-01-01T00:00:00Z'},{ageSeconds:-1},{ageSeconds:0.5},{freshness:'live'},{liveProcess:'running'}])('rejects invalid provenance %j',async invalid=>{
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,...invalid}}});
await expect(runtime.health()).rejects.toThrow('Invalid snapshot provenance');
});
it('retains fresh snapshots as inventory with unknown process state',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,freshness:'fresh'}}});
expect(await runtime.health()).toMatchObject({provenance:{freshness:'fresh',liveProcess:'unknown'}});
});
it('retains validated snapshot provenance and unknown live telemetry across inventory reads',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'1',commit:'x',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'1',overall:'unknown',gateway_running:false,active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:0,sessions:[],provenance}:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0},provenance}}));
expect(await runtime.health()).toMatchObject({provenance});
expect(await runtime.profiles()).toMatchObject([{provenance,liveGatewayState:'unknown'}]);
expect(await runtime.status('dev')).toMatchObject({provenance,liveGatewayState:'unknown',liveActiveAgents:null});
expect(await runtime.sessions('dev')).toMatchObject({provenance});
expect(await runtime.usage('dev')).toMatchObject({provenance});
});
@@ -0,0 +1,28 @@
import api from './api';
export interface RuntimeProvenance {source:'snapshot';capturedAt:string;ageSeconds:number;freshness:'fresh'|'stale';liveProcess:'unknown'}
interface Inventory {provenance?:RuntimeProvenance}
export interface RuntimeHealth extends Inventory {ok:boolean;version:string;commit:string;auth_required:true}
export interface RuntimeProfile extends Inventory {name:string;is_default:boolean;gateway_running:boolean;liveGatewayState?:'unknown'}
export interface RuntimeStatus extends Inventory {version:string;gateway_running:boolean;overall:string;active_agents:number;gateway_state:string|null;liveGatewayState?:'unknown';liveActiveAgents?:null}
export interface RuntimeSession {id:string;profile:string;source:string;is_active:boolean}
export interface RuntimeSessions extends Inventory {total:number;sessions:RuntimeSession[]}
export interface RuntimeUsage extends Inventory {period_days:number;totals:{total_input:number;total_output:number;total_sessions:number;total_estimated_cost:number}}
function object(value:unknown):Record<string,unknown>{if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Invalid runtime contract');return value as Record<string,unknown>}
function text(value:unknown):string{if(typeof value!=='string')throw new Error('Invalid runtime text');return value}
function bool(value:unknown):boolean{if(typeof value!=='boolean')throw new Error('Invalid runtime flag');return value}
function count(value:unknown):number{if(typeof value!=='number'||!Number.isFinite(value)||value<0)throw new Error('Invalid runtime count');return value}
function list(value:unknown):unknown[]{if(!Array.isArray(value)||value.length>1000)throw new Error('Invalid runtime list');return value}
async function read(path:string,params?:Record<string,string|number>):Promise<unknown>{const {data}=await api.get('/admin/orchestration/runtime/'+path,...(params?[{params}]:[]));const row=data&&typeof data==='object'&&!Array.isArray(data)?data:null;if(row&&'success' in row){if(row.success!==true)throw new Error('Runtime unavailable');return row.data}return data}
function provenance(r:Record<string,unknown>):Inventory {
if(r.provenance===undefined)return {};
const p=object(r.provenance);
if(p.source!=='snapshot'||p.liveProcess!=='unknown'||typeof p.capturedAt!=='string'||!p.capturedAt.endsWith('Z')||!Number.isFinite(Date.parse(p.capturedAt))||Date.parse(p.capturedAt)>Date.now()||typeof p.ageSeconds!=='number'||!Number.isInteger(p.ageSeconds)||p.ageSeconds<0||!['fresh','stale'].includes(String(p.freshness)))throw new Error('Invalid snapshot provenance');
return {provenance:{source:'snapshot',capturedAt:p.capturedAt,ageSeconds:p.ageSeconds,freshness:p.freshness as 'fresh'|'stale',liveProcess:'unknown'}};
}
export const runtime={
async health():Promise<RuntimeHealth>{const r=object(await read('health'));if(r.auth_required!==true)throw new Error('Authenticated runtime required');return {...provenance(r),ok:bool(r.ok),version:text(r.version),commit:text(r.commit),auth_required:true}},
async profiles():Promise<RuntimeProfile[]>{return list(await read('profiles')).map(value=>{const r=object(value);return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const}:{}),name:text(r.name),is_default:bool(r.is_default),gateway_running:bool(r.gateway_running)}})},
async status(profile:string):Promise<RuntimeStatus>{const r=object(await read('status',{profile}));return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const,liveActiveAgents:null}:{}),version:text(r.version),gateway_running:bool(r.gateway_running),overall:text(r.overall),active_agents:count(r.active_agents),gateway_state:r.gateway_state===null?null:text(r.gateway_state)}},
async sessions(profile:string,offset=0):Promise<RuntimeSessions>{const r=object(await read('sessions',{profile,limit:20,offset}));return {...provenance(r),total:count(r.total),sessions:list(r.sessions).map(value=>{const s=object(value);if(s.profile!==profile)throw new Error('Runtime profile mismatch');return {id:text(s.id),profile:text(s.profile),source:text(s.source),is_active:bool(s.is_active)}})}},
async usage(profile:string):Promise<RuntimeUsage>{const r=object(await read('usage',{profile,days:30}));const t=object(r.totals);return {...provenance(r),period_days:count(r.period_days),totals:{total_input:count(t.total_input),total_output:count(t.total_output),total_sessions:count(t.total_sessions),total_estimated_cost:count(t.total_estimated_cost)}}},
};