Compare commits

...
Author SHA1 Message Date
devops 09dbe4de48 feat(orchestration): bind PMO editorial proposals to owner Gate1 2026-10-24 03:26:30 +00:00
4 changed files with 468 additions and 1 deletions

No files matched your search

@@ -0,0 +1,44 @@
# Bounded PMO editorial proposal bridge
No live configuration, deployment, publication or execution is introduced. Opt-in transport/startup flag remains unchanged. Core services/controllers are untouched.
## Parent contract
`POST /internal/prepare-worker/editorial-proposals` (plus the application's existing `/api` global prefix when present), Bearer service credential. Strict JSON body, all fields required, no extra fields:
```json
{
"requestId": "a client-generated UUID retained across retries",
"pilotKind": "editorial-research-to-brief-v1",
"operationMode": "PREPARE",
"environment": "staging",
"scope": "EDITORIAL_RESEARCH_TO_BRIEF",
"researchTopic": "Evidence-based senior dog nutrition research",
"acceptanceCriteria": ["Cite primary sources with dates", "Return a research brief; do not publish"],
"commitSha": "40 lowercase hexadecimal characters",
"budgetLimitCents": 20
}
```
Topic 1..180 characters, criteria 1..10 items each 1..500 characters; whitespace-only rejected. commitSha must be a string. requestId must be a UUID. Fixed pilot/scope/environment/mode/budget are checked, not caller-controlled options. Department is server-owned CONTENT. Human research topic and criteria are owner-reviewable proposal data, not instructions executed by this endpoint.
201 returns `{taskId,key,pilotKind,state,version,department,operationMode,budgetLimitCents,metadata:{scope,acceptanceCriteria,environment,commitSha}}`. First success is GATE1_PENDING; replay returns current state, does not undo owner decisions or requeue work. Scope includes pilot kind, topic and explicit no-publication/release/production restriction. `key` is `editorial-v1:` plus SHA256 of JSON `[authenticatedWorkerId,requestId]`. Same request UUID + differing immutable proposal is 409. Concurrent identical requests produce one task, one PREPARE_PROPOSED event, one PREPARE_TRANSITION event. Crash after create can resume DRAFT submission. No arbitrary reads or mutations are exposed.
## Explicit grant and author authority
Only canonical server identity `pmo`, authenticated by a configured unique digest grant with role WORKFLOW_WORKER and included in workerIds, can submit. There was no canonical PMO grant mapping in repository transport configuration: the operator must explicitly provision this grant through the existing fixed `/run/secrets/prepare_worker_grants` configuration, using a new random dedicated credential, **without runtime defaults**. Never copy an arbitrary agent/request actor ID or reuse CI identity. Missing pmo grant denies; other valid workers and Stage CI get 403. Transport disabled remains denied/unregistered according to existing registration boundary. No secrets were read or provisioned by this change.
Existing core create/transition APIs accept only Admin/SUPER_ADMIN. This bounded adapter delegates **author-only Admin capability**, binding id to the authenticated pmo grant, for exactly create PREPARE and DRAFT→GATE1_PENDING. It never uses SUPER_ADMIN, calls decide, approves, queues READY, writes through Prisma, creates outbox/runs, reserves/reconciles costs or submits evidence. Prisma reads only support idempotency/payload reconciliation. Core remains authoritative for kill switch, immutable metadata/events, versioning and independent Gate1 reviewer. No approval bypass or arbitrary Admin endpoint is exposed.
Owner uses existing Backend owner Gate1 queue and independent authenticated SUPER_ADMIN review. This bridge does not replace that UI/API. Current deterministic/Tech transports are not editorial executors: editorial keys are explicitly refused by generic claim/complete even after independent approval. Actual research execution/completion needs a separately reviewed executor/ingestion contract; no toy QA, fake zero cost, release or publication is claimed.
## Verification
Disposable PostgreSQL16 (no published ports/live volumes), Node22 private copied dependencies from readonly orchestration-v4-runtime donor, regenerated private Prisma client and real listening Nest TCP HTTP boundary. Evidence directory `/opt/services/canina/validation/v4-editorial-bridge/`:
- red.log: missing endpoint 404 vs required 201.
- tracer-red.log: approved editorial mistakenly admitted by generic tracer (201 vs required 403), fixed with transport fence.
- green.log: five bridge tests pass, including race/replay/crash recovery, immutable payload conflict, grant/body/scope/production denial, kill switch and independent approval with tracer refusal.
- regression-final.log / build.log: all 4 worker suites, 46 tests pass (exit 0); full backend tsc -b exits 0. New bridge files scoped ESLint exits 0 (lint.log). Initial combined regression hit a shared fixture kill-switch uniqueness collision; tests now preserve and restore the fixture row.
Tests use disposable fixture commit hashes, not deployed commit evidence. No AppModule, production, live DB, release authorization, push or deploy changes. Parent owns ingress service-network/TLS/body/rate limits and reviewed grant provisioning. This commit is the proposal slice only.
@@ -0,0 +1,271 @@
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { createHash, randomUUID } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
import { PrepareWorkflowService } from '../orchestration/prepare-workflow.service';
import { WorkerTransportModule } from './worker-transport.module';
(process.env.EDITORIAL_BRIDGE_DB === '1' ? describe : describe.skip)(
'editorial proposal real TCP boundary',
() => {
const db = new PrismaClient();
const token = 'disposable-pmo-token-'.repeat(3),
other = 'disposable-other-token-'.repeat(3),
ci = 'disposable-ci-token-'.repeat(3);
const digest = (s: string) => createHash('sha256').update(s).digest('hex');
let app: INestApplication, base: string, workflow: PrepareWorkflowService;
const config = (enabled = true, withPmo = true) => ({
enabled,
grants: [
...(withPmo
? [
{
id: 'pmo',
role: 'WORKFLOW_WORKER' as const,
credentialSha256: digest(token),
},
]
: []),
{
id: 'other',
role: 'WORKFLOW_WORKER' as const,
credentialSha256: digest(other),
},
{ id: 'ci', role: 'STAGE_CI' as const, credentialSha256: digest(ci) },
],
workerIds: withPmo ? ['pmo', 'other'] : ['other'],
stageCiIds: ['ci'],
artifactDirectory: '/work/tmp/editorial-artifacts',
artifactBaseUrl:
'https://isolated.invalid/internal/prepare-worker/artifacts',
});
async function start(c = config()) {
const m = await Test.createTestingModule({
imports: [WorkerTransportModule.register(c)],
})
.overrideProvider(PrismaService)
.useValue(db)
.compile();
const a = m.createNestApplication();
await a.listen(0, '127.0.0.1');
return a;
}
beforeAll(async () => {
app = await start();
base = await app.getUrl();
workflow = app.get(PrepareWorkflowService);
});
afterAll(async () => {
await app?.close();
await db.$disconnect();
});
const dto = () => ({
requestId: randomUUID(),
pilotKind: 'editorial-research-to-brief-v1',
operationMode: 'PREPARE',
environment: 'staging',
scope: 'EDITORIAL_RESEARCH_TO_BRIEF',
researchTopic: 'Evidence-based senior dog nutrition research',
acceptanceCriteria: [
'Cite primary sources with dates',
'Return a research brief, not a published article',
],
commitSha: 'a'.repeat(40),
budgetLimitCents: 20,
});
async function post(body: any, secret = token, url = base) {
const r = await fetch(
url + '/internal/prepare-worker/editorial-proposals',
{
method: 'POST',
headers: {
authorization: 'Bearer ' + secret,
'content-type': 'application/json',
},
body: JSON.stringify(body),
},
);
return { status: r.status, body: await r.json() };
}
it('submits immutable owner-reviewable proposal, never approves or dispatches, retries idempotently', async () => {
const body = dto();
const r = await post(body);
expect(r.status).toBe(201);
expect(r.body).toMatchObject({
pilotKind: body.pilotKind,
state: 'GATE1_PENDING',
operationMode: 'PREPARE',
department: 'CONTENT',
budgetLimitCents: 20,
metadata: {
environment: 'staging',
commitSha: body.commitSha,
acceptanceCriteria: body.acceptanceCriteria,
},
});
const task = await db.orchestrationTask.findUniqueOrThrow({
where: { id: r.body.taskId },
});
expect((task.metadata as any).createdBy).toBe('pmo');
expect(task.key).toMatch(/^editorial-v1:/);
expect((await post(body)).body.taskId).toBe(task.id);
expect(
await db.orchestrationEvent.count({ where: { taskId: task.id } }),
).toBe(2);
for (const model of [
db.orchestrationApprovalDecision,
db.orchestrationRun,
db.prepareWorkflowOutbox,
db.orchestrationBudgetLedger,
] as any[])
expect(await model.count({ where: { taskId: task.id } })).toBe(0);
expect(
(await post({ ...body, researchTopic: 'Changed topic' })).status,
).toBe(409);
expect((await post({ ...body, commitSha: 'b'.repeat(40) })).status).toBe(
409,
);
await expect(
workflow.decide(task.id, 1, {}, { id: 'pmo', role: 'Admin' }),
).rejects.toThrow('Authenticated workflow identity required');
});
it('rejects untrusted workers, CI, impersonation, unbounded scope and disabled or absent PMO grants', async () => {
for (const secret of [other, ci])
expect((await post(dto(), secret)).status).toBe(403);
expect((await post(dto(), 'incorrect')).status).toBe(401);
for (const patch of [
{ actorId: 'owner' },
{ role: 'SUPER_ADMIN' },
{ department: 'ENGINEERING' },
{ scope: 'arbitrary' },
{ pilotKind: 'other' },
{ environment: 'production' },
{ operationMode: 'RELEASE' },
{ budgetLimitCents: 21 },
{ researchTopic: ' ' },
{ acceptanceCriteria: [' '] },
{ commitSha: 123 },
{ acceptanceCriteria: [] },
{ taskId: randomUUID() },
])
expect((await post({ ...dto(), ...patch })).status).toBe(400);
for (const c of [config(false), config(true, false)]) {
const isolated = await start(c);
try {
const r = await post(dto(), token, await isolated.getUrl());
expect([401, 403]).toContain(r.status);
} finally {
await isolated.close();
}
}
});
it('races identical requests with one proposal and submission event, and resumes a draft', async () => {
const body = dto();
const responses = await Promise.all(
Array.from({ length: 5 }, () => post(body)),
);
expect(responses.map((r) => r.status)).toEqual([201, 201, 201, 201, 201]);
expect(new Set(responses.map((r) => r.body.taskId)).size).toBe(1);
expect(
await db.orchestrationEvent.count({
where: { taskId: responses[0].body.taskId },
}),
).toBe(2);
const pending = await post(dto());
const task = await db.orchestrationTask.findUniqueOrThrow({
where: { id: pending.body.taskId },
});
// Interrupted transaction fixture: core create exists but no submission.
const retry = dto();
const key =
'editorial-v1:' + digest(JSON.stringify(['pmo', retry.requestId]));
const metadata = task.metadata as any;
await workflow.create(
{
key,
title: task.title,
department: 'CONTENT',
operationMode: 'PREPARE',
budgetLimitCents: 20,
metadata,
},
{ id: 'pmo', role: 'Admin' },
);
expect((await post(retry)).body.state).toBe('GATE1_PENDING');
});
it('honors kill switches without creating work', async () => {
const previous = await db.orchestrationKillSwitch.findUnique({
where: { scope: 'GLOBAL' },
});
await db.orchestrationKillSwitch.upsert({
where: { scope: 'GLOBAL' },
create: {
scope: 'GLOBAL',
level: 'FREEZE_NEW_WORK',
active: true,
reason: 'disposable test',
actorId: 'fixture',
},
update: { level: 'FREEZE_NEW_WORK', active: true },
});
try {
expect((await post(dto())).status).toBe(403);
} finally {
if (previous)
await db.orchestrationKillSwitch.update({
where: { scope: 'GLOBAL' },
data: { level: previous.level, active: previous.active },
});
else
await db.orchestrationKillSwitch.delete({
where: { scope: 'GLOBAL' },
});
}
});
it('never admits an editorial proposal into the deterministic tracer even after real independent Gate1 approval', async () => {
const created = await post(dto());
let t = await db.orchestrationTask.findUniqueOrThrow({
where: { id: created.body.taskId },
});
t = await workflow.decide(
t.id,
1,
{
decision: 'APPROVED',
expiresAt: new Date(Date.now() + 60000).toISOString(),
expectedVersion: t.version,
idempotencyKey: randomUUID(),
},
{ id: 'independent-fixture-owner', role: 'SUPER_ADMIN' },
);
t = await workflow.transition(
t.id,
{
toState: 'READY',
expectedVersion: t.version,
idempotencyKey: randomUUID(),
},
{ id: 'pmo', role: 'Admin' },
);
const r = await fetch(base + '/internal/prepare-worker/claim', {
method: 'POST',
headers: {
authorization: 'Bearer ' + token,
'content-type': 'application/json',
},
body: JSON.stringify({ taskId: t.id }),
});
expect(r.status).toBe(403);
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
0,
);
expect(
await db.orchestrationBudgetLedger.count({ where: { taskId: t.id } }),
).toBe(0);
expect((await post({ ...dto(), requestId: randomUUID() })).status).toBe(
201,
);
});
},
);
@@ -0,0 +1,145 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
} from '@nestjs/common';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsIn,
IsInt,
IsString,
IsUUID,
Matches,
MaxLength,
MinLength,
} from 'class-validator';
import { createHash } from 'crypto';
import {
PrepareWorkflowService,
WorkflowIdentity,
} from '../orchestration/prepare-workflow.service';
import { PrismaService } from '../prisma/prisma.service';
export const EDITORIAL_PILOT_KIND = 'editorial-research-to-brief-v1';
// No new implicit grant. Only an explicitly provisioned existing worker grant with
// canonical id pmo is admitted; absence of that grant means denial, never fallback.
export const EDITORIAL_PMO_WORKER_ID = 'pmo';
export class EditorialProposalDto {
@IsUUID() requestId!: string;
@IsIn([EDITORIAL_PILOT_KIND]) pilotKind!: string;
@IsIn(['PREPARE']) operationMode!: string;
@IsIn(['staging']) environment!: string;
@IsIn(['EDITORIAL_RESEARCH_TO_BRIEF']) scope!: string;
@IsString() @MinLength(1) @MaxLength(180) researchTopic!: string;
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(10)
@IsString({ each: true })
@MinLength(1, { each: true })
@MaxLength(500, { each: true })
acceptanceCriteria!: string[];
@IsString() @Matches(/^[a-f0-9]{40}$/) commitSha!: string;
@IsInt() @IsIn([20]) budgetLimitCents!: number;
}
export function isEditorialProposal(task: any): boolean {
return typeof task?.key === 'string' && task.key.startsWith('editorial-v1:');
}
@Injectable()
export class EditorialProposalBridge {
constructor(
private readonly workflow: PrepareWorkflowService,
private readonly db: PrismaService,
) {}
async submit(identity: WorkflowIdentity, dto: EditorialProposalDto) {
if (
identity.role !== 'WORKFLOW_WORKER' ||
identity.id !== EDITORIAL_PMO_WORKER_ID
)
throw new ForbiddenException(
'Explicit canonical PMO worker grant required',
);
if (
!dto.researchTopic.trim() ||
dto.acceptanceCriteria.some((s) => !s.trim())
)
throw new BadRequestException('Nonblank topic and criteria required');
// Narrow server-owned author capability, NEVER a reviewer/SUPER_ADMIN identity.
// The network credential still authenticates WORKFLOW_WORKER; only these two
// fixed create/submit operations are delegated to core's existing Admin API.
const author: WorkflowIdentity = { id: identity.id, role: 'Admin' };
const key =
'editorial-v1:' +
createHash('sha256')
.update(JSON.stringify([identity.id, dto.requestId]))
.digest('hex');
const scope = `${EDITORIAL_PILOT_KIND}\nTopic: ${dto.researchTopic}\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.`;
const proposal = {
key,
title: `Editorial research: ${dto.researchTopic}`,
department: 'CONTENT',
operationMode: 'PREPARE',
budgetLimitCents: 20,
metadata: {
scope,
acceptanceCriteria: dto.acceptanceCriteria,
commitSha: dto.commitSha,
},
};
let task = await this.db.orchestrationTask.findUnique({ where: { key } });
if (!task) {
try {
task = await this.workflow.create(proposal, author);
} catch (e) {
if (!(e instanceof ConflictException)) throw e;
task = await this.db.orchestrationTask.findUnique({ where: { key } });
if (!task) throw e;
}
}
const m = task!.metadata as any;
if (
task!.operationMode !== 'PREPARE' ||
task!.department !== 'CONTENT' ||
task!.budgetLimitCents !== 20 ||
task!.title !== proposal.title ||
m.createdBy !== identity.id ||
m.workflowScope !== 'STAGE_PREPARE' ||
m.environment !== 'staging' ||
m.scope !== scope ||
m.commitSha !== dto.commitSha ||
JSON.stringify(m.acceptanceCriteria) !==
JSON.stringify(dto.acceptanceCriteria)
)
throw new ConflictException('Editorial request payload mismatch');
// Fixed idempotency token/version permits concurrent submits and recovery from
// a crash between existing core create and transition transactions.
if (task!.state === 'DRAFT')
task = await this.workflow.transition(
task!.id,
{
toState: 'GATE1_PENDING',
expectedVersion: 1,
idempotencyKey: `${key}:submit`,
},
author,
);
return {
taskId: task!.id,
key,
pilotKind: EDITORIAL_PILOT_KIND,
state: task!.state,
version: task!.version,
department: 'CONTENT',
operationMode: 'PREPARE',
budgetLimitCents: 20,
metadata: {
scope,
acceptanceCriteria: m.acceptanceCriteria,
environment: 'staging',
commitSha: m.commitSha,
},
};
}
}
@@ -32,6 +32,7 @@ import {
WorkflowIdentity,
} from "../orchestration/prepare-workflow.service";
import { EditorialProposalBridge, EditorialProposalDto, isEditorialProposal } from "./editorial-bridge";
import { admittedTechTask, TECH_PILOT_KIND, techArtifact, validateTechSource } from "./tech-pilot-validator";
// This is reviewed static configuration, not a URL fetched by the transport.
@@ -155,6 +156,7 @@ class WorkerTransportService {
const t = await this.db.orchestrationTask.findUnique({
where: { id: dto.taskId },
});
if (isEditorialProposal(t)) throw new ForbiddenException("Editorial execution requires a separately reviewed executor");
// Explicit per-task pilot scope; never opportunistically consume arbitrary queued work.
if (!t || !["READY", "RUNNING"].includes(t.state)) return { lease: null };
if (t.budgetLimitCents !== 20)
@@ -168,6 +170,7 @@ class WorkerTransportService {
async complete(a: WorkflowIdentity, dto: CompleteDto) {
this.worker(a);
const task = await this.db.orchestrationTask.findUnique({ where: { id: dto.taskId } });
if (isEditorialProposal(task)) throw new ForbiddenException("Editorial execution requires a separately reviewed executor");
if (task?.key === TECH_PILOT_KIND || (task?.metadata as any)?.scope === TECH_PILOT_KIND)
throw new ForbiddenException("Tech pilot requires separate source completion");
// Recheck stop/interrupt and fencing before artifact creation; core rechecks atomically at commit.
@@ -316,7 +319,10 @@ class WorkerTransportService {
}),
)
class WorkerTransportController {
constructor(private readonly service: WorkerTransportService) {}
constructor(private readonly service: WorkerTransportService, private readonly editorial: EditorialProposalBridge) {}
@Post("editorial-proposals") editorialProposal(@Req() req: any, @Body() dto: EditorialProposalDto) {
return this.editorial.submit(req.workerIdentity, dto);
}
@Post("claim") claim(@Req() req: any, @Body() dto: ClaimDto) {
return this.service.claim(req.workerIdentity, dto);
}
@@ -395,6 +401,7 @@ export class WorkerTransportModule {
PrepareWorkflowService,
WorkerIdentityGuard,
WorkerTransportService,
EditorialProposalBridge,
{ provide: CONFIG, useValue: snapshot },
{
provide: PREPARE_WORKFLOW_CONFIG,