fix(orchestration): expose queued Gate1 expiry and audited renewal
Deploy Canina / deploy (push) Successful in 4m51s

This commit is contained in:
devops authored and devops committed 2026-10-24 09:53:07 +00:00
1 parent 6e465663bd
commit 60a4e14b4b
12 files changed
+162 -12

No files matched your search

@@ -252,7 +252,13 @@ export class EditorialExecutionService {
throw new ForbiddenException('Artifact binding mismatch');
result = { kind, sha256: artifact.sha256, bytes, brief: parsed.brief };
}
const approval = await tx.orchestrationApprovalDecision.findFirst({
where: { taskId: t.id, gate: 1 }, orderBy: { createdAt: 'desc' },
});
const valid = approval?.decision === 'APPROVED' && approval.actorId !== 'pmo' && approval.expiresAt > new Date();
return {
displayState: t.state === 'READY' && !valid ? (approval?.decision === 'APPROVED' && approval.actorId !== 'pmo' && approval.expiresAt <= new Date() ? 'GATE1_RENEWAL_REQUIRED' : 'BLOCKED') : t.state,
gate1Validity: valid ? 'VALID' : 'BLOCKED',
taskId: t.id,
pilotKind: EDITORIAL_PILOT_KIND,
state: t.state,
@@ -0,0 +1,14 @@
import { EditorialExecutionService } from './editorial-execution';
describe('editorial expiry read/claim consistency',()=>{
it('rejects the actual expired claim while status explains blocked READY',async()=>{
jest.useFakeTimers().setSystemTime(new Date('2026-10-24T09:15:00Z'));
const t={id:'565ace1f-8cfc-4447-b978-66c36e7b767b',state:'READY',version:4,metadata:{commitSha:'a'.repeat(40)}};
const tx:any={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationApprovalDecision:{findFirst:jest.fn().mockResolvedValue({decision:'APPROVED',actorId:'owner',expiresAt:new Date('2026-10-24T06:37:00Z')})},orchestrationArtifact:{findMany:jest.fn().mockResolvedValue([])}};
const s=new EditorialExecutionService({$transaction:async(fn:any)=>fn(tx)} as any);
jest.spyOn(s as any,'scope').mockResolvedValue(t);
const a={id:'pmo',role:'WORKFLOW_WORKER'};
await expect(s.claim(a,{taskId:t.id})).rejects.toMatchObject({status:403,message:'Valid independent Gate1 required'});
await expect(s.status(a,t.id)).resolves.toMatchObject({state:'READY',version:4,displayState:'GATE1_RENEWAL_REQUIRED',gate1Validity:'BLOCKED',artifact:null});
jest.useRealTimers();
});
});
@@ -0,0 +1,44 @@
import { PrepareWorkflowService } from './prepare-workflow.service';
describe('queued Gate1 expiry renewal',()=>{
const owner={id:'owner',role:'SUPER_ADMIN'};
let t:any,tx:any,s:PrepareWorkflowService,approval:any;
beforeEach(()=>{
jest.useFakeTimers().setSystemTime(new Date('2026-10-24T09:15:00Z'));
approval={id:'approval',gate:1,decision:'APPROVED',actorId:'owner',createdAt:new Date('2026-10-24T05:37:54.808Z'),expiresAt:new Date('2026-10-24T06:37:00Z')};
t={id:'t',state:'READY',version:4,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo',commitSha:'a'.repeat(40)},decisions:[approval]};
tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>t),update:jest.fn(async({data}:any)=>(t={...t,state:data.state,version:t.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{findFirst:jest.fn(async()=>approval),create:jest.fn()},prepareWorkflowOutbox:{findUnique:jest.fn().mockResolvedValue({status:'PENDING',attempts:0,runId:null,notBefore:null}),create:jest.fn(),update:jest.fn()}};
s=new PrepareWorkflowService({$transaction:async(fn:any)=>fn(tx)},{workerIds:['pmo'],stageCiIds:[]});
});
afterEach(()=>jest.useRealTimers());
const dto={decision:'APPROVED',expectedVersion:4,idempotencyKey:'renew'};
it('shows blocked renewal rather than actionable READY at actual failure time',()=>{
expect(s.project(t,owner)).toMatchObject({displayState:'GATE1_RENEWAL_REQUIRED',availableActions:['APPROVE_GATE1']});
});
it('renews by ordinary independent approval without recreating outbox or changing immutable task binding',async()=>{
await expect(s.decide('t',1,dto,owner)).resolves.toMatchObject({state:'READY',version:5});
expect(tx.prepareWorkflowOutbox.create).not.toHaveBeenCalled();
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:'owner',expiresAt:new Date('2026-10-25T09:15:00Z')})});
expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({eventType:'PREPARE_GATE1_RENEWED',fromState:'READY',toState:'READY'})});
});
it('does not renew valid approvals, self review, active runs, or schedule changes',async()=>{
await expect(s.decide('t',1,dto,{id:'pmo',role:'SUPER_ADMIN'})).rejects.toMatchObject({status:403});
await expect(s.decide('t',1,{...dto,notBefore:'2026-10-25T10:00:00Z'},owner)).rejects.toMatchObject({status:400});
tx.prepareWorkflowOutbox.findUnique.mockResolvedValue({status:'PENDING',attempts:1,runId:'r'});
await expect(s.decide('t',1,dto,owner)).rejects.toMatchObject({status:409});
tx.prepareWorkflowOutbox.findUnique.mockResolvedValue({status:'PENDING',attempts:0,runId:null});
approval.expiresAt=new Date('2026-10-25T09:15:00Z');
await expect(s.decide('t',1,dto,owner)).rejects.toMatchObject({status:409});
});
it('replays identical command after expiry but denies changed payload and stale concurrent command',async()=>{
await s.decide('t',1,dto,owner);
const e=tx.orchestrationEvent.create.mock.calls[0][0].data;
tx.orchestrationEvent.findUnique.mockResolvedValue(e);
jest.setSystemTime(new Date('2026-10-26T09:15:00Z'));
await s.decide('t',1,dto,owner);
expect(tx.orchestrationTask.update).toHaveBeenCalledTimes(1);
await expect(s.decide('t',1,{...dto,notes:'changed'},owner)).rejects.toMatchObject({status:409});
tx.orchestrationEvent.findUnique.mockResolvedValue(null);
await expect(s.decide('t',1,{...dto,idempotencyKey:'competing'},owner)).rejects.toMatchObject({status:409});
});
});
@@ -119,6 +119,7 @@ export class OrchestrationController {
return {
...view,
metadata: w.metadata,
displayState: w.displayState,
availableActions: w.availableActions,
};
}
@@ -619,6 +619,7 @@ export class OrchestrationService {
await this.killSwitch.assertAllowed('OBSERVE');
return (this.prisma as any).orchestrationTask.findMany({
orderBy: { createdAt: 'desc' },
include: { decisions: true },
});
}
async findOne(id: string) {
@@ -261,9 +261,24 @@ export class PrepareWorkflowService {
this.version(t, dto);
if (t.metadata.createdBy === a.id)
throw new ForbiddenException('Independent reviewer required');
if (!['GATE1_PENDING', 'GATE1_HELD'].includes(t.state))
const renewing = t.state === 'READY';
let queue: any;
if (renewing) {
const previous = await tx.orchestrationApprovalDecision.findFirst({
where: { taskId: id, gate: 1 }, orderBy: { createdAt: 'desc' },
});
queue = await tx.prepareWorkflowOutbox.findUnique({ where: { taskId: id } });
if (dto.notBefore !== undefined)
throw new BadRequestException('Renewal preserves the existing schedule');
if (dto.decision !== 'APPROVED' || !previous || previous.decision !== 'APPROVED' ||
previous.actorId === t.metadata.createdBy || previous.expiresAt > new Date() ||
!queue || queue.status !== 'PENDING' || queue.attempts !== 0 || queue.runId || queue.leaseToken)
throw new ConflictException('Only expired independent approval on an unstarted queue can be renewed');
} else if (!['GATE1_PENDING', 'GATE1_HELD'].includes(t.state))
throw new ConflictException('Gate1 pending required');
const now = Date.now();
if (renewing && queue.notBefore && new Date(queue.notBefore).getTime() >= now + 86400000)
throw new ConflictException('Existing schedule is outside the renewal validity window');
const scheduled = dto.notBefore !== undefined;
const notBefore = scheduled ? new Date(dto.notBefore) : null;
if (scheduled && (dto.decision !== 'APPROVED' || typeof dto.notBefore !== 'string' || !Number.isFinite(notBefore!.getTime()) || notBefore!.getTime() <= now || notBefore!.getTime() > now + 30 * 86400000))
@@ -277,7 +292,7 @@ export class PrepareWorkflowService {
throw new BadRequestException('Audit notes must be at most 2000 characters');
if (dto.decision === 'APPROVED') {
await this.allowed(tx, true);
await tx.prepareWorkflowOutbox.create({data:{taskId:id,notBefore}});
if (!renewing) await tx.prepareWorkflowOutbox.create({data:{taskId:id,notBefore}});
}
await tx.orchestrationApprovalDecision.create({
data: {
@@ -296,7 +311,7 @@ export class PrepareWorkflowService {
dto.decision === 'APPROVED' ? 'READY' : 'REJECTED',
a,
dto.idempotencyKey,
'PREPARE_GATE1',
renewing ? 'PREPARE_GATE1_RENEWED' : 'PREPARE_GATE1',
fingerprint,
);
});
@@ -574,7 +589,15 @@ export class PrepareWorkflowService {
(t.metadata?.workflowScope ?? t.metadata?.scope) === 'STAGE_PREPARE';
const owner =
a?.id && (t.metadata?.createdBy === a.id || a.role === 'SUPER_ADMIN');
const latest = [...(t.decisions ?? [])].filter((d: any) => d.gate === 1)
.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];
const expired = safe && t.state === 'READY' && latest?.decision === 'APPROVED' &&
latest.actorId !== t.metadata.createdBy && new Date(latest.expiresAt).getTime() <= Date.now();
const blocked = safe && t.state === 'READY' && (!latest || latest.decision !== 'APPROVED' ||
latest.actorId === t.metadata.createdBy || new Date(latest.expiresAt).getTime() <= Date.now());
const actions: string[] = [];
if (expired && this.reviewer(a) && t.metadata.createdBy !== a.id)
actions.push('APPROVE_GATE1');
if (safe && owner && t.state === 'DRAFT') actions.push('SUBMIT_GATE1');
if (safe && owner && t.state === 'GATE1_APPROVED')
actions.push('QUEUE_PREPARE');
@@ -589,6 +612,7 @@ export class PrepareWorkflowService {
}
return {
...t,
displayState: blocked ? (expired ? 'GATE1_RENEWAL_REQUIRED' : 'BLOCKED') : t.state,
metadata: safe
? {
scope: t.metadata.scope,
@@ -0,0 +1,24 @@
import { PrismaClient } from '@prisma/client';
import { PrepareWorkflowService } from './prepare-workflow.service';
(process.env.WORKFLOW_DB==='1'?describe:describe.skip)('renewal PostgreSQL serialization',()=>{
const db=new PrismaClient();
const service=new PrepareWorkflowService(db,{workerIds:['pmo'],stageCiIds:[]});
const owner={id:'owner',role:'SUPER_ADMIN'};
afterAll(()=>db.$disconnect());
it('denies expired claim, serializes renewal/replay, retains original decision and enables one claim',async()=>{
const t=await db.orchestrationTask.create({data:{key:crypto.randomUUID(),title:'Disposable renewal',department:'CONTENT',operationMode:'PREPARE',state:'READY',version:4,budgetLimitCents:20,metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo',commitSha:'a'.repeat(40)}}});
const old=await db.orchestrationApprovalDecision.create({data:{taskId:t.id,gate:1,decision:'APPROVED',actorId:'owner',expiresAt:new Date('2026-10-24T06:37:00Z'),idempotencyKey:crypto.randomUUID()}});
await db.prepareWorkflowOutbox.create({data:{taskId:t.id}});
const worker={id:'pmo',role:'WORKFLOW_WORKER'};
await expect(service.claim(worker,t.id)).rejects.toMatchObject({status:403});
const dto={expectedVersion:4,decision:'APPROVED',idempotencyKey:crypto.randomUUID()};
const renewed=await Promise.all([service.decide(t.id,1,dto,owner),service.decide(t.id,1,dto,owner)]);
expect(renewed.map(t=>t.version)).toEqual([5,5]);
await expect(service.decide(t.id,1,{...dto,idempotencyKey:crypto.randomUUID()},owner)).rejects.toMatchObject({status:409});
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(2);
expect((await db.orchestrationApprovalDecision.findUniqueOrThrow({where:{id:old.id}})).expiresAt).toEqual(old.expiresAt);
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(1);
const claims=await Promise.all([service.claim(worker,t.id),service.claim(worker,t.id)]);
expect(claims.filter(Boolean)).toHaveLength(1);
});
});
+21
View File
@@ -0,0 +1,21 @@
# Queued Gate1 validity correction
## Read-only Stage evidence (2026-10-24)
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
## Behavior
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
## Owner steps after parent CI integration
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
## Verification
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
@@ -1,5 +1,5 @@
import type {ServerAction} from '../services/orchestration';
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:'تطبیق بودجه'};
const labels:Record<string,string>={GATE1_RENEWAL_REQUIRED:'مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک',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)=>({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}){
@@ -0,0 +1,15 @@
import {render,screen,within} from '@testing-library/react';
import {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()}}));
it('shows expired queued work in owner decisions as blocked, not ready to execute',async()=>{
const t={id:'t',key:'t',title:'Expired queued research',state:'READY',displayState:'GATE1_RENEWAL_REQUIRED',version:4,operationMode:'PREPARE',budgetLimitCents:20,availableActions:['APPROVE_GATE1'],metadata:{scope:'Same immutable scope',acceptanceCriteria:['Evidence']}};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));
render(<OrchestrationCommandCenter/>);
const queue=screen.getByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(queue).findByRole('button',{name:t.title})).toBeInTheDocument();
expect(within(queue).getByText(/نیازمند تأیید مجدد مالک/)).toBeInTheDocument();
expect(screen.queryByText('آماده اجرا')).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();
});
@@ -82,17 +82,17 @@ export default function OrchestrationCommandCenter() {
{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><p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><div className="flex flex-wrap gap-2">{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=><Button key={a.id} disabled={!capabilities.mutations||!!pending||busy||!!actionBlockReason(t,a)} onClick={()=>void decide(t,a)}>{actionLabel(a)}</Button>)}</div>{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>)}
<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','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??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.displayState??t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p><p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><div className="flex flex-wrap gap-2">{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=><Button key={a.id} disabled={!capabilities.mutations||!!pending||busy||!!actionBlockReason(t,a)} onClick={()=>void decide(t,a)}>{actionLabel(a)}</Button>)}</div>{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>}
{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.displayState??t.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>(t.displayState??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.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>
<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','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??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.displayState??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>
{selected.displayState==='GATE1_RENEWAL_REQUIRED'&&<p role="status">مسدود — تأیید Gate1 منقضی شده؛ برای همان وظیفه و محدوده، تأیید مجدد مستقل لازم است. برنامه زمانی و سقف بودجه تغییر نمی‌کند.</p>}<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>
<h3 className="font-bold">تصمیم‌های تأیید تغییرناپذیر</h3><Json value={selected.decisions??[]}/>
<h3 className="font-bold">اجراها و خروجی‌های ثبت‌شده</h3>{!selected.runs?.length&&<p>اجرای ثبت‌شده‌ای وجود ندارد.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {label(r.status)}</h4><p>کامیت: {r.commitSha} · محیط: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
<p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><h3 className="font-bold">دفتر بودجه (سنت؛ رزرو با هزینه واقعی متفاوت است)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی به‌ترتیب</h3><Json value={selected.events??[]}/>
@@ -105,7 +105,7 @@ 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===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===1&&pending.action.decision==='APPROVED'&&pending.task.displayState!=='GATE1_RENEWAL_REQUIRED'&&<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>}
<p>تأیید، وظیفه را در اولویت صف آماده قرار می‌دهد؛ زمان اختیاری فقط زودترین زمان شروع است و اجرای دقیق در آن لحظه تضمین نمی‌شود. حداکثر زمان‌بندی ۳۰ روز است؛ اعتبار تأیید را سرور مدیریت می‌کند.</p>
<label className="block">دلیل (برای تأیید اختیاری)<input aria-label="دلیل" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
@@ -34,7 +34,7 @@ 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 Task { id: string; key: string; title: string; department: string; state: string; displayState?: 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}