diff --git a/frontend/admin-panel/ORCHESTRATION_API_CONTRACT.md b/frontend/admin-panel/ORCHESTRATION_API_CONTRACT.md new file mode 100644 index 00000000..87420bdd --- /dev/null +++ b/frontend/admin-panel/ORCHESTRATION_API_CONTRACT.md @@ -0,0 +1,34 @@ +# Admin orchestration v4 adapter contract + +All client traffic uses existing authenticated Axios client (`src/services/api.ts`). Relative `/admin/...` paths are served below `/api`. No runtime secrets, Hermes tokens, PTY, terminal websocket or direct gateway credentials may enter these DTOs. Backend must project/redact task metadata, artifacts, audit payloads and chat text before returning them. Browser does not enforce authorization. + +## Implemented core API observed in sibling core worktree +- GET `/admin/orchestration/tasks`: bare Task[] or `{success:true,data:Task[]}`. +- GET `/admin/orchestration/tasks/:id`: immutable task detail with runs/artifacts, decisions, events and budgetLedger. +- POST `/admin/orchestration/tasks`: key,title,department,operationMode,budgetLimitCents,metadata {scope,acceptanceCriteria[]} (no execution authorization). +- PUT `/admin/orchestration/tasks/:id/transition`: toState,expectedVersion,idempotencyKey,reason. +- POST `/admin/orchestration/tasks/:id/gates/{1|2}/decide`: decision,expectedVersion,idempotencyKey,expiresAt,notes. Gate2 APPROVED additionally binds runId,artifactHash,commitSha,environment to registered immutable run and artifact. +- PUT `/admin/orchestration/kill-switch`: level,reason. Levels FREEZE_NEW_WORK,STOP_AGENTS,DISABLE_MUTATIONS,EMERGENCY_HALT. No invented reset/resume route. + +Task fields and optional service DTOs are declared in `src/services/orchestration.ts`. + +## Required integration additions (fail closed until backend provides) +Task `availableActions: {id,label,toState?,gate?:1|2,decision?:APPROVED|REJECTED,disabledReason?}[]` must be advertised by backend after permission, state, gate, policy and kill-switch evaluation. Browser never derives transitions from state. Missing actions means read-only, not an invitation to synthesize controls. Backend core inspected initially did not advertise these actions. This is an integration blocker for execution. + +Optional read-only resources GET `/admin/orchestration/{agents|model-policy|schedules|releases}` return `{items:[{id,title?,status?,department?,readiness?,model?,budgetLimitCents?,spentCents?,cron?,timezone?,environment?,commitSha?,reason?}],measuredAt:ISO8601}`. May be wrapped in `{success:true,data:...}`. 404/403/network/malformed replies render unavailable, not mock cards. These endpoint contracts are proposals requiring backend reconciliation, not claims that endpoints exist. Schedule editing, model policy editing, budget adjustments, agent start/stop and release execution require separately advertised typed backend commands; intentionally not implemented against guessed routes. Existing task run/evidence, decisions, ledger and ordered events remain inspectable independent of optional feeds. + +POST `/admin/orchestration/chat/messages`: {sessionId,message,idempotencyKey} -> {id,role:'assistant',content}. Advisory-only bridge; no browser runtime connection or auto-execution of text. Backend must bind sessions to authenticated user and redact sensitive output. + +## Retry and concurrency +Command dialog snapshots immutable task version and allocates one key. On first attempt inputs lock; failed retries use identical payload/key. Cancel and refresh to reconcile 409 conflict; refresh invalidates selection and dialog. Successful command refetches authoritative tasks; no optimistic status. Backend must enforce idempotency transactionally, compare payload bindings and versions; frontend is not a safety boundary. Task creation is keyed by unique business key; reconcile ambiguous failures by refreshing before retry. + +## 9router usage concrete contract (aligned with backend worker b0f4636) +GET `/admin/router-usage?period=today|24h|7d|30d|60d|all` default7d; authenticated admin. Response: source,period,status available|unavailable,reason,data null|{totals,providers[],models[],accounts[]},freshness {retrievedAt,sourceUpdatedAt,stale},attribution {scope:9router_total,hermes:null,additive:false}. +Metrics: requests,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,errors. Last three unsupported=null. Account quota {status:unknown,remaining:null,resetAt:null,reason:upstream_quota_get_mutates_credentials}. No upstream quota GET because it refreshes credentials. No estimates or raw credentials. Nullable provider/model/account IDs are sanitized by backend. +Breakdowns overlap and are never summed. Hermes attribution unknown, not zero and not added. Retrieved timestamp is not source freshness. SourceUpdatedAt and stale remain explicitly unknown. Frontend explicitly projects DTO fields and rejects malformed/unavailable replies. No direct gateway connection. + +## Monitoring +Existing payment stats/health and SMS credit are read independently. Only returned values displayed. Request failures remain unknown with source and client observation timestamp. Database/Redis/Post/OCR/uptime/environment/agent runtime remain unknown without measured endpoints. No fabricated 14-day uptime, Production label, derived DB ping, SMS count or healthy post service. + +## Verification caveats +All verification uses disposable node:22-bookworm Docker runners against this worktree. Plain `npm run typecheck` uses solution-style config and does not verify app files. `tsc --noEmit -p tsconfig.app.json` exposes pre-existing errors in legacy Approvals/Audit/HQ/Tasks imports and Orders/Symptoms types; report these separately, not as a green full application typecheck. Build warning: unresolved existing Shabnam font remains runtime-resolved. diff --git a/frontend/admin-panel/ORCHESTRATION_VERIFICATION.md b/frontend/admin-panel/ORCHESTRATION_VERIFICATION.md new file mode 100644 index 00000000..234bf1e5 --- /dev/null +++ b/frontend/admin-panel/ORCHESTRATION_VERIFICATION.md @@ -0,0 +1,21 @@ +# Verification and remaining integration work + +Remote branch: feature/orchestration-v4-admin. All source changes limited to frontend/admin-panel. No push, deployment, production container command, or live operational mutation performed. + +Disposable node:22-bookworm runners, --userns=host: +- Full `vitest run --maxWorkers=2`: 57 files, 326 tests passed, zero failed. +- Scoped ESLint for all new services/components/tests plus Monitoring: exit 0. +- `npm run typecheck` (solution config): exit 0, not an app check. +- `tsc --noEmit -p tsconfig.app.json`: exit 2, 33 pre-existing diagnostics (legacy unused imports/locals, Orders requiresRx type, Symptoms ConfirmModal props). No diagnostics in new files or Monitoring. Baseline captured before implementation had same legacy errors. +- `npm run build`: exit 0; pre-existing unresolved Shabnam font warning. + +TDD red/green cycles exercised adapter missing exports, unadvertised actions, incomplete/expired Gate2 bindings, exact version/idempotency payloads and retry lock, task creation bounds, UI explicit confirmation, monitoring fake values and failures, navigation, router usage contract migration/unavailable state. Full UI tests use mocked HTTP boundary with realistic backend DTOs; they are not a live backend integration test. Additional UI tests cover immutable artifact binding, kill authorization failure, readiness BLOCKED response, chat escaping and typed bridge. Router usage aligned to concrete backend b0f4636 contract. + +Remaining gaps / do not claim full end-to-end operation: +- Backend must advertise availableActions. Initial core worktree lacks them; client intentionally fails closed read-only without actions. +- Agents/model-policy/schedules/releases snapshots and typed chat bridge are proposed contracts, not initially present core routes. UI displays explicit unavailable errors, never synthetic content. Mutating model policy/schedules/agent operations not implemented against guessed endpoints. +- Kill switch current level cannot be read until backend exposes a status contract. No invented resume command. +- No live auth credentials used; endpoint auth/RBAC and cross-worker DTO integration still need isolated stack smoke tests. +- Legacy Approvals/Tasks/HQ/Audit pages remain separately available and unchanged. New v4 control center is at /orchestration inside existing protected layout; these legacy pages are not v4 authority and should be retired/migrated during integration. +- Full app typecheck is not green due existing errors listed above. +- Browser chat is advisory; no Hermes terminal or raw runtime connection. diff --git a/frontend/admin-panel/src/components/CreateOrchestrationTask.test.tsx b/frontend/admin-panel/src/components/CreateOrchestrationTask.test.tsx new file mode 100644 index 00000000..573578dc --- /dev/null +++ b/frontend/admin-panel/src/components/CreateOrchestrationTask.test.tsx @@ -0,0 +1,14 @@ +import {fireEvent,render,screen} from '@testing-library/react'; +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()=>{ + vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(); + 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}}); + 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(done).toHaveBeenCalledOnce(); +}); diff --git a/frontend/admin-panel/src/components/CreateOrchestrationTask.tsx b/frontend/admin-panel/src/components/CreateOrchestrationTask.tsx new file mode 100644 index 00000000..0201f476 --- /dev/null +++ b/frontend/admin-panel/src/components/CreateOrchestrationTask.tsx @@ -0,0 +1,14 @@ +import {useState} from 'react'; +import Button from './ui/Button'; +import {orchestration} 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('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
Create bounded work
{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])=>