From 60a4e14b4b782ad3d7649c37cd50b03bed242f0f Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 24 Oct 2026 09:52:30 +0000 Subject: [PATCH] fix(orchestration): expose queued Gate1 expiry and audited renewal --- .../editorial-execution.ts | 6 +++ .../editorial-validity.spec.ts | 14 ++++++ .../src/orchestration/gate-validity.spec.ts | 44 +++++++++++++++++++ .../orchestration/orchestration.controller.ts | 1 + .../orchestration/orchestration.service.ts | 1 + .../orchestration/prepare-workflow.service.ts | 30 +++++++++++-- backend/src/orchestration/renewal-db.spec.ts | 24 ++++++++++ docs/orchestration-gate-validity.md | 21 +++++++++ .../components/OrchestrationPresentation.tsx | 2 +- .../src/pages/GateValidity.test.tsx | 15 +++++++ .../src/pages/OrchestrationCommandCenter.tsx | 14 +++--- .../admin-panel/src/services/orchestration.ts | 2 +- 12 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 backend/src/orchestration-worker/editorial-validity.spec.ts create mode 100644 backend/src/orchestration/gate-validity.spec.ts create mode 100644 backend/src/orchestration/renewal-db.spec.ts create mode 100644 docs/orchestration-gate-validity.md create mode 100644 frontend/admin-panel/src/pages/GateValidity.test.tsx diff --git a/backend/src/orchestration-worker/editorial-execution.ts b/backend/src/orchestration-worker/editorial-execution.ts index 7dfcf0ac..79b27389 100644 --- a/backend/src/orchestration-worker/editorial-execution.ts +++ b/backend/src/orchestration-worker/editorial-execution.ts @@ -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, diff --git a/backend/src/orchestration-worker/editorial-validity.spec.ts b/backend/src/orchestration-worker/editorial-validity.spec.ts new file mode 100644 index 00000000..6680cd8c --- /dev/null +++ b/backend/src/orchestration-worker/editorial-validity.spec.ts @@ -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(); + }); +}); diff --git a/backend/src/orchestration/gate-validity.spec.ts b/backend/src/orchestration/gate-validity.spec.ts new file mode 100644 index 00000000..05eb4802 --- /dev/null +++ b/backend/src/orchestration/gate-validity.spec.ts @@ -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}); + }); +}); diff --git a/backend/src/orchestration/orchestration.controller.ts b/backend/src/orchestration/orchestration.controller.ts index 3f95ee6d..0b5e9518 100644 --- a/backend/src/orchestration/orchestration.controller.ts +++ b/backend/src/orchestration/orchestration.controller.ts @@ -119,6 +119,7 @@ export class OrchestrationController { return { ...view, metadata: w.metadata, + displayState: w.displayState, availableActions: w.availableActions, }; } diff --git a/backend/src/orchestration/orchestration.service.ts b/backend/src/orchestration/orchestration.service.ts index 37a92c3e..b8db73cc 100644 --- a/backend/src/orchestration/orchestration.service.ts +++ b/backend/src/orchestration/orchestration.service.ts @@ -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) { diff --git a/backend/src/orchestration/prepare-workflow.service.ts b/backend/src/orchestration/prepare-workflow.service.ts index e4eef68f..bc981f0e 100644 --- a/backend/src/orchestration/prepare-workflow.service.ts +++ b/backend/src/orchestration/prepare-workflow.service.ts @@ -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, diff --git a/backend/src/orchestration/renewal-db.spec.ts b/backend/src/orchestration/renewal-db.spec.ts new file mode 100644 index 00000000..5e5dd16b --- /dev/null +++ b/backend/src/orchestration/renewal-db.spec.ts @@ -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); + }); +}); diff --git a/docs/orchestration-gate-validity.md b/docs/orchestration-gate-validity.md new file mode 100644 index 00000000..88a467f5 --- /dev/null +++ b/docs/orchestration-gate-validity.md @@ -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:}` (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. diff --git a/frontend/admin-panel/src/components/OrchestrationPresentation.tsx b/frontend/admin-panel/src/components/OrchestrationPresentation.tsx index 0b84f8fc..4f6ab567 100644 --- a/frontend/admin-panel/src/components/OrchestrationPresentation.tsx +++ b/frontend/admin-panel/src/components/OrchestrationPresentation.tsx @@ -1,5 +1,5 @@ import type {ServerAction} from '../services/orchestration'; -const labels:Record={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={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}){ diff --git a/frontend/admin-panel/src/pages/GateValidity.test.tsx b/frontend/admin-panel/src/pages/GateValidity.test.tsx new file mode 100644 index 00000000..6d70ae98 --- /dev/null +++ b/frontend/admin-panel/src/pages/GateValidity.test.tsx @@ -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(); + 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(); +}); diff --git a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx index 3023fc5d..0341b93e 100644 --- a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx +++ b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx @@ -82,17 +82,17 @@ export default function OrchestrationCommandCenter() { {section==='وظیفه‌ها و تأییدها'&&capabilities.mutations&&void loadTasks()}/>} {section==='نمای کلی'&&

منتظر تصمیم شما

تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. دکمه‌ها فقط اقدام‌های مجاز اعلام‌شده توسط سرور هستند؛ برای بررسی و تصمیم، جزئیات را باز کنید.

- - {!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&

تصمیمی در این فیلتر منتظر نیست.

} - {!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=>

{label(t.department)} · {label(t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت

رزرو آزمایشی؛ هزینه واقعی نامشخص

{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=>)}
{selected?.id!==t.id&&<>

محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}

معیارهای پذیرش

{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?
    {(t.metadata.acceptanceCriteria as string[]).map((c,i)=>
  • {c}
  • )}
:

گزارش نشده؛ جزئیات را بررسی کنید

}}
)} + + {!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&

تصمیمی در این فیلتر منتظر نیست.

} + {!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=>

{label(t.department)} · {label(t.displayState??t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت

رزرو آزمایشی؛ هزینه واقعی نامشخص

{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=>)}
{selected?.id!==t.id&&<>

محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}

معیارهای پذیرش

{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?
    {(t.metadata.acceptanceCriteria as string[]).map((c,i)=>
  • {c}
  • )}
:

گزارش نشده؛ جزئیات را بررسی کنید

}}
)}
} - {section==='نمای کلی'&&!loading&&!error&&

فهرست وظیفه‌های ثبت‌شده

{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.

{[...new Set(tasks.map(t=>t.state))].map(state=>{label(state)}: {tasks.filter(t=>t.state===state).length})}
} + {section==='نمای کلی'&&!loading&&!error&&

فهرست وظیفه‌های ثبت‌شده

{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.

{[...new Set(tasks.map(t=>t.displayState??t.state))].map(state=>{label(state)}: {tasks.filter(t=>(t.displayState??t.state)===state).length})}
} {(['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها'] as Section[]).includes(section)&&
{!loading&&!error&&!tasks.length&&

وظیفه‌ای از سرور دریافت نشد.

} -
{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=>)}{filtered.filter(t=>section!=='نمای کلی'||!['GATE1_PENDING','GATE1_HELD'].includes(t.state)).map(t=>)}
{h}
{label(t.department)}{label(t.state)}{label(t.operationMode)}{t.budgetLimitCents??'نامشخص'}{t.version}
+
{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].map(h=>)}{filtered.filter(t=>section!=='نمای کلی'||!['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)).map(t=>)}
{h}
{label(t.department)}{label(t.displayState??t.state)}{label(t.operationMode)}{t.budgetLimitCents??'نامشخص'}{t.version}
} {selected&&

{selected.title} · v{selected.version}

{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())?

محدوده و معیارهای پذیرش گزارش‌شده از سرور

:

محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.

}

محدوده گردش کار سرور: در نمای امن در دسترس نیست.

-

اقدام‌های مجاز اعلام‌شده توسط سرور

{!selected.availableActions.length&&

اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.

}
{selected.availableActions.map(a=>)}
+ {selected.displayState==='GATE1_RENEWAL_REQUIRED'&&

مسدود — تأیید Gate1 منقضی شده؛ برای همان وظیفه و محدوده، تأیید مجدد مستقل لازم است. برنامه زمانی و سقف بودجه تغییر نمی‌کند.

}

اقدام‌های مجاز اعلام‌شده توسط سرور

{!selected.availableActions.length&&

اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.

}
{selected.availableActions.map(a=>)}

تصمیم‌های تأیید تغییرناپذیر

اجراها و خروجی‌های ثبت‌شده

{!selected.runs?.length&&

اجرای ثبت‌شده‌ای وجود ندارد.

}{selected.runs?.map(r=>

{r.id} · {label(r.status)}

کامیت: {r.commitSha} · محیط: {r.environment}

{r.artifacts.map(a=>)}
)}

رزرو آزمایشی؛ هزینه واقعی نامشخص

دفتر بودجه (سنت؛ رزرو با هزینه واقعی متفاوت است)

رویدادهای ممیزی به‌ترتیب

@@ -105,7 +105,7 @@ export default function OrchestrationCommandCenter() { {section==='گفت‌وگو'&&!capabilities.chat&&

گفت‌وگو در دسترس نیست؛ پل مورد اعتماد اجرا فعال نیست.

} {section==='گفت‌وگو'&&capabilities.chat&&

گفت‌وگوی متنی از مسیر امن سرور

فقط متن مشورتی؛ بدون ترمینال، PTY، توکن اجرا یا اتصال مستقیم به Hermes. تصمیم‌ها از کنترل تأیید مستقل عبور می‌کنند.

{messages.map(m=>

{m.role}: {m.content}

)}