feat(orchestration): expose owner Gate1 queue and audited hold decisions
Deploy Canina / deploy (push) Successful in 3m9s

This commit is contained in:
devops committed 2026-10-24 02:28:58 +00:00
1 parent 65a6fe1f0c
commit 8cedc2cd67
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);