feat(admin): remove governance, orchestration, approvals, tasks, and audit logs modules
Deploy Canina / deploy (push) Successful in 4m14s
Deploy Canina / deploy (push) Successful in 4m14s
This commit is contained in:
1 parent
99f0c0d626
commit
effe30ee58
128 files changed
+5
-14449
No files matched your search
@@ -1,126 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from './api';
|
||||
import { orchestration } from './orchestration';
|
||||
import type { Task } from './orchestration';
|
||||
vi.mock('./api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
|
||||
const task = {id:'t/1',version:7,state:'GATE2_PENDING',availableActions:[{id:'approve',label:'Approve',gate:2,decision:'APPROVED'}]} as Task;
|
||||
describe('orchestration adapter', () => {
|
||||
beforeEach(() => vi.resetAllMocks());
|
||||
it('loads bare task lists through existing authenticated client and fails closed without actions', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({data:[{id:'t1',title:'Bounded work',version:2,state:'READY'}]});
|
||||
const tasks = await orchestration.tasks();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks');
|
||||
expect(tasks[0].availableActions).toEqual([]);
|
||||
});
|
||||
it('rejects unadvertised transitions and incomplete Gate2 binding without a request', async () => {
|
||||
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/اعلام نشده/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects even fully registered Gate2 evidence because release decisions are disabled', async () => {
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],{idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('refuses expired approvals and unknown artifacts', async () => {
|
||||
await expect(orchestration.command({...task,availableActions:[{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'}]},{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'},{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/انقضا/);
|
||||
const bad={...task,runs:[{id:'r',commitSha:'abc',environment:'staging',status:'DONE',artifacts:[]}]};
|
||||
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
});
|
||||
it('loads immutable detail and rejects malformed optional resources', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{success:true,data:{...task,runs:[]}}}).mockResolvedValueOnce({data:{nonsense:true}});
|
||||
expect((await orchestration.task('t/1')).version).toBe(7);
|
||||
await expect(orchestration.resource('agents')).rejects.toThrow(/نامعتبر/);
|
||||
});
|
||||
it('requires kill reason and uses only typed message bridge', async () => {
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/دلیل/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/پیام/);
|
||||
vi.mocked(api.put).mockResolvedValue({data:{active:true}});
|
||||
await orchestration.kill('STOP_AGENTS','Incident review');
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'STOP_AGENTS',reason:'Incident review'});
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'Review complete'}});
|
||||
expect(await orchestration.chat('session','Review task','key')).toEqual({id:'reply',role:'assistant',content:'Review complete'});
|
||||
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),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),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(/۲۴ ساعت/);
|
||||
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,137 +0,0 @@
|
||||
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> = {
|
||||
HOLD_GATE1:{id:'HOLD_GATE1',label:'تعویق تصمیم Gate1',toState:'GATE1_HELD'},
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'ارسال برای Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'تأیید کار محدود در Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'رد کار در Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'صفبندی آمادهسازی',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; displayState?: string; editorialRecovery?: {runId: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; notBefore?: 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;notBefore?:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
|
||||
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
|
||||
if(action.gate===2)return 'Gate2 و انتشار در این پنل غیرفعال هستند';
|
||||
if(action.disabledReason)return 'اقدام توسط سرور غیرفعال شده است: '+action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'عملیات Production در این پنل در دسترس نیست';
|
||||
if(task.state==='EXPIRED')return 'پیشنهاد منقضی شده است؛ پیشنهاد جدید ایجاد کنید';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'اقدام سرور پشتیبانی نمیشود';
|
||||
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:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',retryable:false};
|
||||
if(status===410)return {message:'پیشنهاد یا تأیید منقضی شده است. وضعیت را بازخوانی کنید؛ پیشنهاد منقضی به پیشنهاد جدید نیاز دارد.',retryable:false};
|
||||
if(status===401||status===403)return {message:'سرور این اقدام را رد کرد. پیش از ادامه مجوزها را بازخوانی کنید.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'سرور این اقدام را رد کرد (HTTP '+status+'). وضعیت را بازخوانی و پیشنهاد را بررسی کنید.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'درخواست سرور در دسترس نیست')+' — نتیجه نامشخص است. فقط همان داده و کلید را تکرار کنید یا وضعیت را برای تطبیق بازخوانی کنید.',retryable:true};
|
||||
}
|
||||
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
|
||||
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:'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 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است';
|
||||
}
|
||||
export interface EditorialFailureInput {runId:string;expectedVersion:number;idempotencyKey:string;reason:string}
|
||||
// Eligibility is a safe server hint, never inferred from elapsed browser time.
|
||||
export function editorialRecoveryRun(task:Task):Run|undefined {
|
||||
if(task.state!=='RUNNING'||task.operationMode!=='PREPARE'||task.department!=='CONTENT'||task.budgetLimitCents!==20||!/^editorial-v1:[a-f0-9]{64}$/.test(task.key))return;
|
||||
const matches=task.runs?.filter(r=>r.id===task.editorialRecovery?.runId&&r.status==='RUNNING'&&r.environment==='staging'&&r.commitSha===task.metadata?.commitSha&&Array.isArray(r.artifacts)&&!r.artifacts.length);
|
||||
return matches?.length===1?matches[0]:undefined;
|
||||
}
|
||||
export const orchestration = {
|
||||
async editorialFailure(task:Task,input:EditorialFailureInput):Promise<unknown> {
|
||||
if(!editorialRecoveryRun(task)||input.runId!==task.editorialRecovery?.runId||input.expectedVersion!==task.version||!Number.isInteger(input.expectedVersion)||!input.idempotencyKey||typeof input.reason!=='string'||!input.reason.trim()||input.reason.length>500)throw new Error('اتصال بازیابی معتبر نیست؛ وضعیت را بازخوانی کنید');
|
||||
return (await api.post('/admin/orchestration/tasks/'+encodeURIComponent(task.id)+'/editorial-failure',{runId:input.runId,expectedVersion:input.expectedVersion,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
|
||||
},
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
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('پاسخ جزئیات وظیفه نامعتبر است');
|
||||
return {...data,availableActions:normalizeActions(data.availableActions)};
|
||||
},
|
||||
async resource(name:Resource):Promise<ResourceSnapshot> {
|
||||
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
|
||||
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('پاسخ نمای ثبتشده نامعتبر است');
|
||||
return data;
|
||||
},
|
||||
async kill(level:KillLevel,reason:string):Promise<unknown> {
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است');
|
||||
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
|
||||
},
|
||||
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('نشست و پیام الزامی است');
|
||||
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('پاسخ گفتوگو نامعتبر است');
|
||||
return data;
|
||||
},
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('اقدام اعلام نشده یا غیرفعال است');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است');
|
||||
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
|
||||
if (action.gate && action.decision) {
|
||||
if (input.notBefore && (action.decision!=='APPROVED' || !(Date.parse(input.notBefore)>Date.now()) || Date.parse(input.notBefore)>Date.now()+30*86400000)) throw new Error('زمان اجرا باید در آینده و حداکثر ۳۰ روز باشد');
|
||||
if (input.expiresAt && !(Date.parse(input.expiresAt)>Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
|
||||
if(input.expiresAt && Date.parse(input.expiresAt)>(input.notBefore?Date.parse(input.notBefore):Date.now())+86400000) throw new Error('انقضای Gate1 باید در ۲۴ ساعت پس از زمان اجرا باشد');
|
||||
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};
|
||||
}
|
||||
return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,...(input.expiresAt?{expiresAt:input.expiresAt}:{}),...(input.notBefore?{notBefore:input.notBefore}:{}),notes:input.reason,...binding})).data;
|
||||
}
|
||||
if (!action.toState) throw new Error('اقدام سرور پشتیبانی نمیشود');
|
||||
return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
|
||||
},
|
||||
async tasks(): Promise<Task[]> {
|
||||
const { data } = await api.get('/admin/orchestration/tasks');
|
||||
const rows = Array.isArray(data) ? data : data.data;
|
||||
if (!Array.isArray(rows)) throw new Error('پاسخ فهرست وظیفهها نامعتبر است');
|
||||
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
||||
},
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
import {render,screen,fireEvent} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from './api';
|
||||
import {routerUsage} from './routerUsage';
|
||||
import RouterUsagePanel from '../components/RouterUsagePanel';
|
||||
vi.mock('./api',()=>({default:{get:vi.fn()}}));
|
||||
const metrics={requests:20,inputTokens:100,outputTokens:50,cacheReadTokens:0,cacheWriteTokens:null,reasoningTokens:null,errors:null};
|
||||
const snapshot={source:'9router',period:'7d',status:'available',reason:null,attribution:{scope:'9router_total',hermes:null,additive:false},freshness:{retrievedAt:'2026-10-22T12:00:00Z',sourceUpdatedAt:null,stale:null},data:{totals:metrics,providers:[{provider:'provider-a',...metrics}],models:[{model:'model-b',provider:'provider-a',...metrics}],accounts:[{accountId:'opaque-1',provider:'provider-a',model:'model-b',...metrics,quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}}]}};
|
||||
it('renders concrete backend contract, unknown quota and source freshness; period selects backend filter',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:snapshot});render(<RouterUsagePanel/>);
|
||||
expect(await screen.findByText('opaque-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('مجموع درگاه (شامل Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('سهم مصرف Hermes: نامشخص و گزارشنشده؛ با مجموع درگاه جمع نکنید.')).toBeInTheDocument();
|
||||
expect(screen.getByText('9router')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('نامشخص — گزارش نشده').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/router-usage',{params:{period:'7d'}});
|
||||
fireEvent.change(screen.getByLabelText('بازه مصرف'),{target:{value:'today'}});
|
||||
await screen.findByText('opaque-1');
|
||||
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
|
||||
});
|
||||
it('rejects missing provenance instead of inventing freshness',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{accounts:[]}});
|
||||
await expect(routerUsage.snapshot()).rejects.toThrow(/Invalid/);
|
||||
});
|
||||
it('shows unavailable configuration honestly and discards arbitrary credential properties',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,status:'unavailable',reason:'not_configured',data:null}});
|
||||
await expect(routerUsage.snapshot()).rejects.toThrow('not_configured');
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,token:'secret',data:{...snapshot.data,credentials:'secret'}}});
|
||||
expect(JSON.stringify(await routerUsage.snapshot())).not.toContain('secret');
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import api from './api';
|
||||
export const usagePeriods=['today','24h','7d','30d','60d','all'] as const;
|
||||
export type UsagePeriod=typeof usagePeriods[number];
|
||||
export interface UsageCounters {requests:number|null;inputTokens:number|null;outputTokens:number|null;cacheReadTokens:number|null;cacheWriteTokens:number|null;reasoningTokens:number|null;errors:number|null}
|
||||
export interface UsageRow extends UsageCounters {provider:string|null;model?:string|null;accountId?:string|null;quota?:{status:string;remaining:number|null;resetAt:string|null;reason:string|null}}
|
||||
export interface RouterUsageSnapshot {source:string;period:UsagePeriod;freshness:{retrievedAt:string|null;sourceUpdatedAt:string|null;stale:boolean|null};attribution:{scope:'9router_total';hermes:null;additive:false};data:{totals:UsageCounters;providers:UsageRow[];models:UsageRow[];accounts:UsageRow[]}}
|
||||
const count=(v:unknown):number|null=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=0?v:null;
|
||||
const text=(v:unknown):string|null=>typeof v==='string'?v:null;
|
||||
function counters(raw:UsageCounters):UsageCounters {
|
||||
return {requests:count(raw?.requests),inputTokens:count(raw?.inputTokens),outputTokens:count(raw?.outputTokens),cacheReadTokens:count(raw?.cacheReadTokens),cacheWriteTokens:count(raw?.cacheWriteTokens),reasoningTokens:count(raw?.reasoningTokens),errors:count(raw?.errors)};
|
||||
}
|
||||
function rows(list:UsageRow[]):UsageRow[]{return list.map(a=>({provider:text(a.provider),model:text(a.model),accountId:text(a.accountId),...counters(a),...(a.quota?{quota:{status:a.quota.status,remaining:count(a.quota.remaining),resetAt:text(a.quota.resetAt),reason:text(a.quota.reason)}}:{})}))}
|
||||
export const routerUsage={async snapshot(period:UsagePeriod='7d'):Promise<RouterUsageSnapshot>{
|
||||
const {data:raw}=await api.get('/admin/router-usage',{params:{period}});
|
||||
const data=raw?.success===true?raw.data:raw;
|
||||
if(data?.status==='unavailable')throw new Error('Usage unavailable: '+(data.reason??'unknown'));
|
||||
if(data?.status!=='available'||data.source!=='9router'||!usagePeriods.includes(data.period)||!data.freshness||!data.data||!Array.isArray(data.data.providers)||!Array.isArray(data.data.models)||!Array.isArray(data.data.accounts))throw new Error('Invalid usage snapshot contract');
|
||||
// Explicit allowlist; never forward raw gateway configuration or arbitrary response properties.
|
||||
return {source:data.source,period:data.period,freshness:{retrievedAt:text(data.freshness.retrievedAt),sourceUpdatedAt:text(data.freshness.sourceUpdatedAt),stale:typeof data.freshness.stale==='boolean'?data.freshness.stale:null},attribution:{scope:'9router_total',hermes:null,additive:false},data:{totals:counters(data.data.totals),providers:rows(data.data.providers),models:rows(data.data.models),accounts:rows(data.data.accounts)}};
|
||||
}};
|
||||
@@ -1,21 +0,0 @@
|
||||
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});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
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)}}},
|
||||
};
|
||||
Reference in new issue
Block a user