Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dfeab874a | ||
|
|
bfb1841370 | ||
|
|
6ba2c51403 | ||
|
|
ba0aa5ee4e | ||
|
|
7485c89e9b | ||
|
|
8869ce2583 | ||
|
|
64419f6755 | ||
|
|
8cedc2cd67 | ||
|
|
65a6fe1f0c | ||
|
|
afbee9cf70 | ||
|
|
5984242ce4 | ||
|
|
c523acc9e8 | ||
|
|
c78bdbcdb5 | ||
|
|
7a081e28df | ||
|
|
93d43fb261 | ||
|
|
8c435ab09e | ||
|
|
4388a5c2e6 | ||
|
|
62a7a87378 | ||
|
|
19583c5ad8 | ||
|
|
1858eba3e6 | ||
|
|
cb20c2acb5 | ||
|
|
105ab07fbd | ||
|
|
bf84e5da43 | ||
|
|
02badd0e25 | ||
|
|
aa23c7ef91 |
No files matched your search
@@ -49,6 +49,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app .
|
||||
COPY --from=admin-builder /app/dist ./admin_static
|
||||
# Build-context umask must not make public assets unreadable by nginx workers.
|
||||
RUN chmod -R a+rX /app/admin_static
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("admin users list contract", () => {
|
||||
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
|
||||
let service: AdminService;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdminService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: RedisService, useValue: {} },
|
||||
{ provide: RevalidationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AdminService);
|
||||
});
|
||||
|
||||
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
|
||||
// Deliberately return extra fields even if the query selects safely.
|
||||
prisma.user.findMany.mockResolvedValue([{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User",
|
||||
mobile: "fixture-mobile", email: null, role: "ADMIN",
|
||||
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
password: "test-only-password-hash", passwordHash: "test-only-hash",
|
||||
refreshToken: "test-only-token", futureSecret: "must-not-leak",
|
||||
walletTransactions: [{ transactionReference: "private-reference" }],
|
||||
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
|
||||
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
|
||||
}]);
|
||||
prisma.user.count.mockResolvedValue(11);
|
||||
const controller = new AdminController(service, {} as never);
|
||||
const result = await controller.getUsers({ page: 2, limit: 10 });
|
||||
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
|
||||
expect(body).toEqual({
|
||||
data: [{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
|
||||
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
|
||||
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
|
||||
}],
|
||||
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
|
||||
});
|
||||
const query = prisma.user.findMany.mock.calls[0][0];
|
||||
expect(query.select).toBeDefined();
|
||||
expect(query.select.password).toBeUndefined();
|
||||
expect(query.include).toBeUndefined();
|
||||
expect(query.skip).toBe(10);
|
||||
});
|
||||
|
||||
it("preserves the empty paginated list contract and filters", async () => {
|
||||
prisma.user.findMany.mockResolvedValue([]);
|
||||
prisma.user.count.mockResolvedValue(0);
|
||||
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
|
||||
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
|
||||
});
|
||||
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -168,12 +168,17 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,9 +202,19 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const { orders: _orders, ...rest } = u;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
return {
|
||||
...rest,
|
||||
id: u.id,
|
||||
firstName: u.firstName,
|
||||
lastName: u.lastName,
|
||||
mobile: u.mobile,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
walletBalance: u.walletBalance,
|
||||
charityDonationTotal: u.charityDonationTotal,
|
||||
createdAt: u.createdAt,
|
||||
addresses: u.addresses,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
|
||||
@@ -24,7 +24,8 @@ export class HermesSessionBroker {
|
||||
const body=JSON.parse(Buffer.concat(chunks).toString('utf8')) as {ok?:unknown};
|
||||
const cookies=response.headers.getSetCookie();
|
||||
const cookie=cookies.find(c=>c.startsWith('hermes_session_at='));
|
||||
const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1];
|
||||
const tokenMatch=cookie?.match(/^hermes_session_at=(?:"([A-Za-z0-9_.=-]+)"|([A-Za-z0-9_.=-]+));/);
|
||||
const token=tokenMatch?.[1]??tokenMatch?.[2];
|
||||
const age=Number(cookie?.match(/(?:^|;)\s*Max-Age=(\d+)/i)?.[1]);
|
||||
if(body.ok!==true || !token || !Number.isSafeInteger(age) || age<30)throw new HermesError('AUTH_REQUIRED');
|
||||
this.cached={token,until:Date.now()+Math.min(age-10,300)*1000};
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Bounded editorial approved-run contract
|
||||
|
||||
Only the explicitly configured WORKFLOW_WORKER grant `pmo` may use these routes under `/api/internal/prepare-worker` (the application's prefix supplies `/api`). No new credential or reviewer grant is provisioned here.
|
||||
|
||||
- `GET editorial-proposals/:taskId`: exact bridge-created proposal status and, after ingestion, canonical immutable brief bytes/digest. No lease token, raw events, reviewer identities or arbitrary task projection.
|
||||
- `POST editorial-claim`: `{ "taskId": "<uuid>" }`. Requires exact bridge key/title/scope/metadata plus original PMO creation/submission events, READY/RUNNING, latest independent unexpired approved Gate1, no blocking kill switch. Core claim runs inside the same admission/task-lock transaction, preserving reservations, ownership and 30-second leases. Competing claim returns null lease. Expired attempts retain unknown reservation; a 20-cent task cannot reserve a second 20 cents.
|
||||
- `POST heartbeat`: existing `{taskId,runId,leaseToken}` while working. Extends lease by 30 seconds. Result rechecks Gate1 independently; heartbeat is not approval extension.
|
||||
- `POST editorial-result`: `{taskId,runId,leaseToken,brief}`. No cost, QA pass, role, URI or caller identity fields accepted.
|
||||
|
||||
`brief` has exactly:
|
||||
|
||||
```json
|
||||
{
|
||||
"researchDate": "YYYY-MM-DD",
|
||||
"inputAvailability": [{"input":"input name","status":"AVAILABLE|UNAVAILABLE|PARTIAL","details":"availability explanation"}],
|
||||
"findings": [{"sourceUrl":"https://public-source.example.org/path","sourceDate":"YYYY-MM-DD","finding":"source-backed finding"}],
|
||||
"candidates": [
|
||||
{"title":"Distinct candidate A","score":80,"rationale":"Reason","sourceUrls":["https://public-source.example.org/path"]},
|
||||
{"title":"Distinct candidate B","score":70,"rationale":"Reason","sourceUrls":["https://public-source.example.org/path"]},
|
||||
{"title":"Distinct candidate C","score":60,"rationale":"Reason","sourceUrls":["https://public-source.example.org/path"]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Limits: canonical brief UTF-8 <=24,576 bytes; 1..10 inputs (name 120/details 500 characters); 1..20 findings (HTTPS DNS URL 2000/finding 1000 characters); 3..10 unique candidates (title 180/rationale 1000, integer score 0..100, 1..10 source references all in findings). Dates must be valid calendar dates, not future; source dates cannot exceed research date. Unknown nested keys rejected. Example URLs above illustrate shape only, not real research evidence.
|
||||
|
||||
Canonical artifact kind `EDITORIAL_RESEARCH_BRIEF` is stored in append-only artifact metadata with SHA-256 and a URN; authenticated status retrieves actual bytes. No filesystem/external URL persistence dependency. Transaction atomically checks task/approval/lease/run/reservation, inserts evidence/event, closes outbox and moves task to VERIFYING. Run is AWAITING_QA, quality PENDING_INDEPENDENT_QA; no attestation, success, publication, Gate2 or release authorization is created. Unknown cost retains RESERVE 20 without RECONCILE. Replay after lease closure is rejected, not silently overwritten.
|
||||
|
||||
Validation checks structure/source references, not source truth, retrieval, novelty, scoring quality, SEO value or factuality. No research/article/LLM execution is performed by this contract. Independent QA ingestion is deliberately not implemented; generic tracer/tech and Stage evidence cannot certify this evidence.
|
||||
|
||||
Verification: disposable Node22 + PostgreSQL16, source/dependency donors read-only and privately copied, generated Prisma client. New suite observed RED (missing routes) then GREEN. Final combined bridge/execution/tech/transport suites: 22/22; `npm run build`: exit 0. Full historical migrations fail on fresh database because pre-existing blog migration expects missing blogs table; final tests instead applied only real orchestration core, immutable-ledger and outbox migrations directly to empty disposable DB, including append-only triggers. No live database, proposal approval, cron, deployment or publication used.
|
||||
@@ -0,0 +1,387 @@
|
||||
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, tracerReport } from './worker-transport.module';
|
||||
|
||||
(process.env.EDITORIAL_EXECUTION_DB === '1' ? describe : describe.skip)(
|
||||
'editorial approved-run real TCP/PostgreSQL',
|
||||
() => {
|
||||
const db = new PrismaClient();
|
||||
const token = 'disposable-editorial-pmo-'.repeat(3),
|
||||
other = 'disposable-other-editor-'.repeat(3),
|
||||
ci = 'disposable-editorial-ci-'.repeat(3);
|
||||
const sha = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
let app: INestApplication, base: string, workflow: PrepareWorkflowService;
|
||||
const brief = () => ({
|
||||
researchDate: '2026-10-24',
|
||||
inputAvailability: [
|
||||
{
|
||||
input: 'search console',
|
||||
status: 'UNAVAILABLE',
|
||||
details: 'No authenticated property supplied',
|
||||
},
|
||||
],
|
||||
findings: [
|
||||
{
|
||||
sourceUrl: 'https://www.who.int/news',
|
||||
sourceDate: '2026-10-20',
|
||||
finding: 'Fixture finding for contract testing, not real research',
|
||||
},
|
||||
],
|
||||
candidates: [0, 1, 2].map((i) => ({
|
||||
title: 'Fixture candidate ' + i,
|
||||
score: 80 - i,
|
||||
rationale: 'Contract fixture only',
|
||||
sourceUrls: ['https://www.who.int/news'],
|
||||
})),
|
||||
});
|
||||
beforeAll(async () => {
|
||||
const m = await Test.createTestingModule({
|
||||
imports: [
|
||||
WorkerTransportModule.register({
|
||||
enabled: true,
|
||||
grants: [
|
||||
{
|
||||
id: 'pmo',
|
||||
role: 'WORKFLOW_WORKER',
|
||||
credentialSha256: sha(token),
|
||||
},
|
||||
{
|
||||
id: 'other',
|
||||
role: 'WORKFLOW_WORKER',
|
||||
credentialSha256: sha(other),
|
||||
},
|
||||
{ id: 'ci', role: 'STAGE_CI', credentialSha256: sha(ci) },
|
||||
],
|
||||
workerIds: ['pmo', 'other'],
|
||||
stageCiIds: ['ci'],
|
||||
artifactDirectory: '/work/tmp/editorial-execution',
|
||||
artifactBaseUrl:
|
||||
'https://isolated.invalid/internal/prepare-worker/artifacts',
|
||||
}),
|
||||
],
|
||||
})
|
||||
.overrideProvider(PrismaService)
|
||||
.useValue(db)
|
||||
.compile();
|
||||
app = m.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
base = await app.getUrl();
|
||||
workflow = app.get(PrepareWorkflowService);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await db.$disconnect();
|
||||
});
|
||||
async function request(route: string, body?: any, secret = token) {
|
||||
const r = await fetch(base + '/internal/prepare-worker/' + route, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
headers: {
|
||||
authorization: 'Bearer ' + secret,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
return { status: r.status, body: await r.json() };
|
||||
}
|
||||
async function proposal(ready = true, ttl = 60000) {
|
||||
const r = await request('editorial-proposals', {
|
||||
requestId: randomUUID(),
|
||||
pilotKind: 'editorial-research-to-brief-v1',
|
||||
operationMode: 'PREPARE',
|
||||
environment: 'staging',
|
||||
scope: 'EDITORIAL_RESEARCH_TO_BRIEF',
|
||||
researchTopic: 'Disposable research contract',
|
||||
acceptanceCriteria: ['Evidence with dates'],
|
||||
commitSha: 'a'.repeat(40),
|
||||
budgetLimitCents: 20,
|
||||
});
|
||||
expect(r.status).toBe(201);
|
||||
let t = await db.orchestrationTask.findUniqueOrThrow({
|
||||
where: { id: r.body.taskId },
|
||||
});
|
||||
if (ready) {
|
||||
t = await workflow.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expiresAt: new Date(Date.now() + ttl).toISOString(),
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: randomUUID(),
|
||||
},
|
||||
{ id: 'independent-disposable-reviewer', role: 'SUPER_ADMIN' },
|
||||
);
|
||||
t = await workflow.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'READY',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: randomUUID(),
|
||||
},
|
||||
{ id: 'pmo', role: 'Admin' },
|
||||
);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
async function lease(ttl = 60000) {
|
||||
const t = await proposal(true, ttl);
|
||||
const r = await request('editorial-claim', { taskId: t.id });
|
||||
expect(r.status).toBe(201);
|
||||
expect(r.body.lease).toBeTruthy();
|
||||
const l = r.body.lease;
|
||||
return {
|
||||
t,
|
||||
l,
|
||||
b: { taskId: t.id, runId: l.runId, leaseToken: l.leaseToken },
|
||||
};
|
||||
}
|
||||
it('projects only owned exact proposals and refuses pending dispatch', async () => {
|
||||
const t = await proposal(false);
|
||||
const p = await request('editorial-proposals/' + t.id);
|
||||
expect(p.status).toBe(200);
|
||||
expect(p.body).toMatchObject({
|
||||
taskId: t.id,
|
||||
state: 'GATE1_PENDING',
|
||||
qaStatus: 'PENDING_INDEPENDENT_QA',
|
||||
});
|
||||
expect(JSON.stringify(p.body)).not.toMatch(
|
||||
/leaseToken|credential|createdBy|fingerprint/,
|
||||
);
|
||||
expect((await request('editorial-claim', { taskId: t.id })).status).toBe(
|
||||
403,
|
||||
);
|
||||
expect(
|
||||
(await request('editorial-proposals/' + t.id, undefined, other)).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
(await request('editorial-proposals/' + randomUUID())).status,
|
||||
).toBe(404);
|
||||
});
|
||||
it('races claims, ingests immutable bounded brief, never self-attests QA or reconciles unknown cost', async () => {
|
||||
const t = await proposal();
|
||||
const claims = await Promise.all([
|
||||
request('editorial-claim', { taskId: t.id }),
|
||||
request('editorial-claim', { taskId: t.id }),
|
||||
]);
|
||||
const leases = claims.filter((x) => x.body.lease);
|
||||
expect(leases).toHaveLength(1);
|
||||
const l = leases[0].body.lease,
|
||||
b = { taskId: t.id, runId: l.runId, leaseToken: l.leaseToken };
|
||||
expect((await request('heartbeat', b)).status).toBe(201);
|
||||
expect((await request('claim', { taskId: t.id })).status).toBe(403);
|
||||
expect((await request('tech-claim', { taskId: t.id })).status).toBe(403);
|
||||
expect(
|
||||
(await request('complete', { ...b, report: tracerReport(l) })).status,
|
||||
).toBe(403);
|
||||
const r = await request('editorial-result', { ...b, brief: brief() });
|
||||
expect(r.status).toBe(201);
|
||||
expect(r.body).toMatchObject({
|
||||
state: 'VERIFYING',
|
||||
qaStatus: 'PENDING_INDEPENDENT_QA',
|
||||
retainedReservationCents: 20,
|
||||
});
|
||||
const p = await request('editorial-proposals/' + t.id);
|
||||
expect(p.body.artifact.brief).toEqual(brief());
|
||||
expect(sha(p.body.artifact.bytes)).toBe(r.body.artifactSha256);
|
||||
await expect(
|
||||
db.orchestrationArtifact.updateMany({
|
||||
where: { runId: l.runId },
|
||||
data: { metadata: { bytes: 'tampered' } },
|
||||
}),
|
||||
).rejects.toThrow('append-only');
|
||||
expect(JSON.parse(p.body.artifact.bytes)).toMatchObject({
|
||||
taskId: t.id,
|
||||
runId: l.runId,
|
||||
brief: brief(),
|
||||
});
|
||||
expect(
|
||||
await db.orchestrationAttestation.count({ where: { runId: l.runId } }),
|
||||
).toBe(0);
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationRun.findUniqueOrThrow({
|
||||
where: { id: l.runId },
|
||||
})
|
||||
).status,
|
||||
).toBe('AWAITING_QA');
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationBudgetLedger.findMany({
|
||||
where: { taskId: t.id },
|
||||
})
|
||||
).map((x) => [x.kind, x.amountCents]),
|
||||
).toEqual([['RESERVE', 20]]);
|
||||
expect(
|
||||
(await request('editorial-result', { ...b, brief: brief() })).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await request(
|
||||
'stage-evidence',
|
||||
{
|
||||
taskId: t.id,
|
||||
runId: l.runId,
|
||||
commitSha: l.commitSha,
|
||||
sha256: r.body.artifactSha256,
|
||||
evidenceSha256: 'b'.repeat(64),
|
||||
uri: 'https://isolated.invalid/fixture',
|
||||
},
|
||||
ci,
|
||||
)
|
||||
).status,
|
||||
).toBe(403);
|
||||
});
|
||||
it('rejects impersonation, unsafe or incomplete briefs, and expired ownership without artifacts', async () => {
|
||||
const { l, b } = await lease();
|
||||
for (const secret of [other, ci])
|
||||
expect(
|
||||
(await request('editorial-result', { ...b, brief: brief() }, secret))
|
||||
.status,
|
||||
).toBe(403);
|
||||
for (const patch of [
|
||||
{ actualCents: 0 },
|
||||
{ qa: { passed: true } },
|
||||
{ actorId: 'pmo' },
|
||||
])
|
||||
expect(
|
||||
(
|
||||
await request('editorial-result', {
|
||||
...b,
|
||||
brief: brief(),
|
||||
...patch,
|
||||
})
|
||||
).status,
|
||||
).toBe(400);
|
||||
for (const bad of [
|
||||
{ ...brief(), candidates: brief().candidates.slice(0, 2) },
|
||||
{ ...brief(), researchDate: '2026-02-30' },
|
||||
{
|
||||
...brief(),
|
||||
findings: [
|
||||
{
|
||||
sourceUrl: 'http://127.0.0.1',
|
||||
sourceDate: '2026-10-20',
|
||||
finding: 'x',
|
||||
},
|
||||
],
|
||||
},
|
||||
{ ...brief(), inputAvailability: [] },
|
||||
{
|
||||
...brief(),
|
||||
candidates: brief().candidates.map((c) => ({ ...c, score: 101 })),
|
||||
},
|
||||
{ ...brief(), article: 'not allowed' },
|
||||
])
|
||||
expect(
|
||||
(await request('editorial-result', { ...b, brief: bad })).status,
|
||||
).toBe(400);
|
||||
expect(
|
||||
(
|
||||
await request('editorial-result', {
|
||||
...b,
|
||||
leaseToken: randomUUID(),
|
||||
brief: brief(),
|
||||
})
|
||||
).status,
|
||||
).toBe(403);
|
||||
await db.prepareWorkflowOutbox.update({
|
||||
where: { taskId: b.taskId },
|
||||
data: { leaseUntil: new Date(Date.now() - 1000) },
|
||||
});
|
||||
expect(
|
||||
(await request('editorial-result', { ...b, brief: brief() })).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
(await request('editorial-claim', { taskId: b.taskId })).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
await db.orchestrationArtifact.count({ where: { runId: l.runId } }),
|
||||
).toBe(0);
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.count({
|
||||
where: { taskId: b.taskId },
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
it('enforces cancellation, approval expiry and kill switch inside ingestion', async () => {
|
||||
for (const mode of ['cancel', 'approval', 'kill']) {
|
||||
const { l, b } = await lease(mode === 'approval' ? 1500 : 60000);
|
||||
if (mode === 'cancel')
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: b.taskId },
|
||||
data: { state: 'CANCELLED' },
|
||||
});
|
||||
if (mode === 'approval')
|
||||
await new Promise((resolve) => setTimeout(resolve, 1600));
|
||||
if (mode === 'kill')
|
||||
await db.orchestrationKillSwitch.upsert({
|
||||
where: { scope: 'GLOBAL' },
|
||||
create: {
|
||||
scope: 'GLOBAL',
|
||||
level: 'STOP_AGENTS',
|
||||
active: true,
|
||||
reason: 'disposable execution test',
|
||||
actorId: 'fixture',
|
||||
},
|
||||
update: { level: 'STOP_AGENTS', active: true },
|
||||
});
|
||||
try {
|
||||
expect(
|
||||
(await request('editorial-result', { ...b, brief: brief() }))
|
||||
.status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
await db.orchestrationArtifact.count({ where: { runId: l.runId } }),
|
||||
).toBe(0);
|
||||
} finally {
|
||||
if (mode === 'kill')
|
||||
await db.orchestrationKillSwitch.update({
|
||||
where: { scope: 'GLOBAL' },
|
||||
data: { active: false },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
it('rejects arbitrary CONTENT tasks and forged stored scope/provenance', async () => {
|
||||
const raw = await workflow.create(
|
||||
{
|
||||
key: 'arbitrary-' + randomUUID(),
|
||||
title: 'arbitrary',
|
||||
department: 'CONTENT',
|
||||
operationMode: 'PREPARE',
|
||||
budgetLimitCents: 20,
|
||||
metadata: {
|
||||
scope: 'editorial-research-to-brief-v1',
|
||||
commitSha: 'a'.repeat(40),
|
||||
acceptanceCriteria: ['x'],
|
||||
},
|
||||
},
|
||||
{ id: 'pmo', role: 'Admin' },
|
||||
);
|
||||
expect((await request('editorial-proposals/' + raw.id)).status).toBe(404);
|
||||
expect(
|
||||
(await request('editorial-claim', { taskId: raw.id })).status,
|
||||
).toBe(404);
|
||||
const t = await proposal();
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: t.id },
|
||||
data: {
|
||||
metadata: {
|
||||
...(t.metadata as any),
|
||||
scope: 'editorial-research-to-brief-v1\nforged',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((await request('editorial-claim', { taskId: t.id })).status).toBe(
|
||||
404,
|
||||
);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
0,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,409 @@
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Tech fixture ingestion adapter contract
|
||||
|
||||
Separate fixed pilot, never application QA, deployment evidence, Gate2 or release authorization.
|
||||
|
||||
## Frozen HTTP contract
|
||||
|
||||
Authenticated worker Bearer credential (same guard/config as existing transport):
|
||||
|
||||
- `POST /internal/prepare-worker/tech-claim` body `{taskId: UUID}` -> `{lease:null | {...existingLease,pilotKind:"tech-dev-clamp-quantity-v1"}}`.
|
||||
- `POST /internal/prepare-worker/heartbeat` body `{taskId,runId,leaseToken}` unchanged.
|
||||
- `POST /internal/prepare-worker/tech-complete` body **only** `{taskId:UUID,runId:UUID,leaseToken:UUID,source:string}`. Source max2048 characters AND UTF-8 bytes. Returns `{taskId,runId,state:"VERIFYING",artifactSha256,costStatus:"upper-bound-reserved"}`.
|
||||
- `GET /internal/prepare-worker/artifacts/<artifactSha256>` authenticated own-worker or independent Stage CI. Returns canonical JSON containing actual source, run/commit binding, server QA9, sourceSha256, `applicationQa:false`, `retainedReservationCents:20`, and costStatus. Hash is over canonical stored JSON, not source bytes; source digest is in `qa.sourceSha256`.
|
||||
|
||||
Stored task admission requires exact key AND metadata.scope `tech-dev-clamp-quantity-v1`, department TECH, PREPARE, budget20, workflowScope STAGE_PREPARE, environment staging and immutable40hex commit. Existing Gate1/READY workflow must be used. No body pilotKind/scope/pass/cost/URI/identity accepted. Task IDs never authorize themselves. Generic tracer completion refuses Tech key or scope so it cannot reconcile unknown provider cost as zero.
|
||||
|
||||
## Parent adapter wiring
|
||||
|
||||
After independent Gate1/READY and provider cap approval, call tech-claim, require pilotKind and existing lease bounds, and pass only the original executor lease fields to `infra/hermes-pilot/executor.py` (strip pilotKind because executor uses strict fields). Reuse authenticated heartbeat with <=5s network deadline/no retry and ongoing executor fencing. On successful local executor result, read actual quantity.py (not a report/QA claim) bounded2048 and submit exact source with original binding to tech-complete. Backend independently parses/interprets a fixed expression grammar without executing Python or any subprocess. It accepts only one clamp_quantity(quantity) function with a single nested min/max/0..99/quantity return. Depth32/nodes128/source2048 bound computation; nine boundary cases must pass. This intentionally narrower grammar can reject Python that local AST QA accepts; fail closed, do not rewrite model source.
|
||||
|
||||
Retain the existing20-cent RESERVE unchanged: no RECONCILE row, actualCents or measured-cost claim. Server creates TECH_PILOT_SOURCE artifact and TECH_PILOT_FIXTURE_QA attestation signed server-bounded-minmax-v1. No generic QA/TEST attestation. State VERIFYING is fixture completion, not application acceptance. Independent CI remains separate and must not infer application QA from this artifact.
|
||||
|
||||
Descriptor-relative O_EXCL/O_NOFOLLOW immutable content storage and bounded authenticated digest/binding checks are reused. Source max2048, artifact JSON read max8192 for escaping/envelope. Same-UID/root storage attackers remain outside boundary. File-before-transaction can leave an unregistered unreadable orphan on cancellation/races; no automatic overwrite/retry. Exact stored task mutation is rechecked at commit, but operational task metadata/key mutation must remain forbidden after review.
|
||||
|
||||
## Verification
|
||||
|
||||
Run existing `WORKER_EVIDENCE_DIR=/opt/services/canina/validation/v4-tech-ingestion bash infra/hermes-worker/test-isolated.sh green-final` from this worktree. Disposable PostgreSQL16/no published ports/no live volumes, real Nest TCP HTTP, existing child executor regression and backend build. Evidence includes red.log (missing route404), tracer-bypass-red.log (old endpoint201 instead of403), green-final.log and build.log. No model/provider call, live database/runtime edit, push, deployment or RELEASE_AUTHORIZE was performed.
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PrepareWorkflowService } from '../orchestration/prepare-workflow.service';
|
||||
import { WorkerTransportModule, tracerReport } from './worker-transport.module';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { mkdtemp, rm, readFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
const enabled = process.env.WORKER_TRANSPORT_DB === '1';
|
||||
(enabled ? describe : describe.skip)('real TCP tech artifact ingestion with PostgreSQL', () => {
|
||||
const db = new PrismaClient();
|
||||
const token = 'test-tech-worker-secret-'.repeat(3), other = 'test-other-worker-secret-'.repeat(3), ci = 'test-ci-secret-'.repeat(3);
|
||||
const sha = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
let app: INestApplication, workflow: PrepareWorkflowService, base: string, directory: string;
|
||||
const kind = 'tech-dev-clamp-quantity-v1';
|
||||
const source = 'def clamp_quantity(quantity):\n return max(0, min(quantity, 99))\n';
|
||||
const owner = {id:'tech-author',role:'Admin'}, reviewer = {id:'tech-reviewer',role:'SUPER_ADMIN'};
|
||||
beforeAll(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), 'tech-artifacts-'));
|
||||
const mod = await Test.createTestingModule({imports:[WorkerTransportModule.register({enabled:true, grants:[{id:'tech',role:'WORKFLOW_WORKER',credentialSha256:sha(token)},{id:'other',role:'WORKFLOW_WORKER',credentialSha256:sha(other)},{id:'ci',role:'STAGE_CI',credentialSha256:sha(ci)}],workerIds:['tech','other'],stageCiIds:['ci'],artifactDirectory:directory,artifactBaseUrl:'https://isolated.invalid/internal/prepare-worker/artifacts'})]}).overrideProvider(PrismaService).useValue(db).compile();
|
||||
workflow = mod.get(PrepareWorkflowService); app = mod.createNestApplication(); await app.listen(0,'127.0.0.1'); base = await app.getUrl();
|
||||
});
|
||||
afterAll(async () => {await app?.close(); await db.$disconnect(); if(directory) await rm(directory,{recursive:true,force:true});});
|
||||
async function post(route: string, body: any, secret=token) {const r=await fetch(base+'/internal/prepare-worker/'+route,{method:'POST',headers:{authorization:'Bearer '+secret,'content-type':'application/json'},body:JSON.stringify(body)});return {status:r.status,body:await r.json()};}
|
||||
async function get(hash: string, secret=token) {const r=await fetch(base+'/internal/prepare-worker/artifacts/'+hash,{headers:{authorization:'Bearer '+secret}});return {status:r.status,body:await r.json()};}
|
||||
async function task(key=kind, scope=kind, ready=true) {
|
||||
// Exact reviewed key is unique; old fixture rows are never reused as admission.
|
||||
if(key===kind) { const existing=await db.orchestrationTask.findUnique({where:{key}}); if(existing) await db.orchestrationTask.update({where:{id:existing.id},data:{key:'used-'+randomUUID()}}); }
|
||||
let t=await workflow.create({key,title:'quantity fixture only',department:'TECH',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope,acceptanceCriteria:['quantity fixture only; not application QA']}},owner);
|
||||
if(ready) {t=await workflow.transition(t.id,{toState:'GATE1_PENDING',expectedVersion:t.version,idempotencyKey:randomUUID()},owner);t=await workflow.decide(t.id,1,{decision:'APPROVED',expiresAt:new Date(Date.now()+60000).toISOString(),expectedVersion:t.version,idempotencyKey:randomUUID()},reviewer);t=await workflow.transition(t.id,{toState:'READY',expectedVersion:t.version,idempotencyKey:randomUUID()},owner);}
|
||||
return t;
|
||||
}
|
||||
it('rejects unreviewed stored key/scope and cannot dispatch before Gate1',async()=>{
|
||||
for(const [key,scope] of [[randomUUID(),kind],[kind,'other scope']]) {const t=await task(key,scope);expect((await post('tech-claim',{taskId:t.id})).status).toBe(403);expect(await db.orchestrationRun.count({where:{taskId:t.id}})).toBe(0);}
|
||||
const t=await task(kind,kind,false);const r=await post('tech-claim',{taskId:t.id});expect(r.status).toBe(201);expect(r.body.lease).toBeNull();expect(await db.orchestrationRun.count({where:{taskId:t.id}})).toBe(0);
|
||||
});
|
||||
it('fences callers, rejects arbitrary source/fields and retains budget on denial',async()=>{
|
||||
const t=await task();const claims=await Promise.all([post('tech-claim',{taskId:t.id}),post('tech-claim',{taskId:t.id})]);const leases=claims.filter(x=>x.body.lease);expect(leases).toHaveLength(1);const l=leases[0].body.lease;const b={taskId:t.id,runId:l.runId,leaseToken:l.leaseToken};
|
||||
expect((await post('tech-complete',{...b,source},ci)).status).toBe(403);expect((await post('tech-complete',{...b,source},other)).status).toBe(403);expect((await post('tech-complete',{...b,leaseToken:randomUUID(),source})).status).toBe(403);
|
||||
for(const bad of ['import os\n'+source, 'def clamp_quantity(quantity):\n return 0\n', 'def clamp_quantity(quantity):\n return __import__("os")\n', 'def clamp_quantity(quantity):\n return min(quantity,99)\n','x'.repeat(2049), 12]) expect((await post('tech-complete',{...b,source:bad})).status).toBe(400);
|
||||
for(const extra of [{actualCents:0},{qa:{passed:true}},{uri:'https://fake.invalid'},{role:'STAGE_CI'}]) expect((await post('tech-complete',{...b,source,...extra})).status).toBe(400);
|
||||
expect(await db.orchestrationArtifact.count({where:{runId:l.runId}})).toBe(0);
|
||||
await db.prepareWorkflowOutbox.update({where:{taskId:t.id},data:{leaseUntil:new Date(Date.now()-1000)}});expect((await post('tech-complete',{...b,source})).status).toBe(403);
|
||||
expect((await db.orchestrationBudgetLedger.findMany({where:{taskId:t.id}})).map(x=>[x.kind,x.amountCents])).toEqual([['RESERVE',20]]);
|
||||
});
|
||||
it('honors cancellation and STOP_AGENTS before storing accepted evidence',async()=>{
|
||||
for(const stop of ['cancel','kill']) {
|
||||
const t=await task();const {body}=await post('tech-claim',{taskId:t.id});const l=body.lease;const b={taskId:t.id,runId:l.runId,leaseToken:l.leaseToken};
|
||||
if(stop==='cancel') await db.orchestrationTask.update({where:{id:t.id},data:{state:'CANCELLED'}});
|
||||
else await db.orchestrationKillSwitch.upsert({where:{scope:'GLOBAL'},create:{scope:'GLOBAL',level:'STOP_AGENTS',active:true,reason:'disposable tech test',actorId:'fixture'},update:{level:'STOP_AGENTS',active:true}});
|
||||
try {expect((await post('tech-complete',{...b,source})).status).toBe(403);expect(await db.orchestrationArtifact.count({where:{runId:l.runId}})).toBe(0);}
|
||||
finally {if(stop==='kill') await db.orchestrationKillSwitch.update({where:{scope:'GLOBAL'},data:{active:false}});}
|
||||
}
|
||||
});
|
||||
it('does not let tracer completion release a Tech reservation',async()=>{
|
||||
const t=await task();const {body}=await post('tech-claim',{taskId:t.id});const l=body.lease;
|
||||
const result=await post('complete',{taskId:t.id,runId:l.runId,leaseToken:l.leaseToken,report:tracerReport(l)});
|
||||
expect(result.status).toBe(403);
|
||||
expect((await db.orchestrationBudgetLedger.findMany({where:{taskId:t.id}})).map(x=>[x.kind,x.amountCents])).toEqual([['RESERVE',20]]);
|
||||
});
|
||||
it('ingests actual source with independent fixture QA and retains unknown-cost reservation',async()=>{
|
||||
const t=await task(); const claim=await post('tech-claim',{taskId:t.id}); expect(claim.status).toBe(201); expect(claim.body.lease.pilotKind).toBe(kind);
|
||||
const l=claim.body.lease, binding={taskId:t.id,runId:l.runId,leaseToken:l.leaseToken};
|
||||
const completed=await post('tech-complete',{...binding,source}); expect(completed.status).toBe(201); expect(completed.body).toEqual({taskId:t.id,runId:l.runId,state:'VERIFYING',artifactSha256:expect.stringMatching(/^[a-f0-9]{64}$/),costStatus:'upper-bound-reserved'});
|
||||
const hash=completed.body.artifactSha256; const artifact=await get(hash); expect(artifact.status).toBe(200); expect(artifact.body).toMatchObject({source,taskId:t.id,runId:l.runId,pilotKind:kind,applicationQa:false,costStatus:'upper-bound-reserved',qa:{passed:true,cases:9,validator:'bounded-minmax-v1'}});
|
||||
expect(sha(await readFile(join(directory,hash+'.json'),'utf8'))).toBe(hash);
|
||||
expect((await get(hash,other)).status).toBe(404); expect((await get(hash,ci)).status).toBe(200);
|
||||
const ledger=await db.orchestrationBudgetLedger.findMany({where:{taskId:t.id}}); expect(ledger.map(x=>[x.kind,x.amountCents])).toEqual([['RESERVE',20]]);
|
||||
const attestations=await db.orchestrationAttestation.findMany({where:{runId:l.runId}}); expect(attestations).toHaveLength(1);expect(attestations[0].kind).toBe('TECH_PILOT_FIXTURE_QA');expect(attestations[0].predicate).toMatchObject({applicationQa:false,sourceSha256:sha(source),cases:9});
|
||||
expect((await post('tech-complete',{...binding,source})).status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { createHash } from 'crypto';
|
||||
export const TECH_PILOT_KIND = 'tech-dev-clamp-quantity-v1';
|
||||
export function admittedTechTask(t: any): boolean {
|
||||
return !!t && t.key === TECH_PILOT_KIND && t.department === 'TECH' &&
|
||||
t.operationMode === 'PREPARE' && t.budgetLimitCents === 20 &&
|
||||
t.metadata?.scope === TECH_PILOT_KIND && t.metadata?.workflowScope === 'STAGE_PREPARE' &&
|
||||
t.metadata?.environment === 'staging' && /^[a-f0-9]{40}$/.test(t.metadata?.commitSha ?? '');
|
||||
}
|
||||
/** Separate bounded recognizer/interpreter. No Python, eval, subprocess or model QA claims. */
|
||||
export function validateTechSource(source: string) {
|
||||
const deny = (): never => { throw new BadRequestException('Only bounded clamp_quantity min/max fixture source passing QA9 accepted'); };
|
||||
if(typeof source !== 'string' || Buffer.byteLength(source, 'utf8') > 2048) deny();
|
||||
const body = /^def clamp_quantity\(quantity\):[ \t]*\r?\n[ \t]+return ([^\r\n]+)[ \t]*\r?\n?$/.exec(source);
|
||||
if(!body) deny();
|
||||
const text = body![1]; let pos=0, nodes=0;
|
||||
type Expr = {kind:'q'} | {kind:'n';value:number} | {kind:'min'|'max';left:Expr;right:Expr};
|
||||
const ws=()=>{while(text[pos]===' ' || text[pos]==='\t') pos++;};
|
||||
function parse(depth:number): Expr {
|
||||
if(depth>32 || ++nodes>128) return deny(); ws();
|
||||
if(text.slice(pos,pos+8)==='quantity') {pos+=8;return {kind:'q'};}
|
||||
const number=/^(0|[1-9][0-9]?)(?![0-9])/.exec(text.slice(pos));
|
||||
if(number) {pos+=number[0].length;return {kind:'n',value:Number(number[0])};}
|
||||
const name=text.slice(pos,pos+3); if(name!=='min' && name!=='max') return deny(); pos+=3;ws();
|
||||
if(text[pos++]!=='(') return deny(); const left=parse(depth+1);ws();if(text[pos++]!==',') return deny();
|
||||
const right=parse(depth+1);ws();if(text[pos++]!==')') return deny();return {kind:name,left,right};
|
||||
}
|
||||
const tree=parse(0);ws();if(pos!==text.length) deny();
|
||||
function evaluate(n:Expr,q:number): number {if(n.kind==='q') return q;if(n.kind==='n') return n.value;const a=evaluate(n.left,q),b=evaluate(n.right,q);return n.kind==='min'?Math.min(a,b):Math.max(a,b);}
|
||||
for(const q of [-1000,-1,0,1,50,98,99,100,1e30]) if(evaluate(tree,q)!==Math.max(0,Math.min(q,99))) deny();
|
||||
return {passed:true,cases:9,validator:'bounded-minmax-v1',scope:'quantity clamp fixture only',sourceSha256:createHash('sha256').update(source).digest('hex')};
|
||||
}
|
||||
export function techArtifact(binding:{taskId:string;runId:string;commitSha:string},source:string) {
|
||||
return JSON.stringify({pilotKind:TECH_PILOT_KIND,schemaVersion:1,...binding,environment:'staging',source,applicationQa:false,costStatus:'upper-bound-reserved',retainedReservationCents:20,qa:validateTechSource(source)});
|
||||
}
|
||||
@@ -32,6 +32,10 @@ import {
|
||||
WorkflowIdentity,
|
||||
} from "../orchestration/prepare-workflow.service";
|
||||
|
||||
import { EditorialProposalBridge, EditorialProposalDto, isEditorialProposal } from "./editorial-bridge";
|
||||
import { EditorialExecutionService, EditorialClaimDto, EditorialResultDto } from './editorial-execution';
|
||||
import { admittedTechTask, TECH_PILOT_KIND, techArtifact, validateTechSource } from "./tech-pilot-validator";
|
||||
|
||||
// This is reviewed static configuration, not a URL fetched by the transport.
|
||||
function validArtifactBase(value: string): boolean {
|
||||
try {
|
||||
@@ -42,7 +46,7 @@ function validArtifactBase(value: string): boolean {
|
||||
/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(u.hostname) &&
|
||||
u.hostname.includes(".") && !/^[0-9.]+$/.test(u.hostname) &&
|
||||
!/(^|\.)(localhost|local|internal|lan|home)$/.test(u.hostname) &&
|
||||
u.pathname === "/internal/prepare-worker/artifacts" &&
|
||||
["/internal/prepare-worker/artifacts", "/api/internal/prepare-worker/artifacts"].includes(u.pathname) &&
|
||||
value === u.origin + u.pathname;
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -69,6 +73,9 @@ class LeaseDto extends ClaimDto {
|
||||
class CompleteDto extends LeaseDto {
|
||||
@IsString() @MaxLength(2048) report!: string;
|
||||
}
|
||||
class TechCompleteDto extends LeaseDto {
|
||||
@IsString() @MaxLength(2048) source!: string;
|
||||
}
|
||||
class StageEvidenceDto extends ClaimDto {
|
||||
@IsUUID() runId!: string;
|
||||
@Matches(/^[a-f0-9]{40}$/) commitSha!: string;
|
||||
@@ -150,6 +157,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)
|
||||
@@ -162,6 +170,10 @@ 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.
|
||||
await this.workflow.heartbeat(a, dto);
|
||||
const run = await this.db.orchestrationRun.findUniqueOrThrow({
|
||||
@@ -196,12 +208,59 @@ class WorkerTransportService {
|
||||
actualCents: 0,
|
||||
};
|
||||
}
|
||||
async techClaim(a: WorkflowIdentity, dto: ClaimDto) {
|
||||
this.worker(a);
|
||||
const t = await this.db.orchestrationTask.findUnique({ where: { id: dto.taskId } });
|
||||
if (!admittedTechTask(t)) throw new ForbiddenException("Reviewed Tech pilot task required");
|
||||
const { lease } = await this.claim(a, dto);
|
||||
return { lease: lease ? { ...lease, pilotKind: TECH_PILOT_KIND } : null };
|
||||
}
|
||||
async techComplete(a: WorkflowIdentity, dto: TechCompleteDto) {
|
||||
this.worker(a);
|
||||
await this.workflow.heartbeat(a, dto);
|
||||
const task = await this.db.orchestrationTask.findUnique({ where: { id: dto.taskId } });
|
||||
const run = await this.db.orchestrationRun.findUnique({ where: { id: dto.runId } });
|
||||
if (!admittedTechTask(task) || !run || run.taskId !== dto.taskId || run.commitSha !== (task!.metadata as any).commitSha || run.environment !== 'staging')
|
||||
throw new ForbiddenException('Reviewed Tech pilot task required');
|
||||
const qa = validateTechSource(dto.source);
|
||||
const bytes = techArtifact({ taskId: dto.taskId, runId: dto.runId, commitSha: run.commitSha }, dto.source);
|
||||
const hash = createHash('sha256').update(bytes).digest('hex');
|
||||
let dir: FileHandle | undefined, file: FileHandle | undefined;
|
||||
try {
|
||||
dir = await this.artifactDir();
|
||||
file = await open(`/proc/self/fd/${dir.fd}/${hash}.json`, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
await file.writeFile(bytes, 'utf8'); await file.sync();
|
||||
} catch { throw new ConflictException('Artifact creation refused'); }
|
||||
finally { await file?.close(); await dir?.close(); }
|
||||
// This fixture path deliberately does not call core complete: its QA attestation and
|
||||
// measured-cost reconciliation would misrepresent generated toy-source evidence.
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
const switches = await tx.$queryRaw`SELECT level, active FROM orchestration_kill_switches WHERE scope = 'GLOBAL' FOR SHARE`;
|
||||
if (switches[0]?.active && switches[0].level !== 'FREEZE_NEW_WORK') throw new ForbiddenException('Kill switch blocks workflow');
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${dto.taskId}::uuid FOR UPDATE`;
|
||||
const t = await tx.orchestrationTask.findUnique({ where: { id: dto.taskId } });
|
||||
const o = await tx.prepareWorkflowOutbox.findUnique({ where: { taskId: dto.taskId } });
|
||||
const r = await tx.orchestrationRun.findUnique({ where: { id: dto.runId } });
|
||||
if (!admittedTechTask(t) || 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.commitSha !== t.metadata.commitSha || r.commitSha !== run.commitSha || r.environment !== 'staging')
|
||||
throw new ForbiddenException('Active owned Tech lease required');
|
||||
const reservation = await tx.orchestrationBudgetLedger.findUnique({ where: { id: o.reservationId } });
|
||||
if (!reservation || reservation.taskId !== t.id || reservation.kind !== 'RESERVE' || reservation.amountCents !== 20 || await tx.orchestrationBudgetLedger.findFirst({ where: { taskId: t.id, kind: 'RECONCILE', metadata: { path: ['reservationId'], equals: reservation.id } } }))
|
||||
throw new ForbiddenException('Unreconciled 20 cent reservation required');
|
||||
await tx.orchestrationArtifact.create({ data: { runId: r.id, kind: 'TECH_PILOT_SOURCE', sha256: hash, uri: this.config.artifactBaseUrl + '/' + hash } });
|
||||
await tx.orchestrationAttestation.create({ data: { runId: r.id, kind: 'TECH_PILOT_FIXTURE_QA', subjectHash: hash, signer: 'server-bounded-minmax-v1', predicate: { ...qa, applicationQa: false, costStatus: 'upper-bound-reserved' } } });
|
||||
await tx.orchestrationRun.update({ where: { id: r.id }, data: { status: 'SUCCEEDED', 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: 'TECH_PILOT_FIXTURE_VALIDATED', fromState: t.state, toState: 'VERIFYING', idempotencyKey: `tech-pilot:${r.id}`, payload: { artifactSha256: hash, ...qa, applicationQa: false, costStatus: 'upper-bound-reserved', retainedReservationCents: 20 } } });
|
||||
return { taskId: t.id, runId: r.id, state: updated.state, artifactSha256: hash, costStatus: 'upper-bound-reserved' };
|
||||
});
|
||||
}
|
||||
async artifact(a: WorkflowIdentity, hash: string) {
|
||||
if (!/^[a-f0-9]{64}$/.test(hash))
|
||||
throw new BadRequestException("Invalid artifact hash");
|
||||
const registered = await this.db.orchestrationArtifact.findFirst({
|
||||
where: {
|
||||
sha256: hash, kind: "QA", uri: this.config.artifactBaseUrl + "/" + hash,
|
||||
sha256: hash, kind: { in: ["QA", "TECH_PILOT_SOURCE"] }, uri: this.config.artifactBaseUrl + "/" + hash,
|
||||
run: { environment: "staging", status: "SUCCEEDED", task: {
|
||||
operationMode: "PREPARE", budgetLimitCents: 20,
|
||||
} },
|
||||
@@ -217,6 +276,9 @@ class WorkerTransportService {
|
||||
const metadata = task.metadata as any;
|
||||
if (metadata?.workflowScope !== "STAGE_PREPARE" || metadata?.commitSha !== run.commitSha)
|
||||
throw new NotFoundException("Artifact not registered");
|
||||
const tech = registered.kind === "TECH_PILOT_SOURCE";
|
||||
if (tech && !admittedTechTask(task)) throw new NotFoundException("Artifact not registered");
|
||||
const limit = tech ? 8192 : 2048;
|
||||
let bytes: string;
|
||||
let dir: FileHandle | undefined, file: FileHandle | undefined;
|
||||
try {
|
||||
@@ -225,19 +287,22 @@ class WorkerTransportService {
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid!() ||
|
||||
(stat.mode & 0o077) !== 0 || stat.size > 2048)
|
||||
(stat.mode & 0o077) !== 0 || stat.size > limit)
|
||||
throw new Error("Unsafe artifact file");
|
||||
// Fixed-size descriptor read: concurrent growth cannot allocate unbounded memory.
|
||||
const buffer = Buffer.alloc(2049);
|
||||
const buffer = Buffer.alloc(limit + 1);
|
||||
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
||||
if (bytesRead > 2048) throw new Error("Oversized artifact");
|
||||
if (bytesRead > limit) throw new Error("Oversized artifact");
|
||||
bytes = buffer.subarray(0, bytesRead).toString("utf8");
|
||||
} catch {
|
||||
throw new NotFoundException("Artifact unavailable");
|
||||
} finally { await file?.close(); await dir?.close(); }
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== hash)
|
||||
throw new ConflictException("Artifact integrity mismatch");
|
||||
if (bytes !== tracerReport({ taskId: run.taskId, runId: run.id, commitSha: run.commitSha }))
|
||||
let expected: string;
|
||||
try { expected = tech ? techArtifact({ taskId: run.taskId, runId: run.id, commitSha: run.commitSha }, JSON.parse(bytes).source) : tracerReport({ taskId: run.taskId, runId: run.id, commitSha: run.commitSha }); }
|
||||
catch { throw new ConflictException("Artifact binding mismatch"); }
|
||||
if (bytes !== expected)
|
||||
throw new ConflictException("Artifact binding mismatch");
|
||||
return JSON.parse(bytes);
|
||||
}
|
||||
@@ -255,10 +320,28 @@ class WorkerTransportService {
|
||||
}),
|
||||
)
|
||||
class WorkerTransportController {
|
||||
constructor(private readonly service: WorkerTransportService) {}
|
||||
constructor(private readonly service: WorkerTransportService, private readonly editorial: EditorialProposalBridge, private readonly execution: EditorialExecutionService) {}
|
||||
@Get('editorial-proposals/:taskId') editorialStatus(@Req() req: any, @Param('taskId') taskId: string) {
|
||||
return this.execution.status(req.workerIdentity, taskId);
|
||||
}
|
||||
@Post('editorial-claim') editorialClaim(@Req() req: any, @Body() dto: EditorialClaimDto) {
|
||||
return this.execution.claim(req.workerIdentity, dto);
|
||||
}
|
||||
@Post('editorial-result') editorialResult(@Req() req: any, @Body() dto: EditorialResultDto) {
|
||||
return this.execution.result(req.workerIdentity, dto);
|
||||
}
|
||||
@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);
|
||||
}
|
||||
@Post("tech-claim") techClaim(@Req() req: any, @Body() dto: ClaimDto) {
|
||||
return this.service.techClaim(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("tech-complete") techComplete(@Req() req: any, @Body() dto: TechCompleteDto) {
|
||||
return this.service.techComplete(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("heartbeat") heartbeat(@Req() req: any, @Body() dto: LeaseDto) {
|
||||
return this.service.heartbeat(req.workerIdentity, dto);
|
||||
}
|
||||
@@ -328,6 +411,8 @@ export class WorkerTransportModule {
|
||||
PrepareWorkflowService,
|
||||
WorkerIdentityGuard,
|
||||
WorkerTransportService,
|
||||
EditorialProposalBridge,
|
||||
EditorialExecutionService,
|
||||
{ provide: CONFIG, useValue: snapshot },
|
||||
{
|
||||
provide: PREPARE_WORKFLOW_CONFIG,
|
||||
|
||||
@@ -97,13 +97,20 @@ export class OrchestrationController {
|
||||
) {}
|
||||
private actor(req: any): WorkflowIdentity {
|
||||
const id = req?.user?.id ?? req?.user?.sub;
|
||||
// Match RolesGuard aliases without promoting an admin to a reviewer.
|
||||
const normalized = typeof req?.user?.role === 'string'
|
||||
? req.user.role.toLowerCase().replace(/[_-]/g, '')
|
||||
: '';
|
||||
const role = normalized === 'admin' ? 'Admin'
|
||||
: ['superadmin', 'adminsuper'].includes(normalized) ? 'SUPER_ADMIN'
|
||||
: undefined;
|
||||
if (
|
||||
typeof id !== 'string' ||
|
||||
!id ||
|
||||
!['Admin', 'SUPER_ADMIN'].includes(req?.user?.role)
|
||||
!role
|
||||
)
|
||||
throw new ForbiddenException('Authenticated workflow identity required');
|
||||
return { id, role: req.user.role };
|
||||
return { id, role };
|
||||
}
|
||||
private safe(row: any, req: any) {
|
||||
const view = project(row);
|
||||
|
||||
@@ -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'});
|
||||
});
|
||||
});
|
||||
@@ -68,6 +68,38 @@ describe('bounded workflow HTTP contracts', () => {
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
it.each([
|
||||
['ADMIN', 'Admin'],
|
||||
['admin', 'Admin'],
|
||||
['Admin', 'Admin'],
|
||||
['SUPER_ADMIN', 'SUPER_ADMIN'],
|
||||
['super-admin', 'SUPER_ADMIN'],
|
||||
['SuperAdmin', 'SUPER_ADMIN'],
|
||||
['ADMIN_SUPER', 'SUPER_ADMIN'],
|
||||
])('canonicalizes guard-supported %s on task reads to %s', async (role, canonical) => {
|
||||
for (const path of ['tasks', 'tasks/t']) {
|
||||
workflow.project.mockClear();
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', role)
|
||||
.expect(200);
|
||||
expect(workflow.project).toHaveBeenCalledWith(t, {
|
||||
id: 'verified-subject', role: canonical,
|
||||
});
|
||||
const task = Array.isArray(response.body) ? response.body[0] : response.body;
|
||||
expect(task.availableActions).toEqual(['SUBMIT_GATE1']);
|
||||
}
|
||||
});
|
||||
it('denies ordinary users before workflow projection', async () => {
|
||||
workflow.project.mockClear();
|
||||
for (const path of ['tasks', 'tasks/t', 'overview']) {
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'User_PetOwner')
|
||||
.expect(403);
|
||||
}
|
||||
expect(workflow.project).not.toHaveBeenCalled();
|
||||
});
|
||||
it('accepts existing proposal DTO, derives actor from JWT sub and returns projected task', async () => {
|
||||
const dto = {
|
||||
key: 'k',
|
||||
@@ -108,6 +140,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);
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# Opt-in Stage runtime provisioning (parent wiring contract)
|
||||
|
||||
This provisions **snapshot inventory** and credentials for the existing PREPARE
|
||||
transport. It does NOT create a real LLM executor. The current deterministic worker
|
||||
is still `llmPilot:false`. No provider credentials are collected, no cron installed,
|
||||
no task claimed and no worker polling/service started by the provisioner.
|
||||
|
||||
## CI-only host invocation
|
||||
|
||||
Parent owns workflow/deploy.sh/AppModule; none are changed here. Run only through
|
||||
the existing pinned authenticated SSH CI boundary, under its Stage environment
|
||||
approval and serialized rollout lock. `CI=true` is an accident guard, not an auth
|
||||
boundary. Provisioner checks clean HEAD equals the full approved commit; no branch
|
||||
promotion, push, Production, RELEASE_AUTHORIZE, Docker or DB writes are performed.
|
||||
Only the CI account should be able to invoke this on a root-owned trusted parent.
|
||||
|
||||
From the clean pinned release checkout on the host (not the dirty Stage checkout):
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000
|
||||
```
|
||||
|
||||
Default output root is `/opt/services/canina/stage-runtime` and its parent must
|
||||
already exist. First creation is staged and atomically renamed. Repeating validates
|
||||
existing state without rotating credentials. Corrupt/missing/unsafe files fail
|
||||
closed, not repaired. CI MUST serialize execution and prevent untrusted edits to
|
||||
source/output parents; this is not a hostile-filesystem sandbox. `--root` is for
|
||||
CI-reviewed test/Stage locations only, not arbitrary browser input. Secure backup
|
||||
and separately approved rotation are parent/operator responsibilities.
|
||||
|
||||
- `secrets/` 0700, files 0400 owned by the runtime UID (1000 in the current backend
|
||||
image); `hermes_username/password/signing_key` are new independent random values.
|
||||
- `prepare_worker_grants` contains SHA256 only, exact separate service identities
|
||||
`stage-prepare-worker`/WORKFLOW_WORKER and `stage-evidence-ci`/STAGE_CI. These are
|
||||
transport service identities, **not invented DB admin users**.
|
||||
- Raw `credentials/prepare_worker_token` and `credentials/stage_ci_token` stay in a
|
||||
CI-owner-only 0700 directory, 0400 files. Do NOT mount either into inventory or
|
||||
backend, log them, upload them as artifacts or send them to browsers. A later
|
||||
reviewed one-shot executor receives only its own token through a private file.
|
||||
- `artifacts/` is 0700 owned by backend UID; backend alone writes it. Persistent
|
||||
local disk is not object storage or external publication evidence.
|
||||
- `hermes_runtime_grants` is `{}`: deny all. No live admin query was needed/performed.
|
||||
Parent must separately query actual Stage admin IDs read-only, review exact ID to
|
||||
profile mapping and provision a private replacement via configuration management
|
||||
before claiming panel access. Never infer identities from usernames or JWT input.
|
||||
Deliberately changed grants require separate review; default provisioner refuses
|
||||
nonempty runtime grants on repeat.
|
||||
- Compose file-backed secrets preserve host permissions/ownership; `uid/gid/mode`
|
||||
declarations do not fix bind mount ownership. Verify effective host IDs if Docker
|
||||
uses userns remapping; do not chmod 0444 as a workaround.
|
||||
|
||||
## Consistent restricted export
|
||||
|
||||
After approval, the SAME CI invocation may explicitly request one profile's source
|
||||
SQLite DB. Resolve its real `HERMES_HOME/state.db` through reviewed host mounts;
|
||||
never guess a gateway volume path or mount the original home into inventory.
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000 \
|
||||
--snapshot-db "$REVIEWED_STATE_DB" --profile default \
|
||||
--snapshot-name "$UNIQUE_CI_CAPTURE_ID"
|
||||
```
|
||||
|
||||
SQLite online `Connection.backup()` reads committed WAL frames into memory (never
|
||||
`cp state.db`, never `immutable=1`). A 30-second callback deadline bounds busy
|
||||
backup. Only explicit source/time/token/cost columns from `sessions` are projected.
|
||||
Private session IDs become capture-local ordinal IDs; sources use an enum; no
|
||||
messages, titles, prompts, user/chat IDs, paths, URLs, model config, credentials,
|
||||
config.yaml, auth.json, .env, cron commands, memory or skills are exported. Unknown
|
||||
schema/nonnumeric metadata fails. One profile per immutable capture; there is no
|
||||
multi-DB atomicity claim. A source DB may be large: backup is memory-bound, so size
|
||||
and host resources need operator review before a real capture.
|
||||
|
||||
Output directory is new/immutable (0500, 0400 files), never overwritten:
|
||||
`inventory.json`, exact three-field `snapshot-manifest.json` and `export-report.json`.
|
||||
Manifest `capturedAt` is measured immediately after successful backup, not startup,
|
||||
mtime or an example. Report records actual projected row count, inventory digest,
|
||||
method/exclusions; it is not a signature or proof of source authenticity. No live
|
||||
capture was performed in this change. Never reuse fixture manifests as evidence.
|
||||
|
||||
Projected HTTP readers never consult gateway config, state DB or cron files:
|
||||
model/provider are explicit `unknown`, context length is a placeholder zero,
|
||||
cron arrays empty mean **not captured**, session activity false is a placeholder,
|
||||
profile inventory doesn't establish live process availability. Status retains
|
||||
`liveProcess:unknown`. Usage days are relative to actual capture time. Snapshot
|
||||
fresh/stale provenance from the existing adapter remains mandatory. No real LLM
|
||||
pilot readiness follows from this inventory responding 200.
|
||||
|
||||
## Exact parent compose/application wiring
|
||||
|
||||
`infra/hermes-runtime/compose.stage-provision.yml` is an opt-in merge fragment,
|
||||
NOT called by the existing deploy script or ci-apply.sh. Parent must include it
|
||||
in **every** Stage compose command after provisioning, using the existing stable
|
||||
Compose project identity and existing release isolation/volume rules:
|
||||
|
||||
```sh
|
||||
export STAGE_RUNTIME_SERVE_FILE="$PINNED_RELEASE/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SNAPSHOT="/opt/services/canina/stage-runtime/snapshots/$UNIQUE_CI_CAPTURE_ID"
|
||||
# Only inside approved CI rollout, never manually:
|
||||
# docker compose -p <existing-stage-project> -f <parent-stage-compose> \
|
||||
# -f "$PINNED_RELEASE/infra/hermes-runtime/compose.stage-provision.yml" \
|
||||
# --profile stage-runtime-inventory <parent-approved command>
|
||||
```
|
||||
|
||||
The fragment adds backend `PREPARE_WORKER_ENABLED=true`, fixed-path secrets
|
||||
`/run/secrets/prepare_worker_grants`, `/run/secrets/hermes_runtime_grants`,
|
||||
`hermes_username/password`, and artifact bind at
|
||||
`/var/lib/canina/prepare-artifacts`. It adds a project-scoped **internal** network
|
||||
between backend and inventory only, alias `canina-hermes-inventory` (not the live
|
||||
`canina-hermes`). No host port, Docker socket or live gateway volume. Inventory is
|
||||
read-only, nonroot, no capabilities, restricted tmpfs and pinned image, mounts only
|
||||
its immutable projected export and script. `create_host_path:false` fails on missing
|
||||
exports/storage. Original compose.readonly.yml/ci-apply.sh remain legacy review-only;
|
||||
do not combine those with this provisioning fragment.
|
||||
|
||||
AppModule must keep AuthModule/JwtStrategy, import
|
||||
`RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')` for reads,
|
||||
and spread `...registerPrepareWorker()` for the opt-in worker transport (verify
|
||||
existing AppModule before adding duplicates). The latter defaults to no module
|
||||
unless exact env `true`; enabling compose alone cannot add missing imports. Routes
|
||||
remain service-authenticated. Artifact base is fixed to
|
||||
`https://stageapi.canina.ir/api/internal/prepare-worker/artifacts`; parent must verify
|
||||
its actual global `/api` prefix/proxy/authenticated retrieval after CI deployment.
|
||||
No URL here is asserted externally reachable by disposable tests.
|
||||
|
||||
Parent still must implement/review a bounded one-shot real LLM executor separately;
|
||||
this commit intentionally adds neither model/provider secrets nor automatic polling.
|
||||
After CI rollout verify backend UID/secret readability by names only, deny-all reads,
|
||||
worker unauth denial, snapshot provenance and authenticated artifact digest readback
|
||||
before a separately authorized task. Do not call RELEASE_AUTHORIZE.
|
||||
|
||||
## Executed disposable validation
|
||||
|
||||
Pinned Hermes image, `--network none`, repository mounted read-only; private
|
||||
TemporaryDirectory fixtures only. RED observed missing provisioner, missing exporter,
|
||||
wrong projected profile and acceptance of malformed credential; GREEN: four
|
||||
provision/export/security/CI-guard unittest cases; projected HTTP auth/profile/session/
|
||||
wrong-profile/model/cron assertions; existing exact-image HTTP acceptance, TCP serve
|
||||
mutation denial and authenticated WebSocket 1008 denial. Compose merged config
|
||||
`--quiet` passed without applying it. An initial test mount mismatch was corrected
|
||||
(`/source` for repo-relative tests, `/contract` for legacy tests). No application
|
||||
backend code changed; full backend suites not rerun. No host credentials, artifact
|
||||
storage, snapshots, DB users, services or networks were provisioned live.
|
||||
@@ -5,12 +5,12 @@ import CreateOrchestrationTask from './CreateOrchestrationTask';
|
||||
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
|
||||
it('submits exact bounded PREPARE contract only after valid commit and budget',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
|
||||
expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Commit SHA (40 lowercase hex)':'a'.repeat(40),'Budget cap in cents':'500','Scope':'Audit staging only','Acceptance criteria (one per line)':'Schema checked\nEvidence attached'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value}});expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();}
|
||||
fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value:'500'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
|
||||
await screen.findByText('Task created by backend.');
|
||||
expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'کلید یکتای وظیفه':'audit-1','عنوان':'Audit schema','دپارتمان':'SEO','شناسه کامیت (۴۰ نویسه هگز کوچک)':'a'.repeat(40),'سقف بودجه به سنت':'500','محدوده':'Audit staging only','معیارهای پذیرش (هر معیار در یک خط)':'Schema checked\nEvidence attached'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value}});expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();}
|
||||
fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value:'500'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'ایجاد وظیفه محدود'}));
|
||||
await screen.findByText('وظیفه توسط سرور ایجاد شد.');
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'audit-1',title:'Audit schema',department:'SEO',operationMode:'PREPARE',budgetLimitCents:500,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked','Evidence attached']}});
|
||||
expect(done).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -7,9 +7,9 @@ export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}
|
||||
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const input:CreateTaskInput={key:fields.key,title:fields.title,department:fields.department,operationMode:'PREPARE',budgetLimitCents:Number(fields.budget),metadata:{commitSha:fields.commitSha,scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n')}};
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&!proposalError(input);
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — Refresh and reconcile the task key before resubmitting.':'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['commitSha','Commit SHA (40 lowercase hex)'],['budget','Budget cap in cents'],['scope','Scope'],['criteria','Acceptance criteria (one per line)']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<p>Operation mode: PREPARE · Environment: staging. Budget: 20..10000 cents. Scope: nonblank, at most 2000 characters. Acceptance criteria: 1..20 nonblank lines, at most 500 characters each. Human scope and criteria are persisted unchanged; the workflow restriction is server-owned.</p><p>Creation does not authorize work. Gate1 is a separate immutable decision. Production proposals are disabled. After an ambiguous failure, refresh and reconcile the unique task key before resubmitting.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>Create bounded task</Button>
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">ایجاد کار محدود</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('وظیفه توسط سرور ایجاد شد.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — پیش از ارسال مجدد، کلید وظیفه را با وضعیت سرور تطبیق دهید.':'ایجاد ناموفق بود؛ پیش از تلاش مجدد کلید وظیفه را تطبیق دهید.')}finally{setBusy(false)}}}>
|
||||
{([['key','کلید یکتای وظیفه'],['title','عنوان'],['department','دپارتمان'],['commitSha','شناسه کامیت (۴۰ نویسه هگز کوچک)'],['budget','سقف بودجه به سنت'],['scope','محدوده'],['criteria','معیارهای پذیرش (هر معیار در یک خط)']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<p>حالت عملیات: PREPARE · محیط: staging. بودجه: ۲۰ تا ۱۰۰۰۰ سنت. محدوده: غیرخالی، حداکثر ۲۰۰۰ نویسه. معیار پذیرش: ۱ تا ۲۰ خط غیرخالی، هر خط حداکثر ۵۰۰ نویسه. محدوده و معیارهای انسانی بدون تغییر ذخیره میشوند؛ محدودیت گردش کار متعلق به سرور است.</p><p>ایجاد وظیفه مجوز اجرا نیست. Gate1 تصمیمی مستقل و تغییرناپذیر است. پیشنهاد Production غیرفعال است. پس از خطای مبهم، پیش از ارسال مجدد کلید یکتا را با وضعیت سرور تطبیق دهید.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>ایجاد وظیفه محدود</Button>
|
||||
</form></details>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {render,screen} from '@testing-library/react';
|
||||
import {expect,it} from 'vitest';
|
||||
import {Records} from './OrchestrationPresentation';
|
||||
it('preserves human scope, criteria and immutable identifiers while translating protocol enums',()=>{
|
||||
render(<Records value={{metadata:{scope:'READY',acceptanceCriteria:['SUCCEEDED'],commitSha:'READY'},operationMode:'PREPARE',status:'SUCCEEDED'}}/>);
|
||||
expect(screen.getAllByText('READY')).toHaveLength(2);
|
||||
expect(screen.getByText('SUCCEEDED')).toBeInTheDocument();
|
||||
expect(screen.getByText('آمادهسازی')).toBeInTheDocument();
|
||||
expect(screen.getByText('موفق')).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
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:'تطبیق بودجه'};
|
||||
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}){
|
||||
if(value===null||value===undefined)return <span>نامشخص — گزارش نشده</span>;
|
||||
if(Array.isArray(value))return value.length?<div className="space-y-3">{value.map((item,index)=><article className="border rounded-lg p-3" key={index}><Records value={item} field={field}/></article>)}</div>:<p>رکوردی ثبت نشده است.</p>;
|
||||
if(typeof value==='object')return <dl className="grid gap-3 sm:grid-cols-2">{Object.entries(value).map(([key,item])=><div key={key} className="min-w-0"><dt className="text-sm text-gray-500">{label(key)}</dt><dd className="break-words"><Records value={item} field={key}/></dd></div>)}</dl>;
|
||||
if(typeof value==='boolean')return <span>{value?'بله':'خیر'}</span>;
|
||||
return <bdi className="break-all">{typeof value==='string'&&['state','status','fromState','toState','operationMode','department','decision','environment','kind'].includes(field??'')?label(value):String(value)}</bdi>;
|
||||
}
|
||||
@@ -2,18 +2,19 @@ import {useEffect,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {routerUsage,usagePeriods} from '../services/routerUsage';
|
||||
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
|
||||
const shown=(value:unknown)=>value===null||value===undefined?'Unknown — not reported':String(value);
|
||||
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{key}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
|
||||
const shown=(value:unknown)=>value===null||value===undefined?'نامشخص — گزارش نشده':String(value);
|
||||
const labels:Record<string,string>={requests:'درخواستها',inputTokens:'توکن ورودی',outputTokens:'توکن خروجی',cacheReadTokens:'توکن خواندن حافظه نهان',cacheWriteTokens:'توکن نوشتن حافظه نهان',reasoningTokens:'توکن استدلال',errors:'خطاها',providers:'تأمینکنندهها',models:'مدلها',accounts:'حسابها'};
|
||||
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{labels[key]}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
|
||||
export default function RouterUsagePanel(){
|
||||
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
|
||||
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'Usage unavailable')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
|
||||
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">9router usage & provider-reported quota</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>Refresh usage</Button></header>
|
||||
<label>Usage period<select aria-label="Usage period" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
|
||||
<p>Gateway totals include all clients. Provider/model/account breakdowns overlap; never add them together. Cache/reasoning counters may overlap token counts. No derived totals or quota estimates.</p>
|
||||
<p>Hermes attribution: Unknown — not reported; do not add to gateway totals.</p>
|
||||
{loading&&<p role="status">Loading gateway usage…</p>}{error&&<p role="alert">Unknown / unavailable: {error}</p>}
|
||||
{data&&<><dl><dt>Source</dt><dd>{data.source}</dd><dt>Retrieved at (not source freshness)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>Source updated at</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>Stale</dt><dd>{shown(data.freshness.stale)}</dd><dt>Reported period</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>Gateway totals (includes Hermes)</h3><Counters data={data.data.totals}/></article>
|
||||
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{group}</h3>{!data.data[group].length&&<p>No {group} reported.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>Provider-reported quota remaining</dt><dd>{shown(row.quota?.remaining)}</dd><dt>Provider-reported quota reset</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>Quota availability reason</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
|
||||
<p>Quota is unknown: upstream quota GET refreshes credentials, so this read-only adapter does not call it.</p></>}
|
||||
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'مصرف در دسترس نیست')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
|
||||
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">مصرف 9router و سهمیه گزارششده تأمینکننده</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>بازخوانی مصرف</Button></header>
|
||||
<label>بازه مصرف<select aria-label="بازه مصرف" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
|
||||
<p>مجموع درگاه شامل همه مشتریهاست. تفکیک تأمینکننده، مدل و حساب همپوشانی دارد؛ آنها را جمع نکنید. شمارنده حافظه نهان و استدلال ممکن است با توکنها همپوشان باشد. مجموع یا سهمیه تخمینی محاسبه نمیشود.</p>
|
||||
<p>سهم مصرف Hermes: نامشخص و گزارشنشده؛ با مجموع درگاه جمع نکنید.</p>
|
||||
{loading&&<p role="status">در حال دریافت مصرف درگاه…</p>}{error&&<p role="alert">دریافت مصرف ناموفق بود: {error}</p>}
|
||||
{data&&<><dl><dt>منبع</dt><dd>{data.source}</dd><dt>زمان دریافت (نه زمان تازگی منبع)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>زمان بهروزرسانی منبع</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>قدیمی بودن داده</dt><dd>{shown(data.freshness.stale)}</dd><dt>بازه گزارششده</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>مجموع درگاه (شامل Hermes)</h3><Counters data={data.data.totals}/></article>
|
||||
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{labels[group]}</h3>{!data.data[group].length&&<p>دادهای برای {labels[group]} گزارش نشده است.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>سهمیه باقیمانده گزارششده تأمینکننده</dt><dd>{shown(row.quota?.remaining)}</dd><dt>زمان بازنشانی سهمیه گزارششده</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>دلیل وضعیت سهمیه</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
|
||||
<p>سهمیه نامشخص است: درخواست سهمیه به منبع، اطلاعات احراز هویت را تغییر میدهد؛ بنابراین این رابط فقطخواندنی آن را فراخوانی نمیکند.</p></>}
|
||||
</section>;
|
||||
}
|
||||
@@ -3,16 +3,16 @@ import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import RuntimeReadPanel from './RuntimeReadPanel';
|
||||
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:5000,freshness:'stale',liveProcess:'unknown'};
|
||||
it('labels snapshot inventory without presenting stopped gateway, zero agents or active sessions as live',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'v1',gateway_running:false,overall:'unknown',active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:1,sessions:[{id:'session-1',profile:'dev',source:'cli',is_active:true}],provenance}:{period_days:30,totals:{total_input:1,total_output:2,total_sessions:1,total_estimated_cost:0},provenance}}));
|
||||
it('labels snapshot inventory without presenting متوقف gateway, zero agents or فعال sessions as live',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'v1',gateway_running:false,overall:'نامشخص',active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:1,sessions:[{id:'session-1',profile:'dev',source:'cli',is_active:true}],provenance}:{period_days:30,totals:{total_input:1,total_output:2,total_sessions:1,total_estimated_cost:0},provenance}}));
|
||||
render(<RuntimeReadPanel/>);
|
||||
expect(await screen.findByText('Inventory service: responsive (not live Hermes health)')).toBeInTheDocument();
|
||||
screen.getAllByText(/Captured at: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('stale'));
|
||||
fireEvent.change(screen.getByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText(/Active agents: unknown/)).toBeInTheDocument();
|
||||
expect(await screen.findByText(/historical snapshot flag: active; live activity unknown/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Gateway.*stopped/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Active agents: 0/)).not.toBeInTheDocument();
|
||||
expect(await screen.findByText('سرویس فهرست ثبتشده: پاسخگو (نه سلامت زنده Hermes)')).toBeInTheDocument();
|
||||
screen.getAllByText(/زمان ثبت: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('قدیمی'));
|
||||
fireEvent.change(screen.getByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText(/عاملهای فعال: نامشخص/)).toBeInTheDocument();
|
||||
expect(await screen.findByText(/پرچم تاریخی نمای ثبتشده: فعال; فعالیت زنده نامشخص است/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/درگاه.*متوقف/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/عاملهای فعال: 0/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/runtime health: healthy/)).not.toBeInTheDocument();
|
||||
});
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
|
||||
@@ -24,21 +24,21 @@ beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async u
|
||||
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
|
||||
throw new Error('Runtime unavailable');
|
||||
});});
|
||||
it('shows actual health identity, explicit stopped gateway, zero usage and profile-bound reads',async()=>{
|
||||
it('shows actual health identity, explicit متوقف gateway, zero usage and profile-bound reads',async()=>{
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).toBeInTheDocument();
|
||||
fireEvent.change(await screen.findByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('No sessions returned.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Input tokens: 0')).toBeInTheDocument();expect(screen.getByText(/Upstream estimated cost: 0/)).toBeInTheDocument();
|
||||
fireEvent.change(await screen.findByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('نشستی دریافت نشد.')).toBeInTheDocument();
|
||||
expect(screen.getByText('توکن ورودی: 0')).toBeInTheDocument();expect(screen.getByText(/هزینه تخمینی منبع: 0/)).toBeInTheDocument();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/runtime/sessions',{params:{profile:'dev',limit:20,offset:0}});
|
||||
});
|
||||
it('shows unavailable rather than healthy when runtime cannot be authenticated',async()=>{
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('Runtime unavailable'));
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText('Authenticated runtime health: healthy')).not.toBeInTheDocument();
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText('اجرای احرازهویتشده health: healthy')).not.toBeInTheDocument();
|
||||
});
|
||||
it('rejects malformed health and never renders unknown secret fields',async()=>{
|
||||
it('rejects malformed health and never renders نامشخص secret fields',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:false,password:'secret-value'}:[]}));
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
|
||||
});
|
||||
it('refreshes the authenticated runtime reads without a browser runtime connection',async()=>{
|
||||
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'Refresh runtime'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
|
||||
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'بازخوانی اطلاعات اجرا'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
|
||||
});
|
||||
@@ -2,34 +2,34 @@ import {useEffect,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {runtime} from '../services/runtime';
|
||||
import type {RuntimeProvenance,RuntimeHealth,RuntimeProfile,RuntimeStatus,RuntimeSessions,RuntimeUsage} from '../services/runtime';
|
||||
function Snapshot({value}:{value?:RuntimeProvenance}){return value?<p>Snapshot inventory · Captured at: {value.capturedAt} · Age: {value.ageSeconds} seconds · {value.freshness} · Live process: {value.liveProcess}. Even fresh snapshots are not live readiness.</p>:null}
|
||||
function Snapshot({value}:{value?:RuntimeProvenance}){return value?<p>فهرست ثبتشده · زمان ثبت: {value.capturedAt} · قدمت: {value.ageSeconds} ثانیه · {value.freshness==='fresh'?'تازه':'قدیمی'} · فرایند زنده: نامشخص. حتی نمای تازه، آمادگی زنده را اثبات نمیکند.</p>:null}
|
||||
export default function RuntimeReadPanel(){
|
||||
const [revision,setRevision]=useState(0);const [profile,setProfile]=useState('');const [offset,setOffset]=useState(0);
|
||||
const [health,setHealth]=useState<RuntimeHealth|null>(null);const [profiles,setProfiles]=useState<RuntimeProfile[]>([]);const [errors,setErrors]=useState<Record<string,string>>({});
|
||||
const [status,setStatus]=useState<RuntimeStatus|null>(null);const [sessions,setSessions]=useState<RuntimeSessions|null>(null);const [usage,setUsage]=useState<RuntimeUsage|null>(null);
|
||||
const [observed,setObserved]=useState('');
|
||||
useEffect(()=>{let active=true;setHealth(null);setProfiles([]);setErrors({});
|
||||
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'Health unavailable — authenticated backend runtime read failed.'}))});
|
||||
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'Profiles unavailable — no authorized runtime identity list.'}))}});
|
||||
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'وضعیت اجرا در دسترس نیست؛ خواندن احرازهویتشده از سرور ناموفق بود.'}))});
|
||||
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'پروفایلها در دسترس نیستند؛ فهرست هویتهای مجاز دریافت نشد.'}))}});
|
||||
return ()=>{active=false};
|
||||
},[revision]);
|
||||
useEffect(()=>{let active=true;setStatus(null);setSessions(null);setUsage(null);setErrors(e=>({health:e.health,profiles:e.profiles}));if(!profile)return;
|
||||
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:name+' unavailable — no fallback values.'}))};
|
||||
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:(({Status:'وضعیت',Sessions:'نشستها',Usage:'مصرف'} as Record<string,string>)[name]??name)+' در دسترس نیست؛ مقدار جایگزین وجود ندارد.'}))};
|
||||
runtime.status(profile).then(v=>{if(active)setStatus(v)}).catch(()=>fail('Status'));
|
||||
runtime.sessions(profile,offset).then(v=>{if(active)setSessions(v)}).catch(()=>fail('Sessions'));
|
||||
runtime.usage(profile).then(v=>{if(active)setUsage(v)}).catch(()=>fail('Usage'));
|
||||
return ()=>{active=false};
|
||||
},[profile,offset,revision]);
|
||||
return <section aria-label="Authenticated runtime" className="bg-white border rounded-2xl p-5 space-y-4">
|
||||
<div className="flex justify-between"><h2 className="font-bold">Hermes runtime — backend authenticated reads</h2><Button onClick={()=>setRevision(r=>r+1)}>Refresh runtime</Button></div>
|
||||
<p>No browser runtime credentials or direct Hermes connection. Refresh observations are not heartbeat timestamps.</p>
|
||||
return <section aria-label="اجرای احرازهویتشده" className="bg-white border rounded-2xl p-5 space-y-4">
|
||||
<div className="flex justify-between"><h2 className="font-bold">اطلاعات اجرای Hermes — خواندن احرازهویتشده از سرور</h2><Button onClick={()=>setRevision(r=>r+1)}>بازخوانی اطلاعات اجرا</Button></div>
|
||||
<p>اطلاعات محرمانه اجرا وارد مرورگر نمیشود و اتصال مستقیم به Hermes وجود ندارد. زمان دریافت پاسخ، زمان ضربان حیات نیست.</p>
|
||||
{Object.entries(errors).filter(([,message])=>message).map(([name,message])=><p key={name} role="alert">{message}</p>)}
|
||||
{health&&<div><p>Inventory service: {health.ok?'responsive':'not responsive'} (not live Hermes health)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>Client observed at: {observed}. Client receipt time only; not capture time or live heartbeat.</p></div>}
|
||||
<label>Authorized runtime profile<select aria-label="Authorized runtime profile" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">Select authorized profile</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
|
||||
{!profiles.length&&!errors.profiles&&<p>No authorized profiles returned.</p>}
|
||||
{profiles.map(p=><div key={p.name}>{p.name} · Gateway {p.provenance?'unknown (snapshot; not process readiness)':p.gateway_running?'running':'stopped'} · {p.is_default?'default profile':'non-default profile'}<Snapshot value={p.provenance}/></div>)}
|
||||
{status&&<div><h3>Profile status</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>Gateway: {status.provenance?'unknown':status.gateway_running?'running':'stopped'} · State: {status.provenance?'unknown':status.gateway_state??'Unknown'} · Active agents: {status.provenance?'unknown':status.active_agents}</p></div>}
|
||||
{usage&&<div><h3>Runtime usage — {usage.period_days} days, selected profile only</h3><Snapshot value={usage.provenance}/><p>Input tokens: {usage.totals.total_input}</p><p>Output tokens: {usage.totals.total_output}</p><p>Sessions: {usage.totals.total_sessions}</p><p>Upstream estimated cost: {usage.totals.total_estimated_cost} (currency unspecified by source; not settled billing)</p><p>Do not add this to 9router totals; attribution overlaps and is not reconciled.</p></div>}
|
||||
{sessions&&<div><h3>Sessions — {sessions.total} returned total</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>No sessions returned.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`historical snapshot flag: ${s.is_active?'active':'inactive'}; live activity unknown`:s.is_active?'active':'inactive'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>Previous sessions</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>Next sessions</Button></div>}
|
||||
{health&&<div><p>سرویس فهرست ثبتشده: {health.ok?'پاسخگو':'بدون پاسخ'} (نه سلامت زنده Hermes)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>زمان دریافت توسط مرورگر: {observed}. فقط زمان دریافت پاسخ است؛ نه زمان ثبت منبع یا ضربان زنده.</p></div>}
|
||||
<label>پروفایل اجرای مجاز<select aria-label="پروفایل اجرای مجاز" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">انتخاب پروفایل مجاز</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
|
||||
{!profiles.length&&!errors.profiles&&<p>پروفایل مجازی دریافت نشد.</p>}
|
||||
{profiles.map(p=><div key={p.name}>{p.name} · درگاه {p.provenance?'نامشخص (نمای ثبتشده؛ نه آمادگی فرایند)':p.gateway_running?'در حال اجرا':'متوقف'} · {p.is_default?'پروفایل پیشفرض':'پروفایل غیرپیشفرض'}<Snapshot value={p.provenance}/></div>)}
|
||||
{status&&<div><h3>وضعیت پروفایل</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>درگاه: {status.provenance?'نامشخص':status.gateway_running?'در حال اجرا':'متوقف'} · وضعیت: {status.provenance?'نامشخص':status.gateway_state??'نامشخص'} · عاملهای فعال: {status.provenance?'نامشخص':status.active_agents}</p></div>}
|
||||
{usage&&<div><h3>مصرف اجرا — {usage.period_days} روز؛ فقط پروفایل انتخابشده</h3><Snapshot value={usage.provenance}/><p>توکن ورودی: {usage.totals.total_input}</p><p>توکن خروجی: {usage.totals.total_output}</p><p>نشستها: {usage.totals.total_sessions}</p><p>هزینه تخمینی منبع: {usage.totals.total_estimated_cost} (ارز توسط منبع مشخص نشده؛ صورتحساب قطعی نیست)</p><p>این مقدار را با مجموع 9router جمع نکنید؛ انتساب مصرف همپوشانی دارد و تطبیق داده نشده است.</p></div>}
|
||||
{sessions&&<div><h3>نشستها — {sessions.total} مجموع گزارششده</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>نشستی دریافت نشد.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`پرچم تاریخی نمای ثبتشده: ${s.is_active?'فعال':'غیرفعال'}; فعالیت زنده نامشخص است`:s.is_active?'فعال':'غیرفعال'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>نشستهای قبلی</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>نشستهای بعدی</Button></div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
@font-face {
|
||||
font-family: 'Shabnam';
|
||||
src: url('/fonts/shabnam-font-v33.003/fonts/webfonts/Shabnam.woff2') format('woff2');
|
||||
src: url('/fonts/shabnam-font-v5.0.1/Shabnam.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
@@ -14,89 +14,71 @@ describe('command center', () => {
|
||||
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
|
||||
render(<OrchestrationCommandCenter />);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button',{name:'Approve bounded work'})).toBeInTheDocument();
|
||||
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(within(detail).getByText(/Only staging/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable');
|
||||
fireEvent.click(screen.getByRole('button',{name:'عاملها و دپارتمانها'}));
|
||||
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(vi.mocked(api.get).mock.calls.some(([url])=>url.endsWith('/agents'))).toBe(false);
|
||||
});
|
||||
it('labels deliberately omitted scope metadata unavailable, not immutable scope',async()=>{
|
||||
const {metadata:_metadata,...safeTask}=task;
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[safeTask]:safeTask}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText('Scope / acceptance criteria unavailable — omitted by the safe backend projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText('محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
|
||||
});
|
||||
it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => {
|
||||
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
|
||||
render(<OrchestrationCommandCenter />);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Approve bounded work'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
|
||||
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Scope checked'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
expect(within(dialog).getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'محدوده checked'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
|
||||
expect(within(dialog).getByLabelText('Reason')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('Expires at')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
expect(within(dialog).getByLabelText('دلیل')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('زمان انقضا')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
await within(dialog).findByRole('alert');
|
||||
expect(api.post).toHaveBeenCalledTimes(2);
|
||||
const first=vi.mocked(api.post).mock.calls[0][1];
|
||||
expect(first).toEqual(expect.objectContaining({expectedVersion:4,decision:'APPROVED'}));
|
||||
expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(first);
|
||||
});
|
||||
it('shows measured readiness snapshot and unknown optional services without synthetic cards',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/tasks'))return {data:[]};
|
||||
return {data:{measuredAt:'2026-10-22T12:00:00Z',items:[{id:'agent-1',title:'SEO worker',status:'BLOCKED',readiness:'Missing model policy',department:'SEO'}]}};
|
||||
});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
|
||||
expect(await screen.findByText('Missing model policy')).toBeInTheDocument();
|
||||
expect(screen.getByText('BLOCKED')).toBeInTheDocument();
|
||||
});
|
||||
it('binds Gate2 using registered evidence, never editable commit or environment',async()=>{
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'SUCCEEDED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[release]:release}));
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
|
||||
it('keeps legacy Gate2 release decisions disabled without sending a command',async()=>{
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[release]:release}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Approve release'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
|
||||
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Evidence reviewed'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
|
||||
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('Registered run / artifact binding'),{target:{value:'run-1|'+'a'.repeat(64)}});
|
||||
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
await screen.findByText(/Command accepted/);
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks/t1/gates/2/decide',expect.objectContaining({runId:'run-1',artifactHash:'a'.repeat(64),commitSha:'abc123',environment:'staging',expectedVersion:4}));
|
||||
expect(await screen.findByRole('button',{name:'تأیید در Gate2'})).toBeDisabled();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('requires global impact confirmation for each kill level and reports backend rejection',async()=>{
|
||||
vi.mocked(api.put).mockRejectedValue(new Error('Forbidden: role'));
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
expect(screen.getAllByRole('option')).toHaveLength(4);
|
||||
expect(screen.getByRole('button',{name:'Apply kill switch'})).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText('Kill level'),{target:{value:'EMERGENCY_HALT'}});
|
||||
fireEvent.change(screen.getByLabelText('Kill reason'),{target:{value:'Incident'}});
|
||||
fireEvent.click(screen.getByLabelText('I confirm global operational impact'));
|
||||
fireEvent.click(screen.getByRole('button',{name:'Apply kill switch'}));
|
||||
expect(screen.getByRole('button',{name:'اعمال توقف سراسری'})).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText('سطح توقف'),{target:{value:'EMERGENCY_HALT'}});
|
||||
fireEvent.change(screen.getByLabelText('دلیل توقف'),{target:{value:'Incident'}});
|
||||
fireEvent.click(screen.getByLabelText('پیامد عملیاتی سراسری را تأیید میکنم'));
|
||||
fireEvent.click(screen.getByRole('button',{name:'اعمال توقف سراسری'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden: role');
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'EMERGENCY_HALT',reason:'Incident'});
|
||||
});
|
||||
it('sends advisory chat via typed bridge and renders text, not HTML',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'<script>unsafe</script>'}});
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
|
||||
fireEvent.change(screen.getByLabelText('Session ID'),{target:{value:'session-1'}});
|
||||
fireEvent.change(screen.getByLabelText('Message'),{target:{value:'Explain bounded work'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Send advisory message'}));
|
||||
fireEvent.click(screen.getByRole('button',{name:'گفتوگو'}));
|
||||
fireEvent.change(screen.getByLabelText('شناسه نشست'),{target:{value:'session-1'}});
|
||||
fireEvent.change(screen.getByLabelText('پیام'),{target:{value:'Explain bounded work'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'ارسال پیام مشورتی'}));
|
||||
expect(await screen.findByText('assistant: <script>unsafe</script>')).toBeInTheDocument();
|
||||
expect(document.querySelector('script')).toBeNull();
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',expect.objectContaining({sessionId:'session-1',message:'Explain bounded work'}));
|
||||
@@ -104,12 +86,12 @@ describe('command center', () => {
|
||||
it('fails closed for creation, kill and chat when overview cannot authorize capabilities',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/tasks'))return {data:[task]};throw new Error('Unavailable');});
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));
|
||||
expect(screen.queryByText('Create bounded work')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
|
||||
expect(screen.queryByRole('button',{name:'Send advisory message'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'وظیفهها و تأییدها'}));
|
||||
expect(screen.queryByText('ایجاد کار محدود')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'گفتوگو'}));
|
||||
expect(screen.queryByRole('button',{name:'ارسال پیام مشورتی'})).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -118,19 +100,19 @@ describe('command center', () => {
|
||||
it('requires explicit kill capability rather than generic mutations',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([{}, {scope:'STAGE_PREPARE'}, {scope:'Human scope',acceptanceCriteria:[]}])('does not claim incomplete or legacy metadata is scope evidence: %j',async metadata=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[{...task,metadata}]:{...task,metadata}}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText(/Scope \/ acceptance criteria unavailable/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText(/محدوده و معیارهای پذیرش در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
|
||||
});
|
||||
it('separates human evidence from server workflow scope without inventing a marker',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:task}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText('Backend-reported scope / acceptance criteria')).toBeInTheDocument();
|
||||
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText('محدوده و معیارهای پذیرش گزارششده از سرور')).toBeInTheDocument();
|
||||
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
|
||||
});
|
||||
@@ -4,21 +4,24 @@ import RouterUsagePanel from '../components/RouterUsagePanel';
|
||||
import RuntimeReadPanel from '../components/RuntimeReadPanel';
|
||||
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
|
||||
import { orchestration, killLevels, actionBlockReason, commandFailure } from '../services/orchestration';
|
||||
import {label,actionLabel,Records} from '../components/OrchestrationPresentation';
|
||||
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
|
||||
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Runtime health & sessions','Chat'] as const;
|
||||
const sections = ['نمای کلی','وظیفهها و تأییدها','اجراها و خروجیها','عاملها و دپارتمانها','مدلها و بودجهها','زمانبندیها','ممیزی و انتشارها','توقف اضطراری','مصرف و سهمیه 9router','اطلاعات اجرا و نشستها','گفتوگو'] as const;
|
||||
type Section = typeof sections[number];
|
||||
const resources:Partial<Record<Section,Resource>> = {'Agents & departments':'agents','Models & budgets':'model-policy','Schedules':'schedules','Audit & releases':'releases'};
|
||||
const errorText=(e:unknown)=> e instanceof Error ? e.message : 'Unknown backend error';
|
||||
function Json({value}:{value:unknown}) {return <pre className="text-xs whitespace-pre-wrap break-all bg-gray-50 border rounded-xl p-3" dir="ltr">{JSON.stringify(value,null,2)}</pre>}
|
||||
const resources:Partial<Record<Section,Resource>> = {'ممیزی و انتشارها':'releases'};
|
||||
const unavailable:Partial<Record<Section,string>> = {'عاملها و دپارتمانها':'فهرست عاملها به هویت و اتصال مورد اعتماد اجرا نیاز دارد. اطلاعات نمای ثبتشده را از بخش اطلاعات اجرا و نشستها ببینید؛ این اطلاعات سلامت زنده نیست.','مدلها و بودجهها':'قرارداد خواندن سیاست مدل در سرور پیادهسازی نشده است. سقف بودجه هر وظیفه در فهرست وظیفهها قابل مشاهده است.','زمانبندیها':'مسیر مدیریت زمانبندی در این نسخه پشتیبانی نمیشود؛ زمانبندی ساختگی نمایش داده نمیشود.'};
|
||||
const errorText=(e:unknown)=> {const status=(e as {response?:{status?:number}})?.response?.status;return status?`خطای سرور (HTTP ${status})`:e instanceof Error?e.message:'پاسخ سرور در دسترس نیست'};
|
||||
function Json({value}:{value:unknown}) {return <Records value={value}/>;}
|
||||
export default function OrchestrationCommandCenter() {
|
||||
const detailEpoch=useRef(0);
|
||||
const [section,setSection]=useState<Section>('Overview');
|
||||
const [section,setSection]=useState<Section>('نمای کلی');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false});
|
||||
const [tasks,setTasks]=useState<Task[]>([]);
|
||||
const [selected,setSelected]=useState<Task|null>(null);
|
||||
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
|
||||
const [error,setError]=useState(''); const [loading,setLoading]=useState(false);
|
||||
const [search,setSearch]=useState('');
|
||||
const [decisionFilter,setDecisionFilter]=useState('ALL');
|
||||
const [pending,setPending]=useState<{task:Task;action:ServerAction;key:string}|null>(null);
|
||||
const [expires,setExpires]=useState(''); const [reason,setReason]=useState('');
|
||||
const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false);
|
||||
@@ -34,7 +37,7 @@ export default function OrchestrationCommandCenter() {
|
||||
const loadTasks=async()=> {setLoading(true);setError(''); try {setTasks(await orchestration.tasks())} catch(e){setTasks([]);setSelected(null);setError(errorText(e))} finally {setLoading(false)}};
|
||||
useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true,killSwitch:s.capabilities?.killSwitch===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false,killSwitch:false}));},[]);
|
||||
useEffect(()=> {
|
||||
const resource=resources[section]; setSnapshot(null);setError('');
|
||||
const resource=resources[section]; setSnapshot(null);
|
||||
if(!resource)return;
|
||||
let active=true;setLoading(true);
|
||||
orchestration.resource(resource).then(data=>{if(active)setSnapshot(data)}).catch(e=>{if(active)setError(errorText(e))}).finally(()=>{if(active)setLoading(false)});
|
||||
@@ -47,42 +50,49 @@ export default function OrchestrationCommandCenter() {
|
||||
setAttempted(true);setBusy(true);setCommandError('');
|
||||
try { const [runId,artifactHash]=binding.split('|');
|
||||
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,expiresAt:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
|
||||
setPending(null);setSelected(null);setSuccess('Command accepted by backend; refreshed authoritative state.');await loadTasks();
|
||||
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
|
||||
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
|
||||
};
|
||||
const refresh=()=>{detailEpoch.current++;setSelected(null);setPending(null);void loadTasks()};
|
||||
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
|
||||
return <div className="space-y-5 font-vazir pb-12">
|
||||
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">Orchestration command center</h1><p className="text-sm text-gray-600">Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding</p></div><Button onClick={refresh} disabled={busy||loading}>Refresh authoritative state</Button></header>
|
||||
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
{loading&&<p role="status">Loading measured backend state…</p>}
|
||||
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">Unknown / unavailable: {error}. No fallback data. <button onClick={refresh}>Reload tasks</button></p>}
|
||||
return <div dir="rtl" lang="fa" className="space-y-5 font-vazir pb-12">
|
||||
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">مرکز فرماندهی ارکستراسیون</h1><p className="text-sm text-gray-600">مرجع عملیات سرور است · Gate1 برای کار محدود · Gate2 و انتشار غیرفعال هستند</p></div><Button onClick={refresh} disabled={busy||loading}>بازخوانی وضعیت از سرور</Button></header>
|
||||
<nav aria-label="بخشهای ارکستراسیون" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
{unavailable[section]&&<section className="bg-amber-50 border border-amber-200 rounded-2xl p-5 space-y-3"><h2 className="font-bold">این بخش در نسخه فعلی در دسترس نیست</h2><p>{unavailable[section]}</p><p>برای این بخش درخواست ناموفق تکراری به سرور ارسال نمیشود.</p></section>}
|
||||
{loading&&<p role="status">در حال دریافت وضعیت از سرور…</p>}
|
||||
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">دریافت اطلاعات از سرور ناموفق بود: {error}. داده جایگزین نمایش داده نمیشود. <button onClick={refresh}>بازخوانی وظیفهها</button></p>}
|
||||
{success&&<p role="status">{success}</p>}
|
||||
{section==='Tasks & approvals'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
|
||||
{section==='Overview'&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">Observed task inventory</h2><p>{tasks.length} tasks returned by backend. This is inventory, not agent health or runtime telemetry.</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">{state}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
|
||||
{(['Overview','Tasks & approvals','Runs & artifacts','Models & budgets','Audit & releases'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>Filter tasks<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
|
||||
{!loading&&!error&&!tasks.length&&<p>No tasks returned by backend.</p>}
|
||||
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.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>{t.department}</td><td>{t.state}</td><td>{t.operationMode}</td><td>{t.budgetLimitCents??'Unknown'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
|
||||
{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>{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>}
|
||||
{selected&&<section aria-label="Task detail" 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>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend projection.</p>}<p>Server workflow scope: unavailable in safe projection.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
|
||||
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</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?'Backend mutations unavailable':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
|
||||
<h3>Immutable approval decisions</h3><Json value={selected.decisions??[]}/>
|
||||
<h3>Runs & registered artifacts</h3>{!selected.runs?.length&&<p>No registered runs.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {r.status}</h4><p>Commit: {r.commitSha} · Environment: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
|
||||
<h3>Budget ledger (cents; not inferred usage)</h3><Json value={selected.budgetLedger??[]}/><h3>Ordered audit events</h3><Json value={selected.events??[]}/>
|
||||
{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>}
|
||||
{(['نمای کلی','وظیفهها و تأییدها','اجراها و خروجیها'] 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>
|
||||
</section>}
|
||||
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>Measured at: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>No records returned by backend.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3>{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{k}</dt><dd>{String(v??'Unknown')}</dd></div>)}</dl></article>)}</div><p>Configuration mutations require backend-advertised commands; none are inferred by this client.</p></section>}
|
||||
{section==='Kill switch'&&!capabilities.killSwitch&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
|
||||
{section==='9router usage & quota'&&<RouterUsagePanel/>}
|
||||
{section==='Runtime health & sessions'&&<RuntimeReadPanel/>}
|
||||
{section==='Chat'&&!capabilities.chat&&<p>Chat unsupported: trusted runtime bridge unavailable.</p>}
|
||||
{section==='Chat'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>Typed backend chat bridge</h2><p>Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.</p><label>Session ID<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>Message<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)}}}>Send advisory message</Button></section>}
|
||||
{pending&&<div role="dialog" aria-modal="true" aria-label="Confirm immutable command" 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>{pending.action.label}</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&&<label className="block">Expires at<input aria-label="Expires at" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</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>}
|
||||
<label className="block">Reason<input aria-label="Reason" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>I reviewed the immutable scope and binding</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
|
||||
{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>
|
||||
<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>)}
|
||||
<h3 className="font-bold">دفتر بودجه (سنت؛ نه مصرف تخمینی)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی بهترتیب</h3><Json value={selected.events??[]}/>
|
||||
</section>}
|
||||
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>زمان دریافت از سرور: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>رکوردی از سرور دریافت نشد.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3 className="font-bold">{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{label(k)}</dt><dd>{String(v??'نامشخص')}</dd></div>)}</dl></article>)}</div><p>تغییر تنظیمات فقط با فرمان مجاز سرور ممکن است؛ مرورگر فرمانی ایجاد نمیکند.</p></section>}
|
||||
{section==='توقف اضطراری'&&!capabilities.killSwitch&&<p>کنترل توقف اضطراری در این نسخه در دسترس نیست؛ مسیر سرور اجازه تغییر نمیدهد.</p>}
|
||||
{section==='توقف اضطراری'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>توقف سراسری — چهار سطح افزایشی</h2><p>این اقدام سراسری است و فقط به Task انتخابشده محدود نیست. ازسرگیری خودکار ندارد. سطح فعال تا دریافت وضعیت سرور نامشخص است.</p><label>سطح<select aria-label="سطح توقف" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l} value={l}>{label(l)}</option>)}</select></label><p>توقف کار جدید ← توقف عاملها ← منع تغییرات ← توقف اضطراری</p><label>دلیل<input aria-label="دلیل توقف" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>پیامد عملیاتی سراسری را تأیید میکنم</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('سرور فرمان توقف را دریافت کرد: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>اعمال توقف سراسری</Button></section>}
|
||||
{section==='مصرف و سهمیه 9router'&&<RouterUsagePanel/>}
|
||||
{section==='اطلاعات اجرا و نشستها'&&<RuntimeReadPanel/>}
|
||||
{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&&<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>}
|
||||
<label className="block">دلیل<input aria-label="دلیل" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>محدوده و اتصال تغییرناپذیر را بررسی کردم</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
|
||||
</div></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,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()}}));
|
||||
const proposal={id:'pending',key:'p',title:'بررسی منابع محتوا',department:'Content',state:'GATE1_PENDING',version:3,operationMode:'PREPARE',budgetLimitCents:240,metadata:{scope:'فقط تحقیق منابع عمومی',acceptanceCriteria:['سه منبع معتبر']},availableActions:['APPROVE_GATE1','HOLD_GATE1','REJECT_GATE1']};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[proposal,{...proposal,id:'held',title:'کار نگهداشته',state:'GATE1_HELD'}, {...proposal,id:'done',title:'کار پایانیافته',state:'CLOSED'}]:proposal}));});
|
||||
it('opens with obvious pending and held owner queue, scope, criteria and budget; filters without invented actions',async()=>{
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
const queue=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
|
||||
expect(await within(queue).findByRole('button',{name:proposal.title})).toBeInTheDocument();
|
||||
const card=within(queue).getByRole('button',{name:proposal.title}).closest('article')!;
|
||||
expect(within(card).getByText(/فقط تحقیق منابع عمومی/)).toBeInTheDocument();
|
||||
expect(within(card).getByText('سه منبع معتبر')).toBeInTheDocument();
|
||||
expect(within(card).getByText(/240/)).toBeInTheDocument();
|
||||
expect(within(queue).queryByText('کار پایانیافته')).not.toBeInTheDocument();
|
||||
fireEvent.change(within(queue).getByLabelText('فیلتر تصمیمها'),{target:{value:'GATE1_HELD'}});
|
||||
expect(within(queue).queryByRole('button',{name:proposal.title})).not.toBeInTheDocument();
|
||||
fireEvent.click(within(queue).getByRole('button',{name:'کار نگهداشته'}));
|
||||
expect(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
|
||||
expect(api.put).not.toHaveBeenCalled();expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('holds through authenticated server transition and reloads instead of fabricating a local decision',async()=>{
|
||||
vi.mocked(api.put).mockResolvedValue({data:{}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:proposal.title}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'تعویق تصمیم Gate1'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'بررسی بودجه'}});
|
||||
fireEvent.click(within(dialog).getByRole('checkbox'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
await waitFor(()=>expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/pending/transition',{toState:'GATE1_HELD',expectedVersion:3,idempotencyKey:expect.any(String),reason:'بررسی بودجه'}));
|
||||
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(await screen.findByRole('button',{name:proposal.title})).toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {render,screen,fireEvent,waitFor} 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(),put:vi.fn(),post:vi.fn()}}));
|
||||
it('offers Persian RTL navigation and honest unavailable tabs without calling unsupported routes',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/tasks'))return {data:[]};
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:false}}};
|
||||
throw new Error('Unexpected request '+url);
|
||||
});
|
||||
const {container}=render(<OrchestrationCommandCenter/>);
|
||||
expect(await screen.findByRole('heading',{name:'مرکز فرماندهی ارکستراسیون'})).toBeInTheDocument();
|
||||
expect(container.firstElementChild).toHaveAttribute('dir','rtl');
|
||||
for(const tab of ['عاملها و دپارتمانها','مدلها و بودجهها','زمانبندیها']){
|
||||
fireEvent.click(screen.getByRole('button',{name:tab}));
|
||||
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
|
||||
}
|
||||
await waitFor(()=>expect(api.get).toHaveBeenCalledTimes(2));
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
it('retains available-read failures in Persian instead of claiming a healthy empty inventory',async()=>{
|
||||
vi.mocked(api.get).mockRejectedValue({response:{status:503}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('دریافت اطلاعات از سرور ناموفق بود');
|
||||
expect(screen.queryByText(/وظیفهای از سرور دریافت نشد/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
import {actionBlockReason} from '../services/orchestration';
|
||||
it('keeps Gate2 disabled even if a legacy server action advertises it',()=>{expect(actionBlockReason({operationMode:'PREPARE',state:'GATE2_PENDING'} as never,{id:'g2',label:'release',gate:2,decision:'APPROVED'})).toMatch(/Gate2.*غیرفعال/)});
|
||||
@@ -57,9 +57,9 @@ describe('Users Page', () => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
// Actual GET /admin/users contract: no success envelope.
|
||||
data: mockUsers,
|
||||
meta: { lastPage: 2, total: 2 },
|
||||
meta: { lastPage: 2, total: 2, page: 1, limit: 10 },
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -260,9 +260,8 @@ describe('Users Page', () => {
|
||||
it('renders empty table state when no users are returned', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { lastPage: 1, total: 0 },
|
||||
meta: { lastPage: 1, total: 0, page: 1, limit: 10 },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -179,7 +179,8 @@ export default function Users() {
|
||||
if (role) params.append('role', role);
|
||||
|
||||
const response = await api.get(`/admin/users?${params.toString()}`);
|
||||
if (response.data?.success) {
|
||||
// The list endpoint returns { data, meta }, not a success envelope.
|
||||
if (Array.isArray(response.data?.data)) {
|
||||
const userList = response.data.data || [];
|
||||
setUsers(userList);
|
||||
setTotalPages(response.data.meta?.lastPage || 1);
|
||||
|
||||
@@ -7,13 +7,13 @@ it('does not restore stale detail after authoritative refresh while detail reque
|
||||
const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[]};
|
||||
let resolve!:(v:unknown)=>void;
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}};if(url.endsWith('/tasks'))return {data:[t]};return await new Promise<unknown>(r=>{resolve=r}) as never});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));
|
||||
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('region',{name:'Task detail'})).not.toBeInTheDocument();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));
|
||||
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('region',{name:'جزئیات وظیفه'})).not.toBeInTheDocument();
|
||||
});
|
||||
it('keeps payload immutable when navigating after an ambiguous network failure',async()=>{
|
||||
vi.resetAllMocks();const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[{id:'g1',label:'Approve safe work',gate:1,decision:'APPROVED'}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));vi.mocked(api.post).mockRejectedValue(new Error('network'));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'Approve safe work'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));fireEvent.click(d.getByRole('button',{name:'Confirm command'}));await d.findByRole('alert');
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));expect(d.getByLabelText('Reason')).toHaveValue('Reviewed');expect(d.getByLabelText('I reviewed the immutable scope and binding')).toBeChecked();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));await d.findByRole('alert');
|
||||
fireEvent.click(screen.getByRole('button',{name:'وظیفهها و تأییدها'}));expect(d.getByLabelText('دلیل')).toHaveValue('Reviewed');expect(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم')).toBeChecked();
|
||||
});
|
||||
@@ -5,43 +5,43 @@ import {orchestration} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
const action={id:'g1',label:'Review Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const action={id:'g1',label:'تأیید در Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const task={id:'t',key:'t',title:'Safe proposal',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[action],runs:[]};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[task]:task}));});
|
||||
it('refuses Production creation even when called outside form',async()=>{
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|advertised/);
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|اعلام نشده/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects ambiguous advertised action rather than selecting a mutation path',async()=>{
|
||||
const ambiguous={...action,toState:'READY'};
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/advertised/);
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/اعلام نشده/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks release transitions even when advertised by server',async()=>{
|
||||
const release={id:'release',label:'Release',toState:'RELEASING'};
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|advertised/);
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|اعلام نشده/);
|
||||
expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects Gate2 evidence from failed runs',async()=>{
|
||||
const g2={...action,gate:2 as const};
|
||||
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/successful/);
|
||||
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'Review Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));return d;}
|
||||
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));return d;}
|
||||
it('locks stale 409 command until authoritative refresh instead of retrying stale payload',async()=>{
|
||||
vi.mocked(api.post).mockRejectedValue({response:{status:409,data:{message:'Version conflict'}}});
|
||||
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'Confirm command'}));
|
||||
await waitFor(()=>expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled());
|
||||
expect(await d.findByRole('alert')).toHaveTextContent(/stale/i);
|
||||
fireEvent.click(d.getByRole('button',{name:'Confirm command'}));expect(api.post).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));
|
||||
await waitFor(()=>expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled());
|
||||
expect(await d.findByRole('alert')).toHaveTextContent(/نسخه قدیمی/);
|
||||
fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));expect(api.post).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
|
||||
});
|
||||
it('does not expose authorized task mutations when capabilities are unavailable',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))throw new Error('offline');return {data:url.endsWith('/tasks')?[task]:task};});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'Task detail'});
|
||||
expect(screen.getByRole('button',{name:'Review Gate1'})).toBeDisabled();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeDisabled();
|
||||
});
|
||||
it('prevents confirming an already expired approval',async()=>{
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
});
|
||||
@@ -13,31 +13,28 @@ describe('orchestration adapter', () => {
|
||||
expect(tasks[0].availableActions).toEqual([]);
|
||||
});
|
||||
it('rejects unadvertised transitions and incomplete Gate2 binding without a request', async () => {
|
||||
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/advertised/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/binding/);
|
||||
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/اعلام نشده/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('binds Gate2 to immutable registered run and sends version and retry-stable key', async () => {
|
||||
it('rejects even fully registered Gate2 evidence because release decisions are disabled', async () => {
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
|
||||
const input={idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)};
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({data:{id:'decision'}});
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],input)).rejects.toThrow('network');
|
||||
await orchestration.command({...task,runs:[run]},task.availableActions[0],input);
|
||||
expect(api.post).toHaveBeenLastCalledWith('/admin/orchestration/tasks/t%2F1/gates/2/decide',{expectedVersion:7,idempotencyKey:'same-key',decision:'APPROVED',expiresAt:input.expiresAt,notes:undefined,runId:'r',artifactHash:'a'.repeat(64),commitSha:'abc',environment:'staging'});
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],{idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('refuses expired approvals and unknown artifacts', async () => {
|
||||
await expect(orchestration.command(task,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/expiry/);
|
||||
await expect(orchestration.command({...task,availableActions:[{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'}]},{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'},{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/انقضا/);
|
||||
const bad={...task,runs:[{id:'r',commitSha:'abc',environment:'staging',status:'DONE',artifacts:[]}]};
|
||||
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/binding/);
|
||||
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
});
|
||||
it('loads immutable detail and rejects malformed optional resources', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{success:true,data:{...task,runs:[]}}}).mockResolvedValueOnce({data:{nonsense:true}});
|
||||
expect((await orchestration.task('t/1')).version).toBe(7);
|
||||
await expect(orchestration.resource('agents')).rejects.toThrow(/Invalid/);
|
||||
await expect(orchestration.resource('agents')).rejects.toThrow(/نامعتبر/);
|
||||
});
|
||||
it('requires kill reason and uses only typed message bridge', async () => {
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/reason/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/message/);
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/دلیل/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/پیام/);
|
||||
vi.mocked(api.put).mockResolvedValue({data:{active:true}});
|
||||
await orchestration.kill('STOP_AGENTS','Incident review');
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'STOP_AGENTS',reason:'Incident review'});
|
||||
@@ -97,7 +94,7 @@ it.each([
|
||||
it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
|
||||
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:['APPROVE_GATE1']}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/24 hours/);
|
||||
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/۲۴ ساعت/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@ import api from './api';
|
||||
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
|
||||
// Only advertised IDs select commands; task state never manufactures authorization.
|
||||
const actionCommands: Record<string, ServerAction> = {
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'Submit Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'Approve Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'Reject Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'Queue PREPARE',toState:'READY'},
|
||||
HOLD_GATE1:{id:'HOLD_GATE1',label:'تعویق تصمیم Gate1',toState:'GATE1_HELD'},
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'ارسال برای Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'تأیید کار محدود در Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'رد کار در Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'صفبندی آمادهسازی',toState:'READY'},
|
||||
};
|
||||
export function normalizeActions(value:unknown):ServerAction[] {
|
||||
if(!Array.isArray(value))return [];
|
||||
@@ -38,19 +39,20 @@ export interface CommandInput { idempotencyKey: string; reason?: string; expires
|
||||
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
|
||||
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
|
||||
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
|
||||
if(action.disabledReason)return action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'Production actions are unavailable in this panel';
|
||||
if(task.state==='EXPIRED')return 'Expired proposal: create a fresh proposal';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'Unsupported server action';
|
||||
if(action.gate===2)return 'Gate2 و انتشار در این پنل غیرفعال هستند';
|
||||
if(action.disabledReason)return 'اقدام توسط سرور غیرفعال شده است: '+action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'عملیات Production در این پنل در دسترس نیست';
|
||||
if(task.state==='EXPIRED')return 'پیشنهاد منقضی شده است؛ پیشنهاد جدید ایجاد کنید';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'اقدام سرور پشتیبانی نمیشود';
|
||||
return undefined;
|
||||
}
|
||||
export function commandFailure(error:unknown):{message:string;retryable:boolean} {
|
||||
const status=(error as {response?:{status?:number}})?.response?.status;
|
||||
if(status===409)return {message:'Stale version or idempotency conflict. Refresh authoritative state and review a fresh decision.',retryable:false};
|
||||
if(status===410)return {message:'Proposal or approval expired. Refresh; expired proposals require a new proposal.',retryable:false};
|
||||
if(status===401||status===403)return {message:'Backend denied this action. Refresh permissions before continuing.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'Backend rejected this action (HTTP '+status+'). Refresh and review the proposal.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'Backend request unavailable')+' — Outcome unknown. Retry only the identical payload/key, or refresh to reconcile.',retryable:true};
|
||||
if(status===409)return {message:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',retryable:false};
|
||||
if(status===410)return {message:'پیشنهاد یا تأیید منقضی شده است. وضعیت را بازخوانی کنید؛ پیشنهاد منقضی به پیشنهاد جدید نیاز دارد.',retryable:false};
|
||||
if(status===401||status===403)return {message:'سرور این اقدام را رد کرد. پیش از ادامه مجوزها را بازخوانی کنید.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'سرور این اقدام را رد کرد (HTTP '+status+'). وضعیت را بازخوانی و پیشنهاد را بررسی کنید.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'درخواست سرور در دسترس نیست')+' — نتیجه نامشخص است. فقط همان داده و کلید را تکرار کنید یا وضعیت را برای تطبیق بازخوانی کنید.',retryable:true};
|
||||
}
|
||||
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean;killSwitch?:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
|
||||
@@ -65,7 +67,7 @@ export function proposalError(input:CreateTaskInput):string|undefined {
|
||||
if(typeof input.metadata?.commitSha!=='string'||!/^[a-f0-9]{40}$/.test(input.metadata.commitSha))return 'Immutable commit must be 40 lowercase hex characters';
|
||||
if(typeof input.metadata?.scope!=='string'||!input.metadata.scope.trim()||input.metadata.scope.length>2000)return 'Scope must be nonblank and at most 2000 characters';
|
||||
if(!Array.isArray(input.metadata?.acceptanceCriteria)||input.metadata.acceptanceCriteria.length<1||input.metadata.acceptanceCriteria.length>20||input.metadata.acceptanceCriteria.some(value=>typeof value!=='string'||!value.trim()||value.length>500))return 'Acceptance criteria must contain 1..20 nonblank strings of at most 500 characters';
|
||||
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'Proposal requires key (1..120), title (1..255), department (1..50)';
|
||||
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است';
|
||||
}
|
||||
export const orchestration = {
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
@@ -75,33 +77,33 @@ export const orchestration = {
|
||||
},
|
||||
async task(id:string):Promise<Task> {
|
||||
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);
|
||||
if (!data?.id || !Number.isInteger(data.version)) throw new Error('Invalid task detail');
|
||||
if (!data?.id || !Number.isInteger(data.version)) throw new Error('پاسخ جزئیات وظیفه نامعتبر است');
|
||||
return {...data,availableActions:normalizeActions(data.availableActions)};
|
||||
},
|
||||
async resource(name:Resource):Promise<ResourceSnapshot> {
|
||||
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
|
||||
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('Invalid resource snapshot');
|
||||
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('پاسخ نمای ثبتشده نامعتبر است');
|
||||
return data;
|
||||
},
|
||||
async kill(level:KillLevel,reason:string):Promise<unknown> {
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('Kill switch level and reason required');
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است');
|
||||
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
|
||||
},
|
||||
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('Session and message required');
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('نشست و پیام الزامی است');
|
||||
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('Invalid typed chat reply');
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('پاسخ گفتوگو نامعتبر است');
|
||||
return data;
|
||||
},
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
||||
if (!action || action.disabledReason) throw new Error('اقدام اعلام نشده یا غیرفعال است');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است');
|
||||
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
|
||||
if (action.gate && action.decision) {
|
||||
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('Future expiry required');
|
||||
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('Gate1 expiry must be within 24 hours');
|
||||
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
|
||||
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('انقضای Gate1 باید در ۲۴ ساعت آینده باشد');
|
||||
let binding = {};
|
||||
if (action.gate === 2 && action.decision === 'APPROVED') {
|
||||
const run = task.runs?.find(r => r.id === input.runId);
|
||||
@@ -111,13 +113,13 @@ export const orchestration = {
|
||||
}
|
||||
return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,expiresAt:input.expiresAt,notes:input.reason,...binding})).data;
|
||||
}
|
||||
if (!action.toState) throw new Error('Unsupported server action');
|
||||
if (!action.toState) throw new Error('اقدام سرور پشتیبانی نمیشود');
|
||||
return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
|
||||
},
|
||||
async tasks(): Promise<Task[]> {
|
||||
const { data } = await api.get('/admin/orchestration/tasks');
|
||||
const rows = Array.isArray(data) ? data : data.data;
|
||||
if (!Array.isArray(rows)) throw new Error('Invalid orchestration task response');
|
||||
if (!Array.isArray(rows)) throw new Error('پاسخ فهرست وظیفهها نامعتبر است');
|
||||
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
||||
},
|
||||
};
|
||||
@@ -9,13 +9,13 @@ const snapshot={source:'9router',period:'7d',status:'available',reason:null,attr
|
||||
it('renders concrete backend contract, unknown quota and source freshness; period selects backend filter',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:snapshot});render(<RouterUsagePanel/>);
|
||||
expect(await screen.findByText('opaque-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Gateway totals (includes Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Hermes attribution: Unknown — not reported; do not add to gateway totals.')).toBeInTheDocument();
|
||||
expect(screen.getByText('مجموع درگاه (شامل Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('سهم مصرف Hermes: نامشخص و گزارشنشده؛ با مجموع درگاه جمع نکنید.')).toBeInTheDocument();
|
||||
expect(screen.getByText('9router')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Unknown — not reported').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('نامشخص — گزارش نشده').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/router-usage',{params:{period:'7d'}});
|
||||
fireEvent.change(screen.getByLabelText('Usage period'),{target:{value:'today'}});
|
||||
fireEvent.change(screen.getByLabelText('بازه مصرف'),{target:{value:'today'}});
|
||||
await screen.findByText('opaque-1');
|
||||
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Hermes editorial runtime distribution v4.1.0
|
||||
|
||||
Config-only tracked artifact for `canina-hermes`, explicit home `/opt/data`.
|
||||
No deployment or runtime writes were performed by this change. Parent owns CI
|
||||
copy/provisioning and Stage bridge acceptance. No dependencies beyond Python stdlib.
|
||||
|
||||
## Isolated verification / approved CI usage
|
||||
|
||||
```
|
||||
python3 -m unittest discover -s infra/hermes-editorial/tests -v
|
||||
python3 infra/hermes-editorial/installer.py install --target-home /ABSOLUTE/DISPOSABLE/HOME
|
||||
python3 infra/hermes-editorial/installer.py verify --target-home /ABSOLUTE/DISPOSABLE/HOME
|
||||
python3 infra/hermes-editorial/installer.py rollback --target-home /ABSOLUTE/DISPOSABLE/HOME
|
||||
```
|
||||
|
||||
Never use live `/opt/data` until the parent-approved CI installation step. Installer
|
||||
requires an explicit existing absolute home. Exact 19-file allowlist and SHA-256
|
||||
manifest cover unique `canina-editorial-v4` skills for six canonical profiles plus
|
||||
blocked status. No root skill inheritance is assumed. Profile discovery requires
|
||||
fresh-session validation after CI; copying bytes alone is not runtime discovery.
|
||||
|
||||
Each changed file is fsynced and atomically replaced on its destination filesystem.
|
||||
A durable write-ahead rollback journal records only allowlisted owned files and
|
||||
original modes; a process lock rejects concurrent installers. Synchronous failures
|
||||
restore the prior files. Process death may leave a partial transaction: rollback
|
||||
before retry; never activate consumers during install. This is per-file atomicity,
|
||||
not a claim of a globally atomic multi-directory swap. Rollback preflights every
|
||||
file, refuses external-edit conflicts, restores old bytes/modes, removes newly
|
||||
installed files, and leaves empty directories/lock. An unchanged reinstall performs
|
||||
no byte/mtime changes. Different-version upgrades require rollback first. Do not
|
||||
edit or symlink managed paths concurrently; installer rejects existing symlink
|
||||
ancestors but is not an adversarial filesystem sandbox.
|
||||
|
||||
## Read-only target findings (2026-10-24 UTC)
|
||||
|
||||
Inspected canonical `pmo`, `canina-competitor-worker`, `canina-seo-worker`,
|
||||
`canina-content-worker`, `canina-vet-review-worker`, `canina-qa-worker` under
|
||||
`/opt/data/profiles`. All exist; registry uses these names. PMO filesystem skill
|
||||
inventory lacks `canina-daily-content-publisher`; Content has it. Root publisher
|
||||
exists at `/opt/data/skills/canina/canina-daily-content-publisher/SKILL.md`.
|
||||
Existing cron JSON contains 17 jobs, all `enabled:false`, `state:paused` (there is
|
||||
no `paused` boolean field). CLI resolves `/opt/hermes/bin/hermes`.
|
||||
No secret values, config files, cron prompts or database contents were copied.
|
||||
Target checks establish filesystem availability, not an end-to-end workflow.
|
||||
|
||||
## Backend proposal bridge integration contract
|
||||
|
||||
Parent reports implementation `09dbe4d`, integrated as `64419f6`. This bundle does
|
||||
not mark dispatch or actual execution verified merely because this endpoint exists.
|
||||
CI/grant provisioning belongs to parent. No speculative token path or grants are
|
||||
created here; parent must pin the dedicated PMO secret file and service origin
|
||||
before implementing/exercising a submitting client. Never pass tokens in argv,
|
||||
print tokens, use generic admin grants, or submit to Production.
|
||||
|
||||
* POST `/api/internal/prepare-worker/editorial-proposals`, authenticated Bearer
|
||||
dedicated grant with id `pmo`, role `WORKFLOW_WORKER`, explicitly listed in
|
||||
`workerIds`.
|
||||
* DTO: `requestId` UUID; `pilotKind:editorial-research-to-brief-v1`;
|
||||
`operationMode:PREPARE`; `environment:staging`;
|
||||
`scope:EDITORIAL_RESEARCH_TO_BRIEF`; `researchTopic` <=180 characters;
|
||||
`acceptanceCriteria` 1..10 strings each <=500 characters; `commitSha` 40 lowercase
|
||||
hexadecimal characters; `budgetLimitCents:20`.
|
||||
* Response: `taskId`, `key`, `state:GATE1_PENDING`, `version`, `metadata`.
|
||||
* Submission is proposal preparation only, not worker execution, Gate1 approval,
|
||||
budget expenditure evidence, article creation or publishing authorization.
|
||||
A fixed reviewed request must be committed separately with a real commit SHA
|
||||
and stable requestId; ambiguous submit requires reconciliation, not new UUID retry.
|
||||
|
||||
## Remaining acceptance blockers
|
||||
|
||||
Read `payload/editorial-v4/status.json`. Dispatch/result transport, durable
|
||||
artifacts, authenticated owner gates, first-party research, image routing,
|
||||
Stage Admin auth, scoped backup/restore, publisher idempotency and public browser
|
||||
verification are all unverified. No cron activation, deployment, Production write
|
||||
or RELEASE_AUTHORIZE is included. Config isolation tests cannot establish any of
|
||||
these bridges. Policy is in each profile-local `references/policy.md`.
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"files": {
|
||||
"editorial-v4/status.json": "5694c82d4ef5ed0b070b72ad009a71c1362a4cffc32fd605e8456a8d1cb39720",
|
||||
"profiles/canina-competitor-worker/skills/canina-editorial-v4/SKILL.md": "c6827fae775b0b6ce897af6131cf56d39e6579c3cce3f8c899ac63f3967cff8b",
|
||||
"profiles/canina-competitor-worker/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/canina-competitor-worker/skills/canina-editorial-v4/references/role.json": "04472ed7d789bde1b1846da04a30d11009ee645be08ca8493eeef7460e9fff48",
|
||||
"profiles/canina-content-worker/skills/canina-editorial-v4/SKILL.md": "a7ddef44876b55174470f7c196f5307870bff93a94fbc67e0a44abb5a287da9e",
|
||||
"profiles/canina-content-worker/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/canina-content-worker/skills/canina-editorial-v4/references/role.json": "3d5cc5fb2c755b7afb69ec7ca6cc238ca13891d04d6c5e64e19c2c07402c473b",
|
||||
"profiles/canina-qa-worker/skills/canina-editorial-v4/SKILL.md": "b1558a923c9daad7ed270f6d997a13e69efa80d87345a0e515026cf8ab768910",
|
||||
"profiles/canina-qa-worker/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/canina-qa-worker/skills/canina-editorial-v4/references/role.json": "4aa981d43f17d998708127da423905bab335a7eccff1bf8f2c7e46da62ffaa60",
|
||||
"profiles/canina-seo-worker/skills/canina-editorial-v4/SKILL.md": "480e8f02bf9051ad1f324783f4231d8ebc29061b97f2602942c69ff7fe216761",
|
||||
"profiles/canina-seo-worker/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/canina-seo-worker/skills/canina-editorial-v4/references/role.json": "0fe8cd663434fd91c7fa43950327bae3aa831943a112d0ba9f5e8f6a47367ea2",
|
||||
"profiles/canina-vet-review-worker/skills/canina-editorial-v4/SKILL.md": "1f57072cf34101fa20f47c06be3d27f455e0460c5638acdaa36caf827d605243",
|
||||
"profiles/canina-vet-review-worker/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/canina-vet-review-worker/skills/canina-editorial-v4/references/role.json": "9c29f4182228221740ec46ab76fd0a47af7885a2fe45e0c3aed0b0e4980f2560",
|
||||
"profiles/pmo/skills/canina-editorial-v4/SKILL.md": "bfff4d548ed920306b35680149bde2f08a9d1264d8ce5e6907482cec61a5e13c",
|
||||
"profiles/pmo/skills/canina-editorial-v4/references/policy.md": "61cf7c686440d542ae249320a2834cba5f06a5b985248b3ace7ca6233507a8a3",
|
||||
"profiles/pmo/skills/canina-editorial-v4/references/role.json": "34627d072c8d9328411db814335165ffceaafb354fc5a5d2f1f15f531f739444"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded PMO proposal only. No approval, execution, cron or publication API."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import tempfile
|
||||
import uuid
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ENDPOINT = 'https://stageapi.canina.ir/api/internal/prepare-worker/editorial-proposals'
|
||||
|
||||
class ClientError(Exception):
|
||||
pass
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def safe(path):
|
||||
if not path.is_absolute() or '..' in path.parts:
|
||||
raise ValueError('Absolute home required')
|
||||
for p in (path, *path.parents):
|
||||
if p.is_symlink(): raise ValueError('Symlink refused')
|
||||
return path
|
||||
|
||||
|
||||
def private_read(path):
|
||||
safe(path)
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
s = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_uid != os.getuid() or s.st_nlink != 1 or stat.S_IMODE(s.st_mode) not in (0o400, 0o600) or not 0 < s.st_size <= 16384:
|
||||
raise ValueError('Private runtime-owned regular file required')
|
||||
return stream.read(16385)
|
||||
|
||||
|
||||
def atomic(path, data):
|
||||
fd, name = tempfile.mkstemp(prefix='.pmo-', dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(data); stream.flush(); os.fsync(stream.fileno())
|
||||
os.chmod(name, 0o400); os.replace(name, path)
|
||||
finally:
|
||||
if os.path.exists(name): os.unlink(name)
|
||||
|
||||
|
||||
def submit(home, commit, proposal, *, endpoint=ENDPOINT, timeout=15):
|
||||
# endpoint override is an in-process disposable-test seam, never CLI/config input.
|
||||
safe(home)
|
||||
if not re.fullmatch('[0-9a-f]{40}', commit): raise ValueError('Full deployment SHA required')
|
||||
if not isinstance(proposal, dict) or set(proposal) != {'researchTopic', 'acceptanceCriteria'}:
|
||||
raise ValueError('Only owner topic and acceptanceCriteria accepted')
|
||||
topic, criteria = proposal['researchTopic'], proposal['acceptanceCriteria']
|
||||
if not isinstance(topic, str) or not topic.strip() or len(topic) > 180 or not isinstance(criteria, list) or not 1 <= len(criteria) <= 10 or any(not isinstance(v, str) or not v.strip() or len(v) > 500 for v in criteria):
|
||||
raise ValueError('Invalid proposal')
|
||||
token = private_read(home/'editorial-v4/credentials/editorial-pmo-token').decode('ascii')
|
||||
if not re.fullmatch('[A-Za-z0-9_-]{64}', token): raise ValueError('Invalid credential')
|
||||
directory = safe(home/'editorial-v4/client-state')
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if directory.stat().st_uid != os.getuid() or stat.S_IMODE(directory.stat().st_mode) != 0o700:
|
||||
raise ValueError('Private state directory required')
|
||||
lock = safe(directory/'lock')
|
||||
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'a') as stream:
|
||||
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
body = {**proposal, 'pilotKind':'editorial-research-to-brief-v1', 'operationMode':'PREPARE', 'environment':'staging', 'scope':'EDITORIAL_RESEARCH_TO_BRIEF', 'commitSha':commit, 'budgetLimitCents':20}
|
||||
state = safe(directory/'proposal.json')
|
||||
if state.exists():
|
||||
stored = json.loads(private_read(state))
|
||||
request_id = stored.get('requestId')
|
||||
if str(uuid.UUID(request_id)) != request_id or {k:v for k,v in stored.items() if k != 'requestId'} != body:
|
||||
raise ValueError('Existing request differs; explicit owner review required')
|
||||
body = stored
|
||||
else:
|
||||
body['requestId'] = str(uuid.uuid4())
|
||||
atomic(state, json.dumps(body, sort_keys=True).encode())
|
||||
req = urllib.request.Request(endpoint, data=json.dumps(body).encode(), headers={'Authorization':'Bearer '+token, 'Content-Type':'application/json'}, method='POST')
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
try:
|
||||
with opener.open(req, timeout=timeout) as response:
|
||||
if response.status != 201: raise ClientError('Unexpected proposal status')
|
||||
raw = response.read(16385)
|
||||
if len(raw)>16384: raise ClientError('Response exceeds bound')
|
||||
result = json.loads(raw)
|
||||
if not isinstance(result, dict) or not isinstance(result.get('taskId'), str): raise ClientError('Invalid proposal response')
|
||||
# Do not reflect arbitrary backend response bodies or credential material.
|
||||
return {'requestId':body['requestId'], 'taskId':result['taskId']}
|
||||
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
|
||||
code = getattr(error, 'code', None)
|
||||
if isinstance(error, urllib.error.HTTPError): error.close()
|
||||
raise ClientError('Proposal rejected HTTP '+str(code) if isinstance(code,int) else 'Proposal unavailable; retry same saved request') from None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--proposal-file', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
home = Path(os.environ['HERMES_HOME'])
|
||||
deployment = json.loads(private_read(home/'editorial-v4/deployment.json'))
|
||||
proposal = json.loads(private_read(args.proposal_file))
|
||||
print(json.dumps(submit(home, deployment['commitSha'], proposal), sort_keys=True))
|
||||
except (OSError, ValueError, KeyError, ClientError):
|
||||
parser.exit(1, 'PMO proposal failed (private details suppressed); saved request retained\n')
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Config-only installer. No process, network, config.yaml or scheduler changes."""
|
||||
import argparse
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PROFILES = ('pmo', 'canina-competitor-worker', 'canina-seo-worker',
|
||||
'canina-content-worker', 'canina-vet-review-worker', 'canina-qa-worker')
|
||||
ALLOWED = {'editorial-v4/status.json'} | {
|
||||
f'profiles/{p}/skills/canina-editorial-v4/{f}'
|
||||
for p in PROFILES for f in ('SKILL.md', 'references/policy.md', 'references/role.json')}
|
||||
|
||||
|
||||
def digest(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def safe(home, relative):
|
||||
path = home / relative
|
||||
for part in (path, *path.parents):
|
||||
if part.is_symlink():
|
||||
raise ValueError(f'symlink refused: {part}')
|
||||
if relative not in ALLOWED and relative not in (
|
||||
'editorial-v4/.installer/transaction.json', 'editorial-v4/.installer/lock'):
|
||||
raise ValueError('path not allowlisted')
|
||||
if path.exists() and not path.is_file():
|
||||
raise ValueError(f'not a regular file: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def atomic(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temp = tempfile.mkstemp(prefix='.editorial-', dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temp, 0o644)
|
||||
os.replace(temp, path)
|
||||
finally:
|
||||
if os.path.exists(temp):
|
||||
os.unlink(temp)
|
||||
|
||||
|
||||
def bundle():
|
||||
manifest = json.loads((ROOT / 'bundle.json').read_text())
|
||||
if set(manifest['files']) != ALLOWED:
|
||||
raise ValueError('bundle allowlist mismatch')
|
||||
result = {}
|
||||
for relative, expected in manifest['files'].items():
|
||||
path = ROOT / 'payload' / relative
|
||||
if path.is_symlink():
|
||||
raise ValueError('source symlink refused')
|
||||
data = path.read_bytes()
|
||||
if digest(data) != expected:
|
||||
raise ValueError(f'bundle digest mismatch: {relative}')
|
||||
result[relative] = data
|
||||
return result
|
||||
|
||||
|
||||
def execute(action, home):
|
||||
if not home.is_absolute() or not home.is_dir():
|
||||
raise ValueError('--target-home must be an existing absolute directory')
|
||||
files = bundle()
|
||||
paths = {r: safe(home, r) for r in files}
|
||||
journal = safe(home, 'editorial-v4/.installer/transaction.json')
|
||||
if action == 'verify':
|
||||
bad = [r for r, p in paths.items() if not p.exists() or p.read_bytes() != files[r]]
|
||||
if bad:
|
||||
raise ValueError('verification mismatch: ' + ', '.join(bad))
|
||||
return {'status': 'configured_only', 'files': len(files), 'workflow_verified': False}
|
||||
lock = safe(home, 'editorial-v4/.installer/lock')
|
||||
lock.parent.mkdir(parents=True, exist_ok=True)
|
||||
with lock.open('a') as stream:
|
||||
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if action == 'rollback':
|
||||
if not journal.exists():
|
||||
return {'status': 'nothing_to_rollback'}
|
||||
state = json.loads(journal.read_text())
|
||||
if set(state['before']) != ALLOWED or set(state['installed']) != ALLOWED:
|
||||
raise ValueError('invalid rollback allowlist')
|
||||
# Refuse external edits rather than destroying another writer\'s work.
|
||||
for r, p in paths.items():
|
||||
current = p.read_bytes() if p.exists() else None
|
||||
before = state['before'][r]
|
||||
old = base64.b64decode(before['data']) if before else None
|
||||
if current != old and (current is None or digest(current) != state['installed'][r]):
|
||||
raise ValueError(f'rollback conflict: {r}')
|
||||
restore(paths, state['before'])
|
||||
journal.unlink()
|
||||
return {'status': 'rolled_back'}
|
||||
changes = [r for r, p in paths.items() if not p.exists() or p.read_bytes() != files[r]]
|
||||
if not changes:
|
||||
return {'status': 'unchanged', 'files': len(files)}
|
||||
if journal.exists():
|
||||
raise ValueError('existing transaction: rollback before upgrade or recovery')
|
||||
before = {r: {'data': base64.b64encode(p.read_bytes()).decode(),
|
||||
'mode': p.stat().st_mode & 0o777} if p.exists() else None
|
||||
for r, p in paths.items()}
|
||||
state = {'before': before, 'installed': {r: digest(v) for r, v in files.items()}}
|
||||
atomic(journal, json.dumps(state, sort_keys=True).encode())
|
||||
try:
|
||||
for r in changes:
|
||||
atomic(paths[r], files[r])
|
||||
except BaseException:
|
||||
restore(paths, before)
|
||||
journal.unlink()
|
||||
raise
|
||||
return {'status': 'installed_config_only', 'files': len(files)}
|
||||
|
||||
|
||||
def restore(paths, before):
|
||||
for r, p in paths.items():
|
||||
old = before[r]
|
||||
if old is None:
|
||||
p.unlink(missing_ok=True)
|
||||
else:
|
||||
atomic(p, base64.b64decode(old['data']))
|
||||
os.chmod(p, old['mode'])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=['install', 'verify', 'rollback'])
|
||||
parser.add_argument('--target-home', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(json.dumps(execute(args.action, args.target_home), sort_keys=True))
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
parser.exit(1, f'{error}\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"stage": "blocked",
|
||||
"production": "unauthorized",
|
||||
"cron_activation_allowed": false,
|
||||
"existing_cron_expected": 17,
|
||||
"workflow_exercised": false,
|
||||
"bridges": {
|
||||
"dispatch_results": "unverified",
|
||||
"artifact_store": "unverified",
|
||||
"owner_gate1_gate2": "unverified",
|
||||
"first_party_research": "unverified",
|
||||
"image_route": "unverified",
|
||||
"stage_admin_auth": "unverified",
|
||||
"backup_restore": "unverified",
|
||||
"publisher_idempotency": "unverified",
|
||||
"public_browser_verification": "unverified"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: canina-competitor-worker
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Independent parallel Persian market/SERP research with retrieved evidence; no publication.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "canina-competitor-worker",
|
||||
"role": "Independent parallel Persian market/SERP research with retrieved evidence; no publication.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: canina-content-worker
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Canina inventory research, immutable draft/image, revisions, then approved authenticated publisher bridge; never self-approve.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "canina-content-worker",
|
||||
"role": "Canina inventory research, immutable draft/image, revisions, then approved authenticated publisher bridge; never self-approve.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: canina-qa-worker
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Independent revised-hash QA and public verification; never waive critical findings.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "canina-qa-worker",
|
||||
"role": "Independent revised-hash QA and public verification; never waive critical findings.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: canina-seo-worker
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Parallel first-party SEO research, then independent same-hash draft review; no self-authored approval.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "canina-seo-worker",
|
||||
"role": "Parallel first-party SEO research, then independent same-hash draft review; no self-authored approval.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: canina-vet-review-worker
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Independent exact-hash medical evidence review; internal AI review, not human veterinary certification.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "canina-vet-review-worker",
|
||||
"role": "Independent exact-hash medical evidence review; internal AI review, not human veterinary certification.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: canina-editorial-v4
|
||||
description: "Use when running Canina editorial research or publishing. Enforce hash-bound departmental gates."
|
||||
version: 4.1.0
|
||||
---
|
||||
|
||||
# Editorial v4: pmo
|
||||
|
||||
Read references/policy.md and references/role.json before acting.
|
||||
|
||||
Synthesize research and route all work; own Gate1/Gate2 queue and evidence report. Never author/review in place of workers.
|
||||
|
||||
Stage is blocked. This installed skill is not execution evidence. No Production or cron activation.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Editorial runtime policy v4.1.0
|
||||
|
||||
This versioned skill is configuration, not a scheduler, delegation transport, approval bridge or publisher implementation. Stage is BLOCKED until every bridge below has real evidence. No Production mutations or RELEASE_AUTHORIZE. The user's approval of ten implementation steps does not approve any article, Gate1, Gate2, deployment or cron activation. Keep all existing 17 cron jobs disabled/paused. Do not overwrite existing config.yaml, SOUL.md, registry, .env, auth, skills or cron files.
|
||||
|
||||
## Mandatory departmental chain (ten steps)
|
||||
1. Preflight: verify Stage authenticated Admin API read authority, author/category, current field manifest, backup mechanism, durable artifact store, dispatch/result transport, authenticated owner approval ingress, publisher idempotency and public browser verification bridges. Check credential handles only. Unverified bridge = BLOCKED, never success. Production inventory/GSC/GA4 may be read for topic decisions only.
|
||||
2. Parallel research: dispatch distinct jobs to canina-competitor-worker (Persian market/SERP), canina-content-worker (Canina live Production inventory, overlap and user value), and canina-seo-worker (first-party demand/SEO). All three return independent evidence artifacts. Never serialize these by having PMO impersonate departments. Missing analytics is labeled unavailable; never fabricate facts, metrics, citations or demand.
|
||||
3. PMO synthesis: consume all three results and propose at least 3 genuinely distinct NEW/UPDATE candidates, with intent, evidence URLs/retrieval timestamps, medical risk, overlap decision, component scores and limitations. Scores are judgments, not invented measured demand. PMO resolves conflicts, does not substitute for content workforce. NEW daily goal never overrides safety gates.
|
||||
4. Gate1: authenticated accountable owner explicitly approves selected candidate and immutable brief hash for this run and Stage. HOLD/REJECT/timeout/missing bridge block progress. No auto approval, inferred approval or previous-run reuse.
|
||||
5. Draft and image: canina-content-worker produces immutable Persian draft and source ledger with SHA-256. Verify current image route/quota before exactly one final generation attempt; network ambiguity counts as an attempt, no retries. Validate bytes, MIME, dimensions and visual appropriateness. Image failure is reported and permits truthful empty image fields, never a fabricated URL. No invented human author/endorsement.
|
||||
6. Independent review: canina-vet-review-worker and canina-seo-worker independently review the same exact draft SHA-256 in parallel. Return identity, hash, evidence, findings, critical blockers and decision. Internal AI veterinary evidence review is not a licensed human certification. High-risk guidance requires two independent authoritative sources, one guideline/official authority/systematic review/primary study; no invented diagnosis, dosing or cure claims.
|
||||
7. Revision and hash QA: Content resolves both reviews into a new immutable artifact and resolution ledger. canina-qa-worker verifies revised SHA-256, source mapping, HTML/metadata, relation IDs, complete current Admin field dispositions, links, truthful author attribution, overlap and review resolutions. QA_PASSED names exact revised hash. Any subsequent byte/payload/image change invalidates QA and approvals and requires renewed affected reviews/QA.
|
||||
8. Gate2: authenticated owner explicitly approves publication of exact QA-passed revised hash, full payload digest, image disposition, environment and run ID. Gate1 is not Gate2. Reject stale/mismatched/replayed approval. Never automatically approve to meet quota.
|
||||
9. Authenticated publisher: Content invokes approved Stage Admin API bridge only after gates, scoped nonempty backup, immediate uniqueness recheck and verified permissions. One idempotent NEW/UPDATE mutation per selected action, keyed by run/environment/payload hash; ambiguous timeout requires authenticated reconciliation, not blind retry. No SQL/Prisma/file-copy bypass, forged JWT or exposed credentials. No changes to products, prices, stock, users, schema or unrelated records.
|
||||
10. Public verification: QA reads back authenticated persisted fields and independently verifies exact public identity, title/H1, content/citations, metadata/canonical/schema/dates, attribution, listing, links and desktop/mobile rendering/image disposition. HTTP 200 alone may be soft-404 and is not completion. Postwrite failure = PUBLISHED BUT VERIFICATION FAILED. Only actual evidence permits PUBLISHED/UPDATED. PMO reports concise Persian evidence and blockers, never claims end-to-end success from config tests.
|
||||
|
||||
## Artifact and bridge contract
|
||||
Every artifact/result includes run_id, task_id, canonical profile, environment, created_at UTC, dependencies, immutable artifact path/URI, sha256, evidence (retrieved URLs and timestamps), assumptions, proposal, risks, acceptance_tests and blockers. Missing/failed worker output cannot be silently replaced by parent prose. Dispatch bridge must demonstrate real canonical-profile invocation and authenticated result ingestion; approval ingress must identify authorized owner and bind exact hashes. Durable object storage, research data access, image endpoint, Stage authenticated read/write, scoped backup/restore, publisher reconciliation and independent browser/public verification need representative evidence before Stage can be unblocked by a separately reviewed tracked change. No bridge flags in this bundle are assertions of runtime capability.
|
||||
|
||||
The root canina-daily-content-publisher skill was not discoverable by PMO on inspection. This self-contained profile-local policy/role distribution intentionally uses unique canina-editorial-v4 paths rather than overwriting that publisher or relying on root inheritance. Existing publisher procedures may supplement but never weaken these gates. Fresh-session skill discovery must be checked after approved CI installation; existing session snapshots may be stale.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "4.1.0",
|
||||
"profile": "pmo",
|
||||
"role": "Synthesize research and route all work; own Gate1/Gate2 queue and evidence report. Never author/review in place of workers.",
|
||||
"policy": "policy.md",
|
||||
"auto_approval": false
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
# Stage editorial runtime wiring
|
||||
|
||||
This slice is executable but does not itself deploy or submit a live proposal. Parent must promote this commit through the existing authenticated, serialized Stage CI. No Production, cron activation, approval, executor or publishing changes.
|
||||
|
||||
`stage_runtime_provision` runs disposable tests and the clean approved-SHA gate before provisioning. It inspects the persistent target home and streams the reviewed Python source plus an exact 22-file package (installer, client, manifest and 19 allowlisted payloads) through `docker exec -i canina-hermes python3 -B`. It uses the container's configured identity, never host-UID writes into the home. The fixed package directory is `$HERMES_HOME/editorial-v4/runtime-package` (0700); source/package files and deployment marker are 0400. The 19 profile/status files are installed and verified by the existing installer; the six skill paths are checked by actual `hermes skills list` calls under each profile home. No profile config.yaml is replaced.
|
||||
|
||||
A dedicated random 64-character PMO credential is generated within the target at `credentials/editorial-pmo-token` (0400, runtime owner). Existing runtime-owned credentials directories may be 0700 or non-writable-by-others 0755 without changing unrelated files. Only the digest crosses back to CI. CI atomically extends the fixed backend four-field secret, preserving existing worker/CI identities and digests; conflicts fail closed. Backend grants remain 0400 and owned by its mapped UID/GID. Repeat Stage provisioning validates the optional canonical third PMO grant rather than rejecting its own installation. Clean approved SHA is checked again at the wiring entrypoint.
|
||||
|
||||
## Verify after successful Stage CI
|
||||
|
||||
On the remote host:
|
||||
|
||||
```sh
|
||||
docker exec canina-hermes sh -c 'python3 -B "$HERMES_HOME/editorial-v4/runtime-package/installer.py" verify --target-home "$HERMES_HOME"'
|
||||
for profile in pmo canina-competitor-worker canina-seo-worker canina-content-worker canina-vet-review-worker canina-qa-worker; do
|
||||
docker exec -e HERMES_HOME="/opt/data/profiles/$profile" canina-hermes /opt/hermes/bin/hermes skills list
|
||||
done
|
||||
```
|
||||
|
||||
Target home `/opt/data` was confirmed read-only during development. CI derives it from inspect rather than hardcoding it. These commands are not evidence that installation happened before promotion.
|
||||
|
||||
## Submit FROM target only
|
||||
|
||||
Owner/PMO supplies a private runtime-owned 0400 JSON file, e.g. `/opt/data/editorial-v4/owner-proposal.json`, containing exactly `researchTopic` and `acceptanceCriteria` as described in `backend/src/orchestration-worker/editorial-bridge.md`. No sample topic/content is authored by this provisioning slice.
|
||||
|
||||
```sh
|
||||
docker exec canina-hermes sh -c 'python3 -B "$HERMES_HOME/editorial-v4/runtime-package/client.py" --proposal-file "$HERMES_HOME/editorial-v4/owner-proposal.json"'
|
||||
```
|
||||
|
||||
The CLI accepts no URL, credential, actor, budget or commit override. It reads the deployment SHA installed by the approved CI rollout and posts only to `https://stageapi.canina.ir/api/internal/prepare-worker/editorial-proposals`, disables redirects and ambient proxies, sends Bearer PMO authentication, and fixes PREPARE/staging/editorial scope/pilot/budget20. Only taskId/requestId are returned. Confirm successful deployed SHA in CI before submitting. The stable request body is saved privately in `editorial-v4/client-state/proposal.json` before the first HTTP attempt. Retry the same invocation after timeout, denial or unknown outcome. Changed immutable proposal/SHA is refused; do not delete the state to retry an ambiguous request. This client intentionally represents one bounded pilot; starting a different proposal requires separate owner review, not automatic state reset.
|
||||
|
||||
The proposal endpoint creates Gate1 pending only; genuine independent authenticated panel review is still required. This commit performs no live approval and claims no ten-step editorial execution.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts/tests
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s infra/hermes-editorial/tests
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p test_editorial_provision.py
|
||||
bash -n scripts/rollout-stage.sh
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Verified 15 existing script tests, six installer/client tests and one real disposable runtime-install/grant test. HTTP tests exercise a real local TCP server (401/403/409/redirect denial, bounded timeout, identical retry body and changed-SHA rejection). Stage wiring tests execute streamed source against a private home and real Compose rendering, preserving existing grants over repeat provisioning; Docker/DB reads are isolated fixtures and no live install occurs in tests.
|
||||
@@ -0,0 +1,57 @@
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
class ClientTests(unittest.TestCase):
|
||||
def test_client_exists(self):
|
||||
self.assertTrue((ROOT / 'client.py').is_file(), 'executable PMO client missing')
|
||||
|
||||
def test_http_boundary_and_stable_request(self):
|
||||
spec = importlib.util.spec_from_file_location('client', ROOT / 'client.py')
|
||||
c = importlib.util.module_from_spec(spec); spec.loader.exec_module(c)
|
||||
received = []
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
status = 201
|
||||
def do_POST(self):
|
||||
received.append((self.path, self.headers['Authorization'], json.loads(self.rfile.read(int(self.headers['Content-Length'])))))
|
||||
if self.status == 0:
|
||||
time.sleep(0.15)
|
||||
return
|
||||
self.send_response(self.status)
|
||||
if self.status == 302: self.send_header('Location', '/leaked')
|
||||
self.end_headers(); self.wfile.write(b'{"taskId":"fixture-task"}')
|
||||
def log_message(self, *args): pass
|
||||
server = HTTPServer(('127.0.0.1', 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp); (home/'editorial-v4/credentials').mkdir(mode=0o700, parents=True)
|
||||
token = home/'editorial-v4/credentials/editorial-pmo-token'; token.write_text('x'*64); token.chmod(0o400)
|
||||
proposal = {'researchTopic':'Owner supplied topic', 'acceptanceCriteria':['Cite dated sources']}
|
||||
endpoint = 'http://127.0.0.1:%s/api/internal/prepare-worker/editorial-proposals' % server.server_port
|
||||
a = c.submit(home, 'a'*40, proposal, endpoint=endpoint)
|
||||
b = c.submit(home, 'a'*40, proposal, endpoint=endpoint)
|
||||
self.assertEqual(a,b); self.assertEqual(received[0][2],received[1][2])
|
||||
self.assertEqual(received[0][2]['budgetLimitCents'],20)
|
||||
self.assertEqual(received[0][1], 'Bearer '+'x'*64)
|
||||
with self.assertRaises(ValueError): c.submit(home,'b'*40,proposal,endpoint=endpoint)
|
||||
for status in (401,403,409,302):
|
||||
Handler.status=status
|
||||
with self.assertRaises(c.ClientError): c.submit(home,'a'*40,proposal,endpoint=endpoint)
|
||||
self.assertEqual(len(received),6)
|
||||
Handler.status=0
|
||||
with self.assertRaises(c.ClientError): c.submit(home,'a'*40,proposal,endpoint=endpoint,timeout=0.02)
|
||||
self.assertEqual(received[-1][2]['requestId'],received[0][2]['requestId'])
|
||||
token.chmod(0o644)
|
||||
with self.assertRaises(ValueError): c.submit(home,'a'*40,proposal,endpoint=endpoint)
|
||||
finally:
|
||||
server.shutdown(); server.server_close(); thread.join()
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,73 @@
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / 'installer.py'
|
||||
|
||||
class InstallerTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.home = pathlib.Path(self.tmp.name) / 'home'
|
||||
self.home.mkdir()
|
||||
(self.home / 'config.yaml').write_text('untouched: true\n')
|
||||
(self.home / 'cron').mkdir()
|
||||
(self.home / 'cron/jobs.json').write_text('{"jobs":[]}')
|
||||
|
||||
def run_cli(self, action, *extra):
|
||||
return subprocess.run([sys.executable, str(SCRIPT), action,
|
||||
'--target-home', str(self.home), *extra],
|
||||
capture_output=True, text=True)
|
||||
|
||||
def test_install_is_idempotent_and_verify_is_read_only(self):
|
||||
result = self.run_cli('install')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
first = {str(p.relative_to(self.home)): (p.read_bytes(), p.stat().st_mtime_ns)
|
||||
for p in self.home.rglob('*') if p.is_file()}
|
||||
self.assertEqual(self.run_cli('install').returncode, 0)
|
||||
self.assertEqual(self.run_cli('verify').returncode, 0)
|
||||
second = {str(p.relative_to(self.home)): (p.read_bytes(), p.stat().st_mtime_ns)
|
||||
for p in self.home.rglob('*') if p.is_file()}
|
||||
self.assertEqual(first, second)
|
||||
self.assertEqual((self.home / 'config.yaml').read_text(), 'untouched: true\n')
|
||||
self.assertEqual((self.home / 'cron/jobs.json').read_text(), '{"jobs":[]}')
|
||||
skills = list((self.home / 'profiles/pmo/skills').rglob('SKILL.md'))
|
||||
self.assertTrue(skills)
|
||||
status = json.loads((self.home / 'editorial-v4/status.json').read_text())
|
||||
self.assertEqual(status['stage'], 'blocked')
|
||||
self.assertFalse(status['cron_activation_allowed'])
|
||||
|
||||
def test_rollback_restores_previous_files_and_modes(self):
|
||||
path = self.home / 'profiles/pmo/skills/canina-editorial-v4/SKILL.md'
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text('previous owned version')
|
||||
path.chmod(0o600)
|
||||
self.assertEqual(self.run_cli('install').returncode, 0)
|
||||
self.assertEqual(self.run_cli('rollback').returncode, 0)
|
||||
self.assertEqual(path.read_text(), 'previous owned version')
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
self.assertFalse((self.home / 'editorial-v4/status.json').exists())
|
||||
self.assertEqual(self.run_cli('rollback').returncode, 0)
|
||||
|
||||
def test_refuses_symlink_escape_before_copy(self):
|
||||
outside = pathlib.Path(self.tmp.name) / 'outside'
|
||||
outside.mkdir()
|
||||
(self.home / 'profiles').symlink_to(outside, target_is_directory=True)
|
||||
self.assertNotEqual(self.run_cli('install').returncode, 0)
|
||||
self.assertEqual(list(outside.iterdir()), [])
|
||||
self.assertFalse((self.home / 'editorial-v4/status.json').exists())
|
||||
|
||||
def test_verify_detects_drift_and_rollback_refuses_external_edits(self):
|
||||
self.assertEqual(self.run_cli('install').returncode, 0)
|
||||
path = self.home / 'profiles/pmo/skills/canina-editorial-v4/SKILL.md'
|
||||
path.write_text('external change')
|
||||
self.assertNotEqual(self.run_cli('verify').returncode, 0)
|
||||
self.assertNotEqual(self.run_cli('rollback').returncode, 0)
|
||||
self.assertEqual(path.read_text(), 'external change')
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,24 @@
|
||||
# Authenticated one-shot Tech adapter (not deployed)
|
||||
|
||||
`tech_adapter.py` is trusted host-side orchestration, not a web endpoint. It takes an explicit task UUID, service origin, private artifact root and reviewed admission JSON file. Credential is read exclusively from `/run/secrets/prepare_worker_credential`, with descriptor-relative no-symlink traversal, private file permissions, ownership, regular-file/one-link and bounded-read checks. No token is emitted. HTTPS only in CLI; loopback HTTP exists only in the Python disposable-test interface. Redirects are never followed.
|
||||
|
||||
Contract frozen with parent:
|
||||
- POST `/internal/prepare-worker/tech-claim` `{taskId}` -> `{lease}` or `{lease:null}`. Backend owns stored task admission, READY and independent Gate1. Lease must include exact `pilotKind:tech-dev-clamp-quantity-v1`; removing that sole extension must yield the existing strict staging/first-attempt/20-cent/30-second lease. Task ID must match explicit caller UUID. No arbitrary task text enters inference.
|
||||
- POST existing `heartbeat` with only taskId/runId/leaseToken -> `{leaseUntil}`. No retries. Entire DNS/connect/response-body operation is isolated in a spawned process, killed after 4.5s plus <=.2s reap. This avoids socket timeout slow-drip gaps. Existing LeaseGuard aborts cancellable inference on denial; no local lease extension.
|
||||
- POST `tech-complete` with binding plus <=2048-byte generated `source`, only after independent local QA9 and final heartbeat. Acknowledge only exact matching task/run, VERIFYING, 64hex artifactSha256 and `upper-bound-reserved`. Backend's independent validator, artifact registration and reservation retention remain separate authority. Never call existing deterministic tracer `complete` with model output.
|
||||
|
||||
Admission file must exactly contain:
|
||||
|
||||
{"maxCalls":1,"maxTokens":160,"reservationCents":20,"monetaryCapVerified":false,"acceptUnverifiedMonetaryCap":true}
|
||||
|
||||
This is explicit conservative acceptance, **not a hard monetary cap**. Provider authenticated GET `/v1/models` on 2026-10-23 returned `[{"id":"Free"}]` after filtering to id/pricing/cost/limits: no price or cap fields. Anonymous GET returned401. Therefore neither zero price nor independently enforced20c spend cap was verified. Retain the complete20c server reservation; no cost-zero/release/reconcile claim.
|
||||
|
||||
Installed pinned Hermes source inspection revealed default API retries3 and automatic recovery5. `inference_budget.SingleCall` now gates the OpenAI-compatible `Completions.create` resource class across client rebuilds, forces nonstreaming/max_tokens160 and denies second invocation. `infer.py` sets app attempts1, recovery0 and checks SDK retries0 before calling the fixed prompt. `runtime.py` injects that trusted gate from source into the isolated pinned process. This bounds requests/output, not provider accounting/input token cost. No new real provider inference was run or represented as authorized by this discovery.
|
||||
|
||||
## Verification (remote worktree only)
|
||||
|
||||
`python3 -m unittest discover -s infra/hermes-pilot -v`:19 tests passed, including adapter process fixture through independent QA9/Git fixture; real TCP Bearer transmission and403 rejection; total slow-drip body deadline<5s; admission rejection before network; exact pilot denial before runner construction; second provider-call prevention; existing real child/descendant cancellation regressions. Source fixture is deterministic and is **not actual model output**. TDD observed missing module, missing end-to-end behavior, missing credential validation and missing SingleCall failures before implementation.
|
||||
|
||||
`disposable_backend.ts` is an isolated Nest/PostgreSQL harness importing sibling's backend module read-only. It is never AppModule code. It records separate author/reviewer Gate1, checks pre-Gate1 denial and VERIFYING/persisted reservation/artifact retrieval. Combined execution PASSED against sibling ingestion source snapshot: task d4e88f7c-3772-47ab-a6fd-dbe00ff8bd2e, run b93a5dbf-3185-4f29-a69d-be8ad85e720c, VERIFYING, artifact b9382f575e9f27f7ad54e0cfb61ba91bc66536fa0e5df5be955563a03c285e17, retrievable with QA9, full20c reservation and zero reconciliations. Evidence: /opt/services/canina/validation/v4-tech-adapter/{adapter-proof,backend-proof}.json. Initial Docker host networking/mounts and stale generated Prisma client failed; corrected with loopback-only disposable backend, copied source and privately generated Prisma client (shared dependencies read-only). Dedicated disposable PostgreSQL had no published ports. No actual authenticated Gate1/model run, Stage change, Production, push/deploy or RELEASE_AUTHORIZE.
|
||||
|
||||
Created/changed files are confined to infra/hermes-pilot. Original dirty core/Stage remain untouched. Parent must combine sibling ingestion commit, run disposable integration and decide whether conservative admission suffices for any later model proof.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Real bounded Tech/Dev Hermes pilot (experimental, NOT enabled)
|
||||
|
||||
Owned files only in `infra/hermes-pilot`; no existing core, module, tracer, profile or runtime config changed. No push/deploy/RELEASE_AUTHORIZE. Do not wire this into the existing tracer completion endpoint: that endpoint deliberately accepts only deterministic JSON.
|
||||
|
||||
## Fixed task and boundaries
|
||||
|
||||
Task `tech-dev-clamp-quantity-v1`: produce one <=2048-byte Python `clamp_quantity(quantity)` implementation, integer range 0..99. No input/browser prompt is accepted. The model has **zero tools**, no shell/browser/Git/deploy credentials. Trusted code alone writes `quantity.py`, runs separate AST-allowlisted QA (9 boundary cases), and commits an isolated, remote-free fixture repository. This is real generated-code QA, not application QA. Source commit is recorded as provenance, not represented as the fixture's base commit.
|
||||
|
||||
`infer.py` uses installed `run_agent.AIAgent`, verified from the installed signature and `agent/agent_init.py`; `enabled_toolsets=[]` is additionally enforced by asserting empty `agent.tools`. Existing approved `OPENAI_API_KEY` is read in memory only; no messaging/API-server credentials/auth pools copied. Separate temporary HERMES_HOME, no memories/context/background review/fallback. Provider/model pinned to current canina-hermes `custom`, `https://nr.parsaaghayi.ir/v1`, `Free`; no provider installation or account changes. Existing configs remain untouched. Model output is untrusted and never directly shell-executed; QA rejects all syntax except the single nested min/max return expression before isolated Python execution.
|
||||
|
||||
Installed image identity: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`, install stamp commit `818c13be1dc4fd28987e1e881a9408224afd4535`, v0.21.6. Discovery: `/opt/hermes/hermes chat --help` supports `--oneshot`, `--max-turns`, `--run-budget`; `/opt/hermes/.venv/bin/python` loads installed API. Official skills and https://hermes-agent.nousresearch.com/docs/llms.txt consulted. The initially guessed developer API docs URL returned404; installed source/signature is authoritative for this pinned build.
|
||||
|
||||
## PREPARE mapping — parent integration required
|
||||
|
||||
`executor.execute(lease, artifact_root, infer, heartbeat)` only accepts a fresh staging, first-attempt, 20-cent, 40hex-source lease and exact lease fields; heartbeat failure aborts before inference and before QA/commit. Trusted adapter must obtain this lease via existing authenticated claim AFTER independent Gate1/READY, verify the explicitly allowlisted task identity/scope/criteria server-side, and supply heartbeat connected to the authenticated backend. A caller-created dict is NOT an authorization. Never expose this Python interface to browser requests.
|
||||
|
||||
## Heartbeat runner and parent API (this revision)
|
||||
|
||||
After independent READY/Gate1, allowlist and provider-cap admission, parent constructs
|
||||
`runner = executor.pinned_inference(executor.IMAGE)` and calls
|
||||
`executor.execute(authenticated_lease, artifact_root, runner, authenticated_heartbeat)`.
|
||||
Only trusted Python may construct runners. Callback receives an unchanged COPY of the
|
||||
original lease binding (taskId/runId/leaseToken), must use authenticated server transport,
|
||||
and must raise on any non-2xx, ownership/fencing/expiry denial or malformed response.
|
||||
Explicit `False` also denies; `None` means success for existing raise-on-error adapters.
|
||||
Callback MUST impose <=5s network timeout, no retries; a blocked callback thread cannot
|
||||
be forcibly killed by Python. It is daemonized; its result cannot restart inference or
|
||||
extend a local lease. Parent must serialize executions per server lease; the runner is
|
||||
single-use and concurrent reuse of that runner is locked out. This is not a browser API.
|
||||
|
||||
Immediate initial heartbeat; dedicated ongoing thread waits 5s between acknowledged
|
||||
calls. With required <=5s transport ceiling, heartbeat starts are <=10s apart. A stalled
|
||||
heartbeat (10s without acknowledgment), exception or denial aborts actual subprocess
|
||||
inference, not just its caller. No leaseUntil mutation/local extension occurs. Fresh
|
||||
server-authorized heartbeats retain fencing; this code cannot create authorization.
|
||||
Guard checks also fence QA/artifact commit/report return. A denial during QA prevents
|
||||
report return; any partial local fixture is not accepted completion evidence.
|
||||
|
||||
Monotonic wall ceiling 90s with cancellation reserve: work aborts at85s, remote kill
|
||||
command <=2s and local reap <=1s; bounded QA3s/Git1s. Pinned runner uses one model
|
||||
call, max_iterations1/max_tokens160, run_budget80s, tools0, no retries. An independent
|
||||
in-container timeout85s survives loss of the Docker client. Cancellation addresses
|
||||
the actual in-container process session via a random PID file plus cancellation
|
||||
marker (handles cancellation before PID publication); it kills that process group.
|
||||
Cancellation transport failure raises and prevents success, but cannot prove immediate
|
||||
remote death; independent inner timeout is the fallback. Small random marker files
|
||||
in container /tmp are intentional fencing tombstones, not configuration changes.
|
||||
|
||||
`rehearse.py` remains synthetic, never a live lease. It uses this cancellable runner
|
||||
but is NOT admission evidence. Do not run it until provider-cap approval. Existing
|
||||
20-cent reservation remains UNKNOWN, never zero, and no completion/claim/release or
|
||||
backend transport is implemented here. Existing tracer endpoint still rejects model
|
||||
reports; parent must separately implement authenticated allowlisted artifact ingestion.
|
||||
No changes to installed Hermes or runtime/profile configuration.
|
||||
|
||||
## Actual evidence and blockers
|
||||
|
||||
Evidence directory `/opt/services/canina/validation/v4-real-pilot`:
|
||||
- `red.log`: missing executor assertion failed before implementation.
|
||||
- `inference-private.log`: actual installed Hermes/provider inference exit0 under75s diagnostic ceiling; generated source saved, not fabricated. This ceiling was ONLY diagnostic, not accepted as a PREPARE lease run.
|
||||
- `model-artifact/quantity.py`: actual model artifact; independent QA passes9 cases, SHA256 `0125246b551896c5f9ee98fabeb02982a6690a9974c0eb24ef3ae676d46380d5`; isolated Git commit `95cb3d27d636ae817d6a778e8053e2f87b50e57b`.
|
||||
- `actual.log`: bounded full rehearsal failed with inner timeout exit137 at18s; no completion/QA success was assumed. Previous client-only timeout was corrected to inner process kill. **Installed model/startup cannot currently complete reliably inside30s PREPARE lease without authenticated ongoing heartbeat.** Do not extend lease locally or call the75s diagnostic a bounded lease success.
|
||||
|
||||
Contract tests: `python3 infra/hermes-pilot/test_contract.py`. Parent still owns backend integration, authenticated heartbeat orchestration, allowlist admission, billing caps, signed artifact transport and Stage CI. This commit is a real generation/independent-QA proof and fail-closed executor seam, not a live autonomous Tech department or released product.
|
||||
|
||||
## Verification of heartbeat revision
|
||||
|
||||
`python3 -m unittest discover -s infra/hermes-pilot -v`: 11 passing tests, including
|
||||
real OS child/descendant cancellation, ongoing rejection, stalled heartbeat, wall
|
||||
ceiling, concurrent runner reuse, immutable lease and unknown-cost preservation.
|
||||
The artifact success test is explicitly a deterministic process fixture, NOT model
|
||||
inference. TDD red observed for missing ongoing runner and explicit false denial;
|
||||
additional cancellation/concurrency regression cases were added and executed.
|
||||
Previously generated real model artifact was rechecked by current AST allowlist QA:
|
||||
9 cases pass, SHA256 `0125246b551896c5f9ee98fabeb02982a6690a9974c0eb24ef3ae676d46380d5`.
|
||||
No new real inference was run: README provider pricing/cap gate remains unresolved.
|
||||
Docker cancellation path is implemented but not runtime-exercised here; OS process
|
||||
group cancellation is exercised. No live backend/claim/release, push or deploy.
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"adapter-proof": {
|
||||
"taskId": "d4e88f7c-3772-47ab-a6fd-dbe00ff8bd2e",
|
||||
"runId": "b93a5dbf-3185-4f29-a69d-be8ad85e720c",
|
||||
"state": "VERIFYING",
|
||||
"costStatus": "upper-bound-reserved",
|
||||
"artifactSha256": "b9382f575e9f27f7ad54e0cfb61ba91bc66536fa0e5df5be955563a03c285e17",
|
||||
"modelInference": false,
|
||||
"disposable": true,
|
||||
"preGate1Denied": true
|
||||
},
|
||||
"backend-proof": {
|
||||
"state": "VERIFYING",
|
||||
"taskId": "d4e88f7c-3772-47ab-a6fd-dbe00ff8bd2e",
|
||||
"artifactSha256": "b9382f575e9f27f7ad54e0cfb61ba91bc66536fa0e5df5be955563a03c285e17",
|
||||
"reservedCents": 20,
|
||||
"reconciliations": 0,
|
||||
"qaCases": 9,
|
||||
"modelInference": false,
|
||||
"disposable": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Deterministic process fixture against actual disposable Nest/PostgreSQL. Not a model proof."""
|
||||
import json, pathlib, sys, time
|
||||
sys.path.insert(0,str(pathlib.Path(__file__).parent))
|
||||
import tech_adapter as a
|
||||
|
||||
def main():
|
||||
evidence=pathlib.Path('/opt/services/canina/validation/v4-tech-adapter')
|
||||
until=time.monotonic()+15
|
||||
while not (evidence/'ready.json').exists():
|
||||
if time.monotonic()>until: raise TimeoutError('Backend not ready')
|
||||
time.sleep(.1)
|
||||
ready=json.loads((evidence/'ready.json').read_text())
|
||||
source='def clamp_quantity(quantity):\n return min(99, max(0, quantity))\n'
|
||||
runner=lambda:a.executor.ProcessInference([sys.executable,'-c','print('+repr(json.dumps({'source':source,'tools':0,'model':'Free'}))+')'])
|
||||
transport=a.Transport(ready['baseUrl'],'DISPOSABLE-ONLY-TECH-ADAPTER-SECRET-1234567890',allow_loopback_http=True)
|
||||
result=a.run_once(transport,ready['taskId'],str(evidence),a.ADMISSION,runner)
|
||||
(evidence/'adapter-proof.json').write_text(json.dumps({**result,'modelInference':False,'disposable':True,'preGate1Denied':ready['preGate1Denied']}))
|
||||
(evidence/'done').touch()
|
||||
print(json.dumps(result))
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,41 @@
|
||||
/** Disposable-only integration harness: never import into AppModule. */
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import { mkdir, writeFile, readFile } from 'fs/promises';
|
||||
import { WorkerTransportModule } from '/backend/src/orchestration-worker/worker-transport.module';
|
||||
import { PrismaService } from '/backend/src/prisma/prisma.service';
|
||||
import { PrepareWorkflowService } from '/backend/src/orchestration/prepare-workflow.service';
|
||||
|
||||
async function main() {
|
||||
if(process.env.DISPOSABLE_TECH_ADAPTER !== 'yes') throw Error('Disposable flag required');
|
||||
const db = new PrismaClient();
|
||||
const token = 'DISPOSABLE-ONLY-TECH-ADAPTER-SECRET-1234567890';
|
||||
const directory = '/evidence/artifacts'; await mkdir(directory,{mode:0o700,recursive:true});
|
||||
const mod = await Test.createTestingModule({imports:[WorkerTransportModule.register({enabled:true,grants:[{id:'adapter-fixture',role:'WORKFLOW_WORKER',credentialSha256:createHash('sha256').update(token).digest('hex')}],workerIds:['adapter-fixture'],stageCiIds:[],artifactDirectory:directory,artifactBaseUrl:'https://isolated.invalid/internal/prepare-worker/artifacts'})]}).overrideProvider(PrismaService).useValue(db).compile();
|
||||
const workflow = mod.get(PrepareWorkflowService);
|
||||
const app=mod.createNestApplication(); await app.listen(31987,'0.0.0.0');
|
||||
const owner={id:'fixture-author',role:'Admin'}, reviewer={id:'fixture-reviewer',role:'SUPER_ADMIN'};
|
||||
await db.orchestrationTask.updateMany({where:{key:'tech-dev-clamp-quantity-v1'},data:{key:'previous-'+randomUUID()}});
|
||||
let t=await workflow.create({key:'tech-dev-clamp-quantity-v1',title:'Disposable clamp fixture',department:'TECH',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'tech-dev-clamp-quantity-v1',acceptanceCriteria:['Independent clamp fixture QA only']}},owner);
|
||||
// Server admission must reject before the independently recorded Gate1.
|
||||
let response=await fetch(('http://127.0.0.1:31987')+'/internal/prepare-worker/tech-claim',{method:'POST',headers:{authorization:'Bearer '+token,'content-type':'application/json'},body:JSON.stringify({taskId:t.id})});
|
||||
if(response.status!==403 && (await response.json()).lease!==null) throw Error('Pre-Gate1 claim accepted');
|
||||
t=await workflow.transition(t.id,{toState:'GATE1_PENDING',expectedVersion:t.version,idempotencyKey:randomUUID()},owner);
|
||||
t=await workflow.decide(t.id,1,{decision:'APPROVED',expiresAt:new Date(Date.now()+60000).toISOString(),expectedVersion:t.version,idempotencyKey:randomUUID()},reviewer);
|
||||
t=await workflow.transition(t.id,{toState:'READY',expectedVersion:t.version,idempotencyKey:randomUUID()},owner);
|
||||
await writeFile('/evidence/ready.json',JSON.stringify({baseUrl:'http://127.0.0.1:31987',taskId:t.id,preGate1Denied:true}));
|
||||
try {
|
||||
const until=Date.now()+45000;
|
||||
while(Date.now()<until) {try {await readFile('/evidence/done');break;}catch{} await new Promise(r=>setTimeout(r,100));}
|
||||
const task=await db.orchestrationTask.findUniqueOrThrow({where:{id:t.id}});
|
||||
const ledger=await db.orchestrationBudgetLedger.findMany({where:{taskId:t.id}});
|
||||
const artifacts=await db.orchestrationArtifact.findMany({where:{run:{taskId:t.id}}});
|
||||
if(task.state!=='VERIFYING' || ledger.length!==1 || ledger[0].kind!=='RESERVE' || ledger[0].amountCents!==20 || artifacts.length!==1) throw Error('Persistence/reservation invariant failed');
|
||||
const get=await fetch(('http://127.0.0.1:31987')+'/internal/prepare-worker/artifacts/'+artifacts[0].sha256,{headers:{authorization:'Bearer '+token}});
|
||||
const artifact=await get.json();
|
||||
if(get.status!==200 || artifact.qa.cases!==9 || artifact.applicationQa!==false) throw Error('Artifact retrieval failed');
|
||||
await writeFile('/evidence/backend-proof.json',JSON.stringify({state:task.state,taskId:t.id,artifactSha256:artifacts[0].sha256,reservedCents:20,reconciliations:0,qaCases:artifact.qa.cases,modelInference:false,disposable:true}));
|
||||
} finally {await app.close(); await db.$disconnect();}
|
||||
}
|
||||
main().catch((e)=>{console.error('Disposable integration failed',e?.message);process.exitCode=1;});
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Fixed Tech/Dev pilot. Adapter must supply a fresh authenticated PREPARE lease."""
|
||||
import datetime, hashlib, json, os, pathlib, re, subprocess, tempfile, time
|
||||
TASK='tech-dev-clamp-quantity-v1'
|
||||
IMAGE='sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f'
|
||||
|
||||
def validate_lease(lease):
|
||||
if (set(lease) != {'taskId','runId','leaseToken','leaseUntil','commitSha','environment','maxCostCents','attempt'}
|
||||
or lease['environment']!='staging' or lease['maxCostCents']!=20 or lease['attempt']!=1
|
||||
or not re.fullmatch('[a-f0-9]{40}',lease['commitSha'])):
|
||||
raise ValueError('Bounded PREPARE lease required')
|
||||
for k in ('taskId','runId','leaseToken'):
|
||||
if not re.fullmatch('[a-f0-9-]{36}',lease[k]): raise ValueError('Invalid lease binding')
|
||||
expiry=datetime.datetime.fromisoformat(lease['leaseUntil'].replace('Z','+00:00')).timestamp()
|
||||
if not 5 < expiry-time.time() <= 31: raise ValueError('Fresh 30-second lease required')
|
||||
return lease
|
||||
|
||||
def _execute(lease, artifact_root, infer, heartbeat):
|
||||
"""No claim/approval generation. heartbeat must call trusted server; errors abort.
|
||||
infer is the pinned runner, not a browser-supplied command or prompt.
|
||||
Completion is deliberately NOT sent: existing transport accepts tracer JSON only.
|
||||
"""
|
||||
validate_lease(lease)
|
||||
heartbeat(lease)
|
||||
root=pathlib.Path(tempfile.mkdtemp(prefix='real-pilot-',dir=artifact_root))
|
||||
def git(*args):
|
||||
return subprocess.check_output(['git','-C',str(root),*args],stderr=subprocess.DEVNULL,text=True,timeout=1).strip()
|
||||
git('init','-q'); git('config','user.email','pilot@invalid'); git('config','user.name','Bounded Hermes Pilot')
|
||||
(root/'README').write_text('Disposable fixture; PREPARE source '+lease['commitSha']+'\n')
|
||||
git('add','README'); git('commit','-qm','Seed isolated pilot fixture')
|
||||
base=git('rev-parse','HEAD')
|
||||
# One cancellable inference, no tools; ongoing authenticated guard.
|
||||
source=infer()
|
||||
heartbeat(lease)
|
||||
if not isinstance(source,str) or len(source.encode())>2048: raise ValueError('Invalid generated artifact')
|
||||
(root/'quantity.py').write_text(source)
|
||||
qa=subprocess.check_output(['python3','-I',str(pathlib.Path(__file__).with_name('qa.py')),str(root)],timeout=3,text=True)
|
||||
heartbeat(lease)
|
||||
git('add','quantity.py'); git('commit','-qm','Hermes generated quantity clamp; independent QA passed')
|
||||
patch=git('diff',base,'HEAD','--','quantity.py')+'\n'
|
||||
(root/'artifact.patch').write_text(patch)
|
||||
report={'kind':'REAL_HERMES_TECH_DEV_PILOT','task':TASK,'taskId':lease['taskId'],'runId':lease['runId'],
|
||||
'sourceCommit':lease['commitSha'],'artifactCommit':git('rev-parse','HEAD'),'baseCommit':base,
|
||||
'patchSha256':hashlib.sha256(patch.encode()).hexdigest(),'qa':json.loads(qa),
|
||||
'costCents':None,'costStatus':'UNKNOWN_RETAIN_FULL_20_CENT_RESERVATION',
|
||||
'gate1':'EXTERNAL_LEASE_REQUIRED','published':False,'deploymentExecuted':False}
|
||||
(root/'evidence.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
return root,report
|
||||
|
||||
from runtime import LeaseGuard, ProcessInference, pinned_inference
|
||||
|
||||
def execute(lease, artifact_root, infer, heartbeat):
|
||||
validate_lease(lease)
|
||||
with LeaseGuard(lease, heartbeat) as guard:
|
||||
guard.check()
|
||||
if not isinstance(infer, ProcessInference):
|
||||
raise TypeError("Cancellable ProcessInference required")
|
||||
def generate():
|
||||
response = json.loads(infer.run(guard))
|
||||
if not isinstance(response,dict) or response.get("tools") != 0 or response.get("model") != "Free":
|
||||
raise ValueError("Pinned tool-less model required")
|
||||
return response["source"]
|
||||
result = _execute(lease, artifact_root, generate, lambda _: guard.check())
|
||||
guard.check()
|
||||
return result
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Executed only inside pinned canina-hermes image by controlled runner."""
|
||||
import contextlib, io, json, os, pathlib, tempfile
|
||||
# Copy ONE existing inference credential in memory; no auth pools or messaging keys.
|
||||
from dotenv import dotenv_values
|
||||
key=dotenv_values('/opt/data/.env').get('OPENAI_API_KEY')
|
||||
if not key: raise RuntimeError('Existing OPENAI_API_KEY unavailable')
|
||||
home=tempfile.TemporaryDirectory(prefix='canina-real-pilot-')
|
||||
os.environ.clear()
|
||||
os.environ.update({'PATH':'/usr/bin:/bin','HOME':home.name,'HERMES_HOME':home.name,'OPENAI_API_KEY':key,'OPENAI_BASE_URL':'https://nr.parsaaghayi.ir/v1','HERMES_DISABLE_PLUGINS':'1'})
|
||||
# Installed API verified by inspect.signature at pinned image commit 818c13be.
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
from openai.resources.chat.completions import Completions
|
||||
# Patch the SDK resource class, so client rebuilds/fallback cannot reset admission.
|
||||
original_create=Completions.create
|
||||
budget=SingleCall() # injected by pinned runner, never imported from runtime disk
|
||||
def bounded_create(self, *args, **kwargs):
|
||||
if args: raise RuntimeError('Unexpected positional completion call')
|
||||
return budget.call(lambda **kw: original_create(self, **kw),kwargs)
|
||||
Completions.create=bounded_create
|
||||
from run_agent import AIAgent
|
||||
agent=AIAgent(model='Free',provider='custom',base_url='https://nr.parsaaghayi.ir/v1',api_key=key,
|
||||
enabled_toolsets=[],max_iterations=1,max_tokens=160,run_budget_seconds=80,
|
||||
skip_context_files=True,skip_memory=True,skip_background_review=True,load_soul_identity=False,
|
||||
quiet_mode=True,fallback_model={},cwd=home.name)
|
||||
agent._api_max_retries=1
|
||||
agent._auto_recovery_cycles=0
|
||||
if getattr(agent.client,'max_retries',None) != 0:
|
||||
raise RuntimeError('SDK retries must be disabled')
|
||||
if agent.tools: raise RuntimeError('Tool-less invariant failed')
|
||||
result=agent.run_conversation('Write only Python source, no markdown: define clamp_quantity(quantity) returning integer quantity clamped to inclusive 0..99. Use one return with nested min/max calls only. No annotations, comments, imports, decorators, docstrings or other statements.')
|
||||
final=result.get('final_response')
|
||||
if not isinstance(final,str) or not final.strip(): raise RuntimeError('No model artifact; result keys='+','.join(result.keys()))
|
||||
print(json.dumps({'source':final.strip()+'\n','model':'Free','tools':0}))
|
||||
home.cleanup()
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Pinned OpenAI-compatible completion boundary; not a monetary spending cap."""
|
||||
import threading
|
||||
|
||||
class SingleCall:
|
||||
def __init__(self):
|
||||
self.used = False
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def call(self, create, kwargs):
|
||||
with self.lock:
|
||||
if self.used:
|
||||
raise RuntimeError('One provider call only; no retries')
|
||||
self.used = True
|
||||
kwargs = dict(kwargs)
|
||||
kwargs['max_tokens'] = 160
|
||||
kwargs['stream'] = False
|
||||
kwargs.pop('max_completion_tokens',None)
|
||||
return create(**kwargs)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Independent structural + behavior QA. Never executes arbitrary model Python."""
|
||||
import ast, hashlib, json, pathlib, sys
|
||||
|
||||
def verify(root):
|
||||
p=pathlib.Path(root)/'quantity.py'
|
||||
if p.is_symlink() or not p.is_file() or p.stat().st_size>2048: raise ValueError('Invalid file')
|
||||
raw=p.read_bytes(); tree=ast.parse(raw)
|
||||
if len(tree.body)!=1 or not isinstance(tree.body[0],ast.FunctionDef): raise ValueError('Single function required')
|
||||
fn=tree.body[0]
|
||||
if fn.name!='clamp_quantity' or fn.decorator_list or fn.returns or fn.args.defaults or fn.args.kw_defaults or fn.args.kwonlyargs or fn.args.posonlyargs or fn.args.vararg or fn.args.kwarg or len(fn.args.args)!=1 or fn.args.args[0].arg!='quantity' or fn.args.args[0].annotation or len(fn.body)!=1 or not isinstance(fn.body[0],ast.Return): raise ValueError('Unexpected function structure')
|
||||
def expr(n):
|
||||
if isinstance(n,ast.Constant) and type(n.value) is int and 0<=n.value<=99: return
|
||||
if isinstance(n,ast.Name) and n.id=='quantity': return
|
||||
if isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id in ('min','max') and len(n.args)==2 and not n.keywords:
|
||||
for a in n.args: expr(a)
|
||||
return
|
||||
raise ValueError('Nonallowlisted syntax')
|
||||
expr(fn.body[0].value)
|
||||
scope={'__builtins__':{},'min':min,'max':max}
|
||||
exec(compile(tree,'generated-quantity','exec'),scope)
|
||||
cases=[-1000,-1,0,1,50,98,99,100,10**30]
|
||||
for q in cases:
|
||||
actual=scope['clamp_quantity'](q)
|
||||
if type(actual) is not int or actual!=max(0,min(q,99)): raise ValueError('Behavior QA failed')
|
||||
return {'passed':True,'cases':len(cases),'sha256':hashlib.sha256(raw).hexdigest(),'scope':'quantity clamp fixture only'}
|
||||
if __name__=='__main__': print(json.dumps(verify(sys.argv[1])))
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Disposable model/artifact exercise, NOT a live Gate1 approval or service completion."""
|
||||
import datetime, json, pathlib, subprocess, time, uuid
|
||||
from executor import execute, IMAGE, pinned_inference
|
||||
|
||||
def main():
|
||||
image=subprocess.check_output(['docker','inspect','--format','{{.Image}}','canina-hermes'],text=True).strip()
|
||||
if image!=IMAGE: raise RuntimeError('Pinned installed image mismatch')
|
||||
infer=pinned_inference(IMAGE)
|
||||
deadline=time.monotonic()+90
|
||||
lease={k:str(uuid.uuid4()) for k in ('taskId','runId','leaseToken')}
|
||||
lease.update(leaseUntil=(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(seconds=30)).isoformat(),commitSha=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip(),environment='staging',maxCostCents=20,attempt=1)
|
||||
def fixture_heartbeat(binding):
|
||||
if time.monotonic()>deadline: raise TimeoutError('Fixture hard deadline')
|
||||
root,report=execute(lease,'/opt/services/canina/validation/v4-real-pilot',infer,fixture_heartbeat)
|
||||
report['executionContext']='DISPOSABLE_FIXTURE_NOT_LIVE_PREPARE_LEASE'
|
||||
(root/'evidence.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps({'artifactDirectory':str(root),'report':report}))
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Trusted subprocess boundary; no claim, lease extension or completion transport."""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
HEARTBEAT_INTERVAL = 5.0
|
||||
HEARTBEAT_TIMEOUT = 5.0
|
||||
MAX_WALL_SECONDS = 90.0
|
||||
|
||||
class LeaseGuard:
|
||||
def __init__(self, lease, heartbeat):
|
||||
self.lease, self.heartbeat = lease, heartbeat
|
||||
self.stop = threading.Event()
|
||||
self.ready = threading.Event()
|
||||
self.error = None
|
||||
self.started = time.monotonic()
|
||||
self.last = self.started
|
||||
self.thread = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def _run(self):
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
if self.heartbeat(dict(self.lease)) is False:
|
||||
raise PermissionError("Authenticated heartbeat denied")
|
||||
self.last = time.monotonic()
|
||||
self.ready.set()
|
||||
except BaseException as exc:
|
||||
self.error = exc
|
||||
self.ready.set()
|
||||
return
|
||||
if self.stop.wait(HEARTBEAT_INTERVAL):
|
||||
return
|
||||
|
||||
def check(self):
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
now = time.monotonic()
|
||||
if now - self.started >= MAX_WALL_SECONDS - 5:
|
||||
raise TimeoutError('Pilot wall deadline (cancellation reserve included)')
|
||||
if now - self.last >= HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT:
|
||||
raise TimeoutError('Authenticated heartbeat stalled')
|
||||
|
||||
def __enter__(self):
|
||||
self.thread.start()
|
||||
if not self.ready.wait(HEARTBEAT_TIMEOUT):
|
||||
self.stop.set()
|
||||
raise TimeoutError('Initial authenticated heartbeat stalled')
|
||||
try:
|
||||
self.check()
|
||||
except BaseException:
|
||||
self.stop.set()
|
||||
raise
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=.05)
|
||||
|
||||
class ProcessInference:
|
||||
"""Trusted argv only. cancel_remote MUST kill the in-container process group."""
|
||||
def __init__(self, argv, input_text=None, cancel_remote=None):
|
||||
self.argv, self.input_text, self.cancel_remote = argv, input_text, cancel_remote
|
||||
self.used = False
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def run(self, guard):
|
||||
with self.lock:
|
||||
if self.used:
|
||||
raise RuntimeError('Exactly one inference allowed; no retry')
|
||||
self.used = True
|
||||
guard.check()
|
||||
# Files avoid pipe deadlocks and unbounded captured output in memory.
|
||||
with tempfile.TemporaryFile(mode='w+') as incoming, tempfile.TemporaryFile(mode='w+') as out, tempfile.TemporaryFile(mode='w+') as err:
|
||||
incoming.write(self.input_text or '')
|
||||
incoming.seek(0)
|
||||
child = subprocess.Popen(self.argv, stdin=incoming, stdout=out, stderr=err, start_new_session=True)
|
||||
try:
|
||||
while child.poll() is None:
|
||||
guard.check()
|
||||
time.sleep(.02)
|
||||
guard.check()
|
||||
if child.returncode:
|
||||
raise RuntimeError('Inference failed (exit %d)' % child.returncode)
|
||||
out.seek(0)
|
||||
result = out.read(4097)
|
||||
if len(result) > 4096:
|
||||
raise ValueError('Oversized inference response')
|
||||
return result
|
||||
finally:
|
||||
# Always cancel remote, even when docker exec itself failed.
|
||||
try:
|
||||
if self.cancel_remote:
|
||||
self.cancel_remote()
|
||||
finally:
|
||||
try:
|
||||
os.killpg(child.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
child.wait(timeout=1)
|
||||
|
||||
|
||||
def pinned_inference(image):
|
||||
actual = subprocess.check_output(['docker','inspect','--format','{{.Image}}','canina-hermes'], text=True, timeout=2).strip()
|
||||
if actual != image:
|
||||
raise RuntimeError('Pinned installed image mismatch')
|
||||
token = uuid.uuid4().hex
|
||||
pidfile = '/tmp/canina-pilot-' + token + '.pid'
|
||||
script = (pathlib.Path(__file__).with_name('inference_budget.py').read_text() + '\n' +
|
||||
pathlib.Path(__file__).with_name('infer.py').read_text())
|
||||
# Session leader is created INSIDE the container. Inner kill is independent of client.
|
||||
wrapper = ('import os,signal,subprocess,sys; '
|
||||
'p=subprocess.Popen(["timeout","--signal=KILL","85","/opt/hermes/.venv/bin/python","-"],stdin=sys.stdin,start_new_session=True); '
|
||||
'open(%r,"w").write(str(p.pid)); '
|
||||
'os.path.exists(%r) and os.killpg(p.pid,signal.SIGKILL); sys.exit(p.wait())') % (pidfile, pidfile+'.cancel')
|
||||
cancel = ('import os,signal; p=%r; '
|
||||
'\nopen(p+".cancel","w").close()\ntry:\n pid=int(open(p).read()); os.killpg(pid,signal.SIGKILL)\n'
|
||||
'except (FileNotFoundError,ProcessLookupError): pass\n'
|
||||
'finally:\n'
|
||||
' try: os.unlink(p)\n except FileNotFoundError: pass\n') % pidfile
|
||||
def cancel_remote():
|
||||
subprocess.run(['docker','exec','canina-hermes','/opt/hermes/.venv/bin/python','-c',cancel], check=True, timeout=2, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return ProcessInference(['docker','exec','-i','canina-hermes','/opt/hermes/.venv/bin/python','-c',wrapper], script, cancel_remote)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Trusted one-shot adapter; fixed task, no arbitrary prompt/command input."""
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import multiprocessing
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import stat
|
||||
import time
|
||||
import urllib.parse
|
||||
import executor
|
||||
|
||||
PILOT_KIND = executor.TASK
|
||||
SECRET_PATH = '/run/secrets/prepare_worker_credential'
|
||||
ADMISSION = {'maxCalls':1, 'maxTokens':160, 'reservationCents':20,
|
||||
'monetaryCapVerified':False, 'acceptUnverifiedMonetaryCap':True}
|
||||
|
||||
|
||||
def read_credential():
|
||||
"""Fixed mount only; pin every directory and never log a secret."""
|
||||
directory = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
|
||||
fd = None
|
||||
try:
|
||||
parts = SECRET_PATH.strip('/').split('/')
|
||||
for part in parts[:-1]:
|
||||
next_dir = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
|
||||
os.close(directory)
|
||||
directory = next_dir
|
||||
if os.fstat(directory).st_mode & 0o022:
|
||||
raise ValueError('Private secret directory required')
|
||||
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
|
||||
s = os.fstat(fd)
|
||||
if (not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_mode & 0o077
|
||||
or s.st_uid not in (0, os.getuid()) or s.st_size > 513):
|
||||
raise ValueError('Private credential required')
|
||||
token = os.read(fd, 514).decode('ascii').strip()
|
||||
if not re.fullmatch(r'[\x21-\x7e]{32,512}', token):
|
||||
raise ValueError('Private credential required')
|
||||
return token
|
||||
finally:
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def _request(pipe, origin, token, route, body):
|
||||
try:
|
||||
u = urllib.parse.urlsplit(origin)
|
||||
connection = (http.client.HTTPSConnection if u.scheme == 'https' else http.client.HTTPConnection)(u.hostname, u.port, timeout=4)
|
||||
connection.request('POST', '/internal/prepare-worker/'+route, json.dumps(body),
|
||||
{'Authorization':'Bearer '+token, 'Content-Type':'application/json'})
|
||||
response = connection.getresponse()
|
||||
raw = response.read(8193)
|
||||
if not 200 <= response.status < 300 or len(raw) > 8192:
|
||||
raise ValueError('Denied or oversized response')
|
||||
result = json.loads(raw)
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError('Invalid response')
|
||||
pipe.send((True,result))
|
||||
except BaseException:
|
||||
pipe.send((False,None))
|
||||
finally:
|
||||
pipe.close()
|
||||
|
||||
|
||||
class Transport:
|
||||
"""Entire network operation (including DNS/body) killed before 5s, no retries."""
|
||||
def __init__(self, origin, credential, *, allow_loopback_http=False):
|
||||
u = urllib.parse.urlsplit(origin)
|
||||
if (u.username or u.password or u.query or u.fragment or u.path not in ('','/')
|
||||
or not u.hostname or (u.scheme != 'https' and not
|
||||
(allow_loopback_http and u.scheme=='http' and u.hostname in ('127.0.0.1','::1')))):
|
||||
raise ValueError('Fixed HTTPS service origin required')
|
||||
if not isinstance(credential,str) or not re.fullmatch(r'[\x21-\x7e]{32,512}',credential):
|
||||
raise ValueError('Service credential required')
|
||||
self.origin, self._credential = origin, credential
|
||||
|
||||
def post(self, route, body):
|
||||
if route not in ('tech-claim','heartbeat','tech-complete'):
|
||||
raise ValueError('Route not admitted')
|
||||
ctx = multiprocessing.get_context('spawn')
|
||||
receive, send = ctx.Pipe(duplex=False)
|
||||
worker = ctx.Process(target=_request, args=(send,self.origin,self._credential,route,body), daemon=True)
|
||||
worker.start()
|
||||
send.close()
|
||||
try:
|
||||
if not receive.poll(4.5):
|
||||
raise TimeoutError('Worker transport deadline')
|
||||
try:
|
||||
ok, result = receive.recv()
|
||||
except EOFError:
|
||||
raise PermissionError('Worker transport failed') from None
|
||||
if not ok:
|
||||
raise PermissionError('Worker request denied or malformed')
|
||||
return result
|
||||
finally:
|
||||
if worker.is_alive():
|
||||
worker.kill()
|
||||
worker.join(timeout=.2)
|
||||
receive.close()
|
||||
|
||||
|
||||
def validate_admission(admission):
|
||||
if (admission != ADMISSION or type(admission.get('maxCalls')) is not int
|
||||
or type(admission.get('maxTokens')) is not int or type(admission.get('reservationCents')) is not int):
|
||||
raise ValueError('Explicit conservative admission required; monetary cap unverified')
|
||||
|
||||
|
||||
def run_once(transport, task_id, artifact_root, admission, runner_factory=None):
|
||||
validate_admission(admission)
|
||||
if not isinstance(task_id,str) or not re.fullmatch('[a-f0-9-]{36}',task_id):
|
||||
raise ValueError('Explicit task UUID required')
|
||||
response = transport.post('tech-claim', {'taskId':task_id})
|
||||
lease = response.get('lease')
|
||||
if lease is None:
|
||||
return {'state':'IDLE'}
|
||||
if not isinstance(lease,dict) or lease.get('pilotKind') != PILOT_KIND or lease.get('taskId') != task_id:
|
||||
raise ValueError('Fixed Tech admission required')
|
||||
lease = dict(lease)
|
||||
del lease['pilotKind']
|
||||
executor.validate_lease(lease)
|
||||
binding = {k:lease[k] for k in ('taskId','runId','leaseToken')}
|
||||
def heartbeat(_):
|
||||
result = transport.post('heartbeat',dict(binding))
|
||||
if set(result) != {'leaseUntil'} or not isinstance(result['leaseUntil'],str):
|
||||
raise PermissionError('Malformed heartbeat acknowledgment')
|
||||
import datetime
|
||||
expiry = datetime.datetime.fromisoformat(result['leaseUntil'].replace('Z','+00:00')).timestamp()
|
||||
if not 0 < expiry-time.time() <= 31:
|
||||
raise PermissionError('Invalid heartbeat acknowledgment')
|
||||
runner = (runner_factory or (lambda:executor.pinned_inference(executor.IMAGE)))()
|
||||
root, report = executor.execute(lease,artifact_root,runner,heartbeat)
|
||||
source = (root/'quantity.py').read_text()
|
||||
heartbeat(lease)
|
||||
result = transport.post('tech-complete',{**binding,'source':source})
|
||||
if (result.get('taskId') != task_id or result.get('runId') != lease['runId']
|
||||
or result.get('state') != 'VERIFYING' or result.get('costStatus') != 'upper-bound-reserved'
|
||||
or not isinstance(result.get('artifactSha256'),str)
|
||||
or not re.fullmatch('[a-f0-9]{64}',result['artifactSha256'])):
|
||||
raise ValueError('Invalid completion acknowledgment; no success assumed')
|
||||
return {k:result[k] for k in ('taskId','runId','state','costStatus','artifactSha256')}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Explicit one-shot Tech pilot; no release')
|
||||
parser.add_argument('--base-url', required=True)
|
||||
parser.add_argument('--task-id', required=True)
|
||||
parser.add_argument('--artifact-root', required=True)
|
||||
parser.add_argument('--admission-file', required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
admission = json.loads(pathlib.Path(args.admission_file).read_text())
|
||||
validate_admission(admission)
|
||||
transport = Transport(args.base_url,read_credential())
|
||||
result = run_once(transport,args.task_id,args.artifact_root,admission)
|
||||
print(json.dumps(result))
|
||||
except BaseException:
|
||||
print('Tech pilot failed closed; reservation retained; no completion assumed',file=__import__('sys').stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,68 @@
|
||||
import json, pathlib, sys, tempfile, threading, time, unittest
|
||||
from unittest.mock import patch
|
||||
sys.path.insert(0,str(pathlib.Path(__file__).parent))
|
||||
import executor as m
|
||||
import runtime
|
||||
from test_contract import lease
|
||||
|
||||
class Cancellation(unittest.TestCase):
|
||||
def test_wall_deadline_kills_descendant(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
marker=pathlib.Path(root,'late')
|
||||
child=f'import pathlib,time; time.sleep(.7); pathlib.Path({str(marker)!r}).touch()'
|
||||
code=f'import subprocess,sys,time; subprocess.Popen([sys.executable,"-c",{child!r}]); time.sleep(5)'
|
||||
with patch.object(runtime,'MAX_WALL_SECONDS',5.2):
|
||||
with self.assertRaises(TimeoutError): m.execute(lease(),root,m.ProcessInference([sys.executable,'-c',code]),lambda _: None)
|
||||
time.sleep(.8)
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
def test_stalled_heartbeat_cancels_child(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
marker=pathlib.Path(root,'late'); release=threading.Event(); calls=[]
|
||||
def heartbeat(_):
|
||||
calls.append(time.monotonic())
|
||||
if len(calls)>1: release.wait(3)
|
||||
code=f'import time,pathlib; time.sleep(.7); pathlib.Path({str(marker)!r}).touch()'
|
||||
try:
|
||||
with patch.object(runtime,'HEARTBEAT_INTERVAL',.05),patch.object(runtime,'HEARTBEAT_TIMEOUT',.1):
|
||||
with self.assertRaises(TimeoutError): m.execute(lease(),root,m.ProcessInference([sys.executable,'-c',code]),heartbeat)
|
||||
finally: release.set()
|
||||
time.sleep(.8); self.assertFalse(marker.exists())
|
||||
|
||||
def test_fixture_artifact_qa_and_cost_reservation(self):
|
||||
# Explicit deterministic PROCESS fixture, never reported as real model inference.
|
||||
source='def clamp_quantity(quantity):\n return min(99, max(0, quantity))\n'
|
||||
response=json.dumps(dict(source=source,model='Free',tools=0))
|
||||
beats=[]; original=lease(); snapshot=dict(original)
|
||||
def heartbeat(binding):
|
||||
beats.append(time.monotonic()); binding['leaseUntil']='untrusted mutation'
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
infer=m.ProcessInference([sys.executable,'-c',f'import time; time.sleep(.25); print({response!r})'])
|
||||
with patch.object(runtime,'HEARTBEAT_INTERVAL',.05):
|
||||
_,report=m.execute(original,root,infer,heartbeat)
|
||||
self.assertEqual(original,snapshot)
|
||||
self.assertGreater(len(beats),2)
|
||||
self.assertIsNone(report['costCents'])
|
||||
self.assertEqual(report['costStatus'],'UNKNOWN_RETAIN_FULL_20_CENT_RESERVATION')
|
||||
with self.assertRaises(RuntimeError):
|
||||
with runtime.LeaseGuard(lease(),lambda _:None) as guard: infer.run(guard)
|
||||
|
||||
def test_concurrent_reuse_rejected(self):
|
||||
infer=m.ProcessInference([sys.executable,"-c","import time; time.sleep(.3); print(1)"])
|
||||
errors=[]
|
||||
with runtime.LeaseGuard(lease(),lambda _:None) as guard:
|
||||
t=threading.Thread(target=lambda:infer.run(guard)); t.start()
|
||||
time.sleep(.05)
|
||||
with self.assertRaises(RuntimeError): infer.run(guard)
|
||||
t.join()
|
||||
|
||||
def test_explicit_false_heartbeat_denied(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
with self.assertRaises(PermissionError):
|
||||
m.execute(lease(),root,m.ProcessInference([sys.executable,"-c","print(1)"]),lambda _:False)
|
||||
|
||||
def test_callable_not_cancellable_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
with self.assertRaises(TypeError): m.execute(lease(),root,lambda:'',lambda _:None)
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,23 @@
|
||||
import datetime, importlib.util, pathlib, tempfile, unittest, uuid
|
||||
p=pathlib.Path(__file__).with_name('executor.py')
|
||||
spec=importlib.util.spec_from_file_location('pilot',p); m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
|
||||
qs=importlib.util.spec_from_file_location('qa',p.with_name('qa.py')); qa=importlib.util.module_from_spec(qs); qs.loader.exec_module(qa)
|
||||
def lease():
|
||||
d={k:str(uuid.uuid4()) for k in ('taskId','runId','leaseToken')}; d.update(environment='staging',maxCostCents=20,attempt=1,commitSha='a'*40,leaseUntil=(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(seconds=30)).isoformat()); return d
|
||||
class Contract(unittest.TestCase):
|
||||
def test_missing_lease_rejected(self):
|
||||
with self.assertRaises(ValueError): m.validate_lease({})
|
||||
def test_bounds(self):
|
||||
for k,v in [('environment','production'),('attempt',2),('maxCostCents',21),('commitSha','main'),('leaseUntil','2000-01-01T00:00:00+00:00')]:
|
||||
d=lease(); d[k]=v
|
||||
with self.assertRaises(ValueError): m.validate_lease(d)
|
||||
def test_heartbeat_denial_prevents_inference(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
def deny(_): raise PermissionError('killed')
|
||||
with self.assertRaises(PermissionError): m.execute(lease(),root,lambda:self.fail('must not infer'),deny)
|
||||
def test_qa_rejects_malicious_and_wrong_behavior(self):
|
||||
for source in ['import os\n','def clamp_quantity(quantity):\n return quantity\n','def clamp_quantity(quantity):\n return __import__("os").system("true")\n']:
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
pathlib.Path(root,'quantity.py').write_text(source)
|
||||
with self.assertRaises(ValueError): qa.verify(root)
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,24 @@
|
||||
import datetime, pathlib, sys, tempfile, threading, time, unittest
|
||||
from unittest.mock import patch
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent))
|
||||
import executor as m
|
||||
import runtime
|
||||
from test_contract import lease
|
||||
|
||||
class Heartbeats(unittest.TestCase):
|
||||
def test_ongoing_denial_kills_real_child(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
marker=pathlib.Path(root,'late')
|
||||
code=f'import time,pathlib; time.sleep(1); pathlib.Path({str(marker)!r}).touch()'
|
||||
beats=[]
|
||||
def beat(binding):
|
||||
beats.append(time.monotonic())
|
||||
if len(beats)>1: raise PermissionError('revoked')
|
||||
with patch.object(runtime,'HEARTBEAT_INTERVAL',.1):
|
||||
with self.assertRaises(PermissionError):
|
||||
m.execute(lease(),root,m.ProcessInference([sys.executable,'-c',code]),beat)
|
||||
time.sleep(1.1)
|
||||
self.assertFalse(marker.exists())
|
||||
self.assertGreaterEqual(len(beats),2)
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,102 @@
|
||||
import datetime, json, pathlib, sys, tempfile, unittest
|
||||
from unittest.mock import patch
|
||||
sys.path.insert(0,str(pathlib.Path(__file__).parent))
|
||||
from test_contract import lease
|
||||
import tech_adapter as a
|
||||
|
||||
class Adapter(unittest.TestCase):
|
||||
def test_wrong_pilot_never_constructs_inference(self):
|
||||
calls=[]
|
||||
class Transport:
|
||||
def post(self, route, body):
|
||||
calls.append(route)
|
||||
return {'lease':dict(lease(),pilotKind='arbitrary')}
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
with self.assertRaises(ValueError):
|
||||
a.run_once(Transport(),lease()['taskId'],root,{'maxCalls':1,'maxTokens':160,'reservationCents':20,'monetaryCapVerified':False,'acceptUnverifiedMonetaryCap':True},lambda: self.fail('inference constructed'))
|
||||
self.assertEqual(calls,['tech-claim'])
|
||||
|
||||
def test_end_to_end_process_fixture(self):
|
||||
source='def clamp_quantity(quantity):\n return min(99, max(0, quantity))\n'
|
||||
d=dict(lease(),pilotKind=a.PILOT_KIND); calls=[]
|
||||
class Transport:
|
||||
def post(self,route,body):
|
||||
calls.append((route,body))
|
||||
if route=='tech-claim': return {'lease':d}
|
||||
if route=='heartbeat': return {'leaseUntil':d['leaseUntil']}
|
||||
return {'taskId':d['taskId'],'runId':d['runId'],'state':'VERIFYING','artifactSha256':'b'*64,'costStatus':'upper-bound-reserved'}
|
||||
policy={'maxCalls':1,'maxTokens':160,'reservationCents':20,'monetaryCapVerified':False,'acceptUnverifiedMonetaryCap':True}
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
runner=lambda: a.executor.ProcessInference([sys.executable,'-c','print('+repr(json.dumps({'source':source,'tools':0,'model':'Free'}))+')'])
|
||||
result=a.run_once(Transport(),d['taskId'],root,policy,runner)
|
||||
self.assertEqual(result['state'],'VERIFYING')
|
||||
self.assertEqual(calls[-1][0],'tech-complete')
|
||||
self.assertEqual(calls[-1][1]['source'],source)
|
||||
self.assertNotIn('leaseToken',result)
|
||||
|
||||
class BudgetTests(unittest.TestCase):
|
||||
def test_second_provider_call_blocked_and_tokens_forced(self):
|
||||
from inference_budget import SingleCall
|
||||
seen=[]
|
||||
gate=SingleCall()
|
||||
def create(**kwargs): seen.append(kwargs); return 'ok'
|
||||
self.assertEqual(gate.call(create,{'max_tokens':999,'stream':True}),'ok')
|
||||
self.assertEqual(seen,[{'max_tokens':160,'stream':False}])
|
||||
with self.assertRaises(RuntimeError): gate.call(create,{})
|
||||
self.assertEqual(len(seen),1)
|
||||
|
||||
class TransportTests(unittest.TestCase):
|
||||
def test_invalid_credential_rejected(self):
|
||||
with self.assertRaises(ValueError): a.Transport('https://stage.invalid','short')
|
||||
|
||||
def test_real_http_auth_and_denial(self):
|
||||
import http.server, threading
|
||||
seen=[]
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self,*args): pass
|
||||
def do_POST(self):
|
||||
seen.append((self.path,self.headers.get('Authorization'),json.loads(self.rfile.read(int(self.headers['Content-Length'])))))
|
||||
self.send_response(403 if self.path.endswith('heartbeat') else 200)
|
||||
self.end_headers(); self.wfile.write(b'{"lease":null}')
|
||||
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
thread=threading.Thread(target=server.serve_forever,daemon=True); thread.start()
|
||||
try:
|
||||
t=a.Transport('http://127.0.0.1:'+str(server.server_port),'x'*48,allow_loopback_http=True)
|
||||
self.assertEqual(t.post('tech-claim',{'taskId':'explicit'}),{'lease':None})
|
||||
with self.assertRaises(PermissionError): t.post('heartbeat',{})
|
||||
self.assertEqual(seen[0],('/internal/prepare-worker/tech-claim','Bearer '+'x'*48,{'taskId':'explicit'}))
|
||||
finally: server.shutdown(); server.server_close(); thread.join()
|
||||
|
||||
def test_total_deadline_includes_slow_response_body(self):
|
||||
import http.server, threading, time
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self,*args): pass
|
||||
def do_POST(self):
|
||||
self.send_response(200); self.end_headers()
|
||||
try:
|
||||
for _ in range(30): self.wfile.write(b' '); self.wfile.flush(); time.sleep(.3)
|
||||
except (BrokenPipeError,ConnectionResetError): pass
|
||||
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
thread=threading.Thread(target=server.serve_forever,daemon=True); thread.start()
|
||||
try:
|
||||
t=a.Transport('http://127.0.0.1:'+str(server.server_port),'x'*48,allow_loopback_http=True)
|
||||
started=time.monotonic()
|
||||
with self.assertRaises(TimeoutError): t.post('heartbeat',{})
|
||||
self.assertLess(time.monotonic()-started,5)
|
||||
finally: server.shutdown(); server.server_close(); thread.join()
|
||||
|
||||
def test_secret_mount_rejects_unsafe_files(self):
|
||||
import os
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
path=pathlib.Path(root,'credential'); path.write_text('x'*48); path.chmod(0o400)
|
||||
# /tmp may be writable; use descriptor traversal rooted in a private fixture.
|
||||
with patch.object(a,'SECRET_PATH',str(path)):
|
||||
with self.assertRaises(ValueError): a.read_credential()
|
||||
|
||||
def test_admission_fails_before_network(self):
|
||||
class Transport:
|
||||
def post(self,*args): raise AssertionError('network forbidden')
|
||||
for policy in [{},dict(a.ADMISSION,maxCalls=2),dict(a.ADMISSION,maxTokens=161),dict(a.ADMISSION,monetaryCapVerified=True),dict(a.ADMISSION,maxCalls=True)]:
|
||||
with self.assertRaises(ValueError): a.run_once(Transport(),lease()['taskId'],'/',policy)
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,66 @@
|
||||
# Parent merges this file with its pinned Stage compose; CI opt-in only.
|
||||
services:
|
||||
backend_stage:
|
||||
environment:
|
||||
PREPARE_WORKER_ENABLED: "true"
|
||||
secrets:
|
||||
- hermes_username
|
||||
- hermes_password
|
||||
- hermes_runtime_grants
|
||||
- prepare_worker_grants
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /opt/services/canina/stage-runtime/artifacts
|
||||
target: /var/lib/canina/prepare-artifacts
|
||||
bind:
|
||||
create_host_path: false
|
||||
networks:
|
||||
- hermes_inventory_backend
|
||||
runtime-inventory:
|
||||
profiles: [stage-runtime-inventory]
|
||||
image: nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784
|
||||
user: "1000:1000"
|
||||
entrypoint: [/opt/hermes/.venv/bin/python3, /runtime/serve.py]
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
environment:
|
||||
HERMES_HOME: /inventory
|
||||
HERMES_SERVE_HEADLESS: "1"
|
||||
HERMES_REQUIRE_PROJECTED_INVENTORY: "1"
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m,mode=1777"]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${STAGE_RUNTIME_SERVE_FILE:?absolute pinned serve.py required}
|
||||
target: /runtime/serve.py
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
- type: bind
|
||||
source: ${STAGE_RUNTIME_SNAPSHOT:?approved immutable projected snapshot required}
|
||||
target: /inventory
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
secrets: [hermes_username, hermes_password, hermes_signing_key]
|
||||
networks:
|
||||
hermes_inventory_backend:
|
||||
aliases: [canina-hermes-inventory]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cap_drop: [ALL]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
networks:
|
||||
hermes_inventory_backend:
|
||||
internal: true
|
||||
secrets:
|
||||
hermes_username:
|
||||
file: /opt/services/canina/stage-runtime/secrets/hermes_username
|
||||
hermes_password:
|
||||
file: /opt/services/canina/stage-runtime/secrets/hermes_password
|
||||
hermes_signing_key:
|
||||
file: /opt/services/canina/stage-runtime/secrets/hermes_signing_key
|
||||
hermes_runtime_grants:
|
||||
file: /opt/services/canina/stage-runtime/secrets/hermes_runtime_grants
|
||||
prepare_worker_grants:
|
||||
file: /opt/services/canina/stage-runtime/secrets/prepare_worker_grants
|
||||
@@ -48,6 +48,48 @@ def build_app():
|
||||
'liveGatewayState':'unknown','liveActiveAgents':None}
|
||||
# Place before installed catch-all UI route.
|
||||
web_server.app.router.routes.insert(0, web_server.app.router.routes.pop())
|
||||
projected=Path(os.environ['HERMES_HOME'])/'inventory.json'
|
||||
if os.environ.get('HERMES_REQUIRE_PROJECTED_INVENTORY')=='1' and not projected.is_file():
|
||||
raise RuntimeError('Projected inventory required')
|
||||
if projected.exists():
|
||||
# Immutable exporter projection, not installed config/session/cron readers.
|
||||
if projected.is_symlink() or projected.stat().st_size>32*1024*1024:
|
||||
raise RuntimeError('Invalid projected inventory')
|
||||
inventory=json.loads(projected.read_text())
|
||||
if set(inventory)!={'schemaVersion','profile','sessions'} or inventory['schemaVersion']!=1 or not isinstance(inventory['sessions'],list):
|
||||
raise RuntimeError('Invalid projected inventory')
|
||||
profile=inventory['profile']
|
||||
import re
|
||||
if not isinstance(profile,str) or not re.fullmatch('[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}',profile):
|
||||
raise RuntimeError('Invalid projected inventory')
|
||||
replaced={'/api/profiles','/api/sessions','/api/analytics/usage','/api/cron/jobs','/api/model/info'}
|
||||
web_server.app.router.routes[:]=[r for r in web_server.app.router.routes if getattr(r,'path',None) not in replaced]
|
||||
async def projected_read(request:Request):
|
||||
from fastapi import HTTPException
|
||||
path=request.url.path
|
||||
requested=request.query_params.get('profile',profile)
|
||||
if requested!=profile: raise HTTPException(status_code=404)
|
||||
if path=='/api/profiles':
|
||||
return {'profiles':[{'name':profile,'is_default':profile=='default','gateway_running':False}]}
|
||||
if path=='/api/model/info':
|
||||
return {'model':'unknown','provider':'unknown','effective_context_length':0}
|
||||
if path=='/api/cron/jobs': return [] # Cron commands deliberately not captured.
|
||||
try:
|
||||
limit=int(request.query_params.get('limit','20'));offset=int(request.query_params.get('offset','0'))
|
||||
days=int(request.query_params.get('days','30'))
|
||||
if not 1<=limit<=100 or not 0<=offset<=10000 or not 1<=days<=365: raise ValueError()
|
||||
except ValueError: raise HTTPException(status_code=400)
|
||||
rows=inventory['sessions']
|
||||
if path=='/api/sessions':
|
||||
return {'total':len(rows),'sessions':[{k:r[k] for k in ['id','profile','source','is_active']} for r in list(reversed(rows))[offset:offset+limit]],'storage':{}}
|
||||
captured=datetime.fromisoformat(snapshot_provenance()['capturedAt'].replace('Z','+00:00')).timestamp()
|
||||
filtered=[r for r in rows if captured-days*86400<=r['startedAt']<=captured]
|
||||
return {'period_days':days,'totals':{'total_input':sum(r['inputTokens'] for r in filtered),
|
||||
'total_output':sum(r['outputTokens'] for r in filtered),'total_sessions':len(filtered),
|
||||
'total_estimated_cost':sum(r['estimatedCost'] for r in filtered)}}
|
||||
for path in replaced:
|
||||
web_server.app.add_api_route(path,projected_read,methods=['GET'])
|
||||
web_server.app.router.routes.insert(0,web_server.app.router.routes.pop())
|
||||
register_global_provider(BasicAuthProvider(username=secret('hermes_username'),password_hash=hash_password(secret('hermes_password')),secret=secret('hermes_signing_key').encode(),ttl_seconds=300))
|
||||
web_server.app.state.auth_required=True
|
||||
web_server.app.state.bound_host='0.0.0.0'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Projected inventory uses no gateway config or session store."""
|
||||
import os, tempfile, json, importlib.util
|
||||
from pathlib import Path
|
||||
os.environ['HERMES_HOME'] = tempfile.mkdtemp()
|
||||
os.environ['HERMES_SERVE_HEADLESS'] = '1'
|
||||
root = Path(os.environ['HERMES_HOME'])
|
||||
from datetime import datetime, timezone
|
||||
(root/'snapshot-manifest.json').write_text(json.dumps({'schemaVersion':1,'source':'snapshot','capturedAt':datetime.now(timezone.utc).isoformat().replace('+00:00','Z')}))
|
||||
(root/'inventory.json').write_text(json.dumps({'schemaVersion':1,'profile':'seo','sessions':[{'id':'snapshot-0','profile':'seo','source':'cli','startedAt':1,'inputTokens':4,'outputTokens':6,'estimatedCost':0.01,'is_active':False}]}))
|
||||
spec=importlib.util.spec_from_file_location('serve',Path(__file__).parent/'serve.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
m.secret=lambda name:'projected-test-only-'+name+'x'*32
|
||||
from fastapi.testclient import TestClient
|
||||
c=TestClient(m.build_app(),base_url='http://localhost')
|
||||
assert c.get('/api/profiles').status_code==401
|
||||
r=c.post('/auth/password-login',json={'provider':'basic','username':m.secret('hermes_username'),'password':m.secret('hermes_password')});assert r.status_code==200
|
||||
r=c.get('/api/profiles');assert [p['name'] for p in r.json()['profiles']]==['seo'],r.text
|
||||
r=c.get('/api/sessions?profile=seo');assert r.json()['total']==1 and r.json()['sessions'][0]['id']=='snapshot-0',r.text
|
||||
r=c.get('/api/sessions?profile=default');assert r.status_code==404,r.text
|
||||
r=c.get('/api/model/info?profile=seo');assert r.json()['model']=='unknown',r.text
|
||||
r=c.get('/api/cron/jobs?profile=seo');assert r.json()==[],r.text
|
||||
assert not (root/'state.db').exists()
|
||||
print('PASS projected profile/session/model/cron HTTP; no state DB/config used')
|
||||
@@ -0,0 +1,75 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SPEC = importlib.util.spec_from_file_location('provision', ROOT / 'scripts/provision-stage-runtime.py')
|
||||
|
||||
class ProvisionTests(unittest.TestCase):
|
||||
def load(self):
|
||||
self.assertTrue(SPEC.origin and Path(SPEC.origin).exists(), 'Stage provisioner missing')
|
||||
m = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
def test_idempotent_dedicated_credentials_deny_all_runtime(self):
|
||||
m = self.load()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d) / 'target'
|
||||
m.provision(root, 1000, 1000)
|
||||
first = {p.name: p.read_bytes() for p in (root / 'secrets').iterdir()}
|
||||
m.provision(root, 1000, 1000)
|
||||
self.assertEqual(first, {p.name: p.read_bytes() for p in (root / 'secrets').iterdir()})
|
||||
self.assertEqual(json.loads(first['hermes_runtime_grants']), {})
|
||||
config = json.loads(first['prepare_worker_grants'])
|
||||
self.assertNotEqual(config['workerIds'], config['stageCiIds'])
|
||||
self.assertEqual(len({g['credentialSha256'] for g in config['grants']}), 2)
|
||||
for p in (root / 'secrets').iterdir(): self.assertEqual(p.stat().st_mode & 0o777, 0o400)
|
||||
self.assertEqual((root / 'artifacts').stat().st_mode & 0o777, 0o700)
|
||||
|
||||
def test_consistent_wal_export_projects_only_allowlisted_inventory(self):
|
||||
m = self.load()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d); db = root / 'state.db'
|
||||
c = sqlite3.connect(db)
|
||||
c.execute('pragma journal_mode=WAL')
|
||||
c.execute('create table sessions(id text,source text,started_at real,input_tokens integer,output_tokens integer,estimated_cost_usd real,system_prompt text,title text)')
|
||||
c.execute("insert into sessions values('private-person-id','cli',100,4,6,0.01,'NEVER_COPY_PROMPT','NEVER_COPY_TITLE')")
|
||||
c.execute('create table messages(content text)')
|
||||
c.execute("insert into messages values('NEVER_COPY_MESSAGE')"); c.commit()
|
||||
(root / 'config.yaml').write_text('NEVER_COPY_KEY')
|
||||
target = root / 'snapshot'
|
||||
self.assertTrue(hasattr(m, 'export_snapshot'), 'Consistent inventory exporter missing')
|
||||
m.export_snapshot(db, target, 'default', 1000, 1000)
|
||||
text = ''.join(p.read_text() for p in target.iterdir())
|
||||
for secret in ['NEVER_COPY', 'private-person-id', 'system_prompt', 'messages']:
|
||||
self.assertNotIn(secret, text)
|
||||
data = json.loads((target / 'inventory.json').read_text())
|
||||
self.assertEqual(data['sessions'][0]['inputTokens'], 4)
|
||||
self.assertEqual(data['sessions'][0]['source'], 'cli')
|
||||
self.assertEqual(set(p.name for p in target.iterdir()), {'inventory.json','snapshot-manifest.json','export-report.json'})
|
||||
self.assertEqual(json.loads((target / 'snapshot-manifest.json').read_text())['source'], 'snapshot')
|
||||
with self.assertRaises(Exception): m.export_snapshot(db, target, 'default', 1000, 1000)
|
||||
c.close()
|
||||
|
||||
def test_rejects_unsafe_paths_and_modified_credentials(self):
|
||||
m = self.load()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d) / 'target'; m.provision(root, 1000, 1000)
|
||||
p = root / 'secrets/hermes_password'
|
||||
p.chmod(0o600); p.write_text('compromised'); p.chmod(0o400)
|
||||
with self.assertRaises(Exception): m.provision(root, 1000, 1000)
|
||||
|
||||
def test_cli_rejects_non_ci_before_mutation(self):
|
||||
import subprocess
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
target = Path(d) / 'target'
|
||||
env = {**os.environ, 'CI':'false'}
|
||||
r = subprocess.run(['python3', str(SPEC.origin), '--root', str(target)], env=env, capture_output=True)
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertFalse(target.exists())
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -41,5 +41,5 @@ script=$(mktemp)
|
||||
trap 'rm -f "$script"' EXIT
|
||||
wget --no-proxy -qO "$script" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${1}/scripts/deploy.sh"
|
||||
# CI marker exists only across this authenticated, fixed Stage boundary.
|
||||
GITHUB_ACTIONS=true DEPLOY_SHA="$1" bash "$script" develop
|
||||
GITHUB_ACTIONS=true STAGE_PROVISION_ENABLED=true DEPLOY_SHA="$1" bash "$script" develop
|
||||
HOST
|
||||
+12
-1
@@ -29,8 +29,16 @@ git cat-file -e "${DEPLOY_SHA}^{commit}"
|
||||
git merge-base --is-ancestor "$DEPLOY_SHA" origin/develop
|
||||
git checkout --detach "$DEPLOY_SHA"
|
||||
[ "$(git rev-parse HEAD)" = "$DEPLOY_SHA" ]
|
||||
# Provision against the pristine approved SHA, before any tracked render edits.
|
||||
source scripts/rollout-stage.sh
|
||||
if [ "${STAGE_PROVISION_ENABLED:-false}" = true ]; then
|
||||
stage_runtime_provision
|
||||
elif [ -e /opt/services/canina/stage-runtime ] && [ "${STAGE_PROVISION_ENABLED:-}" != false ]; then
|
||||
echo 'ERROR: existing runtime requires explicit Stage CI opt-in on every deploy' >&2
|
||||
exit 2
|
||||
fi
|
||||
# Keep operational files out of status/accidental commits in this disposable clone.
|
||||
printf '\n.support-chat.env\n.revalidation.env\n.stage-base.json\n.stage-compose.json\n' >> .git/info/exclude
|
||||
printf '\n.support-chat.env\n.revalidation.env\n.stage-base.json\n.stage-compose.json\n.stage-runtime.json\n.stage-runtime-merged.json\n' >> .git/info/exclude
|
||||
# Runtime secrets/config must never enter the frontend Docker build context.
|
||||
printf '\n.support-chat.env\n.revalidation.env\n.stage-*.json\n' >> .dockerignore
|
||||
# Only these backend/frontend runtime env files are required. Do not copy the
|
||||
@@ -92,6 +100,9 @@ for service in config['services'].values():
|
||||
Path('.stage-compose.json').write_text(json.dumps(config))
|
||||
Path('.stage-base.json').unlink()
|
||||
PY
|
||||
if [ "${STAGE_PROVISION_ENABLED:-false}" = true ]; then
|
||||
stage_runtime_render
|
||||
fi
|
||||
# Read-only checks: missing external storage must fail, never provision blank DB.
|
||||
docker volume inspect stage_canina_stage_db stage_canina_stage_uploads >/dev/null
|
||||
docker network inspect traefik_public >/dev/null
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serialized Stage CI only; stream reviewed bundle into actual Hermes identity."""
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
PROFILES=('pmo','canina-competitor-worker','canina-seo-worker','canina-content-worker','canina-vet-review-worker','canina-qa-worker')
|
||||
FILES={'bundle.json','installer.py','client.py'} | {'payload/editorial-v4/status.json'} | {f'payload/profiles/{p}/skills/canina-editorial-v4/{f}' for p in PROFILES for f in ('SKILL.md','references/policy.md','references/role.json')}
|
||||
|
||||
def safe(path):
|
||||
if not path.is_absolute() or '..' in path.parts: raise ValueError('Canonical path required')
|
||||
for p in (path,*path.parents):
|
||||
if p.is_symlink(): raise ValueError('Symlink refused')
|
||||
return path
|
||||
|
||||
def private(path):
|
||||
safe(path)
|
||||
s=path.lstat()
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_nlink!=1 or s.st_uid!=os.getuid() or stat.S_IMODE(s.st_mode)!=0o400 or not 1<=s.st_size<=1048576:
|
||||
raise ValueError('Private runtime file required')
|
||||
return path.read_bytes()
|
||||
|
||||
def atomic(path, data, uid=None, gid=None):
|
||||
safe(path)
|
||||
fd,name=tempfile.mkstemp(prefix='.editorial-',dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'wb') as f:
|
||||
f.write(data);f.flush();os.fsync(f.fileno())
|
||||
if uid is not None: os.fchown(f.fileno(),uid,gid)
|
||||
os.chmod(name,0o400);os.replace(name,path)
|
||||
finally:
|
||||
if os.path.exists(name):os.unlink(name)
|
||||
|
||||
def package(root, sha):
|
||||
if not re.fullmatch('[0-9a-f]{40}',sha):raise ValueError('Full deployment SHA required')
|
||||
result={}
|
||||
for name in FILES:
|
||||
p=safe(root/name)
|
||||
if p.stat().st_size>65536:raise ValueError('Package exceeds bound')
|
||||
result[name]=base64.b64encode(p.read_bytes()).decode()
|
||||
return {'commitSha':sha,'files':result}
|
||||
|
||||
def install(home, payload):
|
||||
safe(home)
|
||||
if set(payload)!={'commitSha','files'} or set(payload['files'])!=FILES or not re.fullmatch('[0-9a-f]{40}',payload['commitSha']):
|
||||
raise ValueError('Unreviewed package')
|
||||
# Fixed private package path; no archive extraction or arbitrary destinations.
|
||||
root=safe(home/'editorial-v4/runtime-package')
|
||||
root.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if root.stat().st_uid!=os.getuid() or stat.S_IMODE(root.stat().st_mode)!=0o700:raise ValueError('Private package required')
|
||||
for name,value in payload['files'].items():
|
||||
path=safe(root/name);path.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
data=base64.b64decode(value,validate=True)
|
||||
if len(data)>65536:raise ValueError('Package exceeds bound')
|
||||
atomic(path,data)
|
||||
spec=importlib.util.spec_from_file_location('editorial_installer',root/'installer.py')
|
||||
installer=importlib.util.module_from_spec(spec);spec.loader.exec_module(installer)
|
||||
installer.execute('install',home)
|
||||
report=installer.execute('verify',home)
|
||||
# Confirm all six skill discovery paths, without activating any scheduler.
|
||||
for profile in PROFILES:
|
||||
skill=home/f'profiles/{profile}/skills/canina-editorial-v4/SKILL.md'
|
||||
if not skill.is_file() or 'name: canina-editorial-v4' not in skill.read_text():raise ValueError('Skill discovery failed')
|
||||
credentials=safe(home/'editorial-v4/credentials');credentials.mkdir(mode=0o700,exist_ok=True)
|
||||
st=credentials.stat()
|
||||
if st.st_uid!=os.getuid() or stat.S_IMODE(st.st_mode) not in (0o700,0o755):raise ValueError('Runtime-owned non-writable credentials directory required')
|
||||
token=safe(credentials/'editorial-pmo-token')
|
||||
if token.exists():
|
||||
value=private(token).decode('ascii')
|
||||
if not re.fullmatch('[A-Za-z0-9_-]{64}',value):raise ValueError('Invalid PMO credential')
|
||||
else:
|
||||
value=secrets.token_urlsafe(48);atomic(token,value.encode())
|
||||
atomic(home/'editorial-v4/deployment.json',json.dumps({'commitSha':payload['commitSha']}).encode())
|
||||
return {'files':report['files'],'profiles':list(PROFILES),'credentialSha256':hashlib.sha256(value.encode()).hexdigest()}
|
||||
|
||||
def add_grant(config,digest):
|
||||
if set(config)!={'grants','workerIds','stageCiIds','artifactBaseUrl'} or not re.fullmatch('[0-9a-f]{64}',digest):raise ValueError('Invalid grants')
|
||||
out=copy.deepcopy(config)
|
||||
desired={'id':'pmo','role':'WORKFLOW_WORKER','credentialSha256':digest}
|
||||
existing=[g for g in out['grants'] if g['id']=='pmo']
|
||||
if existing:
|
||||
if existing!=[desired] or out['workerIds'].count('pmo')!=1 or 'pmo' in out['stageCiIds']:raise ValueError('Conflicting PMO grant')
|
||||
return out
|
||||
if any(g['credentialSha256']==digest for g in out['grants']) or 'pmo' in out['workerIds']+out['stageCiIds'] or len(out['grants'])>=32:raise ValueError('Ambiguous PMO grant')
|
||||
out['grants'].append(desired);out['workerIds'].append('pmo')
|
||||
return out
|
||||
|
||||
def provision(sha, uid, gid):
|
||||
gate_path=Path(__file__).resolve().with_name('provision-stage-runtime.py')
|
||||
spec=importlib.util.spec_from_file_location('stage_gate',gate_path)
|
||||
gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(gate)
|
||||
gate.ci_gate()
|
||||
if sha!=os.environ.get('STAGE_PROVISION_APPROVED_SHA'):raise ValueError('Deployment SHA mismatch')
|
||||
def docker(*args, data=None):
|
||||
return subprocess.check_output(['docker',*args],input=data,text=True,timeout=60)
|
||||
h=json.loads(docker('inspect','canina-hermes'))[0]
|
||||
if not h['State']['Running'] or h['HostConfig'].get('UsernsMode') not in ('','default'):raise ValueError('Reviewed running Hermes required')
|
||||
env=dict(v.split('=',1) for v in h['Config']['Env'] if '=' in v)
|
||||
home=Path(env.get('HERMES_HOME',''));safe(home)
|
||||
if not any(home==Path(v['Destination']) or Path(v['Destination']) in home.parents for v in h['Mounts'] if v['Type'] in ('bind','volume')):raise ValueError('Persistent home required')
|
||||
# No --user override: Docker executes as configured runtime identity, not host UID.
|
||||
source=Path(__file__).read_text()
|
||||
payload=package(Path(__file__).resolve().parents[1]/'infra/hermes-editorial',sha)
|
||||
code="import json,sys; p=json.load(sys.stdin); ns={'__name__':'editorial_stream'}; exec(compile(p['source'],'<ci-editorial>','exec'),ns); print(json.dumps(ns['install'](ns['Path'](p['home']),p['payload'])))"
|
||||
result=json.loads(docker('exec','-i','canina-hermes','python3','-B','-c',code,data=json.dumps({'source':source,'home':str(home),'payload':payload})))
|
||||
for profile in PROFILES:
|
||||
discovered=docker('exec','-e','HERMES_HOME='+str(home/'profiles'/profile),'canina-hermes','/opt/hermes/bin/hermes','skills','list')
|
||||
if 'canina-editorial-v4' not in discovered:raise ValueError('Hermes CLI skill discovery failed')
|
||||
path=Path('/opt/services/canina/stage-runtime/secrets/prepare_worker_grants');safe(path)
|
||||
st=path.lstat()
|
||||
if not stat.S_ISREG(st.st_mode) or st.st_uid!=uid or st.st_gid!=gid or st.st_nlink!=1 or stat.S_IMODE(st.st_mode)!=0o400 or not 1<=st.st_size<=16384:raise ValueError('Unsafe backend grant file')
|
||||
config=json.loads(path.read_bytes());updated=add_grant(config,result['credentialSha256'])
|
||||
if updated!=config:atomic(path,json.dumps(updated).encode(),uid,gid)
|
||||
print('Editorial: 19 files and six profile skill paths verified; dedicated PMO grant preserved; no workflow activated')
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in CI Stage provisioning. No Docker, DB writes, service start or polling."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
BASE_URL = 'https://stageapi.canina.ir/api/internal/prepare-worker/artifacts'
|
||||
|
||||
|
||||
def safe_path(path):
|
||||
path = Path(path)
|
||||
if not path.is_absolute() or '..' in path.parts:
|
||||
raise ValueError('Absolute canonical path required')
|
||||
for part in [*reversed(path.parents), path]:
|
||||
if part.is_symlink():
|
||||
raise ValueError('Symlink path rejected')
|
||||
if part.exists() and not part.is_dir():
|
||||
raise ValueError('Directory required')
|
||||
return path
|
||||
|
||||
|
||||
def write_private(path, value, uid, gid):
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o400)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
f.write(value)
|
||||
f.flush(); os.fsync(f.fileno())
|
||||
os.fchown(f.fileno(), uid, gid)
|
||||
|
||||
|
||||
def provision(root, uid, gid):
|
||||
root = safe_path(root)
|
||||
if root.exists():
|
||||
# Idempotence never silently rotates or repairs potentially compromised state.
|
||||
validate(root, uid, gid)
|
||||
return
|
||||
if not root.parent.is_dir():
|
||||
raise ValueError('Provision parent must already exist')
|
||||
staging = Path(tempfile.mkdtemp(prefix='.stage-provision-', dir=root.parent))
|
||||
try:
|
||||
for name, mode, owner in [('secrets', 0o700, uid), ('credentials', 0o700, os.getuid()), ('artifacts', 0o700, uid), ('snapshots', 0o700, os.getuid())]:
|
||||
p = staging / name; p.mkdir(mode=mode); os.chown(p, owner, gid)
|
||||
values = {name: secrets.token_urlsafe(48) for name in ['hermes_username', 'hermes_password', 'hermes_signing_key', 'prepare_worker_token', 'stage_ci_token']}
|
||||
config = {'grants': [
|
||||
{'id': 'stage-prepare-worker', 'role': 'WORKFLOW_WORKER', 'credentialSha256': hashlib.sha256(values['prepare_worker_token'].encode()).hexdigest()},
|
||||
{'id': 'stage-evidence-ci', 'role': 'STAGE_CI', 'credentialSha256': hashlib.sha256(values['stage_ci_token'].encode()).hexdigest()}],
|
||||
'workerIds': ['stage-prepare-worker'], 'stageCiIds': ['stage-evidence-ci'], 'artifactBaseUrl': BASE_URL}
|
||||
for name in ['hermes_username', 'hermes_password', 'hermes_signing_key']:
|
||||
write_private(staging / 'secrets' / name, values[name], uid, gid)
|
||||
for name in ['prepare_worker_token', 'stage_ci_token']:
|
||||
write_private(staging / 'credentials' / name, values[name], os.getuid(), os.getgid())
|
||||
for name, value in [('hermes_runtime_grants', {}), ('prepare_worker_grants', config)]:
|
||||
write_private(staging / 'secrets' / name, json.dumps(value), uid, gid)
|
||||
# Root traversal only; each child controls its own readers.
|
||||
staging.chmod(0o711)
|
||||
validate(staging, uid, gid)
|
||||
# Serialized CI invocation required; refuse a concurrent winner.
|
||||
os.rename(staging, root)
|
||||
finally:
|
||||
if staging.exists(): shutil.rmtree(staging)
|
||||
|
||||
|
||||
def validate(root, uid, gid):
|
||||
expected = {'secrets', 'credentials', 'artifacts', 'snapshots'}
|
||||
if set(p.name for p in root.iterdir()) != expected or root.stat().st_mode & 0o077 != 0o011:
|
||||
raise ValueError('Unexpected provision root')
|
||||
for folder in expected:
|
||||
p = safe_path(root / folder); st = p.stat()
|
||||
if stat.S_IMODE(st.st_mode) != 0o700 or st.st_uid != (uid if folder in {'secrets', 'artifacts'} else os.getuid()):
|
||||
raise ValueError('Unsafe provision directory')
|
||||
names = {'hermes_username', 'hermes_password', 'hermes_signing_key', 'hermes_runtime_grants', 'prepare_worker_grants'}
|
||||
if {p.name for p in (root / 'secrets').iterdir()} != names:
|
||||
raise ValueError('Unexpected secrets')
|
||||
if {p.name for p in (root / 'credentials').iterdir()} != {'prepare_worker_token', 'stage_ci_token'}:
|
||||
raise ValueError('Unexpected credentials')
|
||||
for directory, owner in [('secrets', uid), ('credentials', os.getuid())]:
|
||||
for p in (root / directory).iterdir():
|
||||
st = p.lstat()
|
||||
if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1 or st.st_uid != owner or stat.S_IMODE(st.st_mode) != 0o400 or not 1 <= st.st_size <= 16384:
|
||||
raise ValueError('Unsafe credential file')
|
||||
for name in ['hermes_username', 'hermes_password', 'hermes_signing_key']:
|
||||
if not re.fullmatch('[A-Za-z0-9_-]{64}', (root / 'secrets' / name).read_text()):
|
||||
raise ValueError('Invalid dedicated credential')
|
||||
config = json.loads((root / 'secrets/prepare_worker_grants').read_text())
|
||||
if set(config) != {'grants', 'workerIds', 'stageCiIds', 'artifactBaseUrl'} or len(config['grants']) not in (2, 3):
|
||||
raise ValueError('Unexpected worker config')
|
||||
for index, name in enumerate(['prepare_worker_token', 'stage_ci_token']):
|
||||
grant = config['grants'][index]
|
||||
if set(grant) != {'id', 'role', 'credentialSha256'} or grant['id'] != ['stage-prepare-worker', 'stage-evidence-ci'][index]:
|
||||
raise ValueError('Unexpected worker identity')
|
||||
if not re.fullmatch('[A-Za-z0-9_-]{64}', (root / 'credentials' / name).read_text()):
|
||||
raise ValueError('Invalid service credential')
|
||||
if hashlib.sha256((root / 'credentials' / name).read_bytes()).hexdigest() != grant['credentialSha256']:
|
||||
raise ValueError('Credential digest mismatch')
|
||||
editorial = len(config['grants']) == 3
|
||||
if editorial:
|
||||
grant = config['grants'][2]
|
||||
if set(grant) != {'id', 'role', 'credentialSha256'} or grant['id'] != 'pmo' or grant['role'] != 'WORKFLOW_WORKER' or not re.fullmatch('[0-9a-f]{64}', grant['credentialSha256']) or grant['credentialSha256'] in [g['credentialSha256'] for g in config['grants'][:2]]:
|
||||
raise ValueError('Unexpected PMO grant')
|
||||
if config['workerIds'] != ['stage-prepare-worker'] + (['pmo'] if editorial else []) or config['stageCiIds'] != ['stage-evidence-ci'] or config['artifactBaseUrl'] != BASE_URL or [g['role'] for g in config['grants'][:2]] != ['WORKFLOW_WORKER', 'STAGE_CI']:
|
||||
raise ValueError('Unexpected grants')
|
||||
if json.loads((root / 'secrets/hermes_runtime_grants').read_text()) != {}:
|
||||
raise ValueError('Runtime grants require separate verified-ID review')
|
||||
|
||||
|
||||
def export_snapshot(database, destination, profile, uid, gid):
|
||||
"""SQLite online backup -> explicit metadata projection; raw backup never leaves RAM."""
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
if not re.fullmatch('[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}', profile):
|
||||
raise ValueError('Invalid profile')
|
||||
database = Path(database)
|
||||
safe_path(database.parent)
|
||||
st = database.lstat()
|
||||
if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1:
|
||||
raise ValueError('Regular unlinked database required')
|
||||
destination = safe_path(destination)
|
||||
if destination.exists() or not destination.parent.is_dir():
|
||||
raise ValueError('New snapshot destination required')
|
||||
# mode=ro includes committed WAL frames. Never immutable=1 on a live WAL database.
|
||||
src = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=5)
|
||||
backup = sqlite3.connect(':memory:')
|
||||
deadline = time.monotonic() + 30
|
||||
def progress(status, remaining, total):
|
||||
if time.monotonic() > deadline: raise ValueError('Backup deadline exceeded')
|
||||
try:
|
||||
src.backup(backup, pages=256, progress=progress, sleep=0.05)
|
||||
captured = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
# Fail closed on schema drift. No SELECT *, private IDs, titles, prompts, messages,
|
||||
# config, provider credentials, cron commands, filesystem paths or attachments.
|
||||
rows = backup.execute('SELECT source,started_at,input_tokens,output_tokens,estimated_cost_usd FROM sessions ORDER BY started_at').fetchall()
|
||||
if len(rows) > 100000: raise ValueError('Inventory exceeds bound')
|
||||
allowed_sources = {'cli', 'telegram', 'discord', 'slack', 'api', 'web', 'cron'}
|
||||
sessions = []
|
||||
for index, (source, started, inputs, outputs, cost) in enumerate(rows):
|
||||
import math
|
||||
numbers = [started, inputs or 0, outputs or 0, cost or 0]
|
||||
if any(not isinstance(n, (int, float)) or not math.isfinite(n) or n < 0 for n in numbers):
|
||||
raise ValueError('Invalid inventory numeric metadata')
|
||||
sessions.append({'id': 'snapshot-' + str(index), 'profile': profile,
|
||||
'source': source if source in allowed_sources else 'other',
|
||||
'startedAt': started, 'inputTokens': inputs or 0,
|
||||
'outputTokens': outputs or 0, 'estimatedCost': cost or 0,
|
||||
'is_active': False})
|
||||
inventory = {'schemaVersion': 1, 'profile': profile, 'sessions': sessions}
|
||||
payload = json.dumps(inventory, allow_nan=False, separators=(',', ':'))
|
||||
if len(payload.encode()) > 32 * 1024 * 1024: raise ValueError('Inventory exceeds bound')
|
||||
finally:
|
||||
backup.close(); src.close()
|
||||
staging = Path(tempfile.mkdtemp(prefix='.snapshot-', dir=destination.parent))
|
||||
try:
|
||||
manifest = {'schemaVersion': 1, 'source': 'snapshot', 'capturedAt': captured}
|
||||
report = {'schemaVersion': 1, 'method': 'sqlite-online-backup-to-memory-allowlist-projection',
|
||||
'capturedAt': captured, 'sessions': len(sessions),
|
||||
'inventorySha256': hashlib.sha256(payload.encode()).hexdigest(),
|
||||
'excluded': ['credentials', 'config', 'prompts', 'transcripts', 'private-identities', 'cron-commands'],
|
||||
'liveExecutor': False}
|
||||
for name, value in [('inventory.json', payload), ('snapshot-manifest.json', json.dumps(manifest)), ('export-report.json', json.dumps(report))]:
|
||||
write_private(staging / name, value, uid, gid)
|
||||
os.chown(staging, uid, gid)
|
||||
staging.chmod(0o500)
|
||||
os.rename(staging, destination)
|
||||
finally:
|
||||
if staging.exists():
|
||||
staging.chmod(0o700); shutil.rmtree(staging)
|
||||
|
||||
|
||||
def ci_gate():
|
||||
sha = os.environ.get('STAGE_PROVISION_APPROVED_SHA', '')
|
||||
if os.environ.get('CI') != 'true' or os.environ.get('STAGE_PROVISION_ENABLED') != 'true' or not re.fullmatch('[0-9a-f]{40}', sha):
|
||||
raise ValueError('Approved Stage CI invocation required')
|
||||
repo = Path(__file__).resolve().parents[1]
|
||||
def git(*args):
|
||||
return subprocess.check_output(['git', '-C', str(repo), *args], text=True).strip()
|
||||
if git('rev-parse', 'HEAD') != sha or git('status', '--porcelain'):
|
||||
raise ValueError('Clean approved commit required')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--root', type=Path, default=Path('/opt/services/canina/stage-runtime'))
|
||||
parser.add_argument('--uid', type=int, default=1000)
|
||||
parser.add_argument('--gid', type=int, default=1000)
|
||||
parser.add_argument('--snapshot-db', type=Path)
|
||||
parser.add_argument('--snapshot-name')
|
||||
parser.add_argument('--profile', default='default')
|
||||
args = parser.parse_args()
|
||||
ci_gate()
|
||||
if args.uid <= 0 or args.gid <= 0: raise ValueError('Non-root runtime identity required')
|
||||
if bool(args.snapshot_db) != bool(args.snapshot_name) or (args.snapshot_name and not re.fullmatch('[a-zA-Z0-9_-]{1,80}', args.snapshot_name)):
|
||||
raise ValueError('Paired snapshot database and safe unique name required')
|
||||
provision(args.root, args.uid, args.gid)
|
||||
if args.snapshot_db:
|
||||
export_snapshot(args.snapshot_db, args.root / 'snapshots' / args.snapshot_name, args.profile, args.uid, args.gid)
|
||||
print('Stage credentials and artifact storage validated; no services started')
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception: raise SystemExit('Stage provisioning rejected (details suppressed)')
|
||||
@@ -1,9 +1,115 @@
|
||||
#!/bin/bash
|
||||
# Sourced by the CI/CD deploy entrypoint, never a standalone deploy command.
|
||||
# Invoked only by the authenticated Stage CI entrypoint under its rollout lock.
|
||||
stage_runtime_provision() {
|
||||
[ "${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}}" = true ]
|
||||
[ "${STAGE_PROVISION_ENABLED:-}" = true ]
|
||||
export DEPLOY_SHA STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" CI=true
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s infra/hermes-editorial/tests
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p test_editorial_provision.py
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 - <<'PY'
|
||||
import os, json, subprocess, importlib.util, resource, secrets, re, stat
|
||||
from pathlib import Path
|
||||
# Docker Go subprocess requires a larger virtual address reservation; source SQLite stays size-bounded.
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (60, 60))
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (64*1024*1024, 64*1024*1024))
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker', *args], text=True, timeout=45, env={**os.environ, 'GOMAXPROCS':'2', 'GOMEMLIMIT':'256MiB'})
|
||||
spec=importlib.util.spec_from_file_location('provision','scripts/provision-stage-runtime.py')
|
||||
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
m.ci_gate()
|
||||
def inspect(name): return json.loads(docker('inspect',name))[0]
|
||||
b=inspect('canino_backend_stage')
|
||||
# A failed pre-start rollout may leave the previously accepted backend stopped.
|
||||
# Resume that existing container only inside serialized CI, before provisioning reads.
|
||||
if not b['State'].get('Running'):
|
||||
docker('start','canino_backend_stage')
|
||||
b=inspect('canino_backend_stage')
|
||||
if not b['State'].get('Running') or b['State'].get('Pid',0) <= 0:
|
||||
raise ValueError('Running backend required')
|
||||
if b['Config']['User'] not in ('node','1000','1000:1000') or b['HostConfig'].get('UsernsMode') not in ('','default'):
|
||||
raise ValueError('Unreviewed runtime identity/userns')
|
||||
def mapped(kind):
|
||||
for row in Path('/proc/%s/%s_map'%(b['State']['Pid'],kind)).read_text().splitlines():
|
||||
inside,outside,count=map(int,row.split())
|
||||
if inside <= 1000 < inside+count: return outside+1000-inside
|
||||
raise ValueError('Unmapped runtime identity')
|
||||
uid,gid=mapped('uid'),mapped('gid')
|
||||
if min(uid,gid)<=0: raise ValueError('Root identity forbidden')
|
||||
h=inspect('canina-hermes')
|
||||
env=dict(e.split('=',1) for e in h['Config']['Env'] if '=' in e)
|
||||
home=Path(env.get('HERMES_HOME',''))
|
||||
if not home.is_absolute() or '..' in home.parts: raise ValueError('Explicit Hermes home required')
|
||||
mounts=[v for v in h['Mounts'] if home==Path(v['Destination']) or Path(v['Destination']) in home.parents]
|
||||
if not mounts: raise ValueError('Home mount required')
|
||||
mount=max(mounts,key=lambda v:len(v['Destination']))
|
||||
if mount.get('Type') not in ('bind','volume'):
|
||||
raise ValueError('Filesystem home mount required')
|
||||
m.safe_path(Path(mount['Source']))
|
||||
db=Path(mount['Source'])/home.relative_to(mount['Destination'])/'state.db'
|
||||
m.safe_path(db.parent)
|
||||
for p in [db,Path(str(db)+'-wal'),Path(str(db)+'-shm')]:
|
||||
if p.exists() or p.is_symlink():
|
||||
st=p.lstat()
|
||||
if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1:
|
||||
raise ValueError('Unsafe SQLite source')
|
||||
size=sum(p.stat().st_size for p in [db,Path(str(db)+'-wal')] if p.exists())
|
||||
if not 0<size<=512*1024*1024: raise ValueError('Source exceeds 512 MiB cap')
|
||||
root=Path('/opt/services/canina/stage-runtime')
|
||||
query="""const {PrismaClient}=require('@prisma/client');const p=new PrismaClient();
|
||||
(async()=>{try{const rows=await p.$transaction(async tx=>{
|
||||
await tx.$executeRawUnsafe('SET TRANSACTION READ ONLY');
|
||||
return tx.$queryRawUnsafe(\"SELECT id::text FROM users WHERE lower(replace(replace(role::text, '_', ''), '-', '')) IN ('admin','superadmin') ORDER BY id LIMIT 1001\");
|
||||
});process.stdout.write(JSON.stringify(rows));}catch{process.exitCode=1;}finally{await p.$disconnect();}})();"""
|
||||
rows=json.loads(docker('exec','-w','/app','canino_backend_stage','node','-e',query))
|
||||
if not 1<=len(rows)<=1000 or any(not isinstance(r,dict) or set(r)!={'id'} or not isinstance(r['id'],str) or not re.fullmatch('[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}',r['id']) for r in rows):
|
||||
raise ValueError('Verified admin subjects required')
|
||||
m.provision(root,uid,gid)
|
||||
spec=importlib.util.spec_from_file_location('editorial','scripts/provision-editorial-runtime.py')
|
||||
editorial=importlib.util.module_from_spec(spec);spec.loader.exec_module(editorial)
|
||||
editorial.provision(os.environ['DEPLOY_SHA'],uid,gid)
|
||||
# Leave the validated deny-all sentinel unchanged for repeat provisioning.
|
||||
capture=os.environ['DEPLOY_SHA']+'-'+secrets.token_hex(8)
|
||||
dest=root/'snapshots'/capture
|
||||
m.export_snapshot(db,dest,'default',uid,gid)
|
||||
grants=root/'snapshots'/(capture+'-grants.json')
|
||||
m.write_private(grants,json.dumps({r['id']:['default'] for r in rows}),uid,gid)
|
||||
Path('.stage-runtime.json').write_text(json.dumps({'snapshot':str(dest),'grants':str(grants)}))
|
||||
print('Stage projected snapshot captured; existing admin grants verified; no executor started')
|
||||
PY
|
||||
}
|
||||
|
||||
stage_runtime_render() {
|
||||
chmod 644 "$TARGET_DIR/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SERVE_FILE="$TARGET_DIR/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SNAPSHOT
|
||||
STAGE_RUNTIME_SNAPSHOT=$(python3 -c 'import json;print(json.load(open(".stage-runtime.json"))["snapshot"])')
|
||||
command docker compose -p stage --env-file /dev/null --project-directory "$TARGET_DIR" \
|
||||
-f "$TARGET_DIR/.stage-compose.json" -f infra/hermes-runtime/compose.stage-provision.yml \
|
||||
--profile stage-runtime-inventory config --format json > .stage-runtime-merged.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
from pathlib import Path
|
||||
p=Path('.stage-runtime-merged.json');c=json.loads(p.read_text())
|
||||
b=c['services']['backend_stage']
|
||||
b.setdefault('environment',{})['CANINA_RUNTIME_READ_ENABLED']='true'
|
||||
b.setdefault('networks',{})['traefik_public']=None
|
||||
b.setdefault('labels',{})['traefik.docker.network']='traefik_public'
|
||||
c['secrets']['hermes_runtime_grants']['file']=json.loads(Path('.stage-runtime.json').read_text())['grants']
|
||||
assert c['networks']['hermes_inventory_backend']['internal'] is True
|
||||
assert c['networks']['traefik_public']['external'] is True
|
||||
assert set(c['services'])=={'db_stage','redis_stage','frontend_stage','backend_stage','runtime-inventory'}
|
||||
Path('.stage-compose.json').write_text(json.dumps(c));p.unlink()
|
||||
PY
|
||||
}
|
||||
|
||||
stage_rollout() {
|
||||
# Maintenance is deliberate: neither old nor new app serves during DDL.
|
||||
docker compose stop frontend_stage backend_stage
|
||||
docker compose run --rm --no-deps --entrypoint ./node_modules/.bin/prisma backend_stage migrate deploy
|
||||
if [ "${STAGE_PROVISION_ENABLED:-false}" = true ]; then
|
||||
docker compose up -d --no-deps runtime-inventory
|
||||
fi
|
||||
docker compose up -d --no-deps backend_stage
|
||||
if ! docker compose exec -T backend_stage node -e "$(< scripts/rollout-health.cjs)"; then
|
||||
docker compose stop frontend_stage backend_stage
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parent
|
||||
BUNDLE = ROOT/'hermes-editorial' if (ROOT/'hermes-editorial').exists() else ROOT.parent/'infra/hermes-editorial'
|
||||
|
||||
def load(name, path):
|
||||
spec=importlib.util.spec_from_file_location(name,path)
|
||||
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
|
||||
|
||||
class ProvisionTests(unittest.TestCase):
|
||||
def test_runtime_install_and_credential_are_idempotent_and_private(self):
|
||||
self.assertTrue((ROOT/'provision-editorial-runtime.py').exists(), 'CI editorial wiring missing')
|
||||
m=load('editorial',ROOT/'provision-editorial-runtime.py')
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
home=Path(t); sentinel=home/'config.yaml';sentinel.write_text('unchanged')
|
||||
credentials=home/'credentials'; credentials.mkdir(); credentials.chmod(0o755)
|
||||
os.chown(credentials,10000,10000)
|
||||
payload=m.package(BUNDLE,'a'*40)
|
||||
a=m.install(home,payload);b=m.install(home,payload)
|
||||
self.assertEqual(a,b);self.assertEqual(sentinel.read_text(),'unchanged')
|
||||
self.assertEqual((home/'editorial-v4/credentials/editorial-pmo-token').stat().st_mode & 0o777,0o400)
|
||||
self.assertEqual(a['files'],19)
|
||||
grants={'grants':[{'id':'ci','role':'STAGE_CI','credentialSha256':'c'*64},{'id':'worker','role':'WORKFLOW_WORKER','credentialSha256':'d'*64}], 'workerIds':['worker'],'stageCiIds':['ci'],'artifactBaseUrl':'https://stageapi.canina.ir/api/internal/prepare-worker/artifacts'}
|
||||
updated=m.add_grant(grants,a['credentialSha256'])
|
||||
self.assertEqual(updated['grants'][:2],grants['grants']);self.assertEqual(len(updated['grants']),3)
|
||||
self.assertEqual(m.add_grant(updated,a['credentialSha256']),updated)
|
||||
with self.assertRaises(ValueError):m.add_grant(updated,'e'*64)
|
||||
self.assertEqual(grants['workerIds'],['worker'])
|
||||
(home/'editorial-v4/credentials/editorial-pmo-token').chmod(0o644)
|
||||
with self.assertRaises(ValueError):m.install(home,payload)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -36,6 +36,7 @@ class BoundaryTests(unittest.TestCase):
|
||||
payload = (tools/'payload').read_text()
|
||||
self.assertIn('/raw/commit/${1}/scripts/deploy.sh', payload)
|
||||
self.assertIn('python3',payload)
|
||||
self.assertIn('STAGE_PROVISION_ENABLED=true',payload)
|
||||
self.assertIn('refusing container filesystem',payload)
|
||||
self.assertNotIn('docker run', payload)
|
||||
self.assertNotIn('git reset', payload)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""CI runtime integration: execute extracted deploy boundary, never live apply."""
|
||||
import pathlib, subprocess, tempfile, unittest, os
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
class WiringTests(unittest.TestCase):
|
||||
def test_clean_provision_precedes_all_rendered_edits(self):
|
||||
s=(ROOT/'scripts/deploy.sh').read_text()
|
||||
self.assertIn('stage_runtime_provision',s)
|
||||
self.assertLess(s.index('stage_runtime_provision'),s.index('>> .dockerignore'))
|
||||
self.assertIn('CANINA_RUNTIME_READ_ENABLED', (ROOT/'scripts/rollout-stage.sh').read_text())
|
||||
def test_inventory_started_before_backend(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p=pathlib.Path(d)/'docker'; p.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$TRACE"\n');p.chmod(0o755)
|
||||
r=subprocess.run(['bash','-c','set -e; source scripts/rollout-stage.sh; STAGE_PROVISION_ENABLED=true; stage_rollout'],cwd=ROOT,env=dict(os.environ,PATH=d+':'+os.environ['PATH'],TRACE=d+'/trace'),capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
trace=pathlib.Path(d+'/trace').read_text()
|
||||
self.assertIn('up -d --no-deps runtime-inventory',trace)
|
||||
self.assertLess(trace.index('up -d --no-deps runtime-inventory'),trace.index('up -d --no-deps backend_stage'))
|
||||
|
||||
def test_provision_and_real_compose_render_repeat(self):
|
||||
import json, shutil, sqlite3
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
base=pathlib.Path(directory); repo=base/'repo';repo.mkdir()
|
||||
shutil.copytree(ROOT/'scripts',repo/'scripts',ignore=shutil.ignore_patterns('__pycache__'))
|
||||
shutil.copytree(ROOT/'infra',repo/'infra')
|
||||
root=base/'runtime';home=base/'home';home.mkdir();tools=base/'tools';tools.mkdir()
|
||||
db=sqlite3.connect(home/'state.db')
|
||||
db.execute('CREATE TABLE sessions(source,started_at,input_tokens,output_tokens,estimated_cost_usd,title)')
|
||||
db.execute("INSERT INTO sessions VALUES ('cli',1,2,3,0.1,'PRIVATE TITLE')");db.commit();db.close()
|
||||
helper=repo/'scripts/rollout-stage.sh'
|
||||
helper.write_text(helper.read_text().replace('/opt/services/canina/stage-runtime',str(root)))
|
||||
editorial=repo/'scripts/provision-editorial-runtime.py'
|
||||
editorial.write_text(editorial.read_text().replace('/opt/services/canina/stage-runtime',str(root)))
|
||||
def git(*args):return subprocess.check_output(['git',*args],cwd=repo,text=True).strip()
|
||||
git('init','-q');git('config','user.email','fixture@example.invalid');git('config','user.name','Fixture');git('add','.');git('commit','-qm','fixture')
|
||||
sha=git('rev-parse','HEAD')
|
||||
subject='12345678-1234-1234-1234-123456789abc'
|
||||
fixture={'backend':{'Config':{'User':'node'},'HostConfig':{'UsernsMode':''},'State':{'Running':True,'Pid':os.getpid()}},'hermes':{'State':{'Running':True},'HostConfig':{'UsernsMode':''},'Config':{'Env':['HERMES_HOME=/home/runtime']},'Mounts':[{'Type':'bind','Destination':'/home','Source':str(base)}]}}
|
||||
# /home/runtime resolves to base/runtime; point home at the SQLite fixture.
|
||||
fixture['hermes']['Mounts'][0]['Source']=str(home)
|
||||
fixture['hermes']['Config']['Env']=['HERMES_HOME=/home']
|
||||
(base/'inspect.json').write_text(json.dumps(fixture))
|
||||
(tools/'docker').write_text('#!/usr/bin/env python3\nimport os,sys,json,subprocess\na=sys.argv[1:]\nif a[0]=="compose": os.execv("/usr/bin/docker",["docker",*a])\nf=json.load(open(os.environ["INSPECT"]))\nif a[0]=="inspect": print(json.dumps([f["backend" if a[1]=="canino_backend_stage" else "hermes"]]))\nelif a[0]=="exec" and "-i" in a:\n p=json.load(sys.stdin); p["home"]=f["hermes"]["Mounts"][0]["Source"]; subprocess.run([sys.executable,"-B","-c",a[-1]],input=json.dumps(p),text=True,check=True)\nelif a[0]=="exec" and "skills" in a:\n print("canina-editorial-v4")\nelif a[0]=="exec":\n assert "SET TRANSACTION READ ONLY" in a[-1] and "role::text" in a[-1]\n print(json.dumps([{ "id":os.environ["SUBJECT"]}]))\nelse: raise RuntimeError(a)\n');(tools/'docker').chmod(0o755)
|
||||
env=dict(os.environ,PATH=str(tools)+':'+os.environ['PATH'],INSPECT=str(base/'inspect.json'),SUBJECT=subject,GITHUB_ACTIONS='true',STAGE_PROVISION_ENABLED='true',PYTHONDONTWRITEBYTECODE='1')
|
||||
command='set -euo pipefail; source scripts/rollout-stage.sh; DEPLOY_SHA='+sha+'; unset STAGE_PROVISION_APPROVED_SHA; stage_runtime_provision'
|
||||
# DEPLOY_SHA is deliberately shell-local: helper must export it.
|
||||
captures=[]
|
||||
for _ in range(2):
|
||||
r=subprocess.run(['bash','-c',command],cwd=repo,env=env,capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
capture=json.loads((repo/'.stage-runtime.json').read_text());captures.append(capture)
|
||||
self.assertEqual(json.loads(pathlib.Path(capture['grants']).read_text()),{subject:['default']})
|
||||
self.assertNotIn('PRIVATE TITLE',(pathlib.Path(capture['snapshot'])/'inventory.json').read_text())
|
||||
self.assertEqual(json.loads((root/'secrets/hermes_runtime_grants').read_text()),{})
|
||||
if len(captures)==1:
|
||||
(repo/'.git/info/exclude').write_text('.stage-runtime.json\n')
|
||||
secrets_before={p.name:p.read_bytes() for p in (root/'secrets').iterdir()}
|
||||
self.assertNotEqual(captures[0]['snapshot'],captures[1]['snapshot'])
|
||||
self.assertEqual(secrets_before,{p.name:p.read_bytes() for p in (root/'secrets').iterdir()})
|
||||
before=set((root/'snapshots').iterdir())
|
||||
for invalid in ['', 'not-a-uuid', '------------------------------------']:
|
||||
r=subprocess.run(['bash','-c',command],cwd=repo,env=dict(env,SUBJECT=invalid),capture_output=True,text=True)
|
||||
self.assertNotEqual(r.returncode,0)
|
||||
self.assertIn('Verified admin subjects required',r.stderr)
|
||||
self.assertEqual(before,set((root/'snapshots').iterdir()))
|
||||
(home/'state.db-wal').symlink_to(home/'state.db')
|
||||
r=subprocess.run(['bash','-c',command],cwd=repo,env=env,capture_output=True,text=True)
|
||||
self.assertNotEqual(r.returncode,0)
|
||||
self.assertIn('Unsafe SQLite source',r.stderr)
|
||||
self.assertEqual(before,set((root/'snapshots').iterdir()))
|
||||
(home/'state.db-wal').unlink()
|
||||
# Real Compose CLI normalization and merge; no daemon/socket required.
|
||||
base_config={'services':{n:{'image':'fixture:never-start','networks':{'traefik_public':None}} for n in ['db_stage','redis_stage','backend_stage','frontend_stage']},'networks':{'traefik_public':{'external':True,'name':'traefik_public'}}}
|
||||
(repo/'.stage-compose.json').write_text(json.dumps(base_config))
|
||||
r=subprocess.run(['bash','-c','set -euo pipefail; source scripts/rollout-stage.sh; TARGET_DIR="$PWD"; stage_runtime_render'],cwd=repo,env=env,capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
c=json.loads((repo/'.stage-compose.json').read_text());b=c['services']['backend_stage'];inventory=c['services']['runtime-inventory']
|
||||
self.assertEqual(set(b['networks']),{'traefik_public','hermes_inventory_backend'})
|
||||
self.assertEqual(b['labels']['traefik.docker.network'],'traefik_public')
|
||||
self.assertEqual(set(inventory['networks']),{'hermes_inventory_backend'})
|
||||
self.assertTrue(c['networks']['hermes_inventory_backend']['internal'])
|
||||
self.assertEqual(b['environment']['CANINA_RUNTIME_READ_ENABLED'],'true')
|
||||
self.assertEqual(c['secrets']['hermes_runtime_grants']['file'],captures[-1]['grants'])
|
||||
self.assertEqual(inventory['mem_limit'],'1073741824')
|
||||
self.assertTrue(all(m.get('read_only') for m in inventory['volumes']))
|
||||
self.assertFalse(inventory.get('ports'))
|
||||
self.assertEqual(inventory['user'],'1000:1000')
|
||||
|
||||
def test_base_bind_allowlist_rejects_before_runtime_merge(self):
|
||||
import json
|
||||
script=(ROOT/'scripts/deploy.sh').read_text()
|
||||
validation=script.split("config = json.loads(Path('.stage-base.json').read_text())",1)[1].split("\nPY",1)[0]
|
||||
code="import json\nfrom pathlib import Path\nconfig=json.loads(Path('.stage-base.json').read_text())"+validation
|
||||
config={'services':{'db_stage':{},'redis_stage':{},'backend_stage':{'container_name':'canino_backend_stage','volumes':[{'type':'volume','source':'canina_stage_uploads','target':'/app/uploads'},{'type':'bind','source':'/etc','target':'/stolen'}]},'frontend_stage':{'container_name':'canino_frontend_stage'}},'volumes':{n:{'name':'stage_'+n} for n in ['canina_stage_db','canina_stage_uploads']},'networks':{'traefik_public':{'external':True,'name':'traefik_public'}}}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
p=pathlib.Path(directory);(p/'.stage-base.json').write_text(json.dumps(config))
|
||||
result=subprocess.run(['python3','-c',code],cwd=p,capture_output=True,text=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertIn('unexpected Stage bind mount',result.stderr)
|
||||
self.assertFalse((p/'.stage-compose.json').exists())
|
||||
self.assertLess(script.index('unexpected Stage bind mount'),script.index(' stage_runtime_render'))
|
||||
Reference in new issue
Block a user