Complete safe admin workflow and authenticated runtime read UI

This commit is contained in:
devops committed 2026-10-23 12:52:09 +00:00
1 parent 5507fbcb29
commit c058295f35
11 files changed
+228 -19

No files matched your search

@@ -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');
@@ -4,6 +4,23 @@ export interface Artifact { id: string; sha256: string; kind?: string; uri?: str
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 const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const;
@@ -13,6 +30,7 @@ function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof d
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'OBSERVE'|'PREPARE'|'MUTATE_PRODUCTION';budgetLimitCents:number;metadata:{scope:string;acceptanceCriteria:string[]}}
export const orchestration = {
async create(input:CreateTaskInput):Promise<unknown> {
if(input.operationMode==='MUTATE_PRODUCTION')throw new Error('Production proposals are unavailable in this panel');
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<0)throw new Error('Nonnegative integer budget required');
if(!input.key.trim()||!input.title.trim()||!input.department.trim()||!input.metadata.scope.trim()||!input.metadata.acceptanceCriteria.length)throw new Error('Bounded scope and acceptance criteria required');
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:input.operationMode,budgetLimitCents:input.budgetLimitCents,metadata:input.metadata})).data;
@@ -40,6 +58,7 @@ export const orchestration = {
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
const action = 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) {
@@ -47,6 +66,7 @@ export const orchestration = {
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};
}
@@ -0,0 +1,20 @@
import api from './api';
export interface RuntimeHealth {ok:boolean;version:string;commit:string;auth_required:true}
export interface RuntimeProfile {name:string;is_default:boolean;gateway_running:boolean}
export interface RuntimeStatus {version:string;gateway_running:boolean;overall:string;active_agents:number;gateway_state:string|null}
export interface RuntimeSession {id:string;profile:string;source:string;is_active:boolean}
export interface RuntimeSessions {total:number;sessions:RuntimeSession[]}
export interface RuntimeUsage {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}
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 {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 {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 {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 {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 {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)}}},
};