fix(orchestration): atomically queue approvals with optional not-before schedule
Deploy Canina / deploy (push) Successful in 4m56s

This commit is contained in:
devops committed 2026-10-24 06:16:20 +00:00
1 parent ab2f330eb8
commit 50d0df822c
15 files changed
+216 -65

No files matched your search

@@ -30,20 +30,35 @@ describe('command center', () => {
expect(await screen.findByText('محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.')).toBeInTheDocument();
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
});
it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => {
it('approves immediately without date or reason after explicit confirmation',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{...task,state:'READY'}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toHaveValue('');
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await waitFor(()=>expect(api.post).toHaveBeenCalledTimes(1));
const payload=vi.mocked(api.post).mock.calls[0][1] as Record<string,unknown>;
expect(payload.decision).toBe('APPROVED');
expect(payload.expiresAt).toBeUndefined();expect(payload.notBefore).toBeUndefined();
});
it('requires explicit confirmation; retains idempotency across failed retry', async () => {
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});
fireEvent.change(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده'),{target:{value:new Date(Date.now()+3600000).toISOString().slice(0,16)}});
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'محدوده checked'}});
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
expect(within(dialog).getByLabelText('دلیل')).toBeDisabled();
expect(within(dialog).getByLabelText('زمان انقضا')).toBeDisabled();
expect(within(dialog).getByLabelText('زمان اجرای برنامه‌ریزی‌شده')).toBeDisabled();
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await within(dialog).findByRole('alert');
expect(api.post).toHaveBeenCalledTimes(2);
@@ -66,7 +66,7 @@ export default function OrchestrationCommandCenter() {
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});
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,notBefore:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
};
@@ -105,11 +105,12 @@ export default function OrchestrationCommandCenter() {
{section==='گفت‌وگو'&&!capabilities.chat&&<p>گفت‌وگو در دسترس نیست؛ پل مورد اعتماد اجرا فعال نیست.</p>}
{section==='گفت‌وگو'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>گفت‌وگوی متنی از مسیر امن سرور</h2><p>فقط متن مشورتی؛ بدون ترمینال، PTY، توکن اجرا یا اتصال مستقیم به Hermes. تصمیم‌ها از کنترل تأیید مستقل عبور می‌کنند.</p><label>شناسه نشست<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>پیام<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)}}}>ارسال پیام مشورتی</Button></section>}
{pending&&<div role="dialog" aria-modal="true" aria-label="تأیید فرمان تغییرناپذیر" 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>{actionLabel(pending.action)}</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">زمان انقضا<input aria-label="زمان انقضا" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
{pending.action.gate===1&&pending.action.decision==='APPROVED'&&<label className="block">زمان اجرای برنامه‌ریزی‌شده (اختیاری؛ پیش‌فرض فوری)<input aria-label="زمان اجرای برنامه‌ریزی‌شده" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>اتصال اجرای ثبت‌شده به خروجی<select aria-label="اتصال اجرای ثبت‌شده به خروجی" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">انتخاب شواهد تغییرناپذیر</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">دلیل<input aria-label="دلیل" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
<p>تأیید، وظیفه را در اولویت صف آماده قرار می‌دهد؛ زمان اختیاری فقط زودترین زمان شروع است و اجرای دقیق در آن لحظه تضمین نمی‌شود. حداکثر زمان‌بندی ۳۰ روز است؛ اعتبار تأیید را سرور مدیریت می‌کند.</p>
<label className="block">دلیل (برای تأیید اختیاری)<input aria-label="دلیل" 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}/>محدوده و اتصال تغییرناپذیر را بررسی کردم</label>
{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()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||(pending.action.toState==='GATE1_HELD'&&!reason.trim())|| (!!expires&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+30*86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
</div></div>}
</div>;
}
@@ -35,9 +35,9 @@ export function normalizeActions(value:unknown):ServerAction[] {
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 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;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?: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;
@@ -102,8 +102,9 @@ export const orchestration = {
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.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('انقضای Gate1 باید در ۲۴ ساعت آینده باشد');
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);
@@ -111,7 +112,7 @@ export const orchestration = {
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,expiresAt:input.expiresAt,notes:input.reason,...binding})).data;
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;