feat(orchestration): expose owner Gate1 queue and audited hold decisions

This commit is contained in:
devops committed 2026-10-24 02:28:39 +00:00
1 parent 65a6fe1f0c
commit 1b8da58f73
10 files changed
+141 -7

No files matched your search

@@ -3,6 +3,7 @@ import { BadRequestException } from '@nestjs/common';
export enum WorkflowState {
DRAFT = 'DRAFT',
GATE1_PENDING = 'GATE1_PENDING',
GATE1_HELD = 'GATE1_HELD',
GATE1_APPROVED = 'GATE1_APPROVED',
READY = 'READY',
CLAIMED = 'CLAIMED',
@@ -43,7 +44,9 @@ export enum KillSwitchLevel {
const transitions: Record<WorkflowState, WorkflowState[]> = {
DRAFT: [WorkflowState.GATE1_PENDING, WorkflowState.CANCELLED],
GATE1_HELD: [WorkflowState.GATE1_APPROVED, WorkflowState.REJECTED],
GATE1_PENDING: [
WorkflowState.GATE1_HELD,
WorkflowState.GATE1_APPROVED,
WorkflowState.REJECTED,
WorkflowState.EXPIRED,
@@ -0,0 +1,48 @@
import { PrepareWorkflowService } from './prepare-workflow.service';
describe('owner Gate1 hold operation', () => {
const reviewer={id:'reviewer',role:'SUPER_ADMIN'};
let task:any, tx:any, service:PrepareWorkflowService;
beforeEach(()=>{
task={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'proposer'}};
tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>task),update:jest.fn(async({data}:any)=>(task={...task,state:data.state,version:task.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{create:jest.fn()}};
service=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)}, {workerIds:[],stageCiIds:[]});
});
const hold={toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold-t',reason:'Need revised budget'};
it('advertises hold only to independent owner reviewer',()=>{
expect(service.project(task,reviewer).availableActions).toContain('HOLD_GATE1');
expect(service.project(task,{id:'proposer',role:'SUPER_ADMIN'}).availableActions).not.toContain('HOLD_GATE1');
});
it('persists hold with actor, immutable reason and version without approval or queueing',async()=>{
await expect(service.transition('t',hold,reviewer)).resolves.toMatchObject({state:'GATE1_HELD',version:3});
expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:'reviewer',fromState:'GATE1_PENDING',toState:'GATE1_HELD',eventType:'PREPARE_GATE1_HELD',idempotencyKey:'hold-t',payload:expect.objectContaining({fingerprint:expect.stringContaining('Need revised budget')})})});
expect(tx.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
expect(service.project(task,reviewer).availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1']);
});
it.each([{id:'proposer',role:'SUPER_ADMIN'},{id:'other',role:'Admin'}])('denies unauthorized hold %j',async actor=>{
await expect(service.transition('t',hold,actor)).rejects.toMatchObject({status:403});
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
it.each(['DRAFT','READY','GATE1_APPROVED','GATE2_PENDING'])('denies hold from %s',async state=>{
task.state=state;
await expect(service.transition('t',hold,reviewer)).rejects.toMatchObject({status:403});
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
it('rejects missing reason and stale version without writes',async()=>{
await expect(service.transition('t',{...hold,reason:' '},reviewer)).rejects.toMatchObject({status:400});
await expect(service.transition('t',{...hold,expectedVersion:1},reviewer)).rejects.toMatchObject({status:409});
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
it('replays identical hold, rejects changed payload',async()=>{
await service.transition('t',hold,reviewer);
const event=tx.orchestrationEvent.create.mock.calls[0][0].data;
tx.orchestrationEvent.findUnique.mockResolvedValue(event);
await service.transition('t',hold,reviewer);
expect(tx.orchestrationTask.update).toHaveBeenCalledTimes(1);
await expect(service.transition('t',{...hold,reason:'changed'},reviewer)).rejects.toMatchObject({status:409});
});
it.each(['APPROVED','REJECTED'])('decides held proposal via existing Gate1 command: %s',async decision=>{
task.state='GATE1_HELD';
await expect(service.decide('t',1,{decision,expectedVersion:2,idempotencyKey:'decision',expiresAt:new Date(Date.now()+60000).toISOString()},reviewer)).resolves.toMatchObject({state:decision==='APPROVED'?'GATE1_APPROVED':'REJECTED'});
});
});
@@ -108,6 +108,12 @@ describe('bounded workflow HTTP contracts', () => {
idempotencyKey: 'submit',
})
.expect(200);
await request(app.getHttpServer())
.put('/admin/orchestration/tasks/t/transition')
.set('Authorization', 'SUPER_ADMIN')
.send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'})
.expect(200);
expect(workflow.transition).toHaveBeenCalledWith('t', expect.objectContaining({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'}), {id:'verified-subject',role:'SUPER_ADMIN'});
await request(app.getHttpServer())
.post('/admin/orchestration/tasks/t/gates/1/decide')
.set('Authorization', 'SUPER_ADMIN')
@@ -198,6 +198,13 @@ export class PrepareWorkflowService {
const fingerprint = JSON.stringify({ id, dto, a });
if (await this.replay(tx, dto.idempotencyKey, fingerprint)) return t;
this.version(t, dto);
if (dto.toState === 'GATE1_HELD') {
if (a.role !== 'SUPER_ADMIN' || t.metadata.createdBy === a.id || t.state !== 'GATE1_PENDING')
throw new ForbiddenException('Independent Gate1 reviewer and pending proposal required');
if (typeof dto.reason !== 'string' || !dto.reason.trim() || dto.reason.length > 2000)
throw new BadRequestException('Hold requires reason of 1..2000 characters');
return this.event(tx, t, 'GATE1_HELD', a, dto.idempotencyKey, 'PREPARE_GATE1_HELD', fingerprint);
}
if (t.metadata.createdBy !== a.id && a.role !== 'SUPER_ADMIN')
throw new ForbiddenException('Proposal owner required');
if (
@@ -252,7 +259,7 @@ export class PrepareWorkflowService {
this.version(t, dto);
if (t.metadata.createdBy === a.id)
throw new ForbiddenException('Independent reviewer required');
if (t.state !== 'GATE1_PENDING')
if (!['GATE1_PENDING', 'GATE1_HELD'].includes(t.state))
throw new ConflictException('Gate1 pending required');
await tx.orchestrationApprovalDecision.create({
data: {
@@ -538,9 +545,11 @@ export class PrepareWorkflowService {
safe &&
a?.role === 'SUPER_ADMIN' &&
t.metadata?.createdBy !== a.id &&
t.state === 'GATE1_PENDING'
)
['GATE1_PENDING', 'GATE1_HELD'].includes(t.state)
) {
actions.push('APPROVE_GATE1', 'REJECT_GATE1');
if (t.state === 'GATE1_PENDING') actions.push('HOLD_GATE1');
}
return {
...t,
metadata: safe
@@ -69,6 +69,28 @@ const enabled = process.env.WORKFLOW_DB === '1';
afterAll(async () => {
await db.$disconnect();
});
it('serializes competing owner holds and preserves audited reason, then decides held task', async () => {
let t = await service.create(dto(), admin);
t = await service.transition(t.id, {toState:'GATE1_PENDING',expectedVersion:t.version,idempotencyKey:`submit-hold-${t.id}`}, admin);
const command = {toState:'GATE1_HELD',expectedVersion:t.version,idempotencyKey:`hold-${t.id}`,reason:'Need source review'};
const results = await Promise.allSettled([
service.transition(t.id, command, reviewer),
service.transition(t.id, {...command,idempotencyKey:`competing-${t.id}`}, reviewer),
]);
expect(results.filter(r=>r.status==='fulfilled')).toHaveLength(1);
const held = await db.orchestrationTask.findUniqueOrThrow({where:{id:t.id}});
expect(held.state).toBe('GATE1_HELD');
expect(held.version).toBe(t.version+1);
const events = await db.orchestrationEvent.findMany({where:{taskId:t.id,eventType:'PREPARE_GATE1_HELD'}});
expect(events).toHaveLength(1);
expect(events[0].actorId).toBe(reviewer.id);
expect(JSON.stringify(events[0].payload)).toContain('Need source review');
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(0);
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(0);
await expect(service.transition(t.id, {...command,expectedVersion:held.version,reason:'changed'},reviewer)).rejects.toMatchObject({status:409});
const decision = await service.decide(t.id,1,{decision:'REJECTED',expectedVersion:held.version,idempotencyKey:`decline-held-${t.id}`,expiresAt:new Date(Date.now()+60000).toISOString()},reviewer);
expect(decision.state).toBe('REJECTED');
});
it('persists and projects immutable bounded proposal scope without arbitrary metadata', async () => {
const input = dto();
const t = await service.create(input, admin);
@@ -1,7 +1,7 @@
import type {ServerAction} from '../services/orchestration';
const labels:Record<string,string>={DRAFT:'پیش‌نویس',GATE1_PENDING:'در انتظار تأیید Gate1',GATE1_APPROVED:'تأییدشده در Gate1',READY:'آماده اجرا',RUNNING:'در حال اجرا',SUCCEEDED:'موفق',FAILED:'ناموفق',BLOCKED:'مسدود',EXPIRED:'منقضی',REJECTED:'ردشده',APPROVED:'تأییدشده',GATE2_PENDING:'در انتظار Gate2 (غیرفعال)',PREPARE:'آماده‌سازی',MUTATE_PRODUCTION:'تغییر Production (غیرفعال)',SEO:'بهینه‌سازی جست‌وجو (SEO)',Content:'محتوا',Tech:'فنی',operationMode:'حالت عملیات',budgetLimitCents:'سقف بودجه (سنت)',metadata:'اطلاعات ثبت‌شده',scope:'محدوده',acceptanceCriteria:'معیارهای پذیرش',commitSha:'شناسه کامیت',id:'شناسه',taskId:'شناسه وظیفه',expectedVersion:'نسخه مورد انتظار',idempotencyKey:'کلید جلوگیری از اجرای تکراری',gate:'دروازه تأیید',decision:'تصمیم',expiresAt:'زمان انقضا',createdAt:'زمان ثبت',runId:'شناسه اجرا',artifactHash:'هش خروجی',environment:'محیط',sha256:'هش SHA-256',kind:'نوع',eventType:'نوع رویداد',fromState:'وضعیت پیشین',toState:'وضعیت بعدی',sequence:'ترتیب',amountCents:'مبلغ (سنت)',status:'وضعیت',reason:'دلیل',department:'دپارتمان',staging:'آزمایشی (staging)',FREEZE_NEW_WORK:'توقف کار جدید',STOP_AGENTS:'توقف عامل‌ها',DISABLE_MUTATIONS:'منع تغییرات',EMERGENCY_HALT:'توقف اضطراری',RESERVE:'رزرو بودجه',RECONCILE:'تطبیق بودجه'};
const labels:Record<string,string>={DRAFT:'پیش‌نویس',GATE1_HELD:'تصمیم به تعویق افتاده',GATE1_PENDING:'در انتظار تأیید Gate1',GATE1_APPROVED:'تأییدشده در Gate1',READY:'آماده اجرا',RUNNING:'در حال اجرا',SUCCEEDED:'موفق',FAILED:'ناموفق',BLOCKED:'مسدود',EXPIRED:'منقضی',REJECTED:'ردشده',APPROVED:'تأییدشده',GATE2_PENDING:'در انتظار Gate2 (غیرفعال)',PREPARE:'آماده‌سازی',MUTATE_PRODUCTION:'تغییر Production (غیرفعال)',SEO:'بهینه‌سازی جست‌وجو (SEO)',Content:'محتوا',Tech:'فنی',operationMode:'حالت عملیات',budgetLimitCents:'سقف بودجه (سنت)',metadata:'اطلاعات ثبت‌شده',scope:'محدوده',acceptanceCriteria:'معیارهای پذیرش',commitSha:'شناسه کامیت',id:'شناسه',taskId:'شناسه وظیفه',expectedVersion:'نسخه مورد انتظار',idempotencyKey:'کلید جلوگیری از اجرای تکراری',gate:'دروازه تأیید',decision:'تصمیم',expiresAt:'زمان انقضا',createdAt:'زمان ثبت',runId:'شناسه اجرا',artifactHash:'هش خروجی',environment:'محیط',sha256:'هش SHA-256',kind:'نوع',eventType:'نوع رویداد',fromState:'وضعیت پیشین',toState:'وضعیت بعدی',sequence:'ترتیب',amountCents:'مبلغ (سنت)',status:'وضعیت',reason:'دلیل',department:'دپارتمان',staging:'آزمایشی (staging)',FREEZE_NEW_WORK:'توقف کار جدید',STOP_AGENTS:'توقف عامل‌ها',DISABLE_MUTATIONS:'منع تغییرات',EMERGENCY_HALT:'توقف اضطراری',RESERVE:'رزرو بودجه',RECONCILE:'تطبیق بودجه'};
export const label=(value:string)=>labels[value]??value;
export const actionLabel=(action:ServerAction)=>({SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صف‌بندی آماده‌سازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور'));
export const actionLabel=(action:ServerAction)=>({HOLD_GATE1:'تعویق تصمیم Gate1',SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صف‌بندی آماده‌سازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور'));
export function Records({value,field}:{value:unknown;field?:string}){
if(value===null||value===undefined)return <span>نامشخص — گزارش نشده</span>;
if(Array.isArray(value))return value.length?<div className="space-y-3">{value.map((item,index)=><article className="border rounded-lg p-3" key={index}><Records value={item} field={field}/></article>)}</div>:<p>رکوردی ثبت نشده است.</p>;
@@ -14,7 +14,8 @@ describe('command center', () => {
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
expect(within(detail).getByText(/Only staging/)).toBeInTheDocument();
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'عامل‌ها و دپارتمان‌ها'}));
@@ -21,6 +21,7 @@ export default function OrchestrationCommandCenter() {
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
const [error,setError]=useState(''); const [loading,setLoading]=useState(false);
const [search,setSearch]=useState('');
const [decisionFilter,setDecisionFilter]=useState('ALL');
const [pending,setPending]=useState<{task:Task;action:ServerAction;key:string}|null>(null);
const [expires,setExpires]=useState(''); const [reason,setReason]=useState('');
const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false);
@@ -62,10 +63,16 @@ export default function OrchestrationCommandCenter() {
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">دریافت اطلاعات از سرور ناموفق بود: {error}. داده جایگزین نمایش داده نمی‌شود. <button onClick={refresh}>بازخوانی وظیفه‌ها</button></p>}
{success&&<p role="status">{success}</p>}
{section==='وظیفه‌ها و تأییدها'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
{section==='نمای کلی'&&<section aria-label="منتظر تصمیم شما" className="border-2 border-purple-300 bg-purple-50 rounded-2xl p-5 space-y-4">
<h2 className="text-xl font-black">منتظر تصمیم شما</h2><p>تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. اقدام‌ها پس از دریافت جزئیات از سرور نمایش داده می‌شوند.</p>
<label>فیلتر تصمیم‌ها<select aria-label="فیلتر تصمیم‌ها" value={decisionFilter} onChange={e=>setDecisionFilter(e.target.value)} className="border rounded p-2 m-2"><option value="ALL">در انتظار و به‌تعویق‌افتاده</option><option value="GATE1_PENDING">در انتظار تصمیم</option><option value="GATE1_HELD">به‌تعویق‌افتاده</option></select></label>
{!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=><article key={t.id} className="bg-white border rounded-xl p-4 space-y-3"><button disabled={!!pending||busy} className="font-bold text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button><p>{label(t.department)} · {label(t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p>{selected?.id!==t.id&&<><p>محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}</p><h3>معیارهای پذیرش</h3>{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?<ul className="list-disc list-inside">{(t.metadata.acceptanceCriteria as string[]).map((c,i)=><li key={i}>{c}</li>)}</ul>:<p>گزارش نشده؛ جزئیات را بررسی کنید</p>}</>}</article>)}
</section>}
{section==='نمای کلی'&&!loading&&!error&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">فهرست وظیفه‌های ثبت‌شده</h2><p>{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.</p><div className="flex flex-wrap gap-3">{[...new Set(tasks.map(t=>t.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
{(['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>جست‌وجوی وظیفه‌ها<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
{!loading&&!error&&!tasks.length&&<p>وظیفه‌ای از سرور دریافت نشد.</p>}
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{label(t.department)}</td><td>{label(t.state)}</td><td>{label(t.operationMode)}</td><td>{t.budgetLimitCents??'نامشخص'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.filter(t=>section!=='نمای کلی'||!['GATE1_PENDING','GATE1_HELD'].includes(t.state)).map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{label(t.department)}</td><td>{label(t.state)}</td><td>{label(t.operationMode)}</td><td>{t.budgetLimitCents??'نامشخص'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
</section>}
{selected&&<section aria-label="جزئیات وظیفه" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?<h3 className="font-bold">محدوده و معیارهای پذیرش گزارش‌شده از سرور</h3>:<p>محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.</p>}<p>محدوده گردش کار سرور: در نمای امن در دسترس نیست.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
<h3 className="font-bold">اقدام‌های مجاز اعلام‌شده توسط سرور</h3>{!selected.availableActions.length&&<p>اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'تغییرات از طرف سرور مجاز نیست':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{actionLabel(a)}</Button>)}</div>
@@ -0,0 +1,37 @@
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
const proposal={id:'pending',key:'p',title:'بررسی منابع محتوا',department:'Content',state:'GATE1_PENDING',version:3,operationMode:'PREPARE',budgetLimitCents:240,metadata:{scope:'فقط تحقیق منابع عمومی',acceptanceCriteria:['سه منبع معتبر']},availableActions:['APPROVE_GATE1','HOLD_GATE1','REJECT_GATE1']};
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[proposal,{...proposal,id:'held',title:'کار نگه‌داشته',state:'GATE1_HELD'}, {...proposal,id:'done',title:'کار پایان‌یافته',state:'CLOSED'}]:proposal}));});
it('opens with obvious pending and held owner queue, scope, criteria and budget; filters without invented actions',async()=>{
render(<OrchestrationCommandCenter/>);
const queue=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(queue).findByRole('button',{name:proposal.title})).toBeInTheDocument();
const card=within(queue).getByRole('button',{name:proposal.title}).closest('article')!;
expect(within(card).getByText(/فقط تحقیق منابع عمومی/)).toBeInTheDocument();
expect(within(card).getByText('سه منبع معتبر')).toBeInTheDocument();
expect(within(card).getByText(/240/)).toBeInTheDocument();
expect(within(queue).queryByText('کار پایان‌یافته')).not.toBeInTheDocument();
fireEvent.change(within(queue).getByLabelText('فیلتر تصمیم‌ها'),{target:{value:'GATE1_HELD'}});
expect(within(queue).queryByRole('button',{name:proposal.title})).not.toBeInTheDocument();
fireEvent.click(within(queue).getByRole('button',{name:'کار نگه‌داشته'}));
expect(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
expect(api.put).not.toHaveBeenCalled();expect(api.post).not.toHaveBeenCalled();
});
it('holds through authenticated server transition and reloads instead of fabricating a local decision',async()=>{
vi.mocked(api.put).mockResolvedValue({data:{}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:proposal.title}));
fireEvent.click(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'بررسی بودجه'}});
fireEvent.click(within(dialog).getByRole('checkbox'));
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
await waitFor(()=>expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/pending/transition',{toState:'GATE1_HELD',expectedVersion:3,idempotencyKey:expect.any(String),reason:'بررسی بودجه'}));
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(await screen.findByRole('button',{name:proposal.title})).toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();
});
@@ -2,6 +2,7 @@ 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'},