Files
canina/backend/src/orchestration-worker/editorial-execution.ts
T
2026-10-24 04:08:17 +00:00

410 lines
13 KiB
TypeScript

import {
BadRequestException,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { IsObject, IsUUID } from 'class-validator';
import { createHash } from 'crypto';
import {
PrepareWorkflowService,
WorkflowIdentity,
} from '../orchestration/prepare-workflow.service';
import { PrismaService } from '../prisma/prisma.service';
import { EDITORIAL_PILOT_KIND } from './editorial-bridge';
export class EditorialClaimDto {
@IsUUID() taskId!: string;
}
export class EditorialResultDto extends EditorialClaimDto {
@IsUUID() runId!: string;
@IsUUID() leaseToken!: string;
@IsObject() brief!: Record<string, unknown>;
}
const suffix =
'\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.';
export function admittedEditorialTask(t: any): boolean {
const m = t?.metadata;
const topic =
typeof t?.title === 'string' && t.title.startsWith('Editorial research: ')
? t.title.slice(20)
: '';
return !!(
t &&
/^editorial-v1:[a-f0-9]{64}$/.test(t.key) &&
t.department === 'CONTENT' &&
t.operationMode === 'PREPARE' &&
t.budgetLimitCents === 20 &&
m?.createdBy === 'pmo' &&
m.workflowScope === 'STAGE_PREPARE' &&
m.environment === 'staging' &&
typeof m.commitSha === 'string' &&
/^[a-f0-9]{40}$/.test(m.commitSha) &&
topic.trim() &&
topic.length <= 180 &&
m.scope === `${EDITORIAL_PILOT_KIND}\nTopic: ${topic}${suffix}` &&
Array.isArray(m.acceptanceCriteria) &&
m.acceptanceCriteria.length >= 1 &&
m.acceptanceCriteria.length <= 10 &&
m.acceptanceCriteria.every(
(x: unknown) => typeof x === 'string' && x.trim() && x.length <= 500,
)
);
}
function keys(v: any, names: string[]) {
return (
v &&
typeof v === 'object' &&
!Array.isArray(v) &&
Object.keys(v).length === names.length &&
names.every((k) => Object.prototype.hasOwnProperty.call(v, k))
);
}
function text(v: any, max: number) {
return typeof v === 'string' && !!v.trim() && v.length <= max;
}
function date(v: any) {
return (
typeof v === 'string' &&
/^\d{4}-\d{2}-\d{2}$/.test(v) &&
Number.isFinite(Date.parse(v)) &&
new Date(v).toISOString().slice(0, 10) === v &&
v <= new Date().toISOString().slice(0, 10)
);
}
function source(v: any) {
try {
if (!text(v, 2000)) return false;
const u = new URL(v);
return (
u.protocol === 'https:' &&
!u.username &&
!u.password &&
!u.port &&
/^[a-z0-9.-]+\.[a-z]{2,}$/.test(u.hostname) &&
!/(^|\.)(localhost|local|internal|lan|home|invalid|test|example)$/.test(
u.hostname,
)
);
} catch {
return false;
}
}
export function validateEditorialBrief(b: any) {
const fail = () => {
throw new BadRequestException(
'Bounded research brief requires dated sources, input availability and 3..10 scored candidates',
);
};
if (
!keys(b, ['researchDate', 'inputAvailability', 'findings', 'candidates']) ||
Buffer.byteLength(JSON.stringify(b), 'utf8') > 24576 ||
!date(b.researchDate)
)
fail();
if (
!Array.isArray(b.inputAvailability) ||
b.inputAvailability.length < 1 ||
b.inputAvailability.length > 10 ||
!b.inputAvailability.every(
(x: any) =>
keys(x, ['input', 'status', 'details']) &&
text(x.input, 120) &&
['AVAILABLE', 'UNAVAILABLE', 'PARTIAL'].includes(x.status) &&
text(x.details, 500),
)
)
fail();
if (
!Array.isArray(b.findings) ||
b.findings.length < 1 ||
b.findings.length > 20 ||
!b.findings.every(
(x: any) =>
keys(x, ['sourceUrl', 'sourceDate', 'finding']) &&
source(x.sourceUrl) &&
date(x.sourceDate) &&
x.sourceDate <= b.researchDate &&
text(x.finding, 1000),
)
)
fail();
const urls = new Set(b.findings.map((x: any) => x.sourceUrl));
if (
!Array.isArray(b.candidates) ||
b.candidates.length < 3 ||
b.candidates.length > 10 ||
!b.candidates.every(
(x: any) =>
keys(x, ['title', 'score', 'rationale', 'sourceUrls']) &&
text(x.title, 180) &&
Number.isInteger(x.score) &&
x.score >= 0 &&
x.score <= 100 &&
text(x.rationale, 1000) &&
Array.isArray(x.sourceUrls) &&
x.sourceUrls.length >= 1 &&
x.sourceUrls.length <= 10 &&
x.sourceUrls.every((u: any) => urls.has(u)),
) ||
new Set(b.candidates.map((x: any) => x.title.trim().toLowerCase())).size !==
b.candidates.length
)
fail();
return JSON.parse(JSON.stringify(b));
}
const kind = 'EDITORIAL_RESEARCH_BRIEF';
const qaStatus = 'PENDING_INDEPENDENT_QA';
@Injectable()
export class EditorialExecutionService {
constructor(private readonly db: PrismaService) {}
private pmo(a: WorkflowIdentity) {
if (a?.role !== 'WORKFLOW_WORKER' || a.id !== 'pmo')
throw new ForbiddenException(
'Explicit canonical PMO worker grant required',
);
}
private async scope(tx: any, id: string) {
if (typeof id !== 'string' || !/^[0-9a-f-]{36}$/i.test(id))
throw new NotFoundException('Editorial proposal not found');
const t = await tx.orchestrationTask.findUnique({ where: { id } });
if (!admittedEditorialTask(t))
throw new NotFoundException('Editorial proposal not found');
const proposed = await tx.orchestrationEvent.findFirst({
where: {
taskId: id,
sequence: 1,
eventType: 'PREPARE_PROPOSED',
actorId: 'pmo',
toState: 'DRAFT',
},
});
const submitted = await tx.orchestrationEvent.findFirst({
where: {
taskId: id,
sequence: 2,
eventType: 'PREPARE_TRANSITION',
actorId: 'pmo',
fromState: 'DRAFT',
toState: 'GATE1_PENDING',
idempotencyKey: t.key + ':submit',
},
});
if (!proposed || !submitted)
throw new NotFoundException('Editorial proposal not found');
return t;
}
private async approval(tx: any, t: any) {
const approval = await tx.orchestrationApprovalDecision.findFirst({
where: { taskId: t.id, gate: 1 },
orderBy: { createdAt: 'desc' },
});
if (
!approval ||
approval.decision !== 'APPROVED' ||
approval.actorId === 'pmo' ||
approval.expiresAt <= new Date()
)
throw new ForbiddenException('Valid independent Gate1 required');
}
private async lock(tx: any, id: string, claim = false) {
const switches =
await tx.$queryRaw`SELECT level, active FROM orchestration_kill_switches WHERE scope = 'GLOBAL' FOR SHARE`;
if (
switches[0]?.active &&
(claim || switches[0].level !== 'FREEZE_NEW_WORK')
)
throw new ForbiddenException('Kill switch blocks workflow');
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${id}::uuid FOR UPDATE`;
const t = await this.scope(tx, id);
await this.approval(tx, t);
return t;
}
async status(a: WorkflowIdentity, id: string) {
this.pmo(a);
return this.db.$transaction(async (tx: any) => {
const t = await this.scope(tx, id);
const artifacts = await tx.orchestrationArtifact.findMany({
where: { kind, run: { taskId: id } },
orderBy: { createdAt: 'desc' },
take: 1,
});
const artifact = artifacts[0];
let result: any = null;
if (artifact) {
const bytes = artifact.metadata?.bytes;
if (
typeof bytes !== 'string' ||
Buffer.byteLength(bytes) > 32768 ||
createHash('sha256').update(bytes).digest('hex') !== artifact.sha256
)
throw new ForbiddenException('Artifact integrity mismatch');
const parsed = JSON.parse(bytes);
if (
parsed.taskId !== t.id ||
parsed.runId !== artifact.runId ||
parsed.commitSha !== t.metadata.commitSha
)
throw new ForbiddenException('Artifact binding mismatch');
result = { kind, sha256: artifact.sha256, bytes, brief: parsed.brief };
}
return {
taskId: t.id,
pilotKind: EDITORIAL_PILOT_KIND,
state: t.state,
version: t.version,
operationMode: t.operationMode,
budgetLimitCents: 20,
qaStatus,
metadata: {
scope: t.metadata.scope,
acceptanceCriteria: t.metadata.acceptanceCriteria,
commitSha: t.metadata.commitSha,
environment: 'staging',
},
artifact: result,
};
});
}
async claim(a: WorkflowIdentity, dto: EditorialClaimDto) {
this.pmo(a);
return this.db.$transaction(async (tx: any) => {
const t = await this.lock(tx, dto.taskId, true);
if (!['READY', 'RUNNING'].includes(t.state))
throw new ForbiddenException('Ready editorial proposal required');
// Reuse core claim/reservation/lease algorithm in THIS scoped transaction. No
// nested transaction or check-then-claim gap: task lock spans admission/claim.
const core = new PrepareWorkflowService(
new Proxy(tx, {
get(target, key) {
if (key === '$transaction') return (fn: any) => fn(tx);
const value = target[key];
return typeof value === 'function' ? value.bind(target) : value;
},
}),
{ workerIds: ['pmo'], stageCiIds: [] },
);
const lease = await core.claim(a, t.id);
return {
lease: lease ? { ...lease, pilotKind: EDITORIAL_PILOT_KIND } : null,
};
});
}
async result(a: WorkflowIdentity, dto: EditorialResultDto) {
this.pmo(a);
const brief = validateEditorialBrief(dto.brief);
// Core complete writes a passed QA attestation and reconciles supplied costs.
// It is deliberately NOT reused for unreviewed research or unknown cost.
return this.db.$transaction(async (tx: any) => {
const t = await this.lock(tx, dto.taskId);
const o = await tx.prepareWorkflowOutbox.findUnique({
where: { taskId: t.id },
});
const r = await tx.orchestrationRun.findUnique({
where: { id: dto.runId },
});
if (
t.state !== 'RUNNING' ||
!o ||
o.status !== 'PENDING' ||
o.leaseOwner !== a.id ||
o.leaseToken !== dto.leaseToken ||
o.runId !== dto.runId ||
!o.leaseUntil ||
o.leaseUntil <= new Date() ||
!r ||
r.taskId !== t.id ||
r.status !== 'RUNNING' ||
r.environment !== 'staging' ||
r.commitSha !== t.metadata.commitSha
)
throw new ForbiddenException('Active owned editorial lease required');
const reserve = await tx.orchestrationBudgetLedger.findUnique({
where: { id: o.reservationId },
});
const ledger = await tx.orchestrationBudgetLedger.aggregate({
where: { taskId: t.id },
_sum: { amountCents: true },
});
if (
!reserve ||
reserve.taskId !== t.id ||
reserve.actorId !== a.id ||
reserve.kind !== 'RESERVE' ||
reserve.amountCents !== 20 ||
reserve.idempotencyKey !== `prepare-reserve:${r.id}` ||
ledger._sum.amountCents !== 20 ||
(await tx.orchestrationBudgetLedger.findFirst({
where: { taskId: t.id, kind: 'RECONCILE' },
}))
)
throw new ForbiddenException(
'Unreconciled owned 20 cent reservation required',
);
const bytes = JSON.stringify({
kind,
pilotKind: EDITORIAL_PILOT_KIND,
schemaVersion: 1,
taskId: t.id,
runId: r.id,
commitSha: r.commitSha,
environment: 'staging',
qaStatus,
costStatus: 'upper-bound-reserved',
brief,
});
const hash = createHash('sha256').update(bytes).digest('hex');
// Canonical bytes live in append-only DB artifact metadata, not a caller URI
// or mutable external file. PMO status is the authenticated retrieval path.
await tx.orchestrationArtifact.create({
data: {
runId: r.id,
kind,
sha256: hash,
uri: `urn:canina:editorial-brief:sha256:${hash}`,
sizeBytes: Buffer.byteLength(bytes),
metadata: { bytes, qaStatus, costStatus: 'upper-bound-reserved' },
},
});
await tx.orchestrationRun.update({
where: { id: r.id },
data: { status: 'AWAITING_QA', finishedAt: new Date() },
});
await tx.prepareWorkflowOutbox.update({
where: { id: o.id },
data: { status: 'DONE', leaseToken: null, leaseUntil: null },
});
const updated = await tx.orchestrationTask.update({
where: { id: t.id },
data: { state: 'VERIFYING', version: { increment: 1 } },
});
await tx.orchestrationEvent.create({
data: {
taskId: t.id,
sequence: updated.version,
actorId: a.id,
eventType: 'EDITORIAL_BRIEF_RECEIVED',
fromState: t.state,
toState: 'VERIFYING',
idempotencyKey: `editorial-result:${r.id}`,
payload: {
artifactSha256: hash,
qaStatus,
costStatus: 'upper-bound-reserved',
retainedReservationCents: 20,
},
},
});
return {
taskId: t.id,
runId: r.id,
state: updated.state,
artifactSha256: hash,
qaStatus,
costStatus: 'upper-bound-reserved',
retainedReservationCents: 20,
};
});
}
}