Files
canina/frontend/admin-panel/src/services/orchestration.test.ts
T

103 lines
8.3 KiB
TypeScript

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(/advertised/);
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/binding/);
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:'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');
await orchestration.command({...task,runs:[run]},task.availableActions[0],input);
expect(api.post).toHaveBeenLastCalledWith('/admin/orchestration/tasks/t%2F1/gates/2/decide',{expectedVersion:7,idempotencyKey:'same-key',decision:'APPROVED',expiresAt:input.expiresAt,notes:undefined,runId:'r',artifactHash:'a'.repeat(64),commitSha:'abc',environment:'staging'});
});
it('refuses expired approvals and unknown artifacts', async () => {
await expect(orchestration.command(task,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/expiry/);
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(/binding/);
});
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(/Invalid/);
});
it('requires kill reason and uses only typed message bridge', async () => {
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/reason/);
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/message/);
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)}})).rejects.toThrow(/budget/);
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40)}});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40)}});
});
});
describe('actual PREPARE backend contract',()=>{
beforeEach(()=>vi.resetAllMocks());
it('normalizes strings by fixed mapping, drops unknown and tampered objects, never infers from state',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE','RELEASE_AUTHORIZE',{id:'SUBMIT_GATE1',label:'bad',toState:'RELEASING'},null]}});
const detail=await orchestration.task('t/1');
expect(detail.availableActions.map(a=>a.id)).toEqual(['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE']);
vi.mocked(api.put).mockResolvedValue({data:{}});
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'submit'});
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1/transition',{toState:'GATE1_PENDING',expectedVersion:7,idempotencyKey:'submit',reason:undefined});
vi.mocked(api.get).mockResolvedValue({data:[{...task,state:'DRAFT',availableActions:[]}]});
expect((await orchestration.tasks())[0].availableActions).toEqual([]);
});
it('rejects arbitrary object transitions and conflicting known mappings',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:[{id:'evil',label:'go',toState:'RUNNING'},{id:'SUBMIT_GATE1',label:'go',toState:'READY'}]}});
expect((await orchestration.task('t/1')).availableActions).toEqual([]);
});
it.each([0,19,10001,20.5])('rejects invalid budget %s',async budget=>{
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40)}})).rejects.toThrow(/budget/i);
expect(api.post).not.toHaveBeenCalled();
});
it.each(['abc','A'.repeat(40),'a'.repeat(64),''])('rejects invalid commit %s',async commitSha=>{
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha}})).rejects.toThrow(/commit/i);
});
it.each([20,10000])('posts exact DTO at boundary %s',async budget=>{
vi.mocked(api.post).mockResolvedValue({data:{}});
const dto={key:'k',title:'t',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40)}};
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
});
});
it.each([
['APPROVE_GATE1','post','/gates/1/decide',{decision:'APPROVED'}],
['REJECT_GATE1','post','/gates/1/decide',{decision:'REJECTED'}],
['QUEUE_PREPARE','put','/transition',{toState:'READY'}],
])('routes actual advertised %s regardless of state',async(id,method,path,payload)=>{
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:[id]}});
vi.mocked(api.post).mockResolvedValue({data:{}});vi.mocked(api.put).mockResolvedValue({data:{}});
const detail=await orchestration.task('t/1');
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:new Date(Date.now()+3600000).toISOString()});
expect(method==='post'?api.post:api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1'+path,expect.objectContaining({...payload,expectedVersion:7,idempotencyKey:'k'}));
});
it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:['APPROVE_GATE1']}});
const detail=await orchestration.task('t/1');
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/24 hours/);
expect(api.post).not.toHaveBeenCalled();
});