Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6db634a35 | ||
|
|
01f56c6db7 |
No files matched your search
+16
-16
@@ -10,25 +10,25 @@ jobs:
|
||||
deploy:
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Authenticated host Stage deployment (Production blocked)
|
||||
shell: bash
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ "${BRANCH}" == develop ]] || { echo 'Production blocked' >&2; exit 2; }
|
||||
[[ "${DEPLOY_SHA}" =~ ^[0-9a-f]{40}$ ]] || exit 2
|
||||
# Provision DEPLOY_KNOWN_HOSTS from an independently verified host key.
|
||||
# Never use baked-in /opt/services, runner SSH keys or docker.sock.
|
||||
[[ -n "${DEPLOY_KEY}" && -n "${DEPLOY_KNOWN_HOSTS}" ]] || { echo 'Host boundary requires DEPLOY_KEY and verified DEPLOY_KNOWN_HOSTS' >&2; exit 2; }
|
||||
export http_proxy="" https_proxy="" HTTP_PROXY="" HTTPS_PROXY=""
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
export https_proxy=""
|
||||
export HTTP_PROXY=""
|
||||
export HTTPS_PROXY=""
|
||||
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
|
||||
umask 077
|
||||
wrapper=$(mktemp)
|
||||
trap 'rm -f "$wrapper"' EXIT
|
||||
wget --no-proxy -qO "$wrapper" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/ci-host-deploy.sh"
|
||||
bash "$wrapper"
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -1,41 +0,0 @@
|
||||
name: Owner authorized Stage test principal
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
approval:
|
||||
required: true
|
||||
description: "Exact owner grant: owner-authorized-stage-editorial"
|
||||
session:
|
||||
required: true
|
||||
description: "Unique session (8-64 lowercase letters/digits/hyphens)"
|
||||
ttl:
|
||||
required: true
|
||||
description: "Bounded session TTL, 60-3600 seconds"
|
||||
action:
|
||||
required: true
|
||||
description: "open or close"
|
||||
jobs:
|
||||
principal:
|
||||
if: github.ref == 'refs/heads/develop'
|
||||
runs-on: canina
|
||||
steps:
|
||||
- name: Explicit authenticated Stage CI seed authority
|
||||
shell: bash
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
STAGE_TEST_APPROVAL: ${{ inputs.approval }}
|
||||
STAGE_TEST_SESSION: ${{ inputs.session }}
|
||||
STAGE_TEST_TTL_SECONDS: ${{ inputs.ttl }}
|
||||
STAGE_TEST_ACTION: ${{ inputs.action }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ "$DEPLOY_SHA" =~ ^[a-f0-9]{40}$ ]] || exit 2
|
||||
umask 077
|
||||
script=$(mktemp)
|
||||
trap 'rm -f "$script"' EXIT
|
||||
wget --no-proxy -qO "$script" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/$DEPLOY_SHA/scripts/ci-stage-test-principal.sh"
|
||||
bash "$script"
|
||||
@@ -1,30 +0,0 @@
|
||||
name: Bounded Stage v4 credential acceptance window
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ci/v4-stage-acceptance
|
||||
jobs:
|
||||
acceptance-window:
|
||||
if: github.ref == 'refs/heads/ci/v4-stage-acceptance'
|
||||
runs-on: canina
|
||||
timeout-minutes: 12
|
||||
steps:
|
||||
- name: Open fixed Stage session and finally close (no model calls)
|
||||
shell: bash
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_RUN_ATTEMPT: ${{ github.run_attempt }}
|
||||
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
set +x
|
||||
[[ "$BRANCH" == ci/v4-stage-acceptance && "$DEPLOY_SHA" =~ ^[a-f0-9]{40}$ && "$GITHUB_RUN_ATTEMPT" == 1 ]] || exit 2
|
||||
umask 077
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
for file in ci-stage-acceptance.sh ci-stage-test-principal.sh; do
|
||||
wget --no-proxy -qO "$scratch/$file" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/$DEPLOY_SHA/scripts/$file"
|
||||
done
|
||||
bash "$scratch/ci-stage-acceptance.sh"
|
||||
@@ -49,8 +49,6 @@ 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
|
||||
|
||||
|
||||
+1
-3
@@ -32,10 +32,8 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
||||
FROM node:20-alpine
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
WORKDIR /app
|
||||
ARG STAGE_TEST_ARTIFACT_SHA=disabled
|
||||
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
@@ -1,3 +0,0 @@
|
||||
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
|
||||
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
|
||||
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
|
||||
@@ -1 +0,0 @@
|
||||
ALTER TABLE "users" ADD COLUMN "auth_expires_at" TIMESTAMPTZ, ADD COLUMN "stage_test_session" VARCHAR(64), ADD COLUMN "stage_test_generation" UUID;
|
||||
@@ -16,9 +16,6 @@ model User {
|
||||
mobile String @unique @db.VarChar(15)
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
||||
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
|
||||
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@ -1235,22 +1232,3 @@ model OrchestrationKillSwitch {
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@map("orchestration_kill_switches")
|
||||
}
|
||||
|
||||
// Transactional dispatch intent. Lease tokens are server-only fencing credentials.
|
||||
model PrepareWorkflowOutbox {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @unique @map("task_id") @db.Uuid
|
||||
status String @default("PENDING") @db.VarChar(20)
|
||||
attempts Int @default(0)
|
||||
notBefore DateTime? @map("not_before") @db.Timestamptz()
|
||||
leaseOwner String? @map("lease_owner") @db.VarChar(100)
|
||||
leaseToken String? @map("lease_token") @db.Uuid
|
||||
leaseUntil DateTime? @map("lease_until") @db.Timestamptz()
|
||||
heartbeatAt DateTime? @map("heartbeat_at") @db.Timestamptz()
|
||||
runId String? @map("run_id") @db.Uuid
|
||||
reservationId String? @map("reservation_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@index([status, leaseUntil])
|
||||
@@index([status, notBefore, createdAt], map: "prepare_workflow_outbox_due_idx")
|
||||
@@map("prepare_workflow_outbox")
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
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) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
@@ -28,7 +27,6 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
@@ -64,8 +62,8 @@ export class AdminController {
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -82,8 +80,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -93,8 +91,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -103,8 +101,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -115,7 +113,6 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -133,7 +130,6 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -61,10 +61,15 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { randomUUID } from "crypto";
|
||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -163,17 +168,12 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
include: {
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,19 +197,9 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
const { orders: _orders, ...rest } = u;
|
||||
return {
|
||||
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,
|
||||
...rest,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
@@ -237,12 +227,7 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
return this.persistUser(dto);
|
||||
}
|
||||
|
||||
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
|
||||
async createUser(dto: CreateUserDto) {
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -275,7 +260,6 @@ export class AdminService {
|
||||
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
mobile,
|
||||
@@ -290,30 +274,7 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
||||
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
|
||||
if (existing) {
|
||||
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
|
||||
return existing; // Never renew TTL on retry.
|
||||
}
|
||||
if (password.length < 32) throw new Error('Server generated secret required');
|
||||
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
|
||||
}
|
||||
|
||||
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
if (!existing) { onRevoked(); return; }
|
||||
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
|
||||
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
|
||||
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
|
||||
onRevoked();
|
||||
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -325,8 +286,6 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -381,11 +340,17 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
}
|
||||
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
async deleteUser(id: string) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -395,17 +360,7 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.deleteUserRecords(id);
|
||||
}
|
||||
|
||||
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (stage) {
|
||||
// Acquire the row lock with an exact fence before deleting any related rows.
|
||||
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
|
||||
}
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
await tx.pet.deleteMany({ where: { userId: id } });
|
||||
@@ -1442,15 +1397,12 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -5,12 +5,9 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -44,7 +41,6 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -89,7 +85,6 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
|
||||
export const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
|
||||
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
|
||||
];
|
||||
|
||||
export interface UserAdminActor {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
}
|
||||
|
||||
// Match RolesGuard semantics; keep stored values unchanged.
|
||||
export function isSuperAdminRole(role?: string): boolean {
|
||||
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
|
||||
return normalized === "superadmin" || normalized === "adminsuper";
|
||||
}
|
||||
|
||||
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
|
||||
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
|
||||
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
|
||||
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
|
||||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
|
||||
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { registerPrepareWorker } from './orchestration-worker/worker-registration';
|
||||
import { RouterUsageModule } from './router-usage/router-usage.module';
|
||||
import { runtimeReadRegistration } from './hermes-management/runtime-read.registration';
|
||||
import { HermesManagementModule } from './hermes-management/hermes-management.module';
|
||||
import { TasksModule } from './common/services/tasks.module';
|
||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||
import { PrismaModule } from "./prisma/prisma.module";
|
||||
@@ -46,10 +45,9 @@ import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
...registerPrepareWorker(),
|
||||
RouterUsageModule,
|
||||
// Deny-all registration: no request identity or runtime credentials are accepted yet.
|
||||
runtimeReadRegistration(),
|
||||
HermesManagementModule.register({origin:'http://canina-hermes:9119',token:async()=>''}),
|
||||
OrchestrationModule,
|
||||
SupportChatModule,
|
||||
RevalidationModule,
|
||||
|
||||
@@ -14,7 +14,6 @@ import { SmsService } from "../common/services/sms.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtRefreshSecret } from "./auth.constants";
|
||||
|
||||
export class RegisterInput {
|
||||
@@ -201,8 +200,7 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -259,8 +257,7 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -303,8 +300,7 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
@@ -330,12 +326,10 @@ export class AuthService {
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||
if (isMatch) {
|
||||
assertPrincipalActive(dbAdmin);
|
||||
const payload = {
|
||||
sub: dbAdmin.id,
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
@@ -449,14 +443,11 @@ export class AuthService {
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (user) {
|
||||
assertPrincipalActive(user);
|
||||
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
userPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phoneNumber: user.mobile,
|
||||
role: user.role,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
@@ -496,15 +487,12 @@ export class AuthService {
|
||||
email?: string;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
phoneNumber: user.mobile,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const sha='a'.repeat(40), generation='8311eb41-23b4-4aab-ade2-e97b90debc11';
|
||||
const env={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'cleanup-session',STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
describe('durable cleanup ownership fence',()=>{
|
||||
it('does not revoke a replacement generation',async()=>{
|
||||
const update=jest.fn();
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:'replacement',authExpiresAt:new Date()}),update}};
|
||||
await expect(new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal(env,sha)).rejects.toThrow('Refusing');
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
it('confirms revocation before relational deletion failure',async()=>{
|
||||
const events:string[]=[];
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:generation,authExpiresAt:new Date()}),update:async()=>events.push('revoke')},$transaction:async()=>{events.push('delete');throw Error('FK failure');}};
|
||||
await expect((new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal as any)(env,sha,()=>events.push('handle-removed'))).rejects.toThrow('FK failure');
|
||||
expect(events).toEqual(['revoke','handle-removed','delete']);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
@@ -13,8 +12,6 @@ export interface JwtPayload {
|
||||
email?: string;
|
||||
role?: string;
|
||||
phoneNumber?: string;
|
||||
stageTestSession?: string;
|
||||
stageTestGeneration?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -62,13 +59,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
||||
if (user.stageTestSession) {
|
||||
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
|
||||
const path = req.originalUrl?.split('?')[0] || '';
|
||||
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure)$/.test(path));
|
||||
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID } from './stage-test-principal';
|
||||
import { createServer, Server } from 'http';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST==='true';
|
||||
(enabled?describe:describe.skip)('actual internal CLI disposable lifecycle',()=>{
|
||||
const sha='a'.repeat(40), generation='b411eb41-23b4-4aab-ade2-e97b90debc11', session='cli-integration-session';
|
||||
const handle=`/app/private-stage-test/${session}.json`;
|
||||
const db=new PrismaClient({log:[]}), redis=new RedisService(); let server:Server;
|
||||
const env={...process.env,APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:session,STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
const cli=(action:string)=>promisify(execFile)(process.execPath,['-r','ts-node/register','src/auth/stage-test-principal.cli.ts',action],{env,timeout:90000});
|
||||
beforeAll(async()=>{
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw Error('Disposable database only');
|
||||
writeFileSync('/app/STAGE_TEST_ARTIFACT_SHA',sha); redis.onModuleInit();
|
||||
const auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
server=createServer(async(req,res)=>{
|
||||
try {let body='';for await(const chunk of req) body+=chunk;
|
||||
if(req.url!=='/api/auth/admin-login') {res.writeHead(404).end();return;}
|
||||
const login=await auth.adminLogin(JSON.parse(body));res.setHeader('content-type','application/json');res.end(JSON.stringify(login));
|
||||
} catch {res.writeHead(401).end();}
|
||||
});
|
||||
await new Promise<void>(r=>server.listen(3000,'127.0.0.1',r));
|
||||
},120000);
|
||||
afterAll(async()=>{await new Promise<void>(r=>server.close(()=>r()));redis.onModuleDestroy();await db.$disconnect();});
|
||||
it('logs in using persisted credentials and removes handle on confirmed revocation despite failed delete',async()=>{
|
||||
await cli('open'); expect(existsSync(handle)).toBe(true);
|
||||
const credential=JSON.parse(readFileSync(handle,'utf8'));expect(credential.accessToken).toBeTruthy();
|
||||
expect((await db.user.findUnique({where:{id:STAGE_TEST_ID}}))?.stageTestGeneration).toBe(generation);
|
||||
await db.$executeRawUnsafe(`CREATE FUNCTION deny_principal_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test FK deletion failure'; END $$`);
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER deny_principal_delete BEFORE DELETE ON users FOR EACH ROW EXECUTE FUNCTION deny_principal_delete()`);
|
||||
try {
|
||||
await expect(cli('close')).rejects.toThrow();
|
||||
expect(existsSync(handle)).toBe(false);
|
||||
const revoked=await db.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
expect(revoked?.authExpiresAt?.getTime()).toBe(0);expect(revoked?.password).toBe('');
|
||||
} finally {await db.$executeRawUnsafe(`DROP TRIGGER deny_principal_delete ON users`);await db.$executeRawUnsafe(`DROP FUNCTION deny_principal_delete()`);}
|
||||
await cli('close');expect(await db.user.findUnique({where:{id:STAGE_TEST_ID}})).toBeNull();
|
||||
},240000);
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { mkdirSync, openSync, writeFileSync, closeSync, readFileSync, statSync, unlinkSync, constants } from 'fs';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { authorizeStageSession, STAGE_TEST_EMAIL } from './stage-test-principal';
|
||||
|
||||
// CI-only internal seed command; deliberately not registered in AppModule.
|
||||
async function main() {
|
||||
const sha = readFileSync('/app/STAGE_TEST_ARTIFACT_SHA', 'utf8').trim();
|
||||
const grant = authorizeStageSession(process.env, sha);
|
||||
const action = process.argv[2];
|
||||
if (action === 'cleanup-capability') { process.stdout.write('stage-generation-cleanup-v1'); return; }
|
||||
if (!['open','close'].includes(action)) throw new Error('Unknown command');
|
||||
const root = '/app/private-stage-test';
|
||||
mkdirSync(root,{recursive:true,mode:0o700});
|
||||
const st = statSync(root);
|
||||
if (st.uid !== process.getuid!() || (st.mode & 0o777) !== 0o700) throw new Error('Unsafe private directory');
|
||||
if (!/^[a-f0-9-]{36}$/.test(process.env.STAGE_TEST_GENERATION || '')) throw new Error('Generation required');
|
||||
const handle = `${root}/${grant.session}.json`;
|
||||
const removeHandle = () => { try {unlinkSync(handle);} catch(e:any) {if(e.code !== 'ENOENT') throw e;} };
|
||||
const audit = (event:string) => {
|
||||
const fd = openSync(`${root}/audit.jsonl`, constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND|constants.O_NOFOLLOW,0o600);
|
||||
try { writeFileSync(fd,JSON.stringify({event,sha,session:grant.session,at:new Date().toISOString()})+'\n'); } finally {closeSync(fd);}
|
||||
};
|
||||
const db = new PrismaClient({log:[]});
|
||||
const service = new AdminService(db as any,undefined as any,undefined as any);
|
||||
try {
|
||||
audit(`${action}-requested`);
|
||||
if(action === 'close') {
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle);
|
||||
audit('revoked-and-deleted');
|
||||
return;
|
||||
}
|
||||
let fd:number;
|
||||
let password:string;
|
||||
try {
|
||||
fd = openSync(handle,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
|
||||
password = randomBytes(48).toString('base64url');
|
||||
try {writeFileSync(fd,JSON.stringify({password}));} finally {closeSync(fd);}
|
||||
} catch(e:any) {
|
||||
if(e.code !== 'EEXIST') throw e;
|
||||
fd = openSync(handle,constants.O_RDONLY|constants.O_NOFOLLOW);
|
||||
try {
|
||||
const {fstatSync} = await import('fs'); const s=fstatSync(fd);
|
||||
if(!s.isFile() || s.uid !== process.getuid!() || (s.mode & 0o777) !== 0o600) throw new Error('Unsafe handle');
|
||||
password=JSON.parse(readFileSync(fd,'utf8')).password;
|
||||
} finally {closeSync(fd);}
|
||||
}
|
||||
const user=await service.provisionStageTestPrincipal(process.env,sha,password);
|
||||
// Use deployed persisted-account HTTP login, never sign tokens here.
|
||||
const response=await fetch('http://127.0.0.1:3000/api/auth/admin-login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:STAGE_TEST_EMAIL,password}),signal:AbortSignal.timeout(15000)});
|
||||
if(!response.ok) throw new Error('Persisted login failed');
|
||||
const result:any=await response.json();
|
||||
if(result.data?.user?.id !== user.id || result.data?.user?.role !== 'SUPER_ADMIN' || !result.data?.accessToken) throw new Error('Persisted login mismatch');
|
||||
fd=openSync(handle,constants.O_WRONLY|constants.O_TRUNC|constants.O_NOFOLLOW);
|
||||
try {writeFileSync(fd,JSON.stringify({password,...result.data,expiresAt:user.authExpiresAt}));} finally {closeSync(fd);}
|
||||
audit('created-and-login-verified');
|
||||
// Only an opaque local path is public. Never upload this file as a CI artifact.
|
||||
process.stdout.write(`Stage credential handle: ${handle}\n`);
|
||||
} catch {
|
||||
audit('failed');
|
||||
// Leave only a revoked account if relational cleanup fails.
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle).catch(()=>undefined);
|
||||
throw new Error('Stage test principal operation failed; inspect private audit');
|
||||
} finally {await db.$disconnect();}
|
||||
}
|
||||
main().catch(()=>{process.stderr.write('Stage test principal denied or failed\n');process.exitCode=1;});
|
||||
@@ -1,58 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST === 'true';
|
||||
(enabled ? describe : describe.skip)('disposable persisted Stage principal lifecycle',()=>{
|
||||
const sha='a'.repeat(40), grant={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'integration-session',STAGE_TEST_TTL_SECONDS:'600'};
|
||||
const db=new PrismaClient({log:[]}); const redis=new RedisService();
|
||||
let admin:AdminService,auth:AuthService,strategy:JwtStrategy,password:string;
|
||||
beforeAll(async()=>{
|
||||
// Deliberately require a disposable database name; never point this suite at Stage.
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw new Error('Disposable database required');
|
||||
redis.onModuleInit(); password=randomBytes(48).toString('base64url');
|
||||
admin=new AdminService(db as any,redis,undefined as any);
|
||||
auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
strategy=new JwtStrategy(new UsersService(db as any),redis);
|
||||
});
|
||||
afterAll(async()=>{await admin.cleanupStageTestPrincipal(grant,sha); await db.$disconnect();redis.onModuleDestroy();});
|
||||
it('rejects unowned collision and never changes it',async()=>{
|
||||
const collision=await db.user.create({data:{firstName:'Unowned',lastName:'Account',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE}});
|
||||
try {
|
||||
await expect(admin.provisionStageTestPrincipal(grant,sha,password)).rejects.toThrow('Refusing');
|
||||
expect((await db.user.findUnique({where:{id:collision.id}}))?.role).toBe('User_PetOwner');
|
||||
} finally {await db.user.delete({where:{id:collision.id}});}
|
||||
});
|
||||
it('creates through account service, logs in, verifies signed tokens, never renews retry TTL',async()=>{
|
||||
const u=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(u.id).toBe(STAGE_TEST_ID); expect(u.role).toBe('SUPER_ADMIN'); expect(u.password).not.toBe(password);
|
||||
const retry=await admin.provisionStageTestPrincipal(grant,sha,password); expect(retry.authExpiresAt).toEqual(u.authExpiresAt);
|
||||
await expect(admin.provisionStageTestPrincipal({...grant,STAGE_TEST_SESSION:'different-session'},sha,password)).rejects.toThrow('Refusing');
|
||||
const login=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const payload=jwt.verify(login.data.accessToken); expect(payload.sub).toBe(u.id);expect(payload.role).toBe('SUPER_ADMIN');
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{authorization:`Bearer ${login.data.accessToken}`}};
|
||||
expect((await strategy.validate(req,payload)).id).toBe(u.id);
|
||||
await expect(strategy.validate({...req,originalUrl:'/api/admin/users'},payload)).rejects.toThrow('scope denied');
|
||||
await expect(strategy.validate({...req,method:'POST',originalUrl:'/api/admin/orchestration/tasks/abcd/gates/2/decide'},payload)).rejects.toThrow('scope denied');
|
||||
// Fixture time travel: persisted expiry is enforced independently of the long-lived signed token.
|
||||
await db.user.update({where:{id:u.id},data:{authExpiresAt:new Date(0)}});
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.adminLogin({email:STAGE_TEST_EMAIL,password})).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
await admin.cleanupStageTestPrincipal(grant,sha);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
expect(await db.user.findUnique({where:{id:u.id}})).toBeNull();
|
||||
const replacement=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(replacement.stageTestGeneration).not.toBe(u.stageTestGeneration);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
const fresh=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
expect((await strategy.validate(req,jwt.verify(fresh.data.accessToken))).id).toBe(u.id);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import { assertPrincipalActive, authorizeStageSession } from './stage-test-principal';
|
||||
const sha = 'a'.repeat(40);
|
||||
const valid = { APP_ENV: 'stage', STAGE_TEST_PRINCIPAL_ENABLED: 'true', CI: 'true', STAGE_TEST_APPROVAL: 'owner-authorized-stage-editorial', STAGE_TEST_SHA: sha, STAGE_TEST_SESSION: 'editorial-20261024', STAGE_TEST_TTL_SECONDS: '600' };
|
||||
describe('Stage CI authority', () => {
|
||||
it('denies by default and in Production despite opt in', () => {
|
||||
expect(() => authorizeStageSession({}, sha)).toThrow();
|
||||
expect(() => authorizeStageSession({...valid, APP_ENV:'production'}, sha)).toThrow();
|
||||
});
|
||||
it('requires immutable matching SHA and bounded explicit authorization', () => {
|
||||
expect(authorizeStageSession(valid, sha).ttl).toBe(600);
|
||||
for(const patch of [{STAGE_TEST_SHA:'main'}, {STAGE_TEST_SHA:'b'.repeat(40)}, {STAGE_TEST_TTL_SECONDS:'3601'}, {STAGE_TEST_TTL_SECONDS:'0'}, {STAGE_TEST_APPROVAL:''}, {CI:''}]) expect(() => authorizeStageSession({...valid,...patch},sha)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
|
||||
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
|
||||
export const STAGE_TEST_MOBILE = '09999999071';
|
||||
export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: string) {
|
||||
if (env.APP_ENV !== 'stage' || env.STAGE_TEST_PRINCIPAL_ENABLED !== 'true' || env.CI !== 'true' || env.STAGE_TEST_APPROVAL !== 'owner-authorized-stage-editorial' || !/^[a-f0-9]{40}$/.test(artifactSha) || env.STAGE_TEST_SHA !== artifactSha || !/^[a-z0-9-]{8,64}$/.test(env.STAGE_TEST_SESSION || '')) throw new Error('Stage CI authority denied');
|
||||
const ttl = Number(env.STAGE_TEST_TTL_SECONDS);
|
||||
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
|
||||
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
|
||||
}
|
||||
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
|
||||
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('Stage credentials remain fenced to their creation session', () => {
|
||||
const id='e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)};
|
||||
const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()};
|
||||
beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';});
|
||||
it('rejects an old-session access token after fixed account ID is recreated',async()=>{
|
||||
const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any);
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}};
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id})).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id});
|
||||
});
|
||||
it('rejects an old-session refresh token even while its Redis entry remains active',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
|
||||
const token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET});
|
||||
await expect(auth.refreshToken(token)).rejects.toThrow();
|
||||
});
|
||||
it('includes session fencing in newly issued credentials',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({} as any,jwt,redis,undefined as any);
|
||||
const result=await auth.refresh(current);
|
||||
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
|
||||
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
|
||||
expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session');
|
||||
});
|
||||
});
|
||||
@@ -24,8 +24,7 @@ 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 tokenMatch=cookie?.match(/^hermes_session_at=(?:"([A-Za-z0-9_.=-]+)"|([A-Za-z0-9_.=-]+));/);
|
||||
const token=tokenMatch?.[1]??tokenMatch?.[2];
|
||||
const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1];
|
||||
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};
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { runtimeReadRegistration } from './runtime-read.registration';
|
||||
import { RuntimeReadModule } from './runtime-read.module';
|
||||
describe('application runtime registration',()=>{
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
it('registers denied routes without reading files when not explicitly enabled',async()=>{
|
||||
const file=jest.spyOn(RuntimeReadModule,'registerFromFile');
|
||||
const register=jest.spyOn(RuntimeReadModule,'register');
|
||||
await runtimeReadRegistration({});
|
||||
expect(file).not.toHaveBeenCalled();expect(register).toHaveBeenCalledWith({});
|
||||
});
|
||||
it('uses only the fixed reviewed grants mount when enabled',async()=>{
|
||||
const file=jest.spyOn(RuntimeReadModule,'registerFromFile').mockResolvedValue({module:RuntimeReadModule});
|
||||
await runtimeReadRegistration({CANINA_RUNTIME_READ_ENABLED:'true'});
|
||||
expect(file).toHaveBeenCalledWith('/run/secrets/hermes_runtime_grants');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
import { RuntimeReadModule } from './runtime-read.module';
|
||||
export function runtimeReadRegistration(env:Record<string,string|undefined>=process.env) {
|
||||
return env.CANINA_RUNTIME_READ_ENABLED === 'true'
|
||||
? RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
: RuntimeReadModule.register({});
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
# Opt-in fragment ONLY: merge into the reviewed Stage backend service definition.
|
||||
# Not a standalone compose file; does not enable the worker automatically.
|
||||
# Host files/dirs must already exist, with reviewed ownership and modes.
|
||||
x-prepare-worker-backend:
|
||||
environment:
|
||||
PREPARE_WORKER_ENABLED: "${PREPARE_WORKER_ENABLED:-false}"
|
||||
secrets:
|
||||
- source: prepare_worker_grants
|
||||
target: prepare_worker_grants
|
||||
mode: 0400
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${PREPARE_WORKER_ARTIFACT_HOST_DIRECTORY:?review private artifact directory}
|
||||
target: /var/lib/canina/prepare-artifacts
|
||||
bind:
|
||||
create_host_path: false
|
||||
secrets:
|
||||
prepare_worker_grants:
|
||||
file: ${PREPARE_WORKER_GRANTS_FILE:?review mounted grants JSON file}
|
||||
@@ -1,44 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,271 +0,0 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,145 +0,0 @@
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,407 +0,0 @@
|
||||
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' },
|
||||
);
|
||||
// Gate decision now atomically queues READY; no second queue transition.
|
||||
}
|
||||
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('stops a held run through authenticated failure API, fences late writes and preserves unknown reservation', async () => {
|
||||
const {t,l,b}=await lease();
|
||||
const d={...b,expectedVersion: t.version+1,idempotencyKey:'stop:'+l.runId,reason:'Disposable subprocess failure'};
|
||||
expect((await request('editorial-failure',{...d,leaseToken:randomUUID()})).status).toBe(403);
|
||||
expect((await request('editorial-failure',d,other)).status).toBe(403);
|
||||
expect((await request('editorial-failure',{...d,actualCents:0})).status).toBe(400);
|
||||
const stopped=await Promise.all([request('editorial-failure',d),request('editorial-failure',d)]);
|
||||
expect(stopped.map(x=>x.status)).toEqual([201,201]);
|
||||
expect(stopped[0].body).toMatchObject({state:'FAILED',retainedReservationCents:20});
|
||||
expect((await request('heartbeat',b)).status).toBe(403);
|
||||
expect((await request('editorial-result',{...b,brief:brief()})).status).toBe(403);
|
||||
expect((await request('editorial-claim',{taskId:t.id})).status).toBe(403);
|
||||
expect(await db.orchestrationArtifact.count({where:{runId:l.runId}})).toBe(0);
|
||||
expect(await db.orchestrationAttestation.count({where:{runId:l.runId}})).toBe(0);
|
||||
expect((await db.orchestrationBudgetLedger.findMany({where:{taskId:t.id}})).map(x=>[x.kind,x.amountCents])).toEqual([['RESERVE',20]]);
|
||||
});
|
||||
it('recovers an expired run only as independent reviewer and fences original token', async () => {
|
||||
const {t,l,b}=await lease();
|
||||
const d={runId:l.runId,expectedVersion:t.version+1,idempotencyKey:'stale-stop:'+l.runId,reason:'Disposable ended process'};
|
||||
await expect(workflow.editorialFailure(t.id,d,{id:'reviewer',role:'SUPER_ADMIN'})).rejects.toThrow();
|
||||
await db.prepareWorkflowOutbox.update({where:{taskId:t.id},data:{leaseUntil:new Date(Date.now()-1000)}});
|
||||
const results=await Promise.all([workflow.editorialFailure(t.id,d,{id:'reviewer',role:'SUPER_ADMIN'}),workflow.editorialFailure(t.id,d,{id:'reviewer',role:'SUPER_ADMIN'})]);
|
||||
expect(results.map(x=>x.state)).toEqual(['FAILED','FAILED']);
|
||||
expect((await request('heartbeat',b)).status).toBe(403);
|
||||
expect((await request('editorial-result',{...b,brief:brief()})).status).toBe(403);
|
||||
expect(await db.orchestrationEvent.count({where:{taskId:t.id,eventType:'EDITORIAL_RUN_STOPPED'}})).toBe(1);
|
||||
expect(await db.orchestrationBudgetLedger.count({where:{taskId:t.id}})).toBe(1);
|
||||
});
|
||||
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,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,431 +0,0 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { IsInt, Min, IsNotEmpty, IsString, 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 EditorialQueueDto extends EditorialClaimDto {
|
||||
@IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: 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 };
|
||||
}
|
||||
const approval = await tx.orchestrationApprovalDecision.findFirst({
|
||||
where: { taskId: t.id, gate: 1 }, orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const valid = approval?.decision === 'APPROVED' && approval.actorId !== 'pmo' && approval.expiresAt > new Date();
|
||||
return {
|
||||
displayState: t.state === 'READY' && !valid ? (approval?.decision === 'APPROVED' && approval.actorId !== 'pmo' && approval.expiresAt <= new Date() ? 'GATE1_RENEWAL_REQUIRED' : 'BLOCKED') : t.state,
|
||||
gate1Validity: valid ? 'VALID' : 'BLOCKED',
|
||||
taskId: t.id,
|
||||
pilotKind: EDITORIAL_PILOT_KIND,
|
||||
state: t.state,
|
||||
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 queue(a: WorkflowIdentity, dto: EditorialQueueDto) {
|
||||
this.pmo(a);
|
||||
return this.db.$transaction(async (tx:any)=>{
|
||||
await this.lock(tx,dto.taskId,true);
|
||||
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 t=await core.enqueueApproved(a,dto);
|
||||
return {taskId:t.id,state:t.state,version:t.version};
|
||||
});
|
||||
}
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { EditorialExecutionService } from './editorial-execution';
|
||||
describe('editorial expiry read/claim consistency',()=>{
|
||||
it('rejects the actual expired claim while status explains blocked READY',async()=>{
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-10-24T09:15:00Z'));
|
||||
const t={id:'565ace1f-8cfc-4447-b978-66c36e7b767b',state:'READY',version:4,metadata:{commitSha:'a'.repeat(40)}};
|
||||
const tx:any={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationApprovalDecision:{findFirst:jest.fn().mockResolvedValue({decision:'APPROVED',actorId:'owner',expiresAt:new Date('2026-10-24T06:37:00Z')})},orchestrationArtifact:{findMany:jest.fn().mockResolvedValue([])}};
|
||||
const s=new EditorialExecutionService({$transaction:async(fn:any)=>fn(tx)} as any);
|
||||
jest.spyOn(s as any,'scope').mockResolvedValue(t);
|
||||
const a={id:'pmo',role:'WORKFLOW_WORKER'};
|
||||
await expect(s.claim(a,{taskId:t.id})).rejects.toMatchObject({status:403,message:'Valid independent Gate1 required'});
|
||||
await expect(s.status(a,t.id)).resolves.toMatchObject({state:'READY',version:4,displayState:'GATE1_RENEWAL_REQUIRED',gate1Validity:'BLOCKED',artifact:null});
|
||||
jest.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,74 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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)});
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { constants, openSync, closeSync, fstatSync, readSync } from 'fs';
|
||||
import { WorkerTransportConfig, WorkerTransportModule } from './worker-transport.module';
|
||||
|
||||
export const PREPARE_WORKER_CONFIG_PATH = '/run/secrets/prepare_worker_grants';
|
||||
export const PREPARE_WORKER_ARTIFACT_DIRECTORY = '/var/lib/canina/prepare-artifacts';
|
||||
const MAX_BYTES = 16384;
|
||||
const fail = () => { throw new Error('Prepare worker startup configuration rejected'); };
|
||||
function exact(value: any, keys: string[]): boolean {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value) &&
|
||||
Object.keys(value).length === keys.length && keys.every(k => Object.hasOwn(value, k));
|
||||
}
|
||||
|
||||
/** Fixed-path, descriptor-pinned, bounded startup read; never logs file contents. */
|
||||
export function loadPrepareWorkerConfig(): WorkerTransportConfig {
|
||||
let dir: number | undefined, file: number | undefined;
|
||||
try {
|
||||
dir = openSync('/', constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
for (const part of ['run', 'secrets']) {
|
||||
const next = openSync(`/proc/self/fd/${dir}/${part}`, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
closeSync(dir); dir = next;
|
||||
if ((fstatSync(dir).mode & 0o022) !== 0) fail();
|
||||
}
|
||||
file = openSync(`/proc/self/fd/${dir}/prepare_worker_grants`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
const stat = fstatSync(file);
|
||||
if (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o022) !== 0 || stat.size > MAX_BYTES ||
|
||||
(stat.uid !== 0 && stat.uid !== process.getuid!())) fail();
|
||||
const bytes = Buffer.alloc(MAX_BYTES + 1);
|
||||
let length = 0, n: number;
|
||||
do { n = readSync(file, bytes, length, bytes.length - length, length); length += n; }
|
||||
while (n > 0 && length < bytes.length);
|
||||
if (length > MAX_BYTES) fail();
|
||||
const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length)));
|
||||
if (!exact(input, ['grants', 'workerIds', 'stageCiIds', 'artifactBaseUrl']) ||
|
||||
!Array.isArray(input.grants) || input.grants.length < 1 || input.grants.length > 32 ||
|
||||
!Array.isArray(input.workerIds) || !Array.isArray(input.stageCiIds) ||
|
||||
input.workerIds.length < 1 || input.stageCiIds.length < 1 ||
|
||||
input.workerIds.length + input.stageCiIds.length !== input.grants.length ||
|
||||
typeof input.artifactBaseUrl !== 'string' || input.artifactBaseUrl.length > 2048 ||
|
||||
input.grants.some((g: any) => !exact(g, ['id', 'role', 'credentialSha256']))) fail();
|
||||
// Transport registration performs shared role, SHA256, ID, overlap and HTTPS validation.
|
||||
const config: WorkerTransportConfig = { ...input, enabled: true, artifactDirectory: PREPARE_WORKER_ARTIFACT_DIRECTORY };
|
||||
WorkerTransportModule.register(config); // Reuse the real transport's reviewed validation, no IO.
|
||||
config.grants.forEach(Object.freeze);
|
||||
Object.freeze(config.grants); Object.freeze(config.workerIds); Object.freeze(config.stageCiIds);
|
||||
return Object.freeze(config);
|
||||
} catch { return fail(); }
|
||||
finally { if (file !== undefined) closeSync(file); if (dir !== undefined) closeSync(dir); }
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
# Prepare worker startup boundary
|
||||
|
||||
Parent integration API (AppModule remains untouched here):
|
||||
|
||||
```ts
|
||||
import { registerPrepareWorker } from './orchestration-worker/worker-registration';
|
||||
// In AppModule imports:
|
||||
...registerPrepareWorker(),
|
||||
```
|
||||
|
||||
Only literal `PREPARE_WORKER_ENABLED=true` registers the transport. Missing or other values register nothing (404 routes), do not read configuration, and do not instantiate Prisma. Enabled malformed/missing configuration throws synchronously before Nest starts, with one generic error and no secret logging.
|
||||
|
||||
The fixed mount `/run/secrets/prepare_worker_grants` contains JSON with exactly `grants`, `workerIds`, `stageCiIds`, `artifactBaseUrl`. Each grant contains exactly `id`, `role` (`WORKFLOW_WORKER` or `STAGE_CI`), `credentialSha256` (64 lowercase hexadecimal characters; never the bearer credential). Require at least one worker and CI, distinct role-bound IDs/digests, exact allowlist coverage, and at most 32 grants. No enabled flag, directory, token, user, or request-derived fields accepted in JSON.
|
||||
|
||||
`artifactBaseUrl` must be explicitly reviewed by the operator: canonical public-DNS HTTPS origin plus `/internal/prepare-worker/artifacts`, no credentials, IP, alternate port, query or fragment. Shared transport validation is authoritative. This loader does not fetch the URL or perform DNS resolution. Directory is always `/var/lib/canina/prepare-artifacts`.
|
||||
|
||||
Descriptor-relative Linux `/proc/self/fd` traversal refuses symlink directories/files, nonregular files, hardlinks, files over 16 KiB, group/world writable files/directories, and foreign-owned files (root/runtime UID only). Reads are bounded even on concurrent growth. Configuration is frozen recursively and transport takes its own frozen snapshot. Trusted operator owns mounted configuration; edits require restart and review.
|
||||
|
||||
`compose.prepare-worker.fragment.yml` is an extension fragment, not a deployable compose file. Parent must merge its `x-prepare-worker-backend` into the correct reviewed Stage backend service and merge `secrets`. Compose bind-backed secrets may ignore mode/UID declarations: provision actual host grants file as root/runtime-owned mode 0400 and artifact directory runtime-owned mode 0700 first. No mounts or live configuration are created by this change.
|
||||
|
||||
Tests deliberately use the fixed `/run/secrets` path. Run ONLY in a fresh disposable container with source and donor dependencies read-only, private dependency copy, and private `prisma generate`; never on a live service. Tests need a disposable Linux root filesystem and do not require DB credentials. Registration test uses a real Nest HTTP listener to prove disabled routes are absent. Existing DB-backed transport tracer remains separately gated by `WORKER_TRANSPORT_DB=1`.
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { writeFileSync, chmodSync, symlinkSync, mkdirSync, rmSync } from 'fs';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { registerPrepareWorker } from './worker-registration';
|
||||
import { loadPrepareWorkerConfig } from './worker-config';
|
||||
import { linkSync } from 'fs';
|
||||
|
||||
|
||||
describe('reviewed prepare-worker startup registration', () => {
|
||||
const path = '/run/secrets/prepare_worker_grants';
|
||||
const valid = () => ({ grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' });
|
||||
it('loader itself rejects malformed SHA grants', () => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const c = valid(); c.grants[0].credentialSha256 = 'secret-not-a-sha';
|
||||
writeFileSync(path, JSON.stringify(c), { mode: 0o400 });
|
||||
try { expect(() => loadPrepareWorkerConfig()).toThrow('Prepare worker startup configuration rejected'); }
|
||||
finally { rmSync(path, { force: true }); }
|
||||
});
|
||||
it.each(['1', 'TRUE', 'yes', ' true', 'false', ''])('does not opt in for %s', value => {
|
||||
expect(registerPrepareWorker({ PREPARE_WORKER_ENABLED: value })).toEqual([]);
|
||||
});
|
||||
it.each(['missing', 'symlink', 'directory', 'fifo', 'oversize', 'group-write', 'world-write', 'hardlink'])('fails startup on unsafe file: %s', kind => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const other = '/run/secrets/test-other';
|
||||
try {
|
||||
if (kind === 'fifo') execFileSync('mkfifo', [path]);
|
||||
else if (kind === 'directory') mkdirSync(path);
|
||||
else if (kind === 'symlink') symlinkSync(other, path);
|
||||
else if (kind !== 'missing') {
|
||||
writeFileSync(path, kind === 'oversize' ? ' '.repeat(16385) : JSON.stringify(valid()), { mode: 0o400 });
|
||||
if (kind === 'group-write') chmodSync(path, 0o420);
|
||||
if (kind === 'world-write') chmodSync(path, 0o402);
|
||||
if (kind === 'hardlink') linkSync(path, other);
|
||||
}
|
||||
expect(() => registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' })).toThrow('Prepare worker startup configuration rejected');
|
||||
} finally { rmSync(path, { recursive: true, force: true }); rmSync(other, { force: true }); }
|
||||
});
|
||||
it.each(['extra', 'raw-token', 'wrong-role', 'overlap', 'duplicate-sha', 'missing-grant', 'http', 'credentials', 'localhost', 'query', 'bad-json', 'null'])('rejects unreviewed JSON: %s without leaking contents or logging', kind => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const c: any = valid();
|
||||
if (kind === 'extra') c.artifactDirectory = '/user-selected';
|
||||
if (kind === 'raw-token') c.grants[0].token = 'DO_NOT_LOG_THIS_SECRET';
|
||||
if (kind === 'wrong-role') c.grants[0].role = 'Admin';
|
||||
if (kind === 'overlap') c.stageCiIds = ['worker'];
|
||||
if (kind === 'duplicate-sha') c.grants[1].credentialSha256 = c.grants[0].credentialSha256;
|
||||
if (kind === 'missing-grant') c.workerIds.push('unbound');
|
||||
if (kind === 'http') c.artifactBaseUrl = 'http://stage.example.com/internal/prepare-worker/artifacts';
|
||||
if (kind === 'credentials') c.artifactBaseUrl = 'https://DO_NOT_LOG_THIS_SECRET@stage.example.com/internal/prepare-worker/artifacts';
|
||||
if (kind === 'localhost') c.artifactBaseUrl = 'https://127.0.0.1/internal/prepare-worker/artifacts';
|
||||
if (kind === 'query') c.artifactBaseUrl += '?secret=DO_NOT_LOG_THIS_SECRET';
|
||||
writeFileSync(path, kind === 'bad-json' ? 'DO_NOT_LOG_THIS_SECRET' : kind === 'null' ? 'null' : JSON.stringify(c), { mode: 0o400 });
|
||||
const logs = [jest.spyOn(console, 'log'), jest.spyOn(console, 'warn'), jest.spyOn(console, 'error')];
|
||||
try {
|
||||
expect(() => registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' })).toThrow(/^Prepare worker startup configuration rejected$/);
|
||||
logs.forEach(log => expect(log).not.toHaveBeenCalled());
|
||||
} finally { logs.forEach(log => log.mockRestore()); rmSync(path, { force: true }); }
|
||||
});
|
||||
it('defaults to no module/no config IO and exposes no worker routes', async () => {
|
||||
expect(registerPrepareWorker({})).toEqual([]);
|
||||
expect(registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'false' })).toEqual([]);
|
||||
const module = await Test.createTestingModule({ imports: registerPrepareWorker({}) }).compile();
|
||||
const app = module.createNestApplication();
|
||||
await app.listen(0, '127.0.0.1');
|
||||
try {
|
||||
const response = await fetch((await app.getUrl()) + '/internal/prepare-worker/claim', { method: 'POST' });
|
||||
expect(response.status).toBe(404);
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
it('loads immutable reviewed JSON into the real transport registration', async () => {
|
||||
mkdirSync('/run/secrets', { recursive: true });
|
||||
const file = '/run/secrets/prepare_worker_grants';
|
||||
const config = { grants: [{ id: 'worker', role: 'WORKFLOW_WORKER', credentialSha256: 'a'.repeat(64) }, { id: 'ci', role: 'STAGE_CI', credentialSha256: 'b'.repeat(64) }], workerIds: ['worker'], stageCiIds: ['ci'], artifactBaseUrl: 'https://stage.example.com/internal/prepare-worker/artifacts' };
|
||||
writeFileSync(file, JSON.stringify(config), { mode: 0o400 });
|
||||
try {
|
||||
const [registered] = registerPrepareWorker({ PREPARE_WORKER_ENABLED: 'true' });
|
||||
expect(registered.module.name).toBe('WorkerTransportModule');
|
||||
expect(registered.controllers?.length).toBe(1);
|
||||
const snapshot = (registered.providers as any[]).find(p => p.useValue?.artifactDirectory)?.useValue;
|
||||
expect(snapshot).toEqual({ ...config, enabled: true, artifactDirectory: '/var/lib/canina/prepare-artifacts' });
|
||||
expect(Object.isFrozen(snapshot)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.grants[0])).toBe(true);
|
||||
} finally { rmSync(file, { force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import { DynamicModule } from '@nestjs/common';
|
||||
import { loadPrepareWorkerConfig } from './worker-config';
|
||||
import { WorkerTransportModule } from './worker-transport.module';
|
||||
|
||||
/** AppModule imports: ...registerPrepareWorker(); disabled means no module or IO. */
|
||||
export function registerPrepareWorker(env: NodeJS.ProcessEnv = process.env): DynamicModule[] {
|
||||
if (env.PREPARE_WORKER_ENABLED !== 'true') return [];
|
||||
try { return [WorkerTransportModule.register(loadPrepareWorkerConfig())]; }
|
||||
catch { throw new Error('Prepare worker startup configuration rejected'); }
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
CanActivate,
|
||||
ConflictException,
|
||||
Controller,
|
||||
DynamicModule,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Inject,
|
||||
Injectable,
|
||||
Module,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from "@nestjs/common";
|
||||
import { IsString, IsUUID, Matches, MaxLength } from "class-validator";
|
||||
import { createHash, timingSafeEqual } from "crypto";
|
||||
import { mkdir, open, FileHandle } from "fs/promises";
|
||||
import { constants } from "fs";
|
||||
import { isAbsolute } from "path";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
PREPARE_WORKFLOW_CONFIG,
|
||||
PrepareWorkflowService,
|
||||
WorkflowIdentity,
|
||||
} from "../orchestration/prepare-workflow.service";
|
||||
|
||||
import { EditorialFailureDto } from '../orchestration/dto/orchestration.dto';
|
||||
import { EditorialProposalBridge, EditorialProposalDto, isEditorialProposal } from "./editorial-bridge";
|
||||
import { EditorialExecutionService, EditorialClaimDto, EditorialQueueDto, 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 {
|
||||
const u = new URL(value);
|
||||
// DNS name only: reject all IP literals, localhost/private single-label names,
|
||||
// noncanonical paths/escapes, credentials, query, fragment and alternate ports.
|
||||
return u.protocol === "https:" && !u.username && !u.password && !u.port &&
|
||||
/^[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) &&
|
||||
["/internal/prepare-worker/artifacts", "/api/internal/prepare-worker/artifacts"].includes(u.pathname) &&
|
||||
value === u.origin + u.pathname;
|
||||
} catch { return false; }
|
||||
}
|
||||
const CONFIG = Symbol("WORKER_TRANSPORT_CONFIG");
|
||||
export interface WorkerTransportConfig {
|
||||
enabled: boolean;
|
||||
grants: {
|
||||
id: string;
|
||||
role: "WORKFLOW_WORKER" | "STAGE_CI";
|
||||
credentialSha256: string;
|
||||
}[];
|
||||
workerIds: string[];
|
||||
stageCiIds: string[];
|
||||
artifactDirectory: string;
|
||||
artifactBaseUrl: string;
|
||||
}
|
||||
class ClaimDto {
|
||||
@IsUUID() taskId!: string;
|
||||
}
|
||||
class LeaseDto extends ClaimDto {
|
||||
@IsUUID() runId!: string;
|
||||
@IsUUID() leaseToken!: string;
|
||||
}
|
||||
class EditorialHeldFailureDto extends EditorialFailureDto {
|
||||
@IsUUID() taskId!: string;
|
||||
@IsUUID() leaseToken!: string;
|
||||
}
|
||||
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;
|
||||
@Matches(/^[a-f0-9]{64}$/) sha256!: string;
|
||||
@Matches(/^[a-f0-9]{64}$/) evidenceSha256!: string;
|
||||
@Matches(/^https:\/\/[^\s]+$/) @MaxLength(2000) uri!: string;
|
||||
}
|
||||
export function tracerReport(lease: {
|
||||
taskId: string;
|
||||
runId: string;
|
||||
commitSha: string;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
kind: "DETERMINISTIC_PREPARE_TRACER",
|
||||
schemaVersion: 1,
|
||||
taskId: lease.taskId,
|
||||
runId: lease.runId,
|
||||
commitSha: lease.commitSha,
|
||||
environment: "staging",
|
||||
llmPilot: false,
|
||||
browserExecuted: false,
|
||||
shellExecuted: false,
|
||||
deploymentExecuted: false,
|
||||
checks: ["lease-bound identity", "deterministic JSON serialization"],
|
||||
actualCents: 0,
|
||||
});
|
||||
}
|
||||
@Injectable()
|
||||
class WorkerIdentityGuard implements CanActivate {
|
||||
constructor(@Inject(CONFIG) private readonly config: WorkerTransportConfig) {}
|
||||
canActivate(context: any) {
|
||||
if (!this.config.enabled)
|
||||
throw new ForbiddenException("Worker transport disabled");
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const auth = req.headers.authorization;
|
||||
if (typeof auth !== "string" || !/^Bearer [\x21-\x7e]{32,512}$/.test(auth))
|
||||
throw new UnauthorizedException();
|
||||
const digest = createHash("sha256").update(auth.slice(7)).digest();
|
||||
const grant = this.config.grants.find((g) =>
|
||||
timingSafeEqual(Buffer.from(g.credentialSha256, "hex"), digest),
|
||||
);
|
||||
if (!grant) throw new UnauthorizedException();
|
||||
req.workerIdentity = { id: grant.id, role: grant.role };
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
class WorkerTransportService {
|
||||
constructor(
|
||||
private readonly workflow: PrepareWorkflowService,
|
||||
private readonly db: PrismaService,
|
||||
@Inject(CONFIG) private readonly config: WorkerTransportConfig,
|
||||
) {}
|
||||
// Linux descriptor-relative traversal pins each directory across renames. Never
|
||||
// realpath-check then reopen by name: that reintroduces a symlink race.
|
||||
private async artifactDir(): Promise<FileHandle> {
|
||||
let dir = await open("/", constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try {
|
||||
for (const part of this.config.artifactDirectory.split("/").filter(Boolean)) {
|
||||
const path = `/proc/self/fd/${dir.fd}/${part}`;
|
||||
try { await mkdir(path, { mode: 0o700 }); }
|
||||
catch (e: any) { if (e.code !== "EEXIST") throw e; }
|
||||
const next = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
await dir.close();
|
||||
dir = next;
|
||||
}
|
||||
const stat = await dir.stat();
|
||||
if (stat.uid !== process.getuid!() || (stat.mode & 0o077) !== 0)
|
||||
throw new Error("Private owned artifact directory required");
|
||||
return dir;
|
||||
} catch (e) { await dir.close(); throw e; }
|
||||
}
|
||||
private worker(a: WorkflowIdentity) {
|
||||
if (a.role !== "WORKFLOW_WORKER" || !this.config.workerIds.includes(a.id))
|
||||
throw new ForbiddenException("Worker allowlist required");
|
||||
}
|
||||
async claim(a: WorkflowIdentity, dto: ClaimDto) {
|
||||
this.worker(a);
|
||||
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)
|
||||
throw new ForbiddenException("Pilot hard task cap is 20 cents");
|
||||
return { lease: await this.workflow.claim(a, dto.taskId) };
|
||||
}
|
||||
heartbeat(a: WorkflowIdentity, dto: LeaseDto) {
|
||||
this.worker(a);
|
||||
return this.workflow.heartbeat(a, dto);
|
||||
}
|
||||
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({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
const expected = tracerReport({ ...dto, commitSha: run.commitSha });
|
||||
if (dto.report !== expected)
|
||||
throw new BadRequestException(
|
||||
"Only deterministic harmless tracer report accepted",
|
||||
);
|
||||
const sha256 = createHash("sha256").update(expected).digest("hex");
|
||||
let dir: FileHandle | undefined, file: FileHandle | undefined;
|
||||
try {
|
||||
dir = await this.artifactDir();
|
||||
file = await open(`/proc/self/fd/${dir.fd}/${sha256}.json`,
|
||||
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
await file.writeFile(expected, "utf8");
|
||||
await file.sync();
|
||||
} catch { throw new ConflictException("Artifact creation refused"); }
|
||||
finally { await file?.close(); await dir?.close(); }
|
||||
const result = await this.workflow.complete(a, {
|
||||
...dto,
|
||||
sha256,
|
||||
uri: this.config.artifactBaseUrl + "/" + sha256,
|
||||
actualCents: 0,
|
||||
});
|
||||
return {
|
||||
state: result.state,
|
||||
taskId: result.id,
|
||||
runId: dto.runId,
|
||||
sha256,
|
||||
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: { in: ["QA", "TECH_PILOT_SOURCE"] }, uri: this.config.artifactBaseUrl + "/" + hash,
|
||||
run: { environment: "staging", status: "SUCCEEDED", task: {
|
||||
operationMode: "PREPARE", budgetLimitCents: 20,
|
||||
} },
|
||||
},
|
||||
});
|
||||
if (!registered) throw new NotFoundException("Artifact not registered");
|
||||
const run = await this.db.orchestrationRun.findUniqueOrThrow({ where: { id: registered.runId } });
|
||||
const task = await this.db.orchestrationTask.findUniqueOrThrow({ where: { id: run.taskId } });
|
||||
const outbox = await this.db.prepareWorkflowOutbox.findUnique({ where: { taskId: run.taskId } });
|
||||
if (!outbox || outbox.status !== "DONE" || outbox.runId !== run.id ||
|
||||
(a.role === "WORKFLOW_WORKER" && outbox.leaseOwner !== a.id))
|
||||
throw new NotFoundException("Artifact not registered");
|
||||
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 {
|
||||
dir = await this.artifactDir();
|
||||
file = await open(`/proc/self/fd/${dir.fd}/${hash}.json`,
|
||||
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 > limit)
|
||||
throw new Error("Unsafe artifact file");
|
||||
// Fixed-size descriptor read: concurrent growth cannot allocate unbounded memory.
|
||||
const buffer = Buffer.alloc(limit + 1);
|
||||
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
||||
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");
|
||||
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);
|
||||
}
|
||||
async editorialFailure(a: WorkflowIdentity, dto: EditorialHeldFailureDto) {
|
||||
const { taskId, ...failure } = dto;
|
||||
const t = await this.workflow.editorialFailure(taskId, failure, a);
|
||||
return { taskId: t.id, state: t.state, version: t.version, costStatus: 'unknown-upper-bound-reserved', retainedReservationCents: 20 };
|
||||
}
|
||||
stage(a: WorkflowIdentity, dto: StageEvidenceDto) {
|
||||
return this.workflow.stageEvidence(a, dto);
|
||||
}
|
||||
}
|
||||
@Controller("internal/prepare-worker")
|
||||
@UseGuards(WorkerIdentityGuard)
|
||||
@UsePipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
)
|
||||
class WorkerTransportController {
|
||||
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-queue') editorialQueue(@Req() req: any, @Body() dto: EditorialQueueDto) {
|
||||
return this.execution.queue(req.workerIdentity, dto);
|
||||
}
|
||||
@Post('editorial-claim') editorialClaim(@Req() req: any, @Body() dto: EditorialClaimDto) {
|
||||
return this.execution.claim(req.workerIdentity, dto);
|
||||
}
|
||||
@Post('editorial-failure') editorialFailure(@Req() req: any, @Body() dto: EditorialHeldFailureDto) {
|
||||
return this.service.editorialFailure(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);
|
||||
}
|
||||
@Post("complete") complete(@Req() req: any, @Body() dto: CompleteDto) {
|
||||
return this.service.complete(req.workerIdentity, dto);
|
||||
}
|
||||
@Post("stage-evidence") stage(
|
||||
@Req() req: any,
|
||||
@Body() dto: StageEvidenceDto,
|
||||
) {
|
||||
return this.service.stage(req.workerIdentity, dto);
|
||||
}
|
||||
@Get("artifacts/:hash") artifact(@Req() req: any, @Param("hash") hash: string) {
|
||||
return this.service.artifact(req.workerIdentity, hash);
|
||||
}
|
||||
}
|
||||
@Module({})
|
||||
export class WorkerTransportModule {
|
||||
static register(config: WorkerTransportConfig): DynamicModule {
|
||||
if (typeof config.enabled !== "boolean" || !Array.isArray(config.grants) ||
|
||||
!Array.isArray(config.workerIds) || !Array.isArray(config.stageCiIds))
|
||||
throw new Error("Explicit boolean enable and credential allowlists required");
|
||||
const allIds = [...config.workerIds, ...config.stageCiIds];
|
||||
if (allIds.some(id => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id)) ||
|
||||
new Set(allIds).size !== allIds.length)
|
||||
throw new Error("Invalid or overlapping worker/CI allowlists");
|
||||
const ids = new Set<string>(),
|
||||
digests = new Set<string>();
|
||||
if (
|
||||
!isAbsolute(config.artifactDirectory) || config.artifactDirectory === "/" ||
|
||||
config.artifactDirectory.split("/").some(p => p === "." || p === "..") ||
|
||||
!validArtifactBase(config.artifactBaseUrl)
|
||||
)
|
||||
throw new Error(
|
||||
"Absolute artifact directory and fixed HTTPS artifact base required",
|
||||
);
|
||||
for (const g of config.grants) {
|
||||
const allowed =
|
||||
g.role === "WORKFLOW_WORKER"
|
||||
? config.workerIds
|
||||
: g.role === "STAGE_CI"
|
||||
? config.stageCiIds
|
||||
: [];
|
||||
if (
|
||||
!/^[a-zA-Z0-9_-]{1,100}$/.test(g.id) ||
|
||||
!allowed.includes(g.id) ||
|
||||
!/^[a-f0-9]{64}$/.test(g.credentialSha256) ||
|
||||
ids.has(g.id) ||
|
||||
digests.has(g.credentialSha256) ||
|
||||
(config.workerIds.includes(g.id) && config.stageCiIds.includes(g.id))
|
||||
)
|
||||
throw new Error("Invalid or overlapping worker/CI credential grants");
|
||||
ids.add(g.id);
|
||||
digests.add(g.credentialSha256);
|
||||
}
|
||||
const snapshot = JSON.parse(JSON.stringify(config)) as WorkerTransportConfig;
|
||||
snapshot.grants.forEach(Object.freeze);
|
||||
Object.freeze(snapshot.grants);
|
||||
Object.freeze(snapshot.workerIds);
|
||||
Object.freeze(snapshot.stageCiIds);
|
||||
Object.freeze(snapshot);
|
||||
return {
|
||||
module: WorkerTransportModule,
|
||||
imports: [PrismaModule],
|
||||
controllers: [WorkerTransportController],
|
||||
providers: [
|
||||
PrepareWorkflowService,
|
||||
WorkerIdentityGuard,
|
||||
WorkerTransportService,
|
||||
EditorialProposalBridge,
|
||||
EditorialExecutionService,
|
||||
{ provide: CONFIG, useValue: snapshot },
|
||||
{
|
||||
provide: PREPARE_WORKFLOW_CONFIG,
|
||||
useValue: Object.freeze({
|
||||
workerIds: snapshot.workerIds,
|
||||
stageCiIds: snapshot.stageCiIds,
|
||||
}),
|
||||
},
|
||||
],
|
||||
exports: [PrepareWorkflowService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,438 +0,0 @@
|
||||
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, readFile, rm, writeFile, symlink, link, rename } from "fs/promises";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
import { execFile } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
const enabled = process.env.WORKER_TRANSPORT_DB === "1";
|
||||
(enabled ? describe : describe.skip)(
|
||||
"isolated PostgreSQL HTTP executor tracer",
|
||||
() => {
|
||||
const db = new PrismaClient();
|
||||
const token = "test-only-worker-secret-".repeat(3);
|
||||
const ciToken = "test-only-ci-secret-".repeat(3);
|
||||
const digest = (s: string) => createHash("sha256").update(s).digest("hex");
|
||||
let app: INestApplication,
|
||||
workflow: PrepareWorkflowService,
|
||||
base: string,
|
||||
directory: string;
|
||||
let pilot: any;
|
||||
beforeAll(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "worker-artifacts-"));
|
||||
const mod = await Test.createTestingModule({
|
||||
imports: [
|
||||
WorkerTransportModule.register({
|
||||
enabled: true,
|
||||
grants: [
|
||||
{
|
||||
id: "pilot",
|
||||
role: "WORKFLOW_WORKER",
|
||||
credentialSha256: digest(token),
|
||||
},
|
||||
{ id: "ci", role: "STAGE_CI", credentialSha256: digest(ciToken) },
|
||||
{ id: "other", role: "WORKFLOW_WORKER", credentialSha256: digest("other-worker-secret-".repeat(3)) },
|
||||
],
|
||||
workerIds: ["pilot", "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();
|
||||
pilot = {
|
||||
runOnce: async (options: any) => {
|
||||
const program =
|
||||
'import {runOnce} from "../infra/hermes-worker/pilot.mjs"; console.log(JSON.stringify(await runOnce(JSON.parse(process.env.TEST_PILOT_OPTIONS))));';
|
||||
const result = await promisify(execFile)(
|
||||
process.execPath,
|
||||
["--input-type=module", "-e", program],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
TEST_PILOT_OPTIONS: JSON.stringify(options),
|
||||
},
|
||||
timeout: 15000,
|
||||
},
|
||||
);
|
||||
return JSON.parse(result.stdout);
|
||||
},
|
||||
};
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await db.$disconnect();
|
||||
if (directory) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
const owner = { id: "author", role: "Admin" },
|
||||
reviewer = { id: "reviewer", role: "SUPER_ADMIN" };
|
||||
async function proposal(queue = true, budget = 20) {
|
||||
let t = await workflow.create(
|
||||
{
|
||||
key: randomUUID(),
|
||||
title: "deterministic tracer",
|
||||
department: "TEST",
|
||||
operationMode: "PREPARE",
|
||||
budgetLimitCents: budget,
|
||||
metadata: {
|
||||
commitSha: "a".repeat(40),
|
||||
scope: "Harmless tracer only",
|
||||
acceptanceCriteria: ["writes deterministic JSON; no release"],
|
||||
},
|
||||
},
|
||||
owner,
|
||||
);
|
||||
if (queue) {
|
||||
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;
|
||||
}
|
||||
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() };
|
||||
}
|
||||
it("rejects overlapping worker and CI grants and accepts no credentials when disabled", async () => {
|
||||
expect(() =>
|
||||
WorkerTransportModule.register({
|
||||
enabled: true,
|
||||
grants: [
|
||||
{
|
||||
id: "both",
|
||||
role: "WORKFLOW_WORKER",
|
||||
credentialSha256: digest(token),
|
||||
},
|
||||
],
|
||||
workerIds: ["both"],
|
||||
stageCiIds: ["both"],
|
||||
artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts",
|
||||
}),
|
||||
).toThrow(/overlapping/);
|
||||
const mod = await Test.createTestingModule({
|
||||
imports: [
|
||||
WorkerTransportModule.register({
|
||||
enabled: false,
|
||||
grants: [],
|
||||
workerIds: [],
|
||||
stageCiIds: [],
|
||||
artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts",
|
||||
}),
|
||||
],
|
||||
})
|
||||
.overrideProvider(PrismaService)
|
||||
.useValue(db)
|
||||
.compile();
|
||||
const disabled = mod.createNestApplication();
|
||||
await disabled.listen(0, "127.0.0.1");
|
||||
try {
|
||||
const r = await fetch(
|
||||
(await disabled.getUrl()) + "/internal/prepare-worker/claim",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: "Bearer " + token,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ taskId: randomUUID() }),
|
||||
},
|
||||
);
|
||||
expect(r.status).toBe(403);
|
||||
} finally {
|
||||
await disabled.close();
|
||||
}
|
||||
});
|
||||
it("rejects unsafe artifact bases and freezes validated configuration", () => {
|
||||
const config = { enabled: true, grants: [], workerIds: [], stageCiIds: [], artifactDirectory: directory,
|
||||
artifactBaseUrl: "https://isolated.invalid/internal/prepare-worker/artifacts" };
|
||||
for (const artifactBaseUrl of ["https://user:pass@isolated.invalid/internal/prepare-worker/artifacts", "https://127.0.0.1/internal/prepare-worker/artifacts", "https://10.1.2.3/internal/prepare-worker/artifacts", "https://localhost/internal/prepare-worker/artifacts", "https://isolated.invalid/arbitrary", "https://isolated.invalid/x/../internal/prepare-worker/artifacts", "https://[::1]/internal/prepare-worker/artifacts"]) {
|
||||
expect(() => WorkerTransportModule.register({ ...config, artifactBaseUrl })).toThrow();
|
||||
}
|
||||
const registered = WorkerTransportModule.register(config);
|
||||
const snapshot = (registered.providers as any[]).find(p => p.useValue?.artifactBaseUrl)?.useValue;
|
||||
expect(Object.isFrozen(snapshot)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.workerIds)).toBe(true);
|
||||
expect(Object.isFrozen(snapshot.grants)).toBe(true);
|
||||
const workflowConfig = (registered.providers as any[]).find(p => p.provide === "PREPARE_WORKFLOW_CONFIG").useValue;
|
||||
expect(Object.isFrozen(workflowConfig)).toBe(true);
|
||||
expect(() => WorkerTransportModule.register({ ...config, enabled: "true" as any })).toThrow();
|
||||
});
|
||||
it("denies untrusted identities and body impersonation; dispatches nothing before Gate1", async () => {
|
||||
const t = await proposal(false);
|
||||
expect((await post("claim", {}, "wrong")).status).toBe(401);
|
||||
expect((await post("claim", { taskId: t.id }, ciToken)).status).toBe(403);
|
||||
expect(
|
||||
(await post("claim", { taskId: t.id, actorId: "pilot" })).status,
|
||||
).toBe(400);
|
||||
expect((await post("claim", { taskId: t.id })).body).toEqual({
|
||||
lease: null,
|
||||
});
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
0,
|
||||
);
|
||||
});
|
||||
it("races claims, fences expired leases and reserves unknown cost against the 20 cent cap", async () => {
|
||||
const t = await proposal();
|
||||
const claims = await Promise.all([
|
||||
post("claim", { taskId: t.id }),
|
||||
post("claim", { taskId: t.id }),
|
||||
]);
|
||||
const leases = claims.map((r) => r.body.lease).filter(Boolean);
|
||||
expect(leases).toHaveLength(1);
|
||||
const lease = leases[0],
|
||||
binding = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
leaseToken: lease.leaseToken,
|
||||
};
|
||||
expect(
|
||||
(await post("heartbeat", { ...binding, leaseToken: randomUUID() }))
|
||||
.status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await post("complete", {
|
||||
...binding,
|
||||
report: "arbitrary shell or prompt",
|
||||
})
|
||||
).status,
|
||||
).toBe(400);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}", actualCents: 21 }))
|
||||
.status,
|
||||
).toBe(400);
|
||||
await db.prepareWorkflowOutbox.update({
|
||||
where: { taskId: t.id },
|
||||
data: { leaseUntil: new Date(Date.now() - 1000) },
|
||||
});
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect((await post("claim", { taskId: t.id })).status).toBe(403);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
})
|
||||
)._sum.amountCents,
|
||||
).toBe(20);
|
||||
const larger = await proposal(true, 40);
|
||||
expect((await post("claim", { taskId: larger.id })).status).toBe(403);
|
||||
});
|
||||
it("rechecks kill switch and task interrupt on heartbeat and completion; separates CI authority", async () => {
|
||||
const t = await proposal(),
|
||||
lease = (await post("claim", { taskId: t.id })).body.lease;
|
||||
const binding = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
leaseToken: lease.leaseToken,
|
||||
};
|
||||
await db.orchestrationKillSwitch.upsert({
|
||||
where: { scope: "GLOBAL" },
|
||||
create: {
|
||||
scope: "GLOBAL",
|
||||
level: "STOP_AGENTS",
|
||||
active: true,
|
||||
reason: "isolated test",
|
||||
actorId: "test",
|
||||
},
|
||||
update: { level: "STOP_AGENTS", active: true },
|
||||
});
|
||||
try {
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect((await post("claim", { taskId: t.id })).status).toBe(403);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: t.id },
|
||||
data: { state: "CANCELLED" },
|
||||
});
|
||||
expect((await post("heartbeat", binding)).status).toBe(403);
|
||||
expect(
|
||||
(await post("complete", { ...binding, report: "{}" })).status,
|
||||
).toBe(403);
|
||||
expect(
|
||||
await db.orchestrationArtifact.count({ where: { runId: lease.runId } }),
|
||||
).toBe(0);
|
||||
const evidence = {
|
||||
taskId: t.id,
|
||||
runId: lease.runId,
|
||||
commitSha: "a".repeat(40),
|
||||
sha256: "b".repeat(64),
|
||||
evidenceSha256: "c".repeat(64),
|
||||
uri: "https://isolated.invalid/not-real-ci",
|
||||
};
|
||||
expect((await post("stage-evidence", evidence)).status).toBe(403);
|
||||
expect((await post("stage-evidence", evidence, ciToken)).status).toBe(
|
||||
403,
|
||||
);
|
||||
});
|
||||
it("never follows or overwrites preexisting artifact links on completion", async () => {
|
||||
const t = await proposal();
|
||||
const lease = (await post("claim", { taskId: t.id })).body.lease;
|
||||
const report = tracerReport(lease), hash = digest(report);
|
||||
const target = join(directory, "sentinel");
|
||||
await writeFile(target, "do not overwrite");
|
||||
const file = join(directory, hash + ".json");
|
||||
await symlink(target, file);
|
||||
const result = await post("complete", { taskId: t.id, runId: lease.runId, leaseToken: lease.leaseToken, report });
|
||||
expect(await readFile(target, "utf8")).toBe("do not overwrite");
|
||||
expect(result.status).toBe(409);
|
||||
expect(await db.orchestrationArtifact.count({ where: { runId: lease.runId } })).toBe(0);
|
||||
await rm(file);
|
||||
await link(target, file);
|
||||
expect((await post("complete", { taskId: t.id, runId: lease.runId, leaseToken: lease.leaseToken, report })).status).toBe(409);
|
||||
expect(await readFile(target, "utf8")).toBe("do not overwrite");
|
||||
});
|
||||
it("runs actual HTTP deterministic executor to VERIFYING with retrievable content-addressed artifact", async () => {
|
||||
const t = await proposal();
|
||||
const result = await pilot.runOnce({
|
||||
baseUrl: base,
|
||||
credential: token,
|
||||
taskId: t.id,
|
||||
allowLoopbackHttp: true,
|
||||
});
|
||||
expect(result.state).toBe("VERIFYING");
|
||||
const row = await db.orchestrationTask.findUniqueOrThrow({
|
||||
where: { id: t.id },
|
||||
});
|
||||
expect(row.state).toBe("VERIFYING");
|
||||
const artifact = await db.orchestrationArtifact.findFirstOrThrow({
|
||||
where: { run: { taskId: t.id } },
|
||||
});
|
||||
const bytes = await readFile(join(directory, artifact.sha256 + ".json"));
|
||||
expect(digest(bytes.toString())).toBe(artifact.sha256);
|
||||
expect(JSON.parse(bytes.toString())).toMatchObject({
|
||||
kind: "DETERMINISTIC_PREPARE_TRACER",
|
||||
commitSha: "a".repeat(40),
|
||||
environment: "staging",
|
||||
llmPilot: false,
|
||||
});
|
||||
const get = await fetch(
|
||||
base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + token } },
|
||||
);
|
||||
expect(get.status).toBe(200);
|
||||
expect(await get.text()).toBe(bytes.toString());
|
||||
const artifactGet = (secret: string) => fetch(base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + secret } });
|
||||
expect((await artifactGet("other-worker-secret-".repeat(3))).status).toBe(404);
|
||||
expect((await artifactGet(ciToken)).status).toBe(200);
|
||||
const foreignHash = digest("{}");
|
||||
await writeFile(join(directory, foreignHash + ".json"), "{}");
|
||||
await db.orchestrationArtifact.create({ data: { runId: artifact.runId, kind: "QA", sha256: foreignHash, uri: "https://foreign.invalid/" + foreignHash } });
|
||||
expect((await fetch(base + "/internal/prepare-worker/artifacts/" + foreignHash, { headers: { authorization: "Bearer " + token } })).status).toBe(404);
|
||||
const moved = directory + "-moved";
|
||||
await rename(directory, moved);
|
||||
try {
|
||||
await symlink(moved, directory);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
} finally { await rm(directory, { force: true }); await rename(moved, directory); }
|
||||
const file = join(directory, artifact.sha256 + ".json"), saved = file + ".saved";
|
||||
await rename(file, saved);
|
||||
try {
|
||||
await symlink(saved, file);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
await rm(file);
|
||||
await link(saved, file);
|
||||
expect((await artifactGet(token)).status).toBe(404);
|
||||
await rm(file);
|
||||
} finally { await rm(file, { force: true }); await rename(saved, file); }
|
||||
const cost = await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
expect(cost._sum.amountCents).toBe(0);
|
||||
expect(
|
||||
await db.orchestrationAttestation.findFirst({
|
||||
where: { run: { taskId: t.id }, kind: "STAGE" },
|
||||
}),
|
||||
).toBeNull();
|
||||
const evidence = {
|
||||
taskId: t.id,
|
||||
state: row.state,
|
||||
sha256: artifact.sha256,
|
||||
artifact: JSON.parse(bytes.toString()),
|
||||
httpGet: get.status,
|
||||
costCents: cost._sum.amountCents,
|
||||
uriExternalReachability: "NOT_TESTED_ISOLATED_FIXTURE_HOST",
|
||||
};
|
||||
console.log("TRACER_EVIDENCE", JSON.stringify(evidence));
|
||||
if (process.env.TRACER_EVIDENCE_PATH)
|
||||
await writeFile(
|
||||
process.env.TRACER_EVIDENCE_PATH,
|
||||
JSON.stringify(evidence, null, 2),
|
||||
);
|
||||
await writeFile(
|
||||
join(directory, artifact.sha256 + ".json"),
|
||||
'{"tampered":true}',
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await fetch(
|
||||
base + "/internal/prepare-worker/artifacts/" + artifact.sha256,
|
||||
{ headers: { authorization: "Bearer " + token } },
|
||||
)
|
||||
).status,
|
||||
).toBe(409);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,43 +0,0 @@
|
||||
# Bounded Stage PREPARE workflow foundation
|
||||
|
||||
This slice is NOT a runtime executor, deployment mechanism, or full v4 completion. It enables authenticated proposal/Gate1/queue APIs and provides internal worker/CI service methods. Default worker/CI identity allowlists are empty: no browser or production execution route exists.
|
||||
|
||||
## Panel HTTP contract
|
||||
All routes require existing JWT authentication with `Admin` or `SUPER_ADMIN`. Actor is exclusively `req.user.id ?? req.user.sub`, role exclusively `req.user.role`. Top-level unknown mutation fields return 400; client actor/profile fields are never trusted.
|
||||
|
||||
Base `/admin/orchestration`:
|
||||
|
||||
- `GET /tasks`: task array.
|
||||
- `GET /tasks/:id`: task object.
|
||||
- `GET /overview`: existing inventory items plus capabilities `{mutations:true, prepare:true, release:false, gate2Decisions:false, chat:false, runtime:false}`, reason `bounded_stage_prepare_only`.
|
||||
- `POST /tasks`: existing CreateOrchestrationTaskDto `{key,title,department,operationMode:"PREPARE",budgetLimitCents,metadata:{commitSha,scope,acceptanceCriteria}}`; commitSha is required lowercase 40hex; scope is a non-blank string of at most 2000 characters; acceptanceCriteria is 1..20 non-blank strings of at most 500 characters each; budget is integer 20..10000 cents. Returns 201 projected task, state DRAFT/version1. Validated scope and acceptance criteria are persisted exactly and remain unchanged by workflow transitions. The internal `workflowScope:"STAGE_PREPARE"`, environment and createdBy are server-owned; input profile/actor/other arbitrary keys are discarded. Key max120, title max255, department max50. Proposal key is unique; sequential or concurrent duplicate keys return 409, without updating the original task or appending another proposal event. Fetch/reconcile the existing task rather than retry blindly.
|
||||
- `PUT /tasks/:id/transition`: `{toState:"GATE1_PENDING"|"READY",expectedVersion,idempotencyKey,reason?}`. Only DRAFT->GATE1_PENDING and GATE1_APPROVED->READY. Owner or SUPER_ADMIN. Returns 200 projected task. READY atomically creates dispatch outbox. Requires unexpired Gate1.
|
||||
- `POST /tasks/:id/gates/1/decide`: existing GateDecisionDto `{decision:"APPROVED"|"REJECTED",expectedVersion,idempotencyKey,expiresAt,notes?}`. SUPER_ADMIN independent from proposer. Future expiry <=24h. Returns 201 **projected task**, not decision object.
|
||||
- Gate2 decision, budget writes/reconcile, command routes (including release), chat and kill-switch HTTP mutations remain 403. Runtime resource reads remain 503.
|
||||
|
||||
Task projection keeps existing scalar fields and safe nested runs/artifacts, decisions, events and ledger. Adds only `metadata:{scope,acceptanceCriteria,environment:"staging",commitSha}` for bounded proposals, otherwise `{}`. Never includes createdBy, workflowScope, payloads, URI, signatures, tokens or lease credentials. Pre-fix rows with the legacy scope sentinel remain readable/operable but have no recovered acceptance criteria: do not represent those as complete immutable scope review evidence.
|
||||
|
||||
`availableActions:string[]` is state/identity-derived: DRAFT owner -> `SUBMIT_GATE1`; GATE1_PENDING independent SUPER_ADMIN -> `APPROVE_GATE1`,`REJECT_GATE1`; GATE1_APPROVED owner/SUPER_ADMIN -> `QUEUE_PREPARE`; all worker/verification/Gate2 and legacy states -> `[]`. Actions indicate workflow eligibility, not a guarantee: current kill switch, approval expiry and concurrent versions are rechecked transactionally on mutation. Panel must not infer actions from state or send actor identity.
|
||||
|
||||
Common errors: 400 invalid DTO/binding; 403 wrong scope/identity/independence/kill/budget/expiry; 409 duplicate proposal key, stale version or idempotency payload mismatch. Transition/decision replay returns current persisted task and does not duplicate side effects.
|
||||
|
||||
## Internal service contracts (NOT browser endpoints)
|
||||
`PrepareWorkflowService` is exported by OrchestrationModule. Trusted backend composition must override `PREPARE_WORKFLOW_CONFIG` with explicit `workerIds` and `stageCiIds`, default both empty. Do not populate from request bodies or user-selected runtime profiles. Worker identities require role WORKFLOW_WORKER AND ID allowlist; Stage identities require STAGE_CI AND separate ID allowlist. Credential/session provisioning and transport remain the integrating runtime owner's responsibility.
|
||||
|
||||
- `claim(identity, taskId?) -> null | {taskId,runId,attempt,leaseToken,leaseUntil,commitSha,environment:"staging",maxCostCents:20}`. Transactional task row lock with SKIP LOCKED, immutable run binding, 30s lease, max3 attempts. Each attempt reserves **a fixed hard upper bound of 20 cents**, not an estimated or measured departmental cost. Unknown cost on expired attempts remains reserved conservatively.
|
||||
- `heartbeat(identity,{taskId,runId,leaseToken}) -> {leaseUntil}`. Same owner/token, unexpired active lease required.
|
||||
- `complete(identity,{taskId,runId,leaseToken,sha256,uri,actualCents}) -> task`. QA success ingestion only; lowercase sha256, HTTPS URI, actual cost integer0..20 from trusted worker. Atomically records immutable QA artifact/attestation, SUCCEEDED run, reservation reconciliation, DONE outbox and VERIFYING task. Expired/stale/foreign token cannot finish. Not replayable after success; caller must read persisted task/run after response loss.
|
||||
- `stageEvidence(identity,{taskId,runId,sha256,commitSha,evidenceSha256,uri}) -> task`. Independently allowlisted Stage CI identity, successful exact staging commit/run, registered QA subject, independent QA signer. Atomically records Stage artifact/attestation and reaches GATE2_PENDING. No release or Gate2 approval. Does not perform or claim deployment itself. Caller supplies actual trusted CI evidence, not browser assertions.
|
||||
|
||||
## Verification and explicit gaps
|
||||
Real isolated PostgreSQL16, no published ports/no live volumes. Added migrations applied with ON_ERROR_STOP. TDD RED logs cover missing workflow behavior, heartbeat/QA behavior and HTTP enablement. Full backend regression excluding existing legacy release-containing orchestration.integration.spec: 106 suites /851 tests including seven real-DB workflow cases, build exit0. No RELEASE_AUTHORIZE service operation executed.
|
||||
|
||||
DB regressions: concurrent claim winner, queue race/replay mismatch, hard budget rollback, stale lease fencing, max3 attempts, conservative expired costs, kill switch, self approval, trusted IDs, QA reconciliation and Stage evidence to Gate2 pending. Test fixture artifact URIs/hashes are not real deployment evidence.
|
||||
|
||||
Remaining: actual authenticated runtime worker transport/executor and pinned CI evidence transport; shared department/company budget model and locking (NOT implemented or represented by fake totals); retry backoff/dead-letter UX/cancellation; hard total execution wall-time; durable request replay of completion/evidence; kill-switch concurrent insertion/version locking; migration rehearsal with full legacy schema; real Stage CI artifact/deployment verification. No push/deploy/live DB/runtime edits. Production release remains denied at HTTP boundary; unsafe legacy core release method is deliberately untouched and must never be called by this slice.
|
||||
|
||||
## Contract repair verification
|
||||
|
||||
Actual frontend inspection confirmed proposal submission sent human scope and acceptanceCriteria but omitted required commitSha. Frontend repair is separately assigned; no frontend file changed here. New proposals now require all three fields. Internal Stage restriction uses a separate server-owned workflowScope marker rather than overwriting user scope. No metadata update route exists in this bounded workflow.
|
||||
|
||||
TDD RED→GREEN against isolated PostgreSQL16 reproduced dropped scope/criteria, nine invalid metadata acceptances (including array-to-string commit coercion), and duplicate-key P2002 leakage. Final database suite: 24 cases, including authenticated HTTP create/list/detail persistence, 400 validation, and 409 duplicate responses. Full allowed backend regression: 106 suites / 868 tests passed; legacy orchestration.integration.spec.ts excluded to avoid executing RELEASE_AUTHORIZE. Build exit0. Scoped lint remains failing on inherited require-await/no-unnecessary-type-assertion errors (13 errors); no lint suppression or config change applied. Disposable DB only; no live edits/push/deploy.
|
||||
@@ -1,59 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
const enabled=process.env.WORKFLOW_DB==='1';
|
||||
(enabled?describe:describe.skip)('approval queue PostgreSQL atomicity',()=>{
|
||||
const db=new PrismaClient();
|
||||
const service=new PrepareWorkflowService(db,{workerIds:['pmo','worker'],stageCiIds:[]});
|
||||
const owner={id:'pmo',role:'Admin'}, reviewer={id:'reviewer',role:'SUPER_ADMIN'},worker={id:'worker',role:'WORKFLOW_WORKER'};
|
||||
async function pending(){const t=await service.create({key:`queue-${crypto.randomUUID()}`,title:'QA',department:'CONTENT',operationMode:'PREPARE',budgetLimitCents:20,metadata:{scope:'Isolated QA',acceptanceCriteria:['Test queue'],commitSha:'a'.repeat(40)}},owner);return service.transition(t.id,{toState:'GATE1_PENDING',expectedVersion:t.version,idempotencyKey:`submit-${t.id}`},owner);}
|
||||
afterAll(()=>db.$disconnect());
|
||||
it('racing approvals serialize once, replay once, and queue can immediately claim',async()=>{
|
||||
const t=await pending();const dto={decision:'APPROVED',expectedVersion:t.version,idempotencyKey:`approve-${t.id}`};
|
||||
const results=await Promise.all([service.decide(t.id,1,dto,reviewer),service.decide(t.id,1,dto,reviewer)]);
|
||||
expect(results.every(t=>t.state==='READY')).toBe(true);
|
||||
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(1);
|
||||
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(1);
|
||||
const claims=await Promise.all([service.claim(worker,t.id),service.claim(worker,t.id)]);
|
||||
expect(claims.filter(Boolean)).toHaveLength(1);
|
||||
});
|
||||
it('scheduled work cannot claim early via targeted or polling claim; becomes claimable at due time',async()=>{
|
||||
const t=await pending();const notBefore=new Date(Date.now()+3600000).toISOString();
|
||||
await service.decide(t.id,1,{decision:'APPROVED',expectedVersion:t.version,idempotencyKey:`schedule-${t.id}`,notBefore},reviewer);
|
||||
expect(await service.claim(worker,t.id)).toBeNull();
|
||||
expect(await service.claim(worker)).toBeNull();
|
||||
const o=await db.prepareWorkflowOutbox.findUniqueOrThrow({where:{taskId:t.id}});
|
||||
expect(o.notBefore).toEqual(new Date(notBefore));
|
||||
const approval=await db.orchestrationApprovalDecision.findFirstOrThrow({where:{taskId:t.id}});
|
||||
expect(approval.expiresAt.getTime()).toBeGreaterThan(Date.parse(notBefore));
|
||||
await db.prepareWorkflowOutbox.update({where:{taskId:t.id},data:{notBefore:new Date(0)}});
|
||||
expect(await service.claim(worker,t.id)).toMatchObject({taskId:t.id,attempt:1});
|
||||
});
|
||||
it('hold and rejection never queue',async()=>{
|
||||
const t=await pending();const held=await service.transition(t.id,{toState:'GATE1_HELD',expectedVersion:t.version,idempotencyKey:`hold-${t.id}`,reason:'Revise scope'},reviewer);
|
||||
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(0);
|
||||
await service.decide(t.id,1,{decision:'REJECTED',expectedVersion:held.version,idempotencyKey:`reject-${t.id}`},reviewer);
|
||||
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(0);
|
||||
});
|
||||
it('expired approval cannot claim and immutable decision is not edited',async()=>{
|
||||
const t=await pending();await service.decide(t.id,1,{decision:'APPROVED',expectedVersion:t.version,idempotencyKey:`expire-${t.id}`,expiresAt:new Date(Date.now()+300).toISOString()},reviewer);
|
||||
await new Promise(r=>setTimeout(r,350));
|
||||
await expect(service.claim(worker,t.id)).rejects.toThrow(/expired/i);
|
||||
expect(await db.orchestrationRun.count({where:{taskId:t.id}})).toBe(0);
|
||||
});
|
||||
it('PMO recovery queues stored v3 approval without creating a decision, no impersonation',async()=>{
|
||||
const t=await pending();
|
||||
await db.orchestrationTask.update({where:{id:t.id},data:{state:'GATE1_APPROVED',version:3}});
|
||||
await db.orchestrationApprovalDecision.create({data:{taskId:t.id,gate:1,decision:'APPROVED',actorId:'independent',expiresAt:new Date(Date.now()+60000),idempotencyKey:`legacy-${t.id}`}});
|
||||
const dto={taskId:t.id,expectedVersion:3,idempotencyKey:`recover-${t.id}`};
|
||||
const result=await Promise.all([service.enqueueApproved({id:'pmo',role:'WORKFLOW_WORKER'},dto),service.enqueueApproved({id:'pmo',role:'WORKFLOW_WORKER'},dto)]);
|
||||
expect(result.every(t=>t.state==='READY'&&t.version===4)).toBe(true);
|
||||
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(1);
|
||||
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(1);
|
||||
});
|
||||
it('outbox failure rolls back immutable approval and READY together',async()=>{
|
||||
const t=await pending();await db.prepareWorkflowOutbox.create({data:{taskId:t.id}});
|
||||
await expect(service.decide(t.id,1,{decision:'APPROVED',expectedVersion:t.version,idempotencyKey:`fail-${t.id}`},reviewer)).rejects.toThrow();
|
||||
expect((await db.orchestrationTask.findUniqueOrThrow({where:{id:t.id}})).state).toBe('GATE1_PENDING');
|
||||
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
|
||||
describe('atomic approval queue contract', () => {
|
||||
let t:any, tx:any, service:PrepareWorkflowService;
|
||||
const actor={id:'reviewer',role:'SUPER_ADMIN'};
|
||||
const command={decision:'APPROVED',expectedVersion:2,idempotencyKey:'approve'};
|
||||
beforeEach(()=>{
|
||||
t={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo'}};
|
||||
tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>t),update:jest.fn(async({data}:any)=>(t={...t,...data,version:t.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{create:jest.fn()},prepareWorkflowOutbox:{create:jest.fn()}};
|
||||
service=new PrepareWorkflowService({$transaction:async(fn:any)=>fn(tx)},{workerIds:['pmo'],stageCiIds:[]});
|
||||
});
|
||||
it('approval with no date enters READY and creates exactly one outbox atomically',async()=>{
|
||||
await expect(service.decide('t',1,command,actor)).resolves.toMatchObject({state:'READY',version:3});
|
||||
expect(tx.prepareWorkflowOutbox.create).toHaveBeenCalledTimes(1);
|
||||
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:'reviewer',expiresAt:expect.any(Date),notes:expect.any(String)})});
|
||||
tx.orchestrationEvent.findUnique.mockResolvedValue(tx.orchestrationEvent.create.mock.calls[0][0].data);
|
||||
await service.decide('t',1,command,actor);
|
||||
expect(tx.prepareWorkflowOutbox.create).toHaveBeenCalledTimes(1);
|
||||
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledTimes(1);
|
||||
await expect(service.decide('t',1,{...command,notes:'changed'},actor)).rejects.toMatchObject({status:409});
|
||||
});
|
||||
it('future schedule is durable and server expiry extends beyond it',async()=>{
|
||||
const notBefore=new Date(Date.now()+7*86400000).toISOString();
|
||||
await service.decide('t',1,{...command,notBefore},actor);
|
||||
const data=tx.prepareWorkflowOutbox.create.mock.calls[0][0].data;
|
||||
expect(data.notBefore).toEqual(new Date(notBefore));
|
||||
expect(tx.orchestrationApprovalDecision.create.mock.calls[0][0].data.expiresAt.getTime()).toBeGreaterThan(Date.parse(notBefore));
|
||||
});
|
||||
it('rejected decision never queues',async()=>{
|
||||
await expect(service.decide('t',1,{...command,decision:'REJECTED'},actor)).resolves.toMatchObject({state:'REJECTED'});
|
||||
expect(tx.prepareWorkflowOutbox.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([new Date(0).toISOString(),new Date(Date.now()+31*86400000).toISOString(),'bad'])('denies invalid schedule %s',async notBefore=>{
|
||||
await expect(service.decide('t',1,{...command,notBefore},actor)).rejects.toMatchObject({status:400});
|
||||
expect(tx.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it('legacy explicit expiry remains an expiry, never a schedule',async()=>{
|
||||
const expiresAt=new Date(Date.now()+60000).toISOString();
|
||||
await service.decide('t',1,{...command,expiresAt},actor);
|
||||
expect(tx.orchestrationApprovalDecision.create.mock.calls[0][0].data.expiresAt).toEqual(new Date(expiresAt));
|
||||
expect(tx.prepareWorkflowOutbox.create.mock.calls[0][0].data.notBefore).toBeNull();
|
||||
});
|
||||
it('expired approval is denied with no writes',async()=>{
|
||||
await expect(service.decide('t',1,{...command,expiresAt:new Date(0).toISOString()},actor)).rejects.toMatchObject({status:400});
|
||||
expect(tx.prepareWorkflowOutbox.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -8,8 +8,6 @@ import {
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
@@ -32,21 +30,13 @@ export class GateDecisionDto {
|
||||
@IsIn(['APPROVED', 'REJECTED']) decision!: 'APPROVED' | 'REJECTED';
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
// Legacy explicit validity cap; scheduling uses notBefore instead.
|
||||
@IsOptional() @IsISO8601() expiresAt?: string;
|
||||
@IsOptional() @IsISO8601() notBefore?: string;
|
||||
@IsISO8601() expiresAt!: string;
|
||||
@IsOptional() @IsString() notes?: string;
|
||||
@IsOptional() @IsString() runId?: string;
|
||||
@IsOptional() @IsHash('sha256') artifactHash?: string;
|
||||
@IsOptional() @IsString() commitSha?: string;
|
||||
@IsOptional() @IsString() environment?: string;
|
||||
}
|
||||
export class EditorialFailureDto {
|
||||
@IsUUID() runId!: string;
|
||||
@IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() @MaxLength(120) idempotencyKey!: string;
|
||||
@IsString() @IsNotEmpty() @MaxLength(500) reason!: string;
|
||||
}
|
||||
export class RecordBudgetDto {
|
||||
@Type(() => Number) @IsInt() @Min(1) amountCents!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import {PrepareWorkflowService} from './prepare-workflow.service';
|
||||
const sha='a'.repeat(40),runId='run';
|
||||
const task=()=>({id:'task',key:'editorial-v1:'+'a'.repeat(64),title:'Editorial research: Test',department:'CONTENT',operationMode:'PREPARE',budgetLimitCents:20,state:'RUNNING',version:6,metadata:{createdBy:'pmo',workflowScope:'STAGE_PREPARE',environment:'staging',commitSha:sha,scope:'EDITORIAL_KIND',acceptanceCriteria:['Research']},runs:[{id:runId,taskId:'task',status:'RUNNING',environment:'staging',commitSha:sha,artifacts:[]}],budgetLedger:[{id:'reserve',taskId:'task',actorId:'pmo',kind:'RESERVE',amountCents:20,idempotencyKey:'prepare-reserve:run'}]});
|
||||
// Use the real canonical proposal marker, not a permissive admission mock.
|
||||
import {EDITORIAL_PILOT_KIND} from '../orchestration-worker/editorial-bridge';
|
||||
describe('safe editorial recovery detail hint',()=>{
|
||||
let service:any,row:any,db:any,outbox:any;
|
||||
beforeEach(()=>{row=task();row.metadata.scope=EDITORIAL_PILOT_KIND+'\nTopic: Test\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.';outbox={taskId:'task',status:'PENDING',runId,leaseOwner:'pmo',leaseToken:'NEVER_EXPOSE',leaseUntil:new Date(Date.now()-1000),reservationId:'reserve'};db={prepareWorkflowOutbox:{findUnique:jest.fn(async()=>outbox)}};service=Object.create(PrepareWorkflowService.prototype);service.db=db;service.config={reviewerIds:['owner']};});
|
||||
it('returns only matching run id to an independent reviewer',async()=>{expect(await service.editorialRecovery(row,{id:'owner',role:'SUPER_ADMIN'})).toEqual({runId});});
|
||||
it.each(['active','mismatch','artifact','reconciled','other-task','wrong-commit','wrong-mode'])('denies %s',async mode=>{
|
||||
if(mode==='active')outbox.leaseUntil=new Date(Date.now()+100000);
|
||||
if(mode==='mismatch')outbox.runId='other';
|
||||
if(mode==='artifact')row.runs[0].artifacts=[{id:'qa'}];
|
||||
if(mode==='reconciled')row.budgetLedger.push({kind:'RECONCILE',amountCents:0});
|
||||
if(mode==='other-task')row.runs[0].taskId='other';
|
||||
if(mode==='wrong-commit')row.runs[0].commitSha='b'.repeat(40);
|
||||
if(mode==='wrong-mode')row.operationMode='MUTATE_PRODUCTION';
|
||||
expect(await service.editorialRecovery(row,{id:'owner',role:'SUPER_ADMIN'})).toBeUndefined();
|
||||
});
|
||||
it('denies ordinary admin and creator',async()=>{expect(await service.editorialRecovery(row,{id:'admin',role:'Admin'})).toBeUndefined();expect(await service.editorialRecovery(row,{id:'pmo',role:'SUPER_ADMIN'})).toBeUndefined();});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
describe('editorial failure recovery fencing',()=>{
|
||||
const actor={id:'owner',role:'SUPER_ADMIN'},worker={id:'pmo',role:'WORKFLOW_WORKER'};
|
||||
let db:any,core:PrepareWorkflowService,t:any,o:any,r:any,events:any[];
|
||||
beforeEach(()=>{
|
||||
t={id:randomUUID(),key:'editorial-v1:'+'a'.repeat(64),title:'Editorial research: fixture',department:'CONTENT',operationMode:'PREPARE',budgetLimitCents:20,state:'RUNNING',version:6,metadata:{createdBy:'pmo',workflowScope:'STAGE_PREPARE',environment:'staging',commitSha:'a'.repeat(40),scope:'editorial-research-to-brief-v1\nTopic: fixture\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.',acceptanceCriteria:['evidence']}};
|
||||
r={id:randomUUID(),taskId:t.id,status:'RUNNING',commitSha:t.metadata.commitSha,environment:'staging'};
|
||||
o={id:randomUUID(),taskId:t.id,status:'PENDING',runId:r.id,leaseOwner:'pmo',leaseToken:randomUUID(),leaseUntil:new Date(Date.now()-1000),reservationId:'reserve'};events=[];
|
||||
const tx:any={$queryRaw:async()=>[],orchestrationTask:{findUnique:async()=>t,update:async({data}:any)=>(Object.assign(t,{state:data.state,version:t.version+1}),{...t})},prepareWorkflowOutbox:{findUnique:async()=>o,update:async({data}:any)=>Object.assign(o,data)},orchestrationRun:{findUnique:async()=>r,update:async({data}:any)=>Object.assign(r,data)},orchestrationEvent:{findUnique:async({where}:any)=>events.find(e=>e.idempotencyKey===where.idempotencyKey),findFirst:async()=>({}),create:async({data}:any)=>events.push(data)},orchestrationBudgetLedger:{findUnique:async()=>({id:'reserve',taskId:t.id,kind:'RESERVE',actorId:'pmo',amountCents:20,idempotencyKey:'prepare-reserve:'+r.id}),aggregate:async()=>({_sum:{amountCents:20}}),findFirst:async()=>null},orchestrationArtifact:{count:async()=>0}};
|
||||
let tail=Promise.resolve();db={$transaction:(fn:any)=>{const p=tail.then(()=>fn(tx));tail=p.catch(()=>{});return p;}};core=new PrepareWorkflowService(db,{workerIds:['pmo'],stageCiIds:[]});
|
||||
});
|
||||
const dto=()=>({runId:r.id,expectedVersion:6,idempotencyKey:'recover:'+r.id,reason:'local process ended; cost unknown'});
|
||||
it('terminalizes expired run without QA/cost writes and replays concurrently',async()=>{
|
||||
const d=dto();const results=await Promise.all([core.editorialFailure(t.id,d,actor),core.editorialFailure(t.id,d,actor)]);
|
||||
expect(results.map(x=>x.state)).toEqual(['FAILED','FAILED']);expect(t.version).toBe(7);expect(r.status).toBe('FAILED');expect(o.status).toBe('DONE');expect(o.leaseToken).toBeNull();expect(o.reservationId).toBe('reserve');expect(events).toHaveLength(1);expect(events[0].payload.retainedReservationCents).toBe(20);
|
||||
});
|
||||
it('rejects wrong run, stale version, unprivileged actor, active recovery and wrong held token',async()=>{
|
||||
for(const [d,a] of [[{...dto(),runId:randomUUID()},actor],[{...dto(),expectedVersion:5},actor],[dto(),{id:'other',role:'Admin'}],[dto(),worker]] as any)await expect(core.editorialFailure(t.id,d,a)).rejects.toThrow();
|
||||
o.leaseUntil=new Date(Date.now()+30000);
|
||||
await expect(core.editorialFailure(t.id,dto(),actor)).rejects.toThrow();
|
||||
await expect(core.editorialFailure(t.id,{...dto(),leaseToken:randomUUID()},worker)).rejects.toThrow();
|
||||
await core.editorialFailure(t.id,{...dto(),leaseToken:o.leaseToken},worker);expect(t.state).toBe('FAILED');
|
||||
});
|
||||
it('rejects cross-task run binding and changed idempotency payload',async()=>{
|
||||
r.taskId=randomUUID();await expect(core.editorialFailure(t.id,dto(),actor)).rejects.toThrow();r.taskId=t.id;
|
||||
const d=dto();await core.editorialFailure(t.id,d,actor);await expect(core.editorialFailure(t.id,{...d,reason:'changed'},actor)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
|
||||
describe('queued Gate1 expiry renewal',()=>{
|
||||
const owner={id:'owner',role:'SUPER_ADMIN'};
|
||||
let t:any,tx:any,s:PrepareWorkflowService,approval:any;
|
||||
beforeEach(()=>{
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-10-24T09:15:00Z'));
|
||||
approval={id:'approval',gate:1,decision:'APPROVED',actorId:'owner',createdAt:new Date('2026-10-24T05:37:54.808Z'),expiresAt:new Date('2026-10-24T06:37:00Z')};
|
||||
t={id:'t',state:'READY',version:4,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo',commitSha:'a'.repeat(40)},decisions:[approval]};
|
||||
tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>t),update:jest.fn(async({data}:any)=>(t={...t,state:data.state,version:t.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{findFirst:jest.fn(async()=>approval),create:jest.fn()},prepareWorkflowOutbox:{findUnique:jest.fn().mockResolvedValue({status:'PENDING',attempts:0,runId:null,notBefore:null}),create:jest.fn(),update:jest.fn()}};
|
||||
s=new PrepareWorkflowService({$transaction:async(fn:any)=>fn(tx)},{workerIds:['pmo'],stageCiIds:[]});
|
||||
});
|
||||
afterEach(()=>jest.useRealTimers());
|
||||
const dto={decision:'APPROVED',expectedVersion:4,idempotencyKey:'renew'};
|
||||
it('shows blocked renewal rather than actionable READY at actual failure time',()=>{
|
||||
expect(s.project(t,owner)).toMatchObject({displayState:'GATE1_RENEWAL_REQUIRED',availableActions:['APPROVE_GATE1']});
|
||||
});
|
||||
it('renews by ordinary independent approval without recreating outbox or changing immutable task binding',async()=>{
|
||||
await expect(s.decide('t',1,dto,owner)).resolves.toMatchObject({state:'READY',version:5});
|
||||
expect(tx.prepareWorkflowOutbox.create).not.toHaveBeenCalled();
|
||||
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:'owner',expiresAt:new Date('2026-10-25T09:15:00Z')})});
|
||||
expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({eventType:'PREPARE_GATE1_RENEWED',fromState:'READY',toState:'READY'})});
|
||||
});
|
||||
it('does not renew valid approvals, self review, active runs, or schedule changes',async()=>{
|
||||
await expect(s.decide('t',1,dto,{id:'pmo',role:'SUPER_ADMIN'})).rejects.toMatchObject({status:403});
|
||||
await expect(s.decide('t',1,{...dto,notBefore:'2026-10-25T10:00:00Z'},owner)).rejects.toMatchObject({status:400});
|
||||
tx.prepareWorkflowOutbox.findUnique.mockResolvedValue({status:'PENDING',attempts:1,runId:'r'});
|
||||
await expect(s.decide('t',1,dto,owner)).rejects.toMatchObject({status:409});
|
||||
tx.prepareWorkflowOutbox.findUnique.mockResolvedValue({status:'PENDING',attempts:0,runId:null});
|
||||
approval.expiresAt=new Date('2026-10-25T09:15:00Z');
|
||||
await expect(s.decide('t',1,dto,owner)).rejects.toMatchObject({status:409});
|
||||
});
|
||||
it('replays identical command after expiry but denies changed payload and stale concurrent command',async()=>{
|
||||
await s.decide('t',1,dto,owner);
|
||||
const e=tx.orchestrationEvent.create.mock.calls[0][0].data;
|
||||
tx.orchestrationEvent.findUnique.mockResolvedValue(e);
|
||||
jest.setSystemTime(new Date('2026-10-26T09:15:00Z'));
|
||||
await s.decide('t',1,dto,owner);
|
||||
expect(tx.orchestrationTask.update).toHaveBeenCalledTimes(1);
|
||||
await expect(s.decide('t',1,{...dto,notes:'changed'},owner)).rejects.toMatchObject({status:409});
|
||||
tx.orchestrationEvent.findUnique.mockResolvedValue(null);
|
||||
await expect(s.decide('t',1,{...dto,idempotencyKey:'competing'},owner)).rejects.toMatchObject({status:409});
|
||||
});
|
||||
});
|
||||
@@ -92,7 +92,7 @@ describe('integration read boundary', () => {
|
||||
[method]('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.send({})
|
||||
.expect(path === 'tasks' || path.endsWith('/transition') ? 400 : 403);
|
||||
.expect(403);
|
||||
}
|
||||
for (const name of [
|
||||
'createTask',
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import {
|
||||
Controller,
|
||||
Body,
|
||||
Req,
|
||||
Optional,
|
||||
ValidationPipe,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
@@ -17,21 +13,6 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import {
|
||||
PrepareWorkflowService,
|
||||
WorkflowIdentity,
|
||||
} from './prepare-workflow.service';
|
||||
import {
|
||||
CreateOrchestrationTaskDto,
|
||||
TransitionTaskDto,
|
||||
GateDecisionDto,
|
||||
EditorialFailureDto,
|
||||
} from './dto/orchestration.dto';
|
||||
const workflowValidation = new ValidationPipe({
|
||||
transform: true,
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
});
|
||||
|
||||
// Explicit response allowlists: never serialize arbitrary JSON, signatures, URIs or BigInt.
|
||||
function pick(row: any, keys: string[]) {
|
||||
@@ -92,48 +73,12 @@ function project(row: any) {
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
@Controller('admin/orchestration')
|
||||
export class OrchestrationController {
|
||||
constructor(
|
||||
private readonly service: OrchestrationService,
|
||||
@Optional() private readonly workflow?: PrepareWorkflowService,
|
||||
) {}
|
||||
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 ||
|
||||
!role
|
||||
)
|
||||
throw new ForbiddenException('Authenticated workflow identity required');
|
||||
return { id, role };
|
||||
constructor(private readonly service: OrchestrationService) {}
|
||||
@Get('tasks') async all() {
|
||||
return (await this.service.findAll()).map(project);
|
||||
}
|
||||
private safe(row: any, req: any) {
|
||||
const view = project(row);
|
||||
if (!this.workflow) return view;
|
||||
const w = this.workflow.project(row, this.actor(req));
|
||||
return {
|
||||
...view,
|
||||
metadata: w.metadata,
|
||||
displayState: w.displayState,
|
||||
availableActions: w.availableActions,
|
||||
};
|
||||
}
|
||||
@Get('tasks') async all(@Req() req: any) {
|
||||
return (await this.service.findAll()).map((row: any) =>
|
||||
this.safe(row, req),
|
||||
);
|
||||
}
|
||||
@Get('tasks/:id') async one(@Param('id') id: string, @Req() req: any) {
|
||||
const row = await this.service.findOne(id);
|
||||
const editorialRecovery = this.workflow
|
||||
? await this.workflow.editorialRecovery(row, this.actor(req)) : undefined;
|
||||
return { ...this.safe(row, req), ...(editorialRecovery ? { editorialRecovery } : {}) };
|
||||
@Get('tasks/:id') async one(@Param('id') id: string) {
|
||||
return project(await this.service.findOne(id));
|
||||
}
|
||||
@Get('overview') async overview() {
|
||||
const tasks = await this.service.findAll();
|
||||
@@ -142,17 +87,8 @@ export class OrchestrationController {
|
||||
{ id: 'tasks', title: 'Persisted task inventory', count: tasks.length },
|
||||
],
|
||||
measuredAt: new Date().toISOString(),
|
||||
capabilities: {
|
||||
mutations: !!this.workflow,
|
||||
prepare: !!this.workflow,
|
||||
release: false,
|
||||
gate2Decisions: false,
|
||||
chat: false,
|
||||
runtime: false,
|
||||
},
|
||||
reason: this.workflow
|
||||
? 'bounded_stage_prepare_only'
|
||||
: 'security_hardening_pending',
|
||||
capabilities: { mutations: false, chat: false, runtime: false },
|
||||
reason: 'security_hardening_pending',
|
||||
};
|
||||
}
|
||||
@Get('releases') async releases() {
|
||||
@@ -184,48 +120,15 @@ export class OrchestrationController {
|
||||
'No persisted model policy read contract available',
|
||||
);
|
||||
}
|
||||
// Only the separate bounded PREPARE service is exposed; legacy commands remain denied.
|
||||
@Post('tasks') async create(
|
||||
@Body(workflowValidation) dto: CreateOrchestrationTaskDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow) return this.deny();
|
||||
return this.safe(await this.workflow.create(dto, this.actor(req)), req);
|
||||
// The committed legacy core is not safe to expose. No env switch or role may bypass this boundary.
|
||||
@Post('tasks') create() {
|
||||
return this.deny();
|
||||
}
|
||||
@Put('tasks/:id/transition') async transition(
|
||||
@Param('id') id: string,
|
||||
@Body(workflowValidation) dto: TransitionTaskDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow) return this.deny();
|
||||
return this.safe(
|
||||
await this.workflow.transition(id, dto, this.actor(req)),
|
||||
req,
|
||||
);
|
||||
@Put('tasks/:id/transition') transition() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/gates/:gate/decide') async decide(
|
||||
@Param('id') id: string,
|
||||
@Param('gate') gate: string,
|
||||
@Body() body: unknown,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow || gate !== '1') return this.deny();
|
||||
const dto = await workflowValidation.transform(body, {
|
||||
type: 'body',
|
||||
metatype: GateDecisionDto,
|
||||
});
|
||||
return this.safe(
|
||||
await this.workflow.decide(id, 1, dto, this.actor(req)),
|
||||
req,
|
||||
);
|
||||
}
|
||||
@Post('tasks/:id/editorial-failure') async editorialFailure(
|
||||
@Param('id') id: string,
|
||||
@Body(workflowValidation) dto: EditorialFailureDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
if (!this.workflow) return this.deny();
|
||||
return this.safe(await this.workflow.editorialFailure(id, dto, this.actor(req)), req);
|
||||
@Post('tasks/:id/gates/:gate/decide') decide() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/budget') budget() {
|
||||
return this.deny();
|
||||
|
||||
@@ -3,7 +3,6 @@ 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',
|
||||
@@ -44,9 +43,7 @@ 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,
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import {
|
||||
PrepareWorkflowService,
|
||||
PREPARE_WORKFLOW_CONFIG,
|
||||
} from './prepare-workflow.service';
|
||||
import { workflowConfig } from './workflow-config';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
@@ -12,21 +7,7 @@ import { OrchestrationService } from './orchestration.service';
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
OrchestrationService,
|
||||
KillSwitchService,
|
||||
ModelTierPolicyService,
|
||||
PrepareWorkflowService,
|
||||
{
|
||||
provide: PREPARE_WORKFLOW_CONFIG,
|
||||
useFactory: () => workflowConfig(process.env),
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
OrchestrationService,
|
||||
KillSwitchService,
|
||||
ModelTierPolicyService,
|
||||
PrepareWorkflowService,
|
||||
],
|
||||
providers: [OrchestrationService, KillSwitchService, ModelTierPolicyService],
|
||||
exports: [OrchestrationService, KillSwitchService, ModelTierPolicyService],
|
||||
})
|
||||
export class OrchestrationModule {}
|
||||
@@ -200,7 +200,6 @@ export class OrchestrationService {
|
||||
return prior;
|
||||
}
|
||||
if (
|
||||
typeof dto.expiresAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(dto.expiresAt)) ||
|
||||
new Date(dto.expiresAt) <= new Date()
|
||||
)
|
||||
@@ -619,7 +618,6 @@ export class OrchestrationService {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
return (this.prisma as any).orchestrationTask.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { decisions: true },
|
||||
});
|
||||
}
|
||||
async findOne(id: string) {
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
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={prepareWorkflowOutbox:{create:jest.fn()},$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:[],ownerReviewerIds:['12345678-1234-1234-1234-123456789012']} as any);
|
||||
});
|
||||
it('advertises and permits the pinned canonical Admin independent reviewer only',async()=>{
|
||||
const owner={id:'12345678-1234-1234-1234-123456789012',role:'Admin'};
|
||||
expect(service.project(task,owner).availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']);
|
||||
await expect(service.transition('t',hold,owner)).resolves.toMatchObject({state:'GATE1_HELD'});
|
||||
await expect(service.decide('t',1,{decision:'APPROVED',expectedVersion:3,idempotencyKey:'owner-approve',expiresAt:new Date(Date.now()+60000).toISOString()},owner)).resolves.toMatchObject({state:'READY'});
|
||||
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner.id})});
|
||||
});
|
||||
it.each(['Admin','SUPER_ADMIN'])('never permits proposer self-review even if allowlisted: %s',async role=>{
|
||||
const actor={id:'12345678-1234-1234-1234-123456789012',role}; task.metadata.createdBy=actor.id;
|
||||
expect(service.project(task,actor).availableActions).toEqual([]);
|
||||
await expect(service.transition('t',hold,actor)).rejects.toMatchObject({status:403});
|
||||
await expect(service.decide('t',1,{decision:'REJECTED',expectedVersion:2,idempotencyKey:'self',expiresAt:new Date(Date.now()+60000).toISOString()},actor)).rejects.toMatchObject({status:403});
|
||||
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{id:'other',role:'Admin'},{id:'12345678-1234-1234-1234-123456789012',role:'User'},{id:'12345678-1234-1234-1234-123456789012',role:'ADMIN'}])('denies noncanonical or ungranted reviewer %j',async actor=>{
|
||||
expect(service.project(task,actor).availableActions).toEqual([]);
|
||||
await expect(service.decide('t',1,{decision:'REJECTED',expectedVersion:2,idempotencyKey:'deny',expiresAt:new Date(Date.now()+60000).toISOString()},actor)).rejects.toMatchObject({status:403});
|
||||
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
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'?'READY':'REJECTED'});
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import {Test} from '@nestjs/testing';
|
||||
import {INestApplication} from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import {OrchestrationController} from './orchestration.controller';
|
||||
import {OrchestrationService} from './orchestration.service';
|
||||
import {PrepareWorkflowService} from './prepare-workflow.service';
|
||||
import {JwtAuthGuard} from '../auth/jwt-auth.guard';
|
||||
import {RolesGuard} from '../common/guards/roles.guard';
|
||||
describe('configured owner real workflow HTTP authorization',()=>{
|
||||
const owner='12345678-1234-1234-1234-123456789012';
|
||||
let app:INestApplication,task:any,tx:any;
|
||||
beforeAll(async()=>{
|
||||
tx={prepareWorkflowOutbox:{create:jest.fn()},$queryRaw:jest.fn(async()=>[]),orchestrationTask:{findUnique: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()}};
|
||||
const workflow=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)},{workerIds:[],stageCiIds:[],ownerReviewerIds:[owner]});
|
||||
const m=await Test.createTestingModule({controllers:[OrchestrationController],providers:[{provide:OrchestrationService,useValue:{findAll:async()=>[task],findOne:async()=>task}},{provide:PrepareWorkflowService,useValue:workflow},RolesGuard]})
|
||||
.overrideGuard(JwtAuthGuard).useValue({canActivate(c:any){const r=c.switchToHttp().getRequest();if(!r.headers.authorization)return false;r.user={sub:r.headers.authorization,role:'ADMIN'};return true;}}).compile();
|
||||
app=m.createNestApplication();await app.init();
|
||||
});
|
||||
beforeEach(()=>{jest.clearAllMocks();task={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo'}};});
|
||||
afterAll(async()=>{await app.close();});
|
||||
it.each(['APPROVED','REJECTED'])('advertises and executes %s only for verified granted JWT subject',async decision=>{
|
||||
const r=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization',owner).expect(200);
|
||||
expect(r.body[0].availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']);
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',owner).send({decision,expectedVersion:2,idempotencyKey:'decision',expiresAt:new Date(Date.now()+60000).toISOString(),notes:'Delegated system testing by independent owner'}).expect(201);
|
||||
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner,decision})});
|
||||
expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner,payload:expect.objectContaining({fingerprint:expect.stringContaining('Delegated system testing')})})});
|
||||
});
|
||||
it('holds via canonicalized ADMIN without granting proposer powers',async()=>{
|
||||
await request(app.getHttpServer()).put('/admin/orchestration/tasks/t/transition').set('Authorization',owner).send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Independent owner needs evidence'}).expect(200);
|
||||
expect(tx.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['ordinary-admin','pmo'])('denies ungranted subject %s and body impersonation',async subject=>{
|
||||
const r=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization',subject).expect(200);
|
||||
expect(r.body[0].availableActions).toEqual([]);
|
||||
const body={decision:'APPROVED',expectedVersion:2,idempotencyKey:'deny',expiresAt:new Date(Date.now()+60000).toISOString()};
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',subject).send(body).expect(403);
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',subject).send({...body,actorId:owner}).expect(400);
|
||||
await request(app.getHttpServer()).put('/admin/orchestration/tasks/t/transition').set('Authorization',subject).send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'hold'}).expect(403);
|
||||
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it('denies grant holder self review, Gate2 and release',async()=>{
|
||||
task.metadata.createdBy=owner;
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',owner).send({decision:'APPROVED',expectedVersion:2,idempotencyKey:'self',expiresAt:new Date(Date.now()+60000).toISOString()}).expect(403);
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/2/decide').set('Authorization',owner).send({}).expect(403);
|
||||
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/commands/RELEASE_AUTHORIZE').set('Authorization',owner).send({}).expect(403);
|
||||
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,185 +0,0 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('bounded workflow HTTP contracts', () => {
|
||||
let app: INestApplication;
|
||||
const t = {
|
||||
id: 't',
|
||||
key: 'k',
|
||||
state: 'DRAFT',
|
||||
version: 1,
|
||||
metadata: {
|
||||
scope: 'STAGE_PREPARE',
|
||||
environment: 'staging',
|
||||
commitSha: 'a'.repeat(40),
|
||||
token: 'secret',
|
||||
},
|
||||
};
|
||||
const workflow = {
|
||||
editorialRecovery: jest.fn(async () => undefined as undefined | {runId:string}),
|
||||
create: jest.fn(async () => t),
|
||||
transition: jest.fn(async () => t),
|
||||
decide: jest.fn(async () => t),
|
||||
project: jest.fn((row: any) => ({
|
||||
...row,
|
||||
metadata: {
|
||||
scope: 'STAGE_PREPARE',
|
||||
environment: 'staging',
|
||||
commitSha: 'a'.repeat(40),
|
||||
},
|
||||
availableActions: ['SUBMIT_GATE1'],
|
||||
})),
|
||||
};
|
||||
const core = {
|
||||
findAll: async () => [t],
|
||||
findOne: async () => t,
|
||||
command: jest.fn(),
|
||||
};
|
||||
beforeAll(async () => {
|
||||
const m = await Test.createTestingModule({
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
{ provide: OrchestrationService, useValue: core },
|
||||
{ provide: PrepareWorkflowService, useValue: workflow },
|
||||
RolesGuard,
|
||||
],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({
|
||||
canActivate(c: any) {
|
||||
const req = c.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = {
|
||||
sub: 'verified-subject',
|
||||
role: req.headers.authorization,
|
||||
};
|
||||
return true;
|
||||
},
|
||||
})
|
||||
.compile();
|
||||
app = m.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
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('adds only the safe recovery hint to detail, never the list', async () => {
|
||||
workflow.editorialRecovery.mockResolvedValueOnce({runId:'registered-run'});
|
||||
const detail=await request(app.getHttpServer()).get('/admin/orchestration/tasks/t').set('Authorization','SUPER_ADMIN').expect(200);
|
||||
expect(detail.body.editorialRecovery).toEqual({runId:'registered-run'});
|
||||
expect(workflow.editorialRecovery).toHaveBeenCalledWith(t,{id:'verified-subject',role:'SUPER_ADMIN'});
|
||||
const list=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization','SUPER_ADMIN').expect(200);
|
||||
expect(list.body[0].editorialRecovery).toBeUndefined();
|
||||
expect(JSON.stringify(detail.body)).not.toContain('secret');
|
||||
});
|
||||
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',
|
||||
title: 'T',
|
||||
department: 'ENGINEERING',
|
||||
operationMode: 'PREPARE',
|
||||
budgetLimitCents: 20,
|
||||
metadata: {
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: 'Staging audit only',
|
||||
acceptanceCriteria: ['QA passes'],
|
||||
},
|
||||
};
|
||||
const r = await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.set('Authorization', 'Admin')
|
||||
.send(dto)
|
||||
.expect(201);
|
||||
expect(workflow.create).toHaveBeenCalledWith(dto, {
|
||||
id: 'verified-subject',
|
||||
role: 'Admin',
|
||||
});
|
||||
expect(r.body.availableActions).toEqual(['SUBMIT_GATE1']);
|
||||
expect(JSON.stringify(r.body)).not.toMatch(/token|secret/);
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.set('Authorization', 'Admin')
|
||||
.send({ ...dto, actorId: 'browser' })
|
||||
.expect(400);
|
||||
});
|
||||
it('routes fixed transition/gate contracts and rejects invalid gates plus release without invoking core', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.put('/admin/orchestration/tasks/t/transition')
|
||||
.set('Authorization', 'Admin')
|
||||
.send({
|
||||
toState: 'GATE1_PENDING',
|
||||
expectedVersion: 1,
|
||||
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')
|
||||
.send({
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'approval',
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
})
|
||||
.expect(201);
|
||||
expect(workflow.decide).toHaveBeenCalledWith('t', 1, expect.any(Object), {
|
||||
id: 'verified-subject',
|
||||
role: 'SUPER_ADMIN',
|
||||
});
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks/t/gates/2/decide')
|
||||
.set('Authorization', 'SUPER_ADMIN')
|
||||
.send({})
|
||||
.expect(403);
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks/t/commands/RELEASE_AUTHORIZE')
|
||||
.set('Authorization', 'SUPER_ADMIN')
|
||||
.send({})
|
||||
.expect(403);
|
||||
expect(core.command).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,689 +0,0 @@
|
||||
import {
|
||||
Injectable,
|
||||
Inject,
|
||||
ForbiddenException,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
export const PREPARE_WORKFLOW_CONFIG = 'PREPARE_WORKFLOW_CONFIG';
|
||||
export interface WorkflowIdentity {
|
||||
id: string;
|
||||
role: string;
|
||||
}
|
||||
export interface WorkflowConfig {
|
||||
ownerReviewerIds?: string[];
|
||||
workerIds: string[];
|
||||
stageCiIds: string[];
|
||||
}
|
||||
|
||||
/** Bounded Stage preparation only. No release executor, production scope or browser worker identities. */
|
||||
@Injectable()
|
||||
export class PrepareWorkflowService {
|
||||
constructor(
|
||||
@Inject(PrismaService) private readonly db: any,
|
||||
@Inject(PREPARE_WORKFLOW_CONFIG) private readonly config: WorkflowConfig,
|
||||
) {}
|
||||
private identity(a: WorkflowIdentity, roles: string[]) {
|
||||
if (
|
||||
!a?.id ||
|
||||
typeof a.id !== 'string' ||
|
||||
a.id.length > 100 ||
|
||||
!roles.includes(a.role)
|
||||
)
|
||||
throw new ForbiddenException('Authenticated workflow identity required');
|
||||
}
|
||||
private reviewer(a: WorkflowIdentity) {
|
||||
return typeof a?.id === 'string' && !!a.id && a.id.length <= 100 &&
|
||||
(a.role === 'SUPER_ADMIN' ||
|
||||
(a.role === 'Admin' && (this.config.ownerReviewerIds ?? []).includes(a.id)));
|
||||
}
|
||||
private worker(a: WorkflowIdentity) {
|
||||
this.identity(a, ['WORKFLOW_WORKER']);
|
||||
if (!this.config.workerIds.includes(a.id))
|
||||
throw new ForbiddenException('Worker identity not provisioned');
|
||||
}
|
||||
private async allowed(tx: any, claiming = false) {
|
||||
const rows =
|
||||
await tx.$queryRaw`SELECT level, active FROM orchestration_kill_switches WHERE scope = 'GLOBAL' FOR SHARE`;
|
||||
if (rows[0]?.active && !(rows[0].level === 'FREEZE_NEW_WORK' && !claiming))
|
||||
throw new ForbiddenException('Kill switch blocks workflow');
|
||||
}
|
||||
private async task(tx: any, id: string) {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${id}::uuid FOR UPDATE`;
|
||||
const t = await tx.orchestrationTask.findUnique({ where: { id } });
|
||||
if (!t) throw new NotFoundException('Task not found');
|
||||
if (
|
||||
t.operationMode !== 'PREPARE' ||
|
||||
(t.metadata?.workflowScope ?? t.metadata?.scope) !== 'STAGE_PREPARE'
|
||||
)
|
||||
throw new ForbiddenException('Not a bounded Stage proposal');
|
||||
return t;
|
||||
}
|
||||
private async event(
|
||||
tx: any,
|
||||
t: any,
|
||||
state: string,
|
||||
a: WorkflowIdentity,
|
||||
key: string,
|
||||
type: string,
|
||||
fingerprint: string,
|
||||
) {
|
||||
const result = await tx.orchestrationTask.update({
|
||||
where: { id: t.id },
|
||||
data: { state, version: { increment: 1 } },
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
sequence: result.version,
|
||||
actorId: a.id,
|
||||
eventType: type,
|
||||
fromState: t.state,
|
||||
toState: state,
|
||||
idempotencyKey: key,
|
||||
payload: { fingerprint },
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
private async replay(tx: any, key: string, fingerprint: string) {
|
||||
const e = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: key },
|
||||
});
|
||||
if (e && e.payload?.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return e;
|
||||
}
|
||||
private version(t: any, dto: any) {
|
||||
if (
|
||||
!Number.isSafeInteger(dto.expectedVersion) ||
|
||||
dto.expectedVersion !== t.version
|
||||
)
|
||||
throw new ConflictException('Stale task version');
|
||||
if (
|
||||
typeof dto.idempotencyKey !== 'string' ||
|
||||
!dto.idempotencyKey.length ||
|
||||
dto.idempotencyKey.length > 120
|
||||
)
|
||||
throw new BadRequestException('Invalid idempotency key');
|
||||
}
|
||||
async create(dto: any, a: WorkflowIdentity) {
|
||||
this.identity(a, ['Admin', 'SUPER_ADMIN']);
|
||||
const metadata = dto?.metadata;
|
||||
const boundedText = (value: unknown, max: number) =>
|
||||
typeof value === 'string' &&
|
||||
value.trim().length > 0 &&
|
||||
value.length <= max;
|
||||
if (
|
||||
!metadata ||
|
||||
typeof metadata !== 'object' ||
|
||||
Array.isArray(metadata) ||
|
||||
typeof metadata.commitSha !== 'string' ||
|
||||
!boundedText(metadata.scope, 2000) ||
|
||||
!Array.isArray(metadata.acceptanceCriteria) ||
|
||||
metadata.acceptanceCriteria.length < 1 ||
|
||||
metadata.acceptanceCriteria.length > 20 ||
|
||||
!metadata.acceptanceCriteria.every((criterion: unknown) =>
|
||||
boundedText(criterion, 500),
|
||||
)
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'PREPARE requires commitSha, scope 1..2000 characters and 1..20 acceptance criteria of 1..500 characters',
|
||||
);
|
||||
if (
|
||||
dto.operationMode !== 'PREPARE' ||
|
||||
!/^[a-f0-9]{40}$/.test(dto.metadata?.commitSha ?? '') ||
|
||||
!Number.isSafeInteger(dto.budgetLimitCents) ||
|
||||
dto.budgetLimitCents < 20 ||
|
||||
dto.budgetLimitCents > 10000
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'PREPARE requires immutable 40hex commit and budget 20..10000 cents',
|
||||
);
|
||||
if (
|
||||
!dto.key ||
|
||||
dto.key.length > 120 ||
|
||||
!dto.title ||
|
||||
dto.title.length > 255 ||
|
||||
!dto.department ||
|
||||
dto.department.length > 50
|
||||
)
|
||||
throw new BadRequestException('Invalid proposal fields');
|
||||
return this.db
|
||||
.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx, true);
|
||||
const t = await tx.orchestrationTask.create({
|
||||
data: {
|
||||
key: dto.key,
|
||||
title: dto.title,
|
||||
department: dto.department,
|
||||
operationMode: 'PREPARE',
|
||||
budgetLimitCents: dto.budgetLimitCents,
|
||||
metadata: {
|
||||
workflowScope: 'STAGE_PREPARE',
|
||||
scope: dto.metadata.scope,
|
||||
acceptanceCriteria: [...dto.metadata.acceptanceCriteria],
|
||||
environment: 'staging',
|
||||
commitSha: dto.metadata.commitSha,
|
||||
createdBy: a.id,
|
||||
},
|
||||
state: 'DRAFT',
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
sequence: 1,
|
||||
eventType: 'PREPARE_PROPOSED',
|
||||
actorId: a.id,
|
||||
toState: 'DRAFT',
|
||||
},
|
||||
});
|
||||
return t;
|
||||
})
|
||||
.catch((error: any) => {
|
||||
if (
|
||||
error?.code === 'P2002' &&
|
||||
Array.isArray(error.meta?.target) &&
|
||||
error.meta.target.includes('key')
|
||||
)
|
||||
throw new ConflictException(
|
||||
'Proposal key already exists; fetch and reconcile the existing task',
|
||||
);
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
async transition(id: string, dto: any, a: WorkflowIdentity) {
|
||||
this.identity(a, ['Admin', 'SUPER_ADMIN']);
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx, true);
|
||||
const t = await this.task(tx, id);
|
||||
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 (!this.reviewer(a) || 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 (
|
||||
!(
|
||||
(t.state === 'DRAFT' && dto.toState === 'GATE1_PENDING') ||
|
||||
(t.state === 'GATE1_APPROVED' && dto.toState === 'READY')
|
||||
)
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Only submission and approved queueing are available',
|
||||
);
|
||||
if (dto.toState === 'READY') {
|
||||
const approval = await tx.orchestrationApprovalDecision.findFirst({
|
||||
where: { taskId: id, gate: 1, decision: 'APPROVED' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (!approval || approval.expiresAt <= new Date())
|
||||
throw new ForbiddenException('Gate1 expired');
|
||||
await tx.prepareWorkflowOutbox.create({ data: { taskId: id } });
|
||||
}
|
||||
return this.event(
|
||||
tx,
|
||||
t,
|
||||
dto.toState,
|
||||
a,
|
||||
dto.idempotencyKey,
|
||||
'PREPARE_TRANSITION',
|
||||
fingerprint,
|
||||
);
|
||||
});
|
||||
}
|
||||
async decide(id: string, gate: number, dto: any, a: WorkflowIdentity) {
|
||||
if (!this.reviewer(a))
|
||||
throw new ForbiddenException('Provisioned independent Gate1 reviewer required');
|
||||
if (gate !== 1)
|
||||
throw new ForbiddenException(
|
||||
'Gate2 decisions and release remain disabled',
|
||||
);
|
||||
if (!['APPROVED', 'REJECTED'].includes(dto.decision))
|
||||
throw new BadRequestException('Invalid decision');
|
||||
// Time-sensitive validation happens after replay, so a successful command
|
||||
// remains replayable after its original schedule or validity window passes.
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx);
|
||||
const t = await this.task(tx, id);
|
||||
const fingerprint = JSON.stringify({ id, gate, dto, a });
|
||||
if (await this.replay(tx, dto.idempotencyKey, fingerprint)) return t;
|
||||
this.version(t, dto);
|
||||
if (t.metadata.createdBy === a.id)
|
||||
throw new ForbiddenException('Independent reviewer required');
|
||||
const renewing = t.state === 'READY';
|
||||
let queue: any;
|
||||
if (renewing) {
|
||||
const previous = await tx.orchestrationApprovalDecision.findFirst({
|
||||
where: { taskId: id, gate: 1 }, orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
queue = await tx.prepareWorkflowOutbox.findUnique({ where: { taskId: id } });
|
||||
if (dto.notBefore !== undefined)
|
||||
throw new BadRequestException('Renewal preserves the existing schedule');
|
||||
if (dto.decision !== 'APPROVED' || !previous || previous.decision !== 'APPROVED' ||
|
||||
previous.actorId === t.metadata.createdBy || previous.expiresAt > new Date() ||
|
||||
!queue || queue.status !== 'PENDING' || queue.attempts !== 0 || queue.runId || queue.leaseToken)
|
||||
throw new ConflictException('Only expired independent approval on an unstarted queue can be renewed');
|
||||
} else if (!['GATE1_PENDING', 'GATE1_HELD'].includes(t.state))
|
||||
throw new ConflictException('Gate1 pending required');
|
||||
const now = Date.now();
|
||||
if (renewing && queue.notBefore && new Date(queue.notBefore).getTime() >= now + 86400000)
|
||||
throw new ConflictException('Existing schedule is outside the renewal validity window');
|
||||
const scheduled = dto.notBefore !== undefined;
|
||||
const notBefore = scheduled ? new Date(dto.notBefore) : null;
|
||||
if (scheduled && (dto.decision !== 'APPROVED' || typeof dto.notBefore !== 'string' || !Number.isFinite(notBefore!.getTime()) || notBefore!.getTime() <= now || notBefore!.getTime() > now + 30 * 86400000))
|
||||
throw new BadRequestException('notBefore must be a future approval schedule within 30 days');
|
||||
const policyExpiry = (notBefore?.getTime() ?? now) + 86400000;
|
||||
// Legacy expiresAt is an explicit validity cap, never a scheduled start.
|
||||
const expiresAt = dto.expiresAt === undefined ? new Date(policyExpiry) : new Date(dto.expiresAt);
|
||||
if (!Number.isFinite(expiresAt.getTime()) || expiresAt.getTime() <= (notBefore?.getTime() ?? now) || expiresAt.getTime() > policyExpiry)
|
||||
throw new BadRequestException('Approval expiry must cover schedule and remain within backend validity policy');
|
||||
if (dto.notes !== undefined && (typeof dto.notes !== 'string' || dto.notes.length > 2000))
|
||||
throw new BadRequestException('Audit notes must be at most 2000 characters');
|
||||
if (dto.decision === 'APPROVED') {
|
||||
await this.allowed(tx, true);
|
||||
if (!renewing) await tx.prepareWorkflowOutbox.create({data:{taskId:id,notBefore}});
|
||||
}
|
||||
await tx.orchestrationApprovalDecision.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
gate: 1,
|
||||
decision: dto.decision,
|
||||
actorId: a.id,
|
||||
expiresAt,
|
||||
notes: dto.notes?.trim() || `Owner ${dto.decision.toLowerCase()} Gate1`,
|
||||
idempotencyKey: `decision:${dto.idempotencyKey}`,
|
||||
},
|
||||
});
|
||||
return this.event(
|
||||
tx,
|
||||
t,
|
||||
dto.decision === 'APPROVED' ? 'READY' : 'REJECTED',
|
||||
a,
|
||||
dto.idempotencyKey,
|
||||
renewing ? 'PREPARE_GATE1_RENEWED' : 'PREPARE_GATE1',
|
||||
fingerprint,
|
||||
);
|
||||
});
|
||||
}
|
||||
/** Recovery of a stored approval by its provisioned proposal worker, not a new decision. */
|
||||
async enqueueApproved(a: WorkflowIdentity, dto: {taskId:string;expectedVersion:number;idempotencyKey:string}) {
|
||||
this.worker(a);
|
||||
return this.db.$transaction(async (tx:any)=>{
|
||||
await this.allowed(tx,true);
|
||||
const t=await this.task(tx,dto.taskId);
|
||||
if(t.metadata.createdBy!==a.id) throw new ForbiddenException('Proposal worker required');
|
||||
const fingerprint=JSON.stringify({dto,a});
|
||||
if(await this.replay(tx,dto.idempotencyKey,fingerprint)) return t;
|
||||
this.version(t,dto);
|
||||
if(t.state!=='GATE1_APPROVED') throw new ConflictException('Stored Gate1 approval required');
|
||||
const approval=await tx.orchestrationApprovalDecision.findFirst({where:{taskId:t.id,gate:1},orderBy:{createdAt:'desc'}});
|
||||
if(!approval || approval.decision!=='APPROVED' || approval.actorId===a.id || approval.expiresAt<=new Date())
|
||||
throw new ForbiddenException('Valid independent Gate1 required');
|
||||
await tx.prepareWorkflowOutbox.create({data:{taskId:t.id}});
|
||||
return this.event(tx,t,'READY',a,dto.idempotencyKey,'PREPARE_APPROVED_QUEUED',fingerprint);
|
||||
});
|
||||
}
|
||||
async claim(a: WorkflowIdentity, id?: string): Promise<any> {
|
||||
this.worker(a);
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx, true);
|
||||
// Lock order is task then outbox for every worker operation. SKIP LOCKED permits competing workers.
|
||||
const rows: any[] = id
|
||||
? await tx.$queryRaw`SELECT t.id FROM orchestration_tasks t JOIN prepare_workflow_outbox o ON o.task_id=t.id WHERE t.id=${id}::uuid AND t.state IN ('READY','RUNNING') AND o.status='PENDING' AND (o.not_before IS NULL OR o.not_before <= now()) AND (o.lease_until IS NULL OR o.lease_until < now()) ORDER BY o.created_at FOR UPDATE OF t SKIP LOCKED LIMIT 1`
|
||||
: await tx.$queryRaw`SELECT t.id FROM orchestration_tasks t JOIN prepare_workflow_outbox o ON o.task_id=t.id WHERE t.state IN ('READY','RUNNING') AND o.status='PENDING' AND (o.not_before IS NULL OR o.not_before <= now()) AND (o.lease_until IS NULL OR o.lease_until < now()) ORDER BY o.created_at FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
|
||||
if (!rows.length) return null;
|
||||
const t = await this.task(tx, rows[0].id);
|
||||
const o = await tx.prepareWorkflowOutbox.findUnique({
|
||||
where: { taskId: t.id },
|
||||
});
|
||||
const approval = await tx.orchestrationApprovalDecision.findFirst({
|
||||
where: { taskId: t.id, gate: 1, decision: 'APPROVED' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (!approval || approval.expiresAt <= new Date())
|
||||
throw new ForbiddenException('Gate1 expired');
|
||||
if (o.attempts >= 3) throw new ForbiddenException('Attempts exhausted');
|
||||
const costs = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
if ((costs._sum.amountCents ?? 0) + 20 > t.budgetLimitCents)
|
||||
throw new ForbiddenException('Hard task budget exceeded');
|
||||
if (o.runId)
|
||||
await tx.orchestrationRun.update({
|
||||
where: { id: o.runId },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
retryClass: 'TRANSIENT',
|
||||
finishedAt: new Date(),
|
||||
},
|
||||
});
|
||||
const token = randomUUID(),
|
||||
attempt = o.attempts + 1;
|
||||
const run = await tx.orchestrationRun.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
attempt,
|
||||
status: 'RUNNING',
|
||||
environment: 'staging',
|
||||
commitSha: t.metadata.commitSha,
|
||||
idempotencyKey: `prepare-run:${o.id}:${attempt}`,
|
||||
startedAt: new Date(),
|
||||
},
|
||||
});
|
||||
const reservation = await tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
amountCents: 20,
|
||||
kind: 'RESERVE',
|
||||
actorId: a.id,
|
||||
idempotencyKey: `prepare-reserve:${run.id}`,
|
||||
},
|
||||
});
|
||||
const leaseUntil = new Date(Date.now() + 30000);
|
||||
await tx.prepareWorkflowOutbox.update({
|
||||
where: { id: o.id },
|
||||
data: {
|
||||
attempts: attempt,
|
||||
leaseOwner: a.id,
|
||||
leaseToken: token,
|
||||
leaseUntil,
|
||||
heartbeatAt: new Date(),
|
||||
runId: run.id,
|
||||
reservationId: reservation.id,
|
||||
},
|
||||
});
|
||||
await this.event(
|
||||
tx,
|
||||
t,
|
||||
'RUNNING',
|
||||
a,
|
||||
`prepare-claim:${run.id}`,
|
||||
'PREPARE_CLAIMED',
|
||||
token,
|
||||
);
|
||||
return {
|
||||
taskId: t.id,
|
||||
runId: run.id,
|
||||
attempt,
|
||||
leaseToken: token,
|
||||
leaseUntil,
|
||||
commitSha: run.commitSha,
|
||||
environment: 'staging',
|
||||
maxCostCents: 20,
|
||||
};
|
||||
});
|
||||
}
|
||||
private async lease(tx: any, a: WorkflowIdentity, dto: any) {
|
||||
const t = await this.task(tx, dto.taskId);
|
||||
const o = await tx.prepareWorkflowOutbox.findUnique({
|
||||
where: { taskId: t.id },
|
||||
});
|
||||
if (
|
||||
!o ||
|
||||
o.status !== 'PENDING' ||
|
||||
o.leaseOwner !== a.id ||
|
||||
o.leaseToken !== dto.leaseToken ||
|
||||
o.runId !== dto.runId ||
|
||||
!o.leaseUntil ||
|
||||
o.leaseUntil <= new Date() ||
|
||||
t.state !== 'RUNNING'
|
||||
)
|
||||
throw new ForbiddenException('Active owned lease required');
|
||||
return { t, o };
|
||||
}
|
||||
async heartbeat(a: WorkflowIdentity, dto: any) {
|
||||
this.worker(a);
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx);
|
||||
const { o } = await this.lease(tx, a, dto);
|
||||
return tx.prepareWorkflowOutbox.update({
|
||||
where: { id: o.id },
|
||||
data: {
|
||||
heartbeatAt: new Date(),
|
||||
leaseUntil: new Date(Date.now() + 30000),
|
||||
},
|
||||
select: { leaseUntil: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
async complete(a: WorkflowIdentity, dto: any) {
|
||||
this.worker(a);
|
||||
if (
|
||||
!/^[a-f0-9]{64}$/.test(dto.sha256 ?? '') ||
|
||||
!/^https:\/\//.test(dto.uri ?? '') ||
|
||||
!Number.isSafeInteger(dto.actualCents) ||
|
||||
dto.actualCents < 0 ||
|
||||
dto.actualCents > 20
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'QA hash, HTTPS URI and cost 0..20 required',
|
||||
);
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx);
|
||||
const { t, o } = await this.lease(tx, a, dto);
|
||||
await tx.orchestrationArtifact.create({
|
||||
data: { runId: o.runId, kind: 'QA', sha256: dto.sha256, uri: dto.uri },
|
||||
});
|
||||
await tx.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: o.runId,
|
||||
kind: 'QA',
|
||||
subjectHash: dto.sha256,
|
||||
signer: a.id,
|
||||
predicate: { passed: true, scope: 'STAGE_PREPARE' },
|
||||
},
|
||||
});
|
||||
await tx.orchestrationRun.update({
|
||||
where: { id: o.runId },
|
||||
data: { status: 'SUCCEEDED', finishedAt: new Date() },
|
||||
});
|
||||
await tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
kind: 'RECONCILE',
|
||||
amountCents: dto.actualCents - 20,
|
||||
actorId: a.id,
|
||||
idempotencyKey: `prepare-cost:${o.runId}`,
|
||||
metadata: {
|
||||
reservationId: o.reservationId,
|
||||
actualCents: dto.actualCents,
|
||||
},
|
||||
},
|
||||
});
|
||||
await tx.prepareWorkflowOutbox.update({
|
||||
where: { id: o.id },
|
||||
data: { status: 'DONE', leaseToken: null, leaseUntil: null },
|
||||
});
|
||||
return this.event(
|
||||
tx,
|
||||
t,
|
||||
'VERIFYING',
|
||||
a,
|
||||
`prepare-qa:${o.runId}`,
|
||||
'PREPARE_QA_SUCCEEDED',
|
||||
dto.sha256,
|
||||
);
|
||||
});
|
||||
}
|
||||
/** Detail-only eligibility hint. No lease credentials leave this service. Command rechecks atomically. */
|
||||
async editorialRecovery(t: any, a: WorkflowIdentity) {
|
||||
const { admittedEditorialTask } = require('../orchestration-worker/editorial-execution');
|
||||
if (!this.reviewer(a) || t.metadata?.createdBy === a.id || t.state !== 'RUNNING' || !admittedEditorialTask(t)) return undefined;
|
||||
const o = await (this.db as any).prepareWorkflowOutbox.findUnique({ where: { taskId: t.id } });
|
||||
if (!o || o.status !== 'PENDING' || o.leaseOwner !== 'pmo' || !o.leaseUntil || !Number.isFinite(new Date(o.leaseUntil).getTime()) || new Date(o.leaseUntil).getTime() > Date.now()) return undefined;
|
||||
const r = t.runs?.find((r: any) => r.id === o.runId);
|
||||
const ledger = t.budgetLedger ?? [];
|
||||
const reserve = ledger.find((b: any) => b.id === o.reservationId);
|
||||
if (!r || r.taskId !== t.id || r.status !== 'RUNNING' || r.environment !== 'staging' || r.commitSha !== t.metadata.commitSha || !Array.isArray(r.artifacts) || r.artifacts.length ||
|
||||
!reserve || reserve.actorId !== 'pmo' || reserve.kind !== 'RESERVE' || reserve.amountCents !== 20 || reserve.idempotencyKey !== `prepare-reserve:${r.id}` ||
|
||||
ledger.some((b: any) => b.kind === 'RECONCILE') || ledger.reduce((n: number, b: any) => n + b.amountCents, 0) !== 20) return undefined;
|
||||
return { runId: r.id };
|
||||
}
|
||||
/** Stop only; never turns unknown spend into free retry capacity. */
|
||||
async editorialFailure(id: string, dto: any, a: WorkflowIdentity) {
|
||||
const held = dto.leaseToken !== undefined;
|
||||
if (held) {
|
||||
this.worker(a);
|
||||
if (a.id !== 'pmo') throw new ForbiddenException('Canonical PMO required');
|
||||
} else if (!this.reviewer(a)) throw new ForbiddenException('Independent recovery reviewer required');
|
||||
if (typeof dto.reason !== 'string' || !dto.reason.trim() || dto.reason.length > 500)
|
||||
throw new BadRequestException('Bounded failure reason required');
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx);
|
||||
const t = await this.task(tx, id);
|
||||
const { admittedEditorialTask } = require('../orchestration-worker/editorial-execution');
|
||||
if (!admittedEditorialTask(t)) throw new ForbiddenException('Exact editorial proposal required');
|
||||
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 ForbiddenException('Editorial provenance required');
|
||||
if (!held && t.metadata.createdBy === a.id) throw new ForbiddenException('Independent recovery reviewer required');
|
||||
const fingerprint = JSON.stringify({ id, dto, a });
|
||||
if (await this.replay(tx, dto.idempotencyKey, fingerprint)) return t;
|
||||
this.version(t, dto);
|
||||
const o = await tx.prepareWorkflowOutbox.findUnique({ where: { taskId: id } });
|
||||
const r = await tx.orchestrationRun.findUnique({ where: { id: dto.runId } });
|
||||
if (t.state !== 'RUNNING' || !o || o.status !== 'PENDING' || o.runId !== dto.runId ||
|
||||
o.leaseOwner !== 'pmo' || !o.leaseUntil || !r || r.taskId !== id || r.status !== 'RUNNING' ||
|
||||
r.environment !== 'staging' || r.commitSha !== t.metadata.commitSha ||
|
||||
(held ? (o.leaseOwner !== a.id || o.leaseToken !== dto.leaseToken || o.leaseUntil <= new Date()) : o.leaseUntil > new Date()))
|
||||
throw new ForbiddenException('Matching held lease or expired run required');
|
||||
const reserve = await tx.orchestrationBudgetLedger.findUnique({ where: { id: o.reservationId } });
|
||||
const ledger = await tx.orchestrationBudgetLedger.aggregate({ where: { taskId: id }, _sum: { amountCents: true } });
|
||||
if (!reserve || reserve.taskId !== id || reserve.actorId !== 'pmo' || reserve.kind !== 'RESERVE' || reserve.amountCents !== 20 ||
|
||||
reserve.idempotencyKey !== `prepare-reserve:${r.id}` || ledger._sum.amountCents !== 20 ||
|
||||
await tx.orchestrationBudgetLedger.findFirst({ where: { taskId: id, kind: 'RECONCILE' } }) ||
|
||||
await tx.orchestrationArtifact.count({ where: { runId: r.id } }))
|
||||
throw new ForbiddenException('Unreconciled artifact-free editorial reservation required');
|
||||
await tx.orchestrationRun.update({ where: { id: r.id }, data: { status: 'FAILED', retryClass: 'DEPENDENCY', 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 }, data: { state: 'FAILED', version: { increment: 1 } } });
|
||||
await tx.orchestrationEvent.create({ data: {
|
||||
taskId: id, sequence: updated.version, actorId: a.id, eventType: 'EDITORIAL_RUN_STOPPED',
|
||||
fromState: 'RUNNING', toState: 'FAILED', idempotencyKey: dto.idempotencyKey,
|
||||
payload: { fingerprint, runId: r.id, reason: dto.reason, recoveryMode: held ? 'HELD_LEASE' : 'EXPIRED_RUN', costStatus: 'unknown-upper-bound-reserved', retainedReservationCents: 20 },
|
||||
} });
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
async stageEvidence(a: WorkflowIdentity, dto: any) {
|
||||
this.identity(a, ['STAGE_CI']);
|
||||
if (!this.config.stageCiIds.includes(a.id))
|
||||
throw new ForbiddenException('Stage CI identity not provisioned');
|
||||
if (
|
||||
!/^[a-f0-9]{64}$/.test(dto.evidenceSha256 ?? '') ||
|
||||
!/^https:\/\//.test(dto.uri ?? '')
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Stage evidence hash and HTTPS URI required',
|
||||
);
|
||||
return this.db.$transaction(async (tx: any) => {
|
||||
await this.allowed(tx);
|
||||
const t = await this.task(tx, dto.taskId);
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
t.state !== 'VERIFYING' ||
|
||||
!run ||
|
||||
run.taskId !== t.id ||
|
||||
run.environment !== 'staging' ||
|
||||
run.status !== 'SUCCEEDED' ||
|
||||
run.commitSha !== dto.commitSha ||
|
||||
t.metadata.commitSha !== dto.commitSha
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Immutable successful Stage run binding required',
|
||||
);
|
||||
const qa = await tx.orchestrationAttestation.findFirst({
|
||||
where: { runId: run.id, kind: 'QA', subjectHash: dto.sha256 },
|
||||
});
|
||||
if (!qa || qa.signer === a.id)
|
||||
throw new ForbiddenException('Independent QA evidence required');
|
||||
await tx.orchestrationArtifact.create({
|
||||
data: {
|
||||
runId: run.id,
|
||||
kind: 'STAGE_EVIDENCE',
|
||||
sha256: dto.evidenceSha256,
|
||||
uri: dto.uri,
|
||||
},
|
||||
});
|
||||
await tx.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: run.id,
|
||||
kind: 'STAGE',
|
||||
subjectHash: dto.sha256,
|
||||
signer: a.id,
|
||||
predicate: {
|
||||
evidenceSha256: dto.evidenceSha256,
|
||||
commitSha: dto.commitSha,
|
||||
environment: 'staging',
|
||||
},
|
||||
},
|
||||
});
|
||||
return this.event(
|
||||
tx,
|
||||
t,
|
||||
'GATE2_PENDING',
|
||||
a,
|
||||
`prepare-stage:${run.id}`,
|
||||
'STAGE_EVIDENCE_RECORDED',
|
||||
dto.evidenceSha256,
|
||||
);
|
||||
});
|
||||
}
|
||||
project(t: any, a: WorkflowIdentity) {
|
||||
const safe =
|
||||
t.operationMode === 'PREPARE' &&
|
||||
(t.metadata?.workflowScope ?? t.metadata?.scope) === 'STAGE_PREPARE';
|
||||
const owner =
|
||||
a?.id && (t.metadata?.createdBy === a.id || a.role === 'SUPER_ADMIN');
|
||||
const latest = [...(t.decisions ?? [])].filter((d: any) => d.gate === 1)
|
||||
.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];
|
||||
const expired = safe && t.state === 'READY' && latest?.decision === 'APPROVED' &&
|
||||
latest.actorId !== t.metadata.createdBy && new Date(latest.expiresAt).getTime() <= Date.now();
|
||||
const blocked = safe && t.state === 'READY' && (!latest || latest.decision !== 'APPROVED' ||
|
||||
latest.actorId === t.metadata.createdBy || new Date(latest.expiresAt).getTime() <= Date.now());
|
||||
const actions: string[] = [];
|
||||
if (expired && this.reviewer(a) && t.metadata.createdBy !== a.id)
|
||||
actions.push('APPROVE_GATE1');
|
||||
if (safe && owner && t.state === 'DRAFT') actions.push('SUBMIT_GATE1');
|
||||
if (safe && owner && t.state === 'GATE1_APPROVED')
|
||||
actions.push('QUEUE_PREPARE');
|
||||
if (
|
||||
safe &&
|
||||
this.reviewer(a) &&
|
||||
t.metadata?.createdBy !== a.id &&
|
||||
['GATE1_PENDING', 'GATE1_HELD'].includes(t.state)
|
||||
) {
|
||||
actions.push('APPROVE_GATE1', 'REJECT_GATE1');
|
||||
if (t.state === 'GATE1_PENDING') actions.push('HOLD_GATE1');
|
||||
}
|
||||
return {
|
||||
...t,
|
||||
displayState: blocked ? (expired ? 'GATE1_RENEWAL_REQUIRED' : 'BLOCKED') : t.state,
|
||||
metadata: safe
|
||||
? {
|
||||
scope: t.metadata.scope,
|
||||
...(t.metadata.workflowScope === 'STAGE_PREPARE'
|
||||
? { acceptanceCriteria: t.metadata.acceptanceCriteria }
|
||||
: {}),
|
||||
environment: 'staging',
|
||||
commitSha: t.metadata.commitSha,
|
||||
}
|
||||
: {},
|
||||
availableActions: actions,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
(process.env.WORKFLOW_DB==='1'?describe:describe.skip)('renewal PostgreSQL serialization',()=>{
|
||||
const db=new PrismaClient();
|
||||
const service=new PrepareWorkflowService(db,{workerIds:['pmo'],stageCiIds:[]});
|
||||
const owner={id:'owner',role:'SUPER_ADMIN'};
|
||||
afterAll(()=>db.$disconnect());
|
||||
it('denies expired claim, serializes renewal/replay, retains original decision and enables one claim',async()=>{
|
||||
const t=await db.orchestrationTask.create({data:{key:crypto.randomUUID(),title:'Disposable renewal',department:'CONTENT',operationMode:'PREPARE',state:'READY',version:4,budgetLimitCents:20,metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo',commitSha:'a'.repeat(40)}}});
|
||||
const old=await db.orchestrationApprovalDecision.create({data:{taskId:t.id,gate:1,decision:'APPROVED',actorId:'owner',expiresAt:new Date('2026-10-24T06:37:00Z'),idempotencyKey:crypto.randomUUID()}});
|
||||
await db.prepareWorkflowOutbox.create({data:{taskId:t.id}});
|
||||
const worker={id:'pmo',role:'WORKFLOW_WORKER'};
|
||||
await expect(service.claim(worker,t.id)).rejects.toMatchObject({status:403});
|
||||
const dto={expectedVersion:4,decision:'APPROVED',idempotencyKey:crypto.randomUUID()};
|
||||
const renewed=await Promise.all([service.decide(t.id,1,dto,owner),service.decide(t.id,1,dto,owner)]);
|
||||
expect(renewed.map(t=>t.version)).toEqual([5,5]);
|
||||
await expect(service.decide(t.id,1,{...dto,idempotencyKey:crypto.randomUUID()},owner)).rejects.toMatchObject({status:409});
|
||||
expect(await db.orchestrationApprovalDecision.count({where:{taskId:t.id}})).toBe(2);
|
||||
expect((await db.orchestrationApprovalDecision.findUniqueOrThrow({where:{id:old.id}})).expiresAt).toEqual(old.expiresAt);
|
||||
expect(await db.prepareWorkflowOutbox.count({where:{taskId:t.id}})).toBe(1);
|
||||
const claims=await Promise.all([service.claim(worker,t.id),service.claim(worker,t.id)]);
|
||||
expect(claims.filter(Boolean)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import { workflowConfig } from './workflow-config';
|
||||
describe('startup owner reviewer configuration',()=>{
|
||||
it('defaults denied, accepts explicit UUID only in staging',()=>{
|
||||
expect(workflowConfig({}).ownerReviewerIds).toEqual([]);
|
||||
expect(workflowConfig({NODE_ENV:'production',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:'12345678-1234-1234-1234-123456789012'})).toMatchObject({ownerReviewerIds:[]});
|
||||
expect(workflowConfig({CANINA_ENV:'staging',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:'12345678-1234-1234-1234-123456789012'}).ownerReviewerIds).toEqual(['12345678-1234-1234-1234-123456789012']);
|
||||
});
|
||||
it.each(['*','admin','12345678-1234-1234-1234-123456789012,'])('fails startup on malformed explicit grant %s',ids=>{
|
||||
expect(()=>workflowConfig({CANINA_ENV:'staging',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:ids})).toThrow('Invalid owner reviewer UUID allowlist');
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { WorkflowConfig } from './prepare-workflow.service';
|
||||
/** Startup-only configuration; HTTP payloads can never supply reviewer grants. */
|
||||
export function workflowConfig(env: NodeJS.ProcessEnv): WorkflowConfig {
|
||||
const raw = env.CANINA_ENV === 'staging' ? env.CANINA_WORKFLOW_OWNER_REVIEWER_IDS ?? '' : '';
|
||||
const ids = raw ? raw.split(',') : [];
|
||||
if (ids.length > 20 || ids.some(id => !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(id)))
|
||||
throw new Error('Invalid owner reviewer UUID allowlist');
|
||||
return {workerIds:[],stageCiIds:[],ownerReviewerIds:[...new Set(ids)]};
|
||||
}
|
||||
@@ -1,506 +0,0 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrepareWorkflowService } from './prepare-workflow.service';
|
||||
import { OperationMode, WorkflowState } from './orchestration.domain';
|
||||
|
||||
const enabled = process.env.WORKFLOW_DB === '1';
|
||||
(enabled ? describe : describe.skip)('isolated prepare workflow', () => {
|
||||
const db = new PrismaClient();
|
||||
const admin = { id: 'proposer', role: 'Admin' };
|
||||
const reviewer = { id: 'reviewer', role: 'SUPER_ADMIN' };
|
||||
const worker = { id: 'worker-1', role: 'WORKFLOW_WORKER' };
|
||||
const ci = { id: 'isolated-ci', role: 'STAGE_CI' };
|
||||
const service = new PrepareWorkflowService(db as never, {
|
||||
workerIds: ['worker-1', 'worker-2'],
|
||||
stageCiIds: ['isolated-ci'],
|
||||
});
|
||||
let seq = 0;
|
||||
const dto = () => ({
|
||||
key: `wf-${Date.now()}-${seq++}`,
|
||||
title: 'Bounded isolated QA tracer',
|
||||
department: 'ENGINEERING',
|
||||
operationMode: OperationMode.PREPARE,
|
||||
budgetLimitCents: 20,
|
||||
metadata: {
|
||||
commitSha: 'a'.repeat(40),
|
||||
token: 'must-not-persist',
|
||||
scope: 'Staging schema audit only',
|
||||
acceptanceCriteria: ['Report all schema failures'],
|
||||
actorId: 'spoof',
|
||||
},
|
||||
});
|
||||
async function ready() {
|
||||
let t = await service.create(dto(), admin);
|
||||
t = await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.GATE1_PENDING,
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `submit-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
);
|
||||
t = await service.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
return t;
|
||||
}
|
||||
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,idempotencyKey:events[0].idempotencyKey,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);
|
||||
expect(t.metadata).toMatchObject({
|
||||
workflowScope: 'STAGE_PREPARE',
|
||||
scope: input.metadata.scope,
|
||||
acceptanceCriteria: input.metadata.acceptanceCriteria,
|
||||
commitSha: input.metadata.commitSha,
|
||||
});
|
||||
expect(t.metadata).not.toHaveProperty('token');
|
||||
expect(t.metadata).not.toHaveProperty('actorId');
|
||||
const submitted = await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'GATE1_PENDING',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `immutable-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
);
|
||||
expect(submitted.metadata).toEqual(t.metadata);
|
||||
expect(service.project(submitted, reviewer).metadata).toEqual({
|
||||
scope: input.metadata.scope,
|
||||
acceptanceCriteria: input.metadata.acceptanceCriteria,
|
||||
environment: 'staging',
|
||||
commitSha: input.metadata.commitSha,
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
null,
|
||||
[],
|
||||
{},
|
||||
{ commitSha: 'a'.repeat(40), scope: '', acceptanceCriteria: ['ok'] },
|
||||
{
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: ' '.repeat(10),
|
||||
acceptanceCriteria: ['ok'],
|
||||
},
|
||||
{
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: 'x'.repeat(2001),
|
||||
acceptanceCriteria: ['ok'],
|
||||
},
|
||||
{ commitSha: 'a'.repeat(40), scope: 'ok', acceptanceCriteria: [] },
|
||||
{
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: 'ok',
|
||||
acceptanceCriteria: Array(21).fill('ok'),
|
||||
},
|
||||
{
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: 'ok',
|
||||
acceptanceCriteria: ['x'.repeat(501)],
|
||||
},
|
||||
{ commitSha: 'a'.repeat(40), scope: 'ok', acceptanceCriteria: [' '] },
|
||||
{ commitSha: 'a'.repeat(40), scope: 'ok', acceptanceCriteria: [123] },
|
||||
{ commitSha: ['a'.repeat(40)], scope: 'ok', acceptanceCriteria: ['ok'] },
|
||||
{ scope: 'ok', acceptanceCriteria: ['ok'] },
|
||||
])(
|
||||
'rejects unsafe or unbounded metadata %# without persisting',
|
||||
async (metadata) => {
|
||||
const input = { ...dto(), metadata };
|
||||
await expect(service.create(input, admin)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
expect(
|
||||
await db.orchestrationTask.count({ where: { key: input.key } }),
|
||||
).toBe(0);
|
||||
},
|
||||
);
|
||||
it('accepts exact metadata bounds', async () => {
|
||||
const metadata = {
|
||||
commitSha: 'a'.repeat(40),
|
||||
scope: 'x'.repeat(2000),
|
||||
acceptanceCriteria: Array(20).fill('x'.repeat(500)),
|
||||
};
|
||||
expect(
|
||||
(await service.create({ ...dto(), metadata }, admin)).metadata,
|
||||
).toMatchObject(metadata);
|
||||
});
|
||||
it('normalizes racing duplicate proposal keys to conflict without duplicate events', async () => {
|
||||
const input = dto();
|
||||
const results = await Promise.allSettled([
|
||||
service.create(input, admin),
|
||||
service.create({ ...input, title: 'Different intent' }, reviewer),
|
||||
]);
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
const rejected = results.find(
|
||||
(r) => r.status === 'rejected',
|
||||
) as PromiseRejectedResult;
|
||||
expect(rejected.reason).toMatchObject({ status: 409 });
|
||||
const persisted = await db.orchestrationTask.findUniqueOrThrow({
|
||||
where: { key: input.key },
|
||||
});
|
||||
expect(
|
||||
await db.orchestrationEvent.count({ where: { taskId: persisted.id } }),
|
||||
).toBe(1);
|
||||
await expect(service.create(input, admin)).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
});
|
||||
it('enforces create and read contracts over HTTP with real PostgreSQL persistence', async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
{ provide: PrepareWorkflowService, useValue: service },
|
||||
{
|
||||
provide: OrchestrationService,
|
||||
useValue: {
|
||||
findAll: () => db.orchestrationTask.findMany(),
|
||||
findOne: (id: string) =>
|
||||
db.orchestrationTask.findUniqueOrThrow({ where: { id } }),
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({
|
||||
canActivate(context: any) {
|
||||
context.switchToHttp().getRequest().user = {
|
||||
sub: admin.id,
|
||||
role: admin.role,
|
||||
};
|
||||
return true;
|
||||
},
|
||||
})
|
||||
.overrideGuard(RolesGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
const app = module.createNestApplication();
|
||||
await app.init();
|
||||
try {
|
||||
const input = dto();
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.send(input)
|
||||
.expect(201);
|
||||
expect(response.body.metadata).toEqual({
|
||||
scope: input.metadata.scope,
|
||||
acceptanceCriteria: input.metadata.acceptanceCriteria,
|
||||
commitSha: input.metadata.commitSha,
|
||||
environment: 'staging',
|
||||
});
|
||||
expect(response.body.availableActions).toEqual(['SUBMIT_GATE1']);
|
||||
const detail = await request(app.getHttpServer())
|
||||
.get(`/admin/orchestration/tasks/${response.body.id}`)
|
||||
.expect(200);
|
||||
expect(detail.body.metadata).toEqual(response.body.metadata);
|
||||
const list = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/tasks')
|
||||
.expect(200);
|
||||
expect(
|
||||
list.body.find((row: any) => row.id === response.body.id).metadata,
|
||||
).toEqual(response.body.metadata);
|
||||
expect(JSON.stringify(response.body)).not.toMatch(
|
||||
/createdBy|must-not-persist|actorId|workflowScope/,
|
||||
);
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.send(input)
|
||||
.expect(409);
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.send({
|
||||
...input,
|
||||
key: `${input.key}-invalid`,
|
||||
metadata: { scope: 'only stage', acceptanceCriteria: ['QA passes'] },
|
||||
})
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.post('/admin/orchestration/tasks')
|
||||
.send({
|
||||
...input,
|
||||
key: `${input.key}-invalid`,
|
||||
metadata: { ...input.metadata, acceptanceCriteria: [' '] },
|
||||
})
|
||||
.expect(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
it('fences heartbeat and completes QA plus independent Stage evidence only to Gate2 pending', async () => {
|
||||
const t = await ready();
|
||||
const c = await service.claim(worker, t.id);
|
||||
await expect(
|
||||
service.heartbeat({ ...worker, id: 'worker-2' }, c),
|
||||
).rejects.toThrow(/lease/i);
|
||||
await service.heartbeat(worker, c);
|
||||
const qa = {
|
||||
...c,
|
||||
sha256: 'b'.repeat(64),
|
||||
uri: 'https://ci.example/qa',
|
||||
actualCents: 8,
|
||||
};
|
||||
await service.complete(worker, qa);
|
||||
await expect(
|
||||
service.stageEvidence(
|
||||
{ id: 'proposer', role: 'Admin' },
|
||||
{
|
||||
taskId: t.id,
|
||||
runId: c.runId,
|
||||
sha256: qa.sha256,
|
||||
commitSha: c.commitSha,
|
||||
evidenceSha256: 'c'.repeat(64),
|
||||
uri: 'https://ci.example/stage',
|
||||
},
|
||||
),
|
||||
).rejects.toThrow(/identity/i);
|
||||
await service.stageEvidence(ci, {
|
||||
taskId: t.id,
|
||||
runId: c.runId,
|
||||
sha256: qa.sha256,
|
||||
commitSha: c.commitSha,
|
||||
evidenceSha256: 'c'.repeat(64),
|
||||
uri: 'https://ci.example/stage',
|
||||
});
|
||||
expect(
|
||||
await db.orchestrationTask.findUnique({ where: { id: t.id } }),
|
||||
).toMatchObject({ state: 'GATE2_PENDING' });
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
}),
|
||||
).toMatchObject({ _sum: { amountCents: 8 } });
|
||||
await expect(service.complete(worker, qa)).rejects.toThrow(/lease|active/i);
|
||||
});
|
||||
it('bounds expired-lease retries and rejects stale completion without releasing unknown costs', async () => {
|
||||
const t = await service.create({ ...dto(), budgetLimitCents: 60 }, admin);
|
||||
let current = await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'GATE1_PENDING',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `s-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
);
|
||||
current = await service.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: current.version,
|
||||
idempotencyKey: `a-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
expect(current.state).toBe('READY');
|
||||
const first = await service.claim(worker, t.id);
|
||||
for (let i = 0; i < 2; i++) {
|
||||
await db.prepareWorkflowOutbox.update({
|
||||
where: { taskId: t.id },
|
||||
data: { leaseUntil: new Date(0) },
|
||||
});
|
||||
const next = await service.claim(worker, t.id);
|
||||
expect(next.attempt).toBe(i + 2);
|
||||
}
|
||||
await expect(
|
||||
service.complete(worker, {
|
||||
...first,
|
||||
sha256: 'b'.repeat(64),
|
||||
uri: 'https://ci.example/qa',
|
||||
actualCents: 0,
|
||||
}),
|
||||
).rejects.toThrow(/lease/i);
|
||||
await db.prepareWorkflowOutbox.update({
|
||||
where: { taskId: t.id },
|
||||
data: { leaseUntil: new Date(0) },
|
||||
});
|
||||
await expect(service.claim(worker, t.id)).rejects.toThrow(/exhausted/i);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
3,
|
||||
);
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
}),
|
||||
).toMatchObject({ _sum: { amountCents: 60 } });
|
||||
});
|
||||
it('rejects self approval, non-PREPARE and unprovisioned workers', async () => {
|
||||
await expect(
|
||||
service.create(
|
||||
{ ...dto(), operationMode: OperationMode.MUTATE_PRODUCTION },
|
||||
admin,
|
||||
),
|
||||
).rejects.toThrow(/PREPARE/);
|
||||
let t = await service.create(dto(), reviewer);
|
||||
t = await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'GATE1_PENDING',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `s-${t.id}`,
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
await expect(
|
||||
service.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `a-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
reviewer,
|
||||
),
|
||||
).rejects.toThrow(/independent/i);
|
||||
await expect(
|
||||
service.claim({ id: 'spoof', role: 'WORKFLOW_WORKER' }),
|
||||
).rejects.toThrow(/provisioned/i);
|
||||
await expect(service.decide(t.id, 2, {}, reviewer)).rejects.toThrow(
|
||||
/disabled/i,
|
||||
);
|
||||
});
|
||||
it('serializes duplicate queue submission and denies claims beyond remaining task budget', async () => {
|
||||
const t = await ready();
|
||||
await db.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
amountCents: 1,
|
||||
kind: 'SPEND',
|
||||
actorId: 'fixture',
|
||||
idempotencyKey: `spend-${t.id}`,
|
||||
},
|
||||
});
|
||||
await expect(service.claim(worker, t.id)).rejects.toThrow(/budget/i);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
0,
|
||||
);
|
||||
expect(
|
||||
await db.prepareWorkflowOutbox.count({ where: { taskId: t.id } }),
|
||||
).toBe(1);
|
||||
});
|
||||
it('replays submission safely and serializes racing queue requests', async () => {
|
||||
let t = await service.create(dto(), admin);
|
||||
const submit = {
|
||||
toState: 'GATE1_PENDING',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `replay-${t.id}`,
|
||||
};
|
||||
t = await service.transition(t.id, submit, admin);
|
||||
expect((await service.transition(t.id, submit, admin)).version).toBe(
|
||||
t.version,
|
||||
);
|
||||
await expect(
|
||||
service.transition(t.id, { ...submit, toState: 'READY' }, admin),
|
||||
).rejects.toThrow(/mismatch/i);
|
||||
t = await service.decide(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `r-approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
expect(t.state).toBe('READY');
|
||||
expect(
|
||||
await db.prepareWorkflowOutbox.count({ where: { taskId: t.id } }),
|
||||
).toBe(1);
|
||||
});
|
||||
it('kill switch freezes claims without creating run or reservation', async () => {
|
||||
const t = await ready();
|
||||
await db.orchestrationKillSwitch.create({
|
||||
data: {
|
||||
scope: 'GLOBAL',
|
||||
level: 'FREEZE_NEW_WORK',
|
||||
reason: 'isolated test',
|
||||
actorId: 'fixture',
|
||||
},
|
||||
});
|
||||
try {
|
||||
await expect(service.claim(worker, t.id)).rejects.toThrow(/kill switch/i);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.delete({ where: { scope: 'GLOBAL' } });
|
||||
}
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
0,
|
||||
);
|
||||
});
|
||||
it('persists an atomic outbox and exactly one worker wins concurrent claims', async () => {
|
||||
const t = await ready();
|
||||
const claims = await Promise.all([
|
||||
service.claim(worker, t.id),
|
||||
service.claim({ id: 'worker-2', role: 'WORKFLOW_WORKER' }, t.id),
|
||||
]);
|
||||
expect(claims.filter(Boolean)).toHaveLength(1);
|
||||
const claim = claims.find(Boolean)!;
|
||||
expect(claim.taskId).toBe(t.id);
|
||||
expect(claim.attempt).toBe(1);
|
||||
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
}),
|
||||
).toMatchObject({ _sum: { amountCents: 20 } });
|
||||
expect(
|
||||
await service.project(
|
||||
await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }),
|
||||
admin,
|
||||
),
|
||||
).toMatchObject({
|
||||
metadata: {
|
||||
scope: 'Staging schema audit only',
|
||||
acceptanceCriteria: ['Report all schema failures'],
|
||||
environment: 'staging',
|
||||
commitSha: 'a'.repeat(40),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
# Queued Gate1 validity correction
|
||||
|
||||
## Read-only Stage evidence (2026-10-24)
|
||||
|
||||
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
|
||||
|
||||
## Behavior
|
||||
|
||||
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
|
||||
|
||||
## Owner steps after parent CI integration
|
||||
|
||||
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
|
||||
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
|
||||
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
|
||||
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
|
||||
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
|
||||
|
||||
## Verification
|
||||
|
||||
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
|
||||
@@ -1,53 +0,0 @@
|
||||
# Durable Stage cleanup verification
|
||||
|
||||
This change replaces the SHA-pinned transient timer with a root-owned intent journal
|
||||
and a fixed host systemd retry worker. No host service is installed or enabled by
|
||||
the CI credential command. The tracked `deploy.yml` → `ci-host-deploy.sh` →
|
||||
`deploy.sh` path invokes `install-stage-principal-cleanup.py` from the verified
|
||||
immutable release before `stage_rollout`. It atomically installs the root-owned
|
||||
worker (0755) and supplied systemd units (0644), reloads systemd, enables/starts
|
||||
the timer and verifies enabled/active state. Failure aborts rollout. No manual
|
||||
sudo provisioning is required or permitted during review. The open wrapper refuses to operate
|
||||
without an enabled and active timer. Never overwrite or delete the 0700 root-owned
|
||||
`/opt/services/canina/stage-principal-cleanup` journal during deployments.
|
||||
|
||||
A journal entry is fsynced before provisioning and contains the exact session,
|
||||
random generation, creation SHA, bounded TTL and immutable cleanup deadline.
|
||||
Repeated opens fail rather than replace an intent or renew TTL. Close and the
|
||||
30-second boot/periodic retry worker retain intents on lock contention, unavailable
|
||||
containers/DB, and relational deletion failures. Cleanup resolves the current Stage
|
||||
container ID once, verifies its cleanup capability, and authenticates against its
|
||||
current artifact SHA while retaining original session/generation ownership. Older
|
||||
artifacts without generation cleanup support fail closed; never roll back to one
|
||||
with a pending principal. Persisted expiry remains independently enforced at login,
|
||||
refresh and every scoped JWT request.
|
||||
|
||||
Revocation commits before private-handle removal; relational deletion is subsequent.
|
||||
A transaction acquires a generation/session-fenced row lock before touching related
|
||||
records. Failed deletion retains a revoked row and a pending retry intent, but no
|
||||
credential handle. Wrong ownership/generation never invokes the handle callback.
|
||||
The CLI requires the generation supplied by the private journal; no broader admin
|
||||
or production authority was introduced.
|
||||
|
||||
Verification performed in a new isolated worktree and disposable Docker network:
|
||||
- Cleanup fence tests: RED (replacement generation was revoked; callback missing),
|
||||
then GREEN (2 tests).
|
||||
- Python simulated worker tests: restart/redeploy, failed-delete retry, lock
|
||||
contention, immutable container ID/current artifact and old-CLI refusal (4 tests).
|
||||
- Persisted account lifecycle plus delete/recreate access AND refresh regression.
|
||||
- Actual CLI via ts-node with real disposable Postgres/Redis and HTTP adminLogin
|
||||
handler, injected PostgreSQL delete trigger failure: confirmed revocation,
|
||||
private handle removal, then successful repeated cleanup after trigger removal.
|
||||
- TypeScript `tsc --noEmit`: passed.
|
||||
- Full migration chain attempt on fresh disposable database: baseline failure in
|
||||
20261020000000_add_blog_freshness_authorship (`blogs` missing). Not concealed.
|
||||
Independent migration test constructed the pre-Stage schema excluding all three
|
||||
new fields, then applied the EXACT committed 20261024090000 migration with psql
|
||||
ON_ERROR_STOP before exercising persisted lifecycle. Not db-push-only testing.
|
||||
|
||||
No live account, Stage/Production DB mutation, deployment, push, host service change,
|
||||
or retry of the previous pending-approval operation was performed.
|
||||
|
||||
Invocation after normal reviewed deployment and host prerequisite provisioning:
|
||||
`sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/<promoted-sha>/scripts/stage-test-principal-host.sh <promoted-sha> <unique-session> 600 open`
|
||||
Use the same command with `close` immediately after the authorized test.
|
||||
@@ -1,145 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,44 +0,0 @@
|
||||
# Temporary Stage editorial reviewer (disabled by default)
|
||||
|
||||
Authority: repository write/CI-dispatch permission plus the existing authenticated,
|
||||
pinned Stage deployment SSH boundary. This is a narrowly scoped seed operation,
|
||||
not an API-key actor, owner JWT, or a public bootstrap endpoint. The destructive
|
||||
legacy seed is not used. `AdminService` shares its normal hashing/persistence and
|
||||
relational cleanup implementation with the internal command; normal user mutation
|
||||
role checks remain unchanged. The canonical default administrator is untouched.
|
||||
|
||||
## Activation after independent review
|
||||
|
||||
1. Promote this commit through the normal Git/CI Stage deployment. Do not run the
|
||||
seed command against an old image: the embedded immutable SHA must match.
|
||||
Apply the additive migration through the existing migration deployment step.
|
||||
2. Dispatch **Owner authorized Stage test principal** on develop with `approval`
|
||||
exactly `owner-authorized-stage-editorial`, unique `session` such as
|
||||
`editorial-20261024-a`, `ttl` explicitly 600 (maximum 3600), and `action=open`.
|
||||
The workflow uses existing DEPLOY_KEY / pinned DEPLOY_KNOWN_HOSTS only.
|
||||
3. CI reports only `/app/private-stage-test/<session>.json` inside
|
||||
`canino_backend_stage`. This mode-0600 file in a mode-0700 directory contains
|
||||
the process-generated password and real persisted-account login tokens.
|
||||
Consume it only from an approved in-container CI HTTP process; never print,
|
||||
download, publish as an artifact, or type it into a browser. No owner secret is
|
||||
needed. Audit records contain events, session and SHA, never credentials.
|
||||
4. Use this independent reviewer for Gate1 only; the proposer/PMO must be a
|
||||
distinct actor. Existing self-review checks are not changed. This session does
|
||||
NOT authorize Gate2, publication, release, general admin APIs, worker identity
|
||||
replacement, or budget increases. Approve a separate explicit bounded test
|
||||
budget before running inference; unknown prior reservations remain retained.
|
||||
5. Dispatch the same workflow/session/ttl with `action=close` immediately after
|
||||
tests. This revokes persisted authentication BEFORE relational deletion and
|
||||
removes the private credential file. Close is idempotent when absent.
|
||||
|
||||
A durable root-owned host cleanup journal and boot/periodic systemd retry worker must be provisioned before opening a session. Cleanup follows the current Stage artifact but retains the original exact session and generation fence; persisted expiry cannot be extended. See [cleanup verification and promotion prerequisites](stage-principal-cleanup-verification.md). No live host services are changed by review tests.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit guards and existing independent self-review/role tests run with Jest.
|
||||
`stage-test-principal.integration.spec.ts` is opt-in via
|
||||
`STAGE_PRINCIPAL_DISPOSABLE_TEST=true` and requires a database URL ending in
|
||||
`/principal_disposable`; use a new isolated Postgres and Redis, then remove both.
|
||||
It verifies real account persistence/hash, signed access/refresh login tokens,
|
||||
collision refusal, nonrenewing retries, request scope, expiry, deletion/revocation.
|
||||
Never run it against Stage or Production.
|
||||
@@ -1,33 +0,0 @@
|
||||
# Admin v4 completion integration contract
|
||||
|
||||
Frontend-only slice based on 5507fbc. No deployment or runtime writes. The historical read-only integration document does not authorize enabling routes. Backend policy remains the authority; UI adds deny-only safety restrictions, never permissions.
|
||||
|
||||
## Workflow (existing routes retained)
|
||||
|
||||
- GET `/admin/orchestration/overview`: ResourceSnapshot with `items`, ISO `measuredAt`, `capabilities:{mutations:boolean,chat:boolean,runtime:boolean}`. Missing/failed capability read defaults false.
|
||||
- GET `/admin/orchestration/tasks`: Task[] (or `{success:true,data:Task[]}`).
|
||||
- GET `/admin/orchestration/tasks/:id`: Task. Required identity/version/state/mode/budget and server-computed `availableActions`; optional scope/acceptance metadata, runs/artifacts, immutable decisions, events and budgetLedger. Missing actions means no permission. Include structured redacted scope metadata for a useful Gate1 review; no secrets or arbitrary event payloads.
|
||||
- POST `/admin/orchestration/tasks`: existing CreateTaskInput `{key,title,department,operationMode,budgetLimitCents,metadata:{scope,acceptanceCriteria:string[]}}`. UI allows OBSERVE/PREPARE only, not Production. Key is unique business identity; after an ambiguous create, reconcile key before resubmission. Success locks the form to prevent accidental duplicate submission.
|
||||
- PUT `/admin/orchestration/tasks/:id/transition`: TransitionDto `{toState,expectedVersion,idempotencyKey,reason}`.
|
||||
- POST `/admin/orchestration/tasks/:id/gates/:gate/decide`: GateDecisionDto `{decision:'APPROVED'|'REJECTED',expectedVersion,idempotencyKey,expiresAt,notes}`; Gate2 approval additionally binds `{runId,artifactHash,commitSha,environment}` from a registered SUCCEEDED run, never editable commit/environment. Gate1 is bounded work, not release permission.
|
||||
- ServerAction `{id,label,toState? ,gate?:1|2,decision?:'APPROVED'|'REJECTED',disabledReason?}`. Exactly one of transition or gate decision. All role/policy/kill/version checks remain backend-side. Browser identity fields are never posted; actor must derive from verified JWT. HOLD/request changes only appear if advertised as supported transitions. EDIT_AND_APPROVE is unavailable without a separately reviewed DTO; no guessed mutation endpoint.
|
||||
- HTTP409 stale version/idempotency mismatch, 410 expired, 401/403 denied and other 4xx permanently lock that dialog; refresh and review afresh. Network/5xx ambiguous failures allow only identical payload/key. Inputs and navigation are locked after first attempt; authoritative refresh invalidates selection and pending detail reads. No optimistic status update.
|
||||
- Production task actions and release transitions remain disabled even if advertised. Gate2 evidence inspection is not deployment authorization. Server still enforces TTL; browser time is a usability check, not trusted authorization.
|
||||
|
||||
## Runtime read API (aligned by read-only inspection with runtime sibling)
|
||||
|
||||
Uses existing JWT Axios client, never upstream Hermes paths or tokens. No automatic runtime mutations. Tab is explicitly selected; failed auth/config/routes show unavailable.
|
||||
|
||||
- GET `/admin/orchestration/runtime/health` -> `{ok:boolean,version:string,commit:string,auth_required:true}`. Any false/missing authentication flag is rejected.
|
||||
- GET `/admin/orchestration/runtime/profiles` -> `{name:string,is_default:boolean,gateway_running:boolean}[]`, already filtered to principal grants.
|
||||
- GET `/admin/orchestration/runtime/status?profile=<authorized>` -> `{version,gateway_running,overall,active_agents,gateway_state:string|null}`.
|
||||
- GET `/admin/orchestration/runtime/sessions?profile=<authorized>&limit=20&offset=0` -> `{total:number,sessions:{id,profile,source,is_active}[]}`. UI paginates; profile mismatch is rejected.
|
||||
- GET `/admin/orchestration/runtime/usage?profile=<authorized>&days=30` -> `{period_days:number,totals:{total_input,total_output,total_sessions,total_estimated_cost}}`.
|
||||
|
||||
Runtime client explicitly projects known fields; unknown secret fields are discarded. Numeric zero survives. Cost is labelled **upstream estimate**, unspecified currency, not settled billing and never added to overlapping 9router totals. Client observation time is not server heartbeat/freshness. Profile gateway flags and active agent count are source observations, not invented readiness/department counts. Generic Resources for existing agents/model-policy/schedules/releases remain unchanged; unavailable contracts stay visibly unavailable. Runtime schedules/model-info may exist backend-side but are not guessed into generic Resources.
|
||||
|
||||
## Verification
|
||||
|
||||
Runner: disposable node:22-bookworm, --userns=host --network none; source and dependency donor read-only, private copies in /work. No donor/source build writes. Required final gates: `tsc --noEmit -p tsconfig.app.json`, `npm run build`, `npm test -- --maxWorkers=2`. Logs under `/opt/services/canina/validation/v4-panel-completion/` (outside discovery). Earlier RED proves 7 workflow failures and 2 selection/idempotency failures; runtime RED is missing new component. Existing test fixtures migrated from invented VERIFIED run status to backend SUCCEEDED status. No tests skipped or permissions inferred.
|
||||
|
||||
Not claimed: live backend browser acceptance, real authenticated runtime availability, Stage publication, CI evidence authority or Production execution. Parent owns integration and publication.
|
||||
@@ -3,14 +3,12 @@ import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
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()=>{
|
||||
it('submits explicit bounded scope and acceptance criteria, only after valid input',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
|
||||
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(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Bounded scope':'Staging schema audit only','Acceptance criteria (one per line)':'Report all failures','Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
|
||||
await screen.findByText('Task created by backend.');
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
|
||||
expect(done).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -1,15 +1,14 @@
|
||||
import {useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {orchestration,proposalError} from '../services/orchestration';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',commitSha:'',budget:'',scope:'',criteria:''});
|
||||
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">ایجاد کار محدود</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>
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',scope:'',criteria:'',budget:''});
|
||||
const [mode,setMode]=useState<CreateTaskInput['operationMode']>('PREPARE');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&Number.isSafeInteger(Number(fields.budget))&&Number(fields.budget)>=0;
|
||||
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)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message:'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE','MUTATE_PRODUCTION'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy}>Create bounded task</Button>
|
||||
</form></details>;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import {useRef,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {commandFailure,orchestration} from '../services/orchestration';
|
||||
import type {Task,EditorialFailureInput} from '../services/orchestration';
|
||||
export default function EditorialRecoveryDialog({task,onClose,onSuccess}:{task:Task;onClose:()=>void;onSuccess:()=>Promise<void>}) {
|
||||
const [reason,setReason]=useState('');const [confirmed,setConfirmed]=useState(false);
|
||||
const [busy,setBusy]=useState(false);const [attempted,setAttempted]=useState(false);const [blocked,setBlocked]=useState(false);const [error,setError]=useState('');
|
||||
const payload=useRef<EditorialFailureInput|null>(null);const inFlight=useRef(false);
|
||||
const execute=async()=>{
|
||||
if(inFlight.current||blocked||!confirmed||!reason.trim()||reason.length>500)return;
|
||||
if(!payload.current)payload.current={runId:task.editorialRecovery!.runId,expectedVersion:task.version,idempotencyKey:crypto.randomUUID(),reason};
|
||||
inFlight.current=true;setBusy(true);setAttempted(true);setError('');
|
||||
try {await orchestration.editorialFailure(task,payload.current);await onSuccess();}
|
||||
catch(e){const failure=commandFailure(e);setBlocked(!failure.retryable);setError(failure.message)}
|
||||
finally{inFlight.current=false;setBusy(false)}
|
||||
};
|
||||
return <div dir="rtl" lang="fa" 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>ثبت شکست اجرای متوقفشده</h2><p>وظیفه: {task.title} · نسخه: {task.version}</p><p>شناسه اجرا: {task.editorialRecovery!.runId}</p>
|
||||
<p>فقط اجرای منقضیشده به شکست ثبت میشود. رزرو ۲۰ سنت حفظ میشود؛ هزینه واقعی نامشخص است، نه هزینه صفر.</p>
|
||||
<p>این اقدام QA یا تأیید خودکار ایجاد نمیکند؛ انتشار، اجرای دوباره، افزایش بودجه یا آزادسازی رزرو انجام نمیشود. مجوز بازبین مستقل و اتصال اجرای منقضی را سرور دوباره بررسی میکند.</p>
|
||||
<label className="block">دلیل شکست<textarea aria-label="دلیل شکست" maxLength={500} value={reason} disabled={busy||attempted} onChange={e=>{setReason(e.target.value);setConfirmed(false)}} className="border p-2 w-full"/></label><p>{reason.length}/500</p>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} disabled={busy||attempted} onChange={e=>setConfirmed(e.target.checked)}/>ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید میکنم</label>
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
<div className="flex gap-3"><Button disabled={busy||blocked||!confirmed||!reason.trim()||reason.length>500} onClick={()=>void execute()}>ثبت شکست</Button><Button disabled={busy} variant="outline" onClick={onClose}>بازخوانی و بستن</Button></div>
|
||||
</div></div>;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import type {ServerAction} from '../services/orchestration';
|
||||
const labels:Record<string,string>={GATE1_RENEWAL_REQUIRED:'مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک',DRAFT:'پیشنویس',GATE1_HELD:'تصمیم به تعویق افتاده',GATE1_PENDING:'در انتظار تأیید Gate1',GATE1_APPROVED:'تأییدشده در Gate1',READY:'آماده اجرا',RUNNING:'در حال اجرا',SUCCEEDED:'موفق',FAILED:'ناموفق',BLOCKED:'مسدود',EXPIRED:'منقضی',REJECTED:'ردشده',APPROVED:'تأییدشده',GATE2_PENDING:'در انتظار Gate2 (غیرفعال)',PREPARE:'آمادهسازی',MUTATE_PRODUCTION:'تغییر Production (غیرفعال)',SEO:'بهینهسازی جستوجو (SEO)',Content:'محتوا',Tech:'فنی',operationMode:'حالت عملیات',budgetLimitCents:'سقف بودجه (سنت)',metadata:'اطلاعات ثبتشده',scope:'محدوده',acceptanceCriteria:'معیارهای پذیرش',commitSha:'شناسه کامیت',id:'شناسه',taskId:'شناسه وظیفه',expectedVersion:'نسخه مورد انتظار',idempotencyKey:'کلید جلوگیری از اجرای تکراری',gate:'دروازه تأیید',decision:'تصمیم',expiresAt:'زمان انقضا',createdAt:'زمان ثبت',runId:'شناسه اجرا',artifactHash:'هش خروجی',environment:'محیط',sha256:'هش SHA-256',kind:'نوع',eventType:'نوع رویداد',fromState:'وضعیت پیشین',toState:'وضعیت بعدی',sequence:'ترتیب',amountCents:'مبلغ (سنت)',status:'وضعیت',reason:'دلیل',department:'دپارتمان',staging:'آزمایشی (staging)',FREEZE_NEW_WORK:'توقف کار جدید',STOP_AGENTS:'توقف عاملها',DISABLE_MUTATIONS:'منع تغییرات',EMERGENCY_HALT:'توقف اضطراری',RESERVE:'رزرو بودجه',RECONCILE:'تطبیق بودجه'};
|
||||
export const label=(value:string)=>labels[value]??value;
|
||||
export const actionLabel=(action:ServerAction)=>({HOLD_GATE1:'تعویق تصمیم Gate1',SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صفبندی آمادهسازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور'));
|
||||
export function Records({value,field}:{value:unknown;field?:string}){
|
||||
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,19 +2,18 @@ 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?'نامشخص — گزارش نشده':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>}
|
||||
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>}
|
||||
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:'مصرف در دسترس نیست')}).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></>}
|
||||
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></>}
|
||||
</section>;
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
|
||||
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 متوقف 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('سرویس فهرست ثبتشده: پاسخگو (نه سلامت زنده 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()}}));
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/health'))return {data:{ok:true,version:'v1',commit:'abc',auth_required:true}};
|
||||
if(url.endsWith('/profiles'))return {data:[{name:'dev',is_default:false,gateway_running:false}]};
|
||||
if(url.endsWith('/status'))return {data:{version:'v1',gateway_running:false,overall:'degraded',active_agents:0,gateway_state:null}};
|
||||
if(url.endsWith('/sessions'))return {data:{total:0,sessions:[]}};
|
||||
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 متوقف gateway, zero usage and profile-bound reads',async()=>{
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).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(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText('اجرای احرازهویتشده health: healthy')).not.toBeInTheDocument();
|
||||
});
|
||||
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(/وضعیت اجرا در دسترس نیست/)).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:'بازخوانی اطلاعات اجرا'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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>فهرست ثبتشده · زمان ثبت: {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:'وضعیت اجرا در دسترس نیست؛ خواندن احرازهویتشده از سرور ناموفق بود.'}))});
|
||||
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]:(({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="اجرای احرازهویتشده" 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>سرویس فهرست ثبتشده: {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-v5.0.1/Shabnam.woff2') format('woff2');
|
||||
src: url('/fonts/shabnam-font-v33.003/fonts/webfonts/Shabnam.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import {render,screen,within} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
it('shows expired queued work in owner decisions as blocked, not ready to execute',async()=>{
|
||||
const t={id:'t',key:'t',title:'Expired queued research',state:'READY',displayState:'GATE1_RENEWAL_REQUIRED',version:4,operationMode:'PREPARE',budgetLimitCents:20,availableActions:['APPROVE_GATE1'],metadata:{scope:'Same immutable scope',acceptanceCriteria:['Evidence']}};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
const queue=screen.getByRole('region',{name:'منتظر تصمیم شما'});
|
||||
expect(await within(queue).findByRole('button',{name:t.title})).toBeInTheDocument();
|
||||
expect(within(queue).getByText(/نیازمند تأیید مجدد مالک/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('آماده اجرا')).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen, fireEvent, within, waitFor, act } from '@testing-library/react';
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react';
|
||||
import { beforeEach, describe, it, expect, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
@@ -6,7 +6,7 @@ vi.mock('../services/api', () => ({ default: {get:vi.fn(),post:vi.fn(),put:vi.fn
|
||||
const task={id:'t1',key:'bounded-1',title:'Bounded SEO audit',department:'SEO',state:'GATE1_PENDING',version:4,operationMode:'PREPARE',budgetLimitCents:500,availableActions:[{id:'g1',label:'Approve bounded work',gate:1,decision:'APPROVED'}],runs:[],metadata:{scope:'Only staging',acceptanceCriteria:['Audit schema']}};
|
||||
describe('command center', () => {
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => {
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,killSwitch:true,chat:true,runtime:false}}};
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,chat:true,runtime:false}}};
|
||||
if(url.endsWith('/tasks')) return {data:[task]};
|
||||
if(url.endsWith('/tasks/t1')) return {data:task};
|
||||
throw new Error('Unavailable: '+url);
|
||||
@@ -14,86 +14,89 @@ 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'}));
|
||||
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(within(detail).getByText(/Only staging/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeInTheDocument();
|
||||
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button',{name:'Approve bounded work'})).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'عاملها و دپارتمانها'}));
|
||||
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(vi.mocked(api.get).mock.calls.some(([url])=>url.endsWith('/agents'))).toBe(false);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable');
|
||||
});
|
||||
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('محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.')).toBeInTheDocument();
|
||||
expect(await screen.findByText('Scope / acceptance criteria unavailable — omitted by the safe backend projection.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
|
||||
});
|
||||
it('approves immediately without date or reason after explicit confirmation',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{...task,state:'READY'}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
expect(within(dialog).getByLabelText('زمان اجرای برنامهریزیشده')).toHaveValue('');
|
||||
expect(within(dialog).queryByLabelText('زمان انقضا')).not.toBeInTheDocument();
|
||||
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
await waitFor(()=>expect(api.post).toHaveBeenCalledTimes(1));
|
||||
const payload=vi.mocked(api.post).mock.calls[0][1] as Record<string,unknown>;
|
||||
expect(payload.decision).toBe('APPROVED');
|
||||
expect(payload.expiresAt).toBeUndefined();expect(payload.notBefore).toBeUndefined();
|
||||
});
|
||||
it('requires explicit confirmation; retains idempotency across failed retry', async () => {
|
||||
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:'تأیید در Gate1'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Approve bounded work'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
expect(within(dialog).getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('زمان اجرای برنامهریزیشده'),{target:{value:new Date(Date.now()+3600000).toISOString().slice(0,16)}});
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'محدوده checked'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
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(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
|
||||
expect(within(dialog).getByLabelText('دلیل')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('زمان اجرای برنامهریزیشده')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
expect(within(dialog).getByLabelText('Reason')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('Expires at')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
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('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}));
|
||||
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:'VERIFIED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[release]:release}));
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByRole('button',{name:'تأیید در Gate2'})).toBeDisabled();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
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}));
|
||||
});
|
||||
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:'توقف اضطراری'}));
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.getAllByRole('option')).toHaveLength(4);
|
||||
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(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(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:'گفتوگو'}));
|
||||
fireEvent.change(screen.getByLabelText('شناسه نشست'),{target:{value:'session-1'}});
|
||||
fireEvent.change(screen.getByLabelText('پیام'),{target:{value:'Explain bounded work'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'ارسال پیام مشورتی'}));
|
||||
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'}));
|
||||
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'}));
|
||||
@@ -101,98 +104,13 @@ 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:'وظیفهها و تأییدها'}));
|
||||
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();
|
||||
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();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
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:'توقف اضطراری'}));
|
||||
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(/محدوده و معیارهای پذیرش در دسترس نیست/)).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('محدوده و معیارهای پذیرش گزارششده از سرور')).toBeInTheDocument();
|
||||
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows advertised decisions directly on pending card and labels reservation not measured cost',async()=>{
|
||||
const ownerTask={...task,budgetLimitCents:20,availableActions:['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[ownerTask]:ownerTask}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
const card=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
|
||||
expect(await within(card).findByRole('button',{name:'تأیید کار محدود در Gate1'})).toBeEnabled();
|
||||
expect(within(card).getByRole('button',{name:'رد کار در Gate1'})).toBeEnabled();
|
||||
expect(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'})).toBeEnabled();
|
||||
expect(within(card).getByText('رزرو آزمایشی؛ هزینه واقعی نامشخص')).toBeInTheDocument();
|
||||
fireEvent.click(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'}));
|
||||
const dialog=await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByRole('heading',{name:'تعویق تصمیم Gate1'})).toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled(); expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const cardActions=['APPROVE_GATE1','HOLD_GATE1','REJECT_GATE1'];
|
||||
const cardLabels=['تأیید کار محدود در Gate1','تعویق تصمیم Gate1','رد کار در Gate1'];
|
||||
it.each(cardActions)('opens fresh matching %s from the card without a preconfirm mutation',async action=>{
|
||||
vi.resetAllMocks();
|
||||
const fresh={...task,version:9,budgetLimitCents:73,availableActions:[action]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[{...task,availableActions:cardActions}]:fresh}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
const queue=screen.getByRole('region',{name:'منتظر تصمیم شما'});
|
||||
const label=cardLabels[cardActions.indexOf(action)];
|
||||
fireEvent.click(await within(queue).findByRole('button',{name:label}));
|
||||
const dialog=await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByRole('heading',{name:label})).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('9')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('73')).toBeInTheDocument();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks/t1');
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'انصراف'}));
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['missing','disabled','wrong-task','error'])('reports fresh card action failure: %s',async failure=>{
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'now',capabilities:{mutations:true}}};
|
||||
if(url.endsWith('/tasks'))return {data:[{...task,availableActions:cardActions}]};
|
||||
if(failure==='error')throw new Error('offline detail');
|
||||
return {data:{...task,id:failure==='wrong-task'?'other':task.id,availableActions:failure==='missing'?['HOLD_GATE1']:[{id:'APPROVE_GATE1',disabledReason:'policy'}]}};
|
||||
});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await within(screen.getByRole('region',{name:'منتظر تصمیم شما'})).findByRole('button',{name:cardLabels[0]}));
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it('invalidates a delayed card decision on refresh',async()=>{
|
||||
vi.resetAllMocks();let resolve!:(value:{data:unknown})=>void;
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'now',capabilities:{mutations:true}}};
|
||||
if(url.endsWith('/tasks'))return {data:[{...task,availableActions:cardActions}]};
|
||||
return await new Promise<{data:unknown}>(r=>{resolve=r});
|
||||
});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await within(screen.getByRole('region',{name:'منتظر تصمیم شما'})).findByRole('button',{name:cardLabels[0]}));
|
||||
expect(screen.getByRole('status')).toHaveTextContent('در حال');
|
||||
fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));
|
||||
await act(async()=>resolve({data:{...task,availableActions:cardActions}}));
|
||||
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,128 +1,82 @@
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import Button from '../components/ui/Button';
|
||||
import EditorialRecoveryDialog from '../components/EditorialRecoveryDialog';
|
||||
import {editorialRecoveryRun} from '../services/orchestration';
|
||||
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 { orchestration, killLevels } from '../services/orchestration';
|
||||
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
|
||||
const sections = ['نمای کلی','وظیفهها و تأییدها','اجراها و خروجیها','عاملها و دپارتمانها','مدلها و بودجهها','زمانبندیها','ممیزی و انتشارها','توقف اضطراری','مصرف و سهمیه 9router','اطلاعات اجرا و نشستها','گفتوگو'] as const;
|
||||
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Chat'] as const;
|
||||
type Section = typeof sections[number];
|
||||
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}/>;}
|
||||
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>}
|
||||
export default function OrchestrationCommandCenter() {
|
||||
const detailEpoch=useRef(0);
|
||||
const [recovery,setRecovery]=useState<Task|null>(null);
|
||||
const [section,setSection]=useState<Section>('نمای کلی');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false});
|
||||
const [section,setSection]=useState<Section>('Overview');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false});
|
||||
const [tasks,setTasks]=useState<Task[]>([]);
|
||||
const [selected,setSelected]=useState<Task|null>(null);
|
||||
const [decisionLoading,setDecisionLoading]=useState(false);
|
||||
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);
|
||||
const [attempted,setAttempted]=useState(false); const [busy,setBusy]=useState(false); const [commandError,setCommandError]=useState('');
|
||||
const [success,setSuccess]=useState('');
|
||||
const [blocked,setBlocked]=useState(false);
|
||||
const [now,setNow]=useState(Date.now());
|
||||
useEffect(()=>{const timer=setInterval(()=>setNow(Date.now()),1000);return ()=>clearInterval(timer)},[]);
|
||||
const [kill,setKill]=useState<KillLevel>('FREEZE_NEW_WORK');
|
||||
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
|
||||
const [messages,setMessages]=useState<ChatMessage[]>([]);
|
||||
const [chatKey,setChatKey]=useState(()=>crypto.randomUUID());
|
||||
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(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false}));},[]);
|
||||
useEffect(()=> {
|
||||
const resource=resources[section]; setSnapshot(null);
|
||||
const resource=resources[section]; setSnapshot(null);setError('');
|
||||
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)});
|
||||
return ()=>{active=false};
|
||||
},[section]);
|
||||
const select=async(task:Task)=>{const epoch=++detailEpoch.current;setDecisionLoading(false);setSelected(null);setError('');try {const detail=await orchestration.task(task.id);if(epoch===detailEpoch.current)setSelected(detail)}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}};
|
||||
const open=(task:Task,action:ServerAction)=>{if(!capabilities.mutations||actionBlockReason(task,action))return;setBlocked(false);setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
|
||||
const decide=async(task:Task,requested:ServerAction)=>{
|
||||
const epoch=++detailEpoch.current;
|
||||
setSelected(null);setPending(null);setError('');setSuccess('');setDecisionLoading(true);
|
||||
try {
|
||||
const detail=await orchestration.task(task.id);
|
||||
if(epoch!==detailEpoch.current)return;
|
||||
if(detail.id!==task.id)throw new Error('پاسخ جزئیات با وظیفه انتخابشده مطابقت ندارد');
|
||||
const action=detail.availableActions.find(a=>a.id===requested.id);
|
||||
if(!action)throw new Error('این اقدام دیگر توسط سرور مجاز نیست؛ وضعیت را بازخوانی کنید');
|
||||
const blockedReason=actionBlockReason(detail,action);
|
||||
if(blockedReason)throw new Error(blockedReason);
|
||||
if(!capabilities.mutations)throw new Error('تغییرات از طرف سرور مجاز نیست');
|
||||
setSelected(detail);open(detail,action);
|
||||
} catch(e) {if(epoch===detailEpoch.current)setError(errorText(e))}
|
||||
finally {if(epoch===detailEpoch.current)setDecisionLoading(false)}
|
||||
};
|
||||
const select=async(task:Task)=>{setSelected(null);setError('');try {setSelected(await orchestration.task(task.id))}catch(e){setError(errorText(e))}};
|
||||
const open=(task:Task,action:ServerAction)=>{setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
|
||||
const execute=async()=> {
|
||||
if(!pending||busy||!confirmed||blocked||!capabilities.mutations)return;
|
||||
if(!pending||busy||!confirmed)return;
|
||||
setAttempted(true);setBusy(true);setCommandError('');
|
||||
try { const [runId,artifactHash]=binding.split('|');
|
||||
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,notBefore:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
|
||||
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
|
||||
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
|
||||
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();
|
||||
} catch(e) {setCommandError(errorText(e)+' — Refresh before retrying a version conflict; network retries keep the same key.')} finally {setBusy(false)}
|
||||
};
|
||||
const openRecovery=async(task:Task)=>{
|
||||
if(!capabilities.mutations||pending||recovery)return;
|
||||
const epoch=++detailEpoch.current;setDecisionLoading(true);setSelected(null);setError('');
|
||||
try{const detail=await orchestration.task(task.id);if(epoch!==detailEpoch.current)return;
|
||||
if(detail.id!==task.id||!editorialRecoveryRun(detail))throw new Error('بازیابی دیگر مجاز نیست؛ وضعیت را بازخوانی کنید');
|
||||
setRecovery(detail);
|
||||
}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}finally{if(epoch===detailEpoch.current)setDecisionLoading(false)}
|
||||
};
|
||||
const refresh=()=>{detailEpoch.current++;setDecisionLoading(false);setSelected(null);setPending(null);setRecovery(null);void loadTasks()};
|
||||
const refresh=()=>{setSelected(null);setPending(null);void loadTasks()};
|
||||
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
|
||||
return <><div inert={!!recovery} 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={()=>{detailEpoch.current++;setDecisionLoading(false);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||decisionLoading)&&<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>}
|
||||
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} 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>}
|
||||
{success&&<p role="status">{success}</p>}
|
||||
{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','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
|
||||
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??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.displayState??t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p><p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><div className="flex flex-wrap gap-2">{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=><Button key={a.id} disabled={!capabilities.mutations||!!pending||busy||!!actionBlockReason(t,a)} onClick={()=>void decide(t,a)}>{actionLabel(a)}</Button>)}</div>{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==='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>}
|
||||
{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.displayState??t.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>(t.displayState??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','GATE1_RENEWAL_REQUIRED'].includes(t.displayState??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.displayState??t.state)}</td><td>{label(t.operationMode)}</td><td>{t.budgetLimitCents??'نامشخص'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
|
||||
{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>{selected.metadata?<h3>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend 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={!!a.disabledReason} title={a.disabledReason} 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>}
|
||||
{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}}/>
|
||||
{selected.displayState==='GATE1_RENEWAL_REQUIRED'&&<p role="status">مسدود — تأیید Gate1 منقضی شده؛ برای همان وظیفه و محدوده، تأیید مجدد مستقل لازم است. برنامه زمانی و سقف بودجه تغییر نمیکند.</p>}<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>
|
||||
{editorialRecoveryRun(selected)&&<Button disabled={!capabilities.mutations||!!pending||busy||decisionLoading} onClick={()=>void openRecovery(selected)}>ثبت شکست اجرای متوقفشده</Button>}
|
||||
<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>)}
|
||||
<p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><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===1&&pending.action.decision==='APPROVED'&&pending.task.displayState!=='GATE1_RENEWAL_REQUIRED'&&<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>}
|
||||
<p>تأیید، وظیفه را در اولویت صف آماده قرار میدهد؛ زمان اختیاری فقط زودترین زمان شروع است و اجرای دقیق در آن لحظه تضمین نمیشود. حداکثر زمانبندی ۳۰ روز است؛ اعتبار تأیید را سرور مدیریت میکند.</p>
|
||||
<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||(pending.action.toState==='GATE1_HELD'&&!reason.trim())|| (!!expires&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+30*86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
|
||||
{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.mutations&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.mutations&&<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==='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?.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||!confirmed||!reason.trim()|| (!!pending.action.gate&&!Number.isFinite(Date.parse(expires))) || (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>
|
||||
</div></div>}
|
||||
</div>{recovery&&<EditorialRecoveryDialog task={recovery} onClose={refresh} onSuccess={async()=>{detailEpoch.current++;setRecovery(null);setSelected(null);setSuccess('شکست ثبت شد؛ رزرو با هزینه نامشخص حفظ شد.');await loadTasks()}}/>}</>;
|
||||
</div>;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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:'کار نگهداشته'}));
|
||||
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(within(detail).getByRole('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}));
|
||||
const detail=await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
fireEvent.click(within(detail).getByRole('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();
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
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.*غیرفعال/)});
|
||||
@@ -4,46 +4,6 @@ import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Users from './Users';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
vi.mock('../store/adminAuthStore', () => ({ useAdminAuthStore: vi.fn() }));
|
||||
|
||||
describe('Users superadmin editor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('SUPER_ADMIN');
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role: 'SUPER_ADMIN' }], meta: { total: 1 } } });
|
||||
vi.mocked(api.put).mockResolvedValue({ data: { success: true } });
|
||||
});
|
||||
it.each(['SUPER_ADMIN', 'ADMIN', 'Admin', 'User_Vet'])('preserves exact %s role on password-only save', async (role) => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select).toHaveValue(role);
|
||||
expect(screen.getAllByRole('option', { name: /مدیر ارشد/ }).length).toBeGreaterThan(0);
|
||||
fireEvent.change(document.querySelector('input[type="password"]')!, { target: { value: 'Fixture-only-123' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalled());
|
||||
const payload = vi.mocked(api.put).mock.calls[0][1] as Record<string, unknown>;
|
||||
expect(payload).not.toHaveProperty('role');
|
||||
});
|
||||
it('submits explicit superadmin promotion for authorized actor', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'ordinary-fixture', role: 'Admin' }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
fireEvent.change(screen.getAllByRole('combobox')[1], { target: { value: 'SUPER_ADMIN' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/users/ordinary-fixture', expect.objectContaining({ role: 'SUPER_ADMIN' })));
|
||||
});
|
||||
it('does not offer superadmin promotion to ordinary admin', async () => {
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('Admin');
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'افزودن کاربر جدید' }));
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select.querySelector('option[value="SUPER_ADMIN"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
@@ -97,9 +57,9 @@ describe('Users Page', () => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
// Actual GET /admin/users contract: no success envelope.
|
||||
success: true,
|
||||
data: mockUsers,
|
||||
meta: { lastPage: 2, total: 2, page: 1, limit: 10 },
|
||||
meta: { lastPage: 2, total: 2 },
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -300,8 +260,9 @@ 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, page: 1, limit: 10 },
|
||||
meta: { lastPage: 1, total: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
|
||||
|
||||
@@ -45,8 +44,6 @@ export interface UserRecord {
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
export default function Users() {
|
||||
const actorRole = useAdminAuthStore(state => state.adminUser?.role);
|
||||
const canManageSuperAdmin = ['superadmin', 'adminsuper'].includes((actorRole || '').toLowerCase().replace(/[_-]/g, ''));
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [users, setUsers] = useState<UserRecord[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -182,8 +179,7 @@ export default function Users() {
|
||||
if (role) params.append('role', role);
|
||||
|
||||
const response = await api.get(`/admin/users?${params.toString()}`);
|
||||
// The list endpoint returns { data, meta }, not a success envelope.
|
||||
if (Array.isArray(response.data?.data)) {
|
||||
if (response.data?.success) {
|
||||
const userList = response.data.data || [];
|
||||
setUsers(userList);
|
||||
setTotalPages(response.data.meta?.lastPage || 1);
|
||||
@@ -269,7 +265,7 @@ export default function Users() {
|
||||
firstName: editFormData.firstName.trim(),
|
||||
lastName: editFormData.lastName.trim(),
|
||||
mobile: editFormData.mobile.trim(),
|
||||
...(editFormData.role !== editUser.role && { role: editFormData.role }),
|
||||
role: editFormData.role,
|
||||
walletBalance: Number(editFormData.walletBalance) || 0,
|
||||
};
|
||||
if (editFormData.email.trim()) payload.email = editFormData.email.trim();
|
||||
@@ -361,7 +357,6 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
<option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>
|
||||
</select>
|
||||
|
||||
<div className="relative w-full sm:w-64">
|
||||
@@ -637,7 +632,6 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -747,7 +741,6 @@ export default function Users() {
|
||||
<label className="block text-gray-700 font-bold mb-1">نقش دسترسی</label>
|
||||
<select
|
||||
value={editFormData.role}
|
||||
disabled={!canManageSuperAdmin && ['superadmin', 'adminsuper'].includes((editUser?.role || '').toLowerCase().replace(/[_-]/g, ''))}
|
||||
onChange={(e) => setEditFormData({ ...editFormData, role: e.target.value })}
|
||||
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-bold bg-white"
|
||||
>
|
||||
@@ -755,10 +748,6 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
{editUser?.role && !['User_PetOwner', 'User_Wholesale', 'User_B2B', 'ADMIN', ...(canManageSuperAdmin ? ['SUPER_ADMIN'] : [])].includes(editUser.role) && (
|
||||
<option value={editUser.role}>{['superadmin', 'adminsuper'].includes(editUser.role.toLowerCase().replace(/[_-]/g, '')) ? 'مدیر ارشد (Super Admin)' : editUser.role}</option>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
const run={id:'r-expired',status:'RUNNING',environment:'staging',commitSha:'a'.repeat(40),artifacts:[]};
|
||||
const task={id:'editorial',key:'editorial-v1:'+ 'a'.repeat(64),title:'Editorial research: Test',department:'CONTENT',operationMode:'PREPARE',state:'RUNNING',version:6,budgetLimitCents:20,metadata:{commitSha:run.commitSha},availableActions:[],runs:[run],editorialRecovery:{runId:run.id}};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));});
|
||||
it('posts only the exact expired recovery payload through authenticated API',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{}});
|
||||
await orchestration.editorialFailure(task,{runId:run.id,expectedVersion:6,idempotencyKey:'stable',reason:'Process ended'});
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks/editorial/editorial-failure',{runId:run.id,expectedVersion:6,idempotencyKey:'stable',reason:'Process ended'});
|
||||
});
|
||||
it.each([{...task,editorialRecovery:undefined},{...task,runs:[]},{...task,runs:[{...run,status:'SUCCEEDED'}]},{...task,runs:[{...run,commitSha:'b'.repeat(40)}]}])('rejects missing or mismatched server recovery binding',async invalid=>{
|
||||
await expect(orchestration.editorialFailure(invalid,{runId:run.id,expectedVersion:6,idempotencyKey:'k',reason:'Process ended'})).rejects.toThrow();expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['',' ','x'.repeat(501)])('bounds required recovery reason',async reason=>{
|
||||
await expect(orchestration.editorialFailure(task,{runId:run.id,expectedVersion:6,idempotencyKey:'k',reason})).rejects.toThrow();expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('uses fresh detail before modal; freezes retry bytes; blocks concurrency rejection until refresh',async()=>{
|
||||
let details=0;
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:{...task,version:++details===1?6:7}}));
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce({response:{status:409}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:task.title}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقفشده'}));
|
||||
const dialog=await screen.findByRole('dialog',{name:'ثبت شکست اجرای متوقفشده'});
|
||||
expect(details).toBe(2);expect(api.post).not.toHaveBeenCalled();
|
||||
expect(within(dialog).getByText(/۲۰ سنت.*نامشخص/)).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/QA.*تأیید خودکار/)).toBeInTheDocument();
|
||||
const submit=within(dialog).getByRole('button',{name:'ثبت شکست'});
|
||||
expect(submit).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل شکست'),{target:{value:'Process ended'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید میکنم'));
|
||||
fireEvent.click(submit);await within(dialog).findByRole('alert');
|
||||
expect(within(dialog).getByLabelText('دلیل شکست')).toBeDisabled();
|
||||
fireEvent.click(submit);await waitFor(()=>expect(submit).toBeDisabled());
|
||||
expect(api.post).toHaveBeenCalledTimes(2);
|
||||
const payload=vi.mocked(api.post).mock.calls[0][1];expect(payload).toEqual(expect.objectContaining({runId:run.id,expectedVersion:7,reason:'Process ended'}));expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(payload);
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'بازخوانی و بستن'}));await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
});
|
||||
it('refreshes authoritative tasks after success without approval or budget commands',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{state:'FAILED'}});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقفشده'}));
|
||||
const dialog=await screen.findByRole('dialog');
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل شکست'),{target:{value:'Process ended'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید میکنم'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'ثبت شکست'}));
|
||||
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(api.post).toHaveBeenCalledTimes(1);expect(api.put).not.toHaveBeenCalled();
|
||||
expect(vi.mocked(api.get).mock.calls.filter(([url])=>url.endsWith('/tasks'))).toHaveLength(2);
|
||||
});
|
||||
it('does not infer eligibility from RUNNING or guessed age',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:{...task,editorialRecovery:undefined}}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(screen.queryByRole('button',{name:'ثبت شکست اجرای متوقفشده'})).not.toBeInTheDocument();
|
||||
});
|
||||
it('rejects eligibility removed during fresh open without a mutation',async()=>{
|
||||
let details=0;vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:{...task,editorialRecovery:++details===1?task.editorialRecovery:undefined}}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:task.title}));fireEvent.click(await screen.findByRole('button',{name:'ثبت شکست اجرای متوقفشده'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/بازخوانی/);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import {render,screen,fireEvent,within,waitFor,act} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
it('does not restore stale detail after authoritative refresh while detail request is pending',async()=>{
|
||||
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:'بازخوانی وضعیت از سرور'}));
|
||||
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:'تأیید در 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();
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
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:'تأیید در 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|اعلام نشده/);
|
||||
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(/اعلام نشده/);
|
||||
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|اعلام نشده/);
|
||||
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(/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:'تأیید در 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:'تأیید فرمان'}));
|
||||
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:'جزئیات وظیفه'});
|
||||
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeDisabled();
|
||||
});
|
||||
it('prevents confirming an already expired approval',async()=>{
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
});
|
||||
@@ -13,28 +13,31 @@ 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(/اعلام نشده/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
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/);
|
||||
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
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)}]};
|
||||
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('binds Gate2 to immutable registered run and sends version and retry-stable key', async () => {
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'VERIFIED',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'});
|
||||
});
|
||||
it('refuses expired approvals and unknown artifacts', async () => {
|
||||
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(/انقضا/);
|
||||
await expect(orchestration.command(task,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/expiry/);
|
||||
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(/Gate2.*غیرفعال/);
|
||||
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/binding/);
|
||||
});
|
||||
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(/نامعتبر/);
|
||||
await expect(orchestration.resource('agents')).rejects.toThrow(/Invalid/);
|
||||
});
|
||||
it('requires kill reason and uses only typed message bridge', async () => {
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/دلیل/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/پیام/);
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/reason/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/message/);
|
||||
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'});
|
||||
@@ -43,84 +46,9 @@ describe('orchestration adapter', () => {
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',{sessionId:'session',message:'Review task',idempotencyKey:'key'});
|
||||
});
|
||||
it('creates bounded work without permitting invalid caps or client-supplied state',async()=>{
|
||||
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/budget/);
|
||||
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{scope:'staging',acceptanceCriteria:['report']}})).rejects.toThrow(/budget/);
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
|
||||
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}});
|
||||
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
|
||||
});
|
||||
});
|
||||
|
||||
describe('actual PREPARE backend contract',()=>{
|
||||
beforeEach(()=>vi.resetAllMocks());
|
||||
it('normalizes strings by fixed mapping, drops unknown and tampered objects, never infers from state',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE','RELEASE_AUTHORIZE',{id:'SUBMIT_GATE1',label:'bad',toState:'RELEASING'},null]}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
expect(detail.availableActions.map(a=>a.id)).toEqual(['SUBMIT_GATE1','APPROVE_GATE1','REJECT_GATE1','QUEUE_PREPARE']);
|
||||
vi.mocked(api.put).mockResolvedValue({data:{}});
|
||||
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'submit'});
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1/transition',{toState:'GATE1_PENDING',expectedVersion:7,idempotencyKey:'submit',reason:undefined});
|
||||
vi.mocked(api.get).mockResolvedValue({data:[{...task,state:'DRAFT',availableActions:[]}]});
|
||||
expect((await orchestration.tasks())[0].availableActions).toEqual([]);
|
||||
});
|
||||
it('rejects arbitrary object transitions and conflicting known mappings',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:[{id:'evil',label:'go',toState:'RUNNING'},{id:'SUBMIT_GATE1',label:'go',toState:'READY'}]}});
|
||||
expect((await orchestration.task('t/1')).availableActions).toEqual([]);
|
||||
});
|
||||
it.each([0,19,10001,20.5])('rejects invalid budget %s',async budget=>{
|
||||
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/budget/i);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['abc','A'.repeat(40),'a'.repeat(64),''])('rejects invalid commit %s',async commitSha=>{
|
||||
await expect(orchestration.create({key:'k',title:'t',department:'SEO',operationMode:'PREPARE',budgetLimitCents:20,metadata:{commitSha,scope:'Audit staging only',acceptanceCriteria:['Schema checked']}})).rejects.toThrow(/commit/i);
|
||||
});
|
||||
it.each([20,10000])('posts exact DTO at boundary %s',async budget=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{}});
|
||||
const dto={key:'k',title:'t',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:budget,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked']}};
|
||||
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['APPROVE_GATE1','post','/gates/1/decide',{decision:'APPROVED'}],
|
||||
['REJECT_GATE1','post','/gates/1/decide',{decision:'REJECTED'}],
|
||||
['QUEUE_PREPARE','put','/transition',{toState:'READY'}],
|
||||
])('routes actual advertised %s regardless of state',async(id,method,path,payload)=>{
|
||||
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,state:'DRAFT',availableActions:[id]}});
|
||||
vi.mocked(api.post).mockResolvedValue({data:{}});vi.mocked(api.put).mockResolvedValue({data:{}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
await orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:new Date(Date.now()+3600000).toISOString()});
|
||||
expect(method==='post'?api.post:api.put).toHaveBeenCalledWith('/admin/orchestration/tasks/t%2F1'+path,expect.objectContaining({...payload,expectedVersion:7,idempotencyKey:'k'}));
|
||||
});
|
||||
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(/۲۴ ساعت/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const validProposal={key:'scope-1',title:'Review staging',department:'SEO',operationMode:'PREPARE' as const,budgetLimitCents:20,metadata:{commitSha:'a'.repeat(40),scope:' Human scope ',acceptanceCriteria:[' Evidence reviewed ']}};
|
||||
it('preserves immutable human metadata exactly and strips server-owned fields from exact DTO',async()=>{
|
||||
vi.resetAllMocks();
|
||||
const projected={id:'new',...validProposal,state:'DRAFT',version:1,metadata:{...validProposal.metadata,environment:'staging'},availableActions:['SUBMIT_GATE1']};
|
||||
vi.mocked(api.post).mockResolvedValue({data:projected});
|
||||
await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,workflowScope:'PRODUCTION',createdBy:'forged'}} as unknown as import('./orchestration').CreateTaskInput)).resolves.toEqual(projected);
|
||||
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',validProposal);
|
||||
vi.mocked(api.get).mockResolvedValue({data:projected});
|
||||
expect((await orchestration.task('new')).metadata).toEqual(projected.metadata);
|
||||
vi.mocked(api.get).mockResolvedValue({data:[projected]});
|
||||
expect((await orchestration.tasks())[0].metadata).toEqual(projected.metadata);
|
||||
});
|
||||
it.each(['', ' ', 'x'.repeat(2001),undefined,42])('rejects invalid human scope %s before HTTP',async scope=>{
|
||||
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,scope}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/scope/i);expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([[],Array(21).fill('x'),[''],[' '],['x'.repeat(501)],undefined,'criterion',[42]])('rejects invalid acceptance criteria %s before HTTP',async acceptanceCriteria=>{
|
||||
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,acceptanceCriteria}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/criteria/i);expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects array-coerced commit hashes',async()=>{
|
||||
vi.resetAllMocks();await expect(orchestration.create({...validProposal,metadata:{...validProposal.metadata,commitSha:['a'.repeat(40)]}} as unknown as import('./orchestration').CreateTaskInput)).rejects.toThrow(/commit/i);expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('accepts scope and criteria at exact backend limits',async()=>{
|
||||
vi.resetAllMocks();vi.mocked(api.post).mockResolvedValue({data:{}});
|
||||
const dto={...validProposal,metadata:{...validProposal.metadata,scope:'x'.repeat(2000),acceptanceCriteria:Array(20).fill('x'.repeat(500))}};
|
||||
await orchestration.create(dto);expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',dto);
|
||||
});
|
||||
@@ -1,137 +1,64 @@
|
||||
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> = {
|
||||
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 [];
|
||||
const result:ServerAction[]=[];
|
||||
for(const raw of value){
|
||||
let action:ServerAction|undefined;
|
||||
if(typeof raw==='string')action=Object.hasOwn(actionCommands,raw)?actionCommands[raw]:undefined;
|
||||
else if(raw&&typeof raw==='object'&&typeof raw.id==='string'){
|
||||
const fixed=Object.hasOwn(actionCommands,raw.id)?actionCommands[raw.id]:undefined;
|
||||
if(fixed){
|
||||
if(['toState','gate','decision'].some(k=>raw[k]!==undefined&&raw[k]!==fixed[k as keyof ServerAction]))continue;
|
||||
action={...fixed};
|
||||
}else if(!raw.toState&&[1,2].includes(raw.gate)&&['APPROVED','REJECTED'].includes(raw.decision)){
|
||||
// Legacy object format may describe only dedicated gate decisions, never arbitrary transitions.
|
||||
action={id:raw.id,label:raw.id,gate:raw.gate,decision:raw.decision};
|
||||
}
|
||||
if(action){
|
||||
if(typeof raw.label==='string'&&raw.label.trim())action={...action,label:raw.label};
|
||||
if(typeof raw.disabledReason==='string')action={...action,disabledReason:raw.disabledReason};
|
||||
}
|
||||
}
|
||||
if(action&&!result.some(a=>a.id===action.id))result.push({...action});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export interface Artifact { id: string; sha256: string; kind?: string; uri?: string }
|
||||
export interface Run { id: string; commitSha: string; environment: string; status: string; artifacts: Artifact[] }
|
||||
export interface Task { id: string; key: string; title: string; department: string; state: string; displayState?: string; editorialRecovery?: {runId:string}; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
|
||||
export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; notBefore?: string; runId?: string; artifactHash?: string }
|
||||
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
|
||||
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt?:string;notBefore?:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
|
||||
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
|
||||
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:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',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 interface Task { id: string; key: string; title: string; department: string; state: string; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
|
||||
export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; runId?: string; artifactHash?: string }
|
||||
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 }
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime: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 }
|
||||
export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const;
|
||||
export type KillLevel = typeof killLevels[number];
|
||||
export interface ChatMessage {id:string;role:'assistant'|'user';content:string}
|
||||
function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof data === 'object' && 'success' in data) {if (!data.success) throw new Error('Orchestration request failed'); return data.data;} return data as T; }
|
||||
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string;scope:string;acceptanceCriteria:string[]}}
|
||||
export function proposalError(input:CreateTaskInput):string|undefined {
|
||||
if(input.operationMode!=='PREPARE')return 'Only bounded Stage PREPARE proposals are available';
|
||||
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<20||input.budgetLimitCents>10000)return 'PREPARE budget must be an integer 20..10000 cents';
|
||||
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 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است';
|
||||
}
|
||||
export interface EditorialFailureInput {runId:string;expectedVersion:number;idempotencyKey:string;reason:string}
|
||||
// Eligibility is a safe server hint, never inferred from elapsed browser time.
|
||||
export function editorialRecoveryRun(task:Task):Run|undefined {
|
||||
if(task.state!=='RUNNING'||task.operationMode!=='PREPARE'||task.department!=='CONTENT'||task.budgetLimitCents!==20||!/^editorial-v1:[a-f0-9]{64}$/.test(task.key))return;
|
||||
const matches=task.runs?.filter(r=>r.id===task.editorialRecovery?.runId&&r.status==='RUNNING'&&r.environment==='staging'&&r.commitSha===task.metadata?.commitSha&&Array.isArray(r.artifacts)&&!r.artifacts.length);
|
||||
return matches?.length===1?matches[0]:undefined;
|
||||
}
|
||||
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'OBSERVE'|'PREPARE'|'MUTATE_PRODUCTION';budgetLimitCents:number;metadata:{scope:string;acceptanceCriteria:string[]}}
|
||||
export const orchestration = {
|
||||
async editorialFailure(task:Task,input:EditorialFailureInput):Promise<unknown> {
|
||||
if(!editorialRecoveryRun(task)||input.runId!==task.editorialRecovery?.runId||input.expectedVersion!==task.version||!Number.isInteger(input.expectedVersion)||!input.idempotencyKey||typeof input.reason!=='string'||!input.reason.trim()||input.reason.length>500)throw new Error('اتصال بازیابی معتبر نیست؛ وضعیت را بازخوانی کنید');
|
||||
return (await api.post('/admin/orchestration/tasks/'+encodeURIComponent(task.id)+'/editorial-failure',{runId:input.runId,expectedVersion:input.expectedVersion,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
|
||||
},
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
const error=proposalError(input);if(error)throw new Error(error);
|
||||
// Preserve human evidence exactly; workflowScope/environment/identity remain server-owned.
|
||||
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:'PREPARE',budgetLimitCents:input.budgetLimitCents,metadata:{commitSha:input.metadata.commitSha,scope:input.metadata.scope,acceptanceCriteria:[...input.metadata.acceptanceCriteria]}})).data;
|
||||
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<0)throw new Error('Nonnegative integer budget required');
|
||||
if(!input.key.trim()||!input.title.trim()||!input.department.trim()||!input.metadata.scope.trim()||!input.metadata.acceptanceCriteria.length)throw new Error('Bounded scope and acceptance criteria required');
|
||||
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:input.operationMode,budgetLimitCents:input.budgetLimitCents,metadata:input.metadata})).data;
|
||||
},
|
||||
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('پاسخ جزئیات وظیفه نامعتبر است');
|
||||
return {...data,availableActions:normalizeActions(data.availableActions)};
|
||||
if (!data?.id || !Number.isInteger(data.version)) throw new Error('Invalid task detail');
|
||||
return {...data,availableActions: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('پاسخ نمای ثبتشده نامعتبر است');
|
||||
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('Invalid resource snapshot');
|
||||
return data;
|
||||
},
|
||||
async kill(level:KillLevel,reason:string):Promise<unknown> {
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است');
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('Kill switch level and reason required');
|
||||
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('نشست و پیام الزامی است');
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('Session and message required');
|
||||
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('پاسخ گفتوگو نامعتبر است');
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('Invalid typed chat reply');
|
||||
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('اقدام اعلام نشده یا غیرفعال است');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است');
|
||||
const action = task.availableActions.find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
||||
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
|
||||
if (action.gate && action.decision) {
|
||||
if (input.notBefore && (action.decision!=='APPROVED' || !(Date.parse(input.notBefore)>Date.now()) || Date.parse(input.notBefore)>Date.now()+30*86400000)) throw new Error('زمان اجرا باید در آینده و حداکثر ۳۰ روز باشد');
|
||||
if (input.expiresAt && !(Date.parse(input.expiresAt)>Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
|
||||
if(input.expiresAt && Date.parse(input.expiresAt)>(input.notBefore?Date.parse(input.notBefore):Date.now())+86400000) throw new Error('انقضای Gate1 باید در ۲۴ ساعت پس از زمان اجرا باشد');
|
||||
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('Future expiry required');
|
||||
let binding = {};
|
||||
if (action.gate === 2 && action.decision === 'APPROVED') {
|
||||
const run = task.runs?.find(r => r.id === input.runId);
|
||||
if(run?.status!=='SUCCEEDED')throw new Error('Registered successful run binding required for Gate2 evidence');
|
||||
if (!run?.commitSha || !run.environment || !run.artifacts.some(a => a.sha256 === input.artifactHash)) throw new Error('Registered immutable Gate2 binding required');
|
||||
binding = {runId:run.id, artifactHash:input.artifactHash, commitSha:run.commitSha, environment:run.environment};
|
||||
}
|
||||
return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,...(input.expiresAt?{expiresAt:input.expiresAt}:{}),...(input.notBefore?{notBefore:input.notBefore}:{}),notes:input.reason,...binding})).data;
|
||||
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('اقدام سرور پشتیبانی نمیشود');
|
||||
if (!action.toState) throw new Error('Unsupported server action');
|
||||
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('پاسخ فهرست وظیفهها نامعتبر است');
|
||||
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
||||
if (!Array.isArray(rows)) throw new Error('Invalid orchestration task response');
|
||||
return rows.map(row => ({ ...row, availableActions: 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('مجموع درگاه (شامل Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('سهم مصرف Hermes: نامشخص و گزارشنشده؛ با مجموع درگاه جمع نکنید.')).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('9router')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('نامشخص — گزارش نشده').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('Unknown — not reported').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/router-usage',{params:{period:'7d'}});
|
||||
fireEvent.change(screen.getByLabelText('بازه مصرف'),{target:{value:'today'}});
|
||||
fireEvent.change(screen.getByLabelText('Usage period'),{target:{value:'today'}});
|
||||
await screen.findByText('opaque-1');
|
||||
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
|
||||
});
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from './api';
|
||||
import {runtime} from './runtime';
|
||||
vi.mock('./api',()=>({default:{get:vi.fn()}}));
|
||||
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:100,freshness:'stale',liveProcess:'unknown'};
|
||||
it.each([{source:'live'},{capturedAt:'not-a-date'},{capturedAt:'2999-01-01T00:00:00Z'},{ageSeconds:-1},{ageSeconds:0.5},{freshness:'live'},{liveProcess:'running'}])('rejects invalid provenance %j',async invalid=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,...invalid}}});
|
||||
await expect(runtime.health()).rejects.toThrow('Invalid snapshot provenance');
|
||||
});
|
||||
it('retains fresh snapshots as inventory with unknown process state',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{ok:true,version:'1',commit:'x',auth_required:true,provenance:{...provenance,freshness:'fresh'}}});
|
||||
expect(await runtime.health()).toMatchObject({provenance:{freshness:'fresh',liveProcess:'unknown'}});
|
||||
});
|
||||
it('retains validated snapshot provenance and unknown live telemetry across inventory reads',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'1',commit:'x',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'1',overall:'unknown',gateway_running:false,active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:0,sessions:[],provenance}:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0},provenance}}));
|
||||
expect(await runtime.health()).toMatchObject({provenance});
|
||||
expect(await runtime.profiles()).toMatchObject([{provenance,liveGatewayState:'unknown'}]);
|
||||
expect(await runtime.status('dev')).toMatchObject({provenance,liveGatewayState:'unknown',liveActiveAgents:null});
|
||||
expect(await runtime.sessions('dev')).toMatchObject({provenance});
|
||||
expect(await runtime.usage('dev')).toMatchObject({provenance});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import api from './api';
|
||||
export interface RuntimeProvenance {source:'snapshot';capturedAt:string;ageSeconds:number;freshness:'fresh'|'stale';liveProcess:'unknown'}
|
||||
interface Inventory {provenance?:RuntimeProvenance}
|
||||
export interface RuntimeHealth extends Inventory {ok:boolean;version:string;commit:string;auth_required:true}
|
||||
export interface RuntimeProfile extends Inventory {name:string;is_default:boolean;gateway_running:boolean;liveGatewayState?:'unknown'}
|
||||
export interface RuntimeStatus extends Inventory {version:string;gateway_running:boolean;overall:string;active_agents:number;gateway_state:string|null;liveGatewayState?:'unknown';liveActiveAgents?:null}
|
||||
export interface RuntimeSession {id:string;profile:string;source:string;is_active:boolean}
|
||||
export interface RuntimeSessions extends Inventory {total:number;sessions:RuntimeSession[]}
|
||||
export interface RuntimeUsage extends Inventory {period_days:number;totals:{total_input:number;total_output:number;total_sessions:number;total_estimated_cost:number}}
|
||||
function object(value:unknown):Record<string,unknown>{if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Invalid runtime contract');return value as Record<string,unknown>}
|
||||
function text(value:unknown):string{if(typeof value!=='string')throw new Error('Invalid runtime text');return value}
|
||||
function bool(value:unknown):boolean{if(typeof value!=='boolean')throw new Error('Invalid runtime flag');return value}
|
||||
function count(value:unknown):number{if(typeof value!=='number'||!Number.isFinite(value)||value<0)throw new Error('Invalid runtime count');return value}
|
||||
function list(value:unknown):unknown[]{if(!Array.isArray(value)||value.length>1000)throw new Error('Invalid runtime list');return value}
|
||||
async function read(path:string,params?:Record<string,string|number>):Promise<unknown>{const {data}=await api.get('/admin/orchestration/runtime/'+path,...(params?[{params}]:[]));const row=data&&typeof data==='object'&&!Array.isArray(data)?data:null;if(row&&'success' in row){if(row.success!==true)throw new Error('Runtime unavailable');return row.data}return data}
|
||||
function provenance(r:Record<string,unknown>):Inventory {
|
||||
if(r.provenance===undefined)return {};
|
||||
const p=object(r.provenance);
|
||||
if(p.source!=='snapshot'||p.liveProcess!=='unknown'||typeof p.capturedAt!=='string'||!p.capturedAt.endsWith('Z')||!Number.isFinite(Date.parse(p.capturedAt))||Date.parse(p.capturedAt)>Date.now()||typeof p.ageSeconds!=='number'||!Number.isInteger(p.ageSeconds)||p.ageSeconds<0||!['fresh','stale'].includes(String(p.freshness)))throw new Error('Invalid snapshot provenance');
|
||||
return {provenance:{source:'snapshot',capturedAt:p.capturedAt,ageSeconds:p.ageSeconds,freshness:p.freshness as 'fresh'|'stale',liveProcess:'unknown'}};
|
||||
}
|
||||
export const runtime={
|
||||
async health():Promise<RuntimeHealth>{const r=object(await read('health'));if(r.auth_required!==true)throw new Error('Authenticated runtime required');return {...provenance(r),ok:bool(r.ok),version:text(r.version),commit:text(r.commit),auth_required:true}},
|
||||
async profiles():Promise<RuntimeProfile[]>{return list(await read('profiles')).map(value=>{const r=object(value);return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const}:{}),name:text(r.name),is_default:bool(r.is_default),gateway_running:bool(r.gateway_running)}})},
|
||||
async status(profile:string):Promise<RuntimeStatus>{const r=object(await read('status',{profile}));return {...provenance(r),...(r.provenance?{liveGatewayState:'unknown' as const,liveActiveAgents:null}:{}),version:text(r.version),gateway_running:bool(r.gateway_running),overall:text(r.overall),active_agents:count(r.active_agents),gateway_state:r.gateway_state===null?null:text(r.gateway_state)}},
|
||||
async sessions(profile:string,offset=0):Promise<RuntimeSessions>{const r=object(await read('sessions',{profile,limit:20,offset}));return {...provenance(r),total:count(r.total),sessions:list(r.sessions).map(value=>{const s=object(value);if(s.profile!==profile)throw new Error('Runtime profile mismatch');return {id:text(s.id),profile:text(s.profile),source:text(s.source),is_active:bool(s.is_active)}})}},
|
||||
async usage(profile:string):Promise<RuntimeUsage>{const r=object(await read('usage',{profile,days:30}));const t=object(r.totals);return {...provenance(r),period_days:count(r.period_days),totals:{total_input:count(t.total_input),total_output:count(t.total_output),total_sessions:count(t.total_sessions),total_estimated_cost:count(t.total_estimated_cost)}}},
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
# Competitor profile protocol diagnosis (no paid retry)
|
||||
|
||||
Base: `471243390`; runtime inspected read-only as user `hermes`.
|
||||
|
||||
## Observed evidence
|
||||
|
||||
* Installed `/opt/hermes/bin/hermes chat --help` exits 0 and accepts every argument used by runner, including `--query-file -`, `--oneshot`, `--format stream-json`, `--toolsets`, `--max-turns`, `--run-budget`, and `--ignore-rules`. stream-json implies quiet. Invalid flags/banner/model unavailability are not supported by the evidence.
|
||||
* Canonical competitor config, .env, logs, and private cache are readable/writable by hermes. No credential values were returned.
|
||||
* Read-only SQLite metadata for session `20261024_111941_64c954` shows 8 API calls, 8 tool calls, no `ended_at`, and no final assistant answer. Calls were three searches followed by five extracts; the last persisted entry is the fifth extract request without its result.
|
||||
* Agent logs show startup at 11:19:36, first search at 11:20:03, and last extract start at 11:21:23. This is consistent with runner's 120-second hard wall killing an active retrieval, including CLI startup. It is NOT evidence of invalid CLI flags or an unavailable model. Exact original exception cannot be proven: runner deleted stdout/stderr and collapsed the cause to RUNNER_ERROR.
|
||||
* Installed web_extract schema requires char_limit >=2000 and its implementation clamps to 2000. Runner requested 1000 and falsely promised that would fit the emitter's 5000-character cap. Several persisted tool outputs exceeded 5000; such event output is truncated and cannot be decoded as retrieval proof. This remains fail-closed; truncated text is never accepted as source evidence.
|
||||
|
||||
## Changes
|
||||
|
||||
* Preclaim `chat --help` capability check for each canonical profile environment. No model/credential resolution occurs in this help check; it cannot establish upstream model availability.
|
||||
* Preserve constant safe categories for wall-clock timeout, process/init failure, malformed stream, and forbidden tool. Parse nonzero terminal envelopes before classifying; never persist or reflect provider text, prompts, stderr, or raw output.
|
||||
* Correct char_limit to 2000 and bound requested search/retrieval exploration so the model has turns left to finish. Prompt guidance is not an enforcement guarantee and does not make unreliable retrieval available.
|
||||
* Actual installed `StreamJsonEmitter` is exercised directly without constructing an agent or invoking a model. Synthetic process failures are explicitly test-only and not research evidence.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
`python3 -m unittest discover -s infra/hermes-editorial/tests -v` discovers all editorial Python tests. The installed-emitter test runs when the installed module exists, or set `HERMES_STREAM_JSON_SOURCE` to a copied installed source. Never substitute a made-up envelope fixture for this check.
|
||||
|
||||
No task/lease/recovery mutations, runner execution, model invocation, production cron, deploy, or push were performed. No increase in cost reservation or wall-clock limit. Lost live output means timeout is strongly indicated, not conclusively reconstructed. Web availability and successful paid end-to-end completion remain unverified. Reservations remain unknown/retained.
|
||||
@@ -1,76 +0,0 @@
|
||||
# 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`.
|
||||
@@ -1,41 +0,0 @@
|
||||
# Reviewed Stage editorial recovery
|
||||
|
||||
No live change was made by this patch. CI owns installation, parent owns authenticated recovery and any separately approved research. Do not use `complete`, DB writes, forged tokens or root runner invocation.
|
||||
|
||||
## Ownership
|
||||
|
||||
Read-only reconnaissance: `canina-hermes` Docker Config.User=root; `/proc/self/uid_map` maps container 0 to host 100000 for 65536 IDs; passwd hermes is 10000:10000 (host 110000:110000). Migration runs *inside* the container namespace, never with guessed host IDs. Existing package, dedicated PMO token (0400), locks and competitor editorial-runner cache (0700) are root-owned. Profile roots and normal caches are already hermes-owned and must not be recursively changed.
|
||||
|
||||
`provision-editorial-runtime.py` runs the tracked `editorial-ownership.py` through the existing clean-SHA serialized Stage CI gate before installing as hermes. `scan()` preflights every member, symlink ancestor, UID/GID, mode and hardlink; exact package/payload/installed skills, dedicated credential, editorial state names and profile `cache/editorial-runner` only. Read-only scan against the existing container accepted 96 paths. General profile files, provider credentials, other caches and config are excluded. Unknown entries fail closed. Modes and contents never change. Root journal `/opt/data/.editorial-ownership-v1.json` is 0600, records original IDs/modes/inodes; a second migration is a no-op. A partial failure rolls back. Explicit `rollback(home,journal)` refuses inode/mode/path-set conflicts; use only before an installer upgrade replaces files. CI must remain serialized and runner/client inactive during migration. After installation, normal installer rollback and ownership rollback are separate operations; do not blindly restore old journal after file replacement.
|
||||
|
||||
## Stop original RUNNING v6
|
||||
|
||||
After deploying/reviewing this SHA through CI, authenticated independent SUPER_ADMIN or configured owner-reviewer Admin uses the ordinary admin JWT (not a worker token). Read:
|
||||
|
||||
`GET https://stageapi.canina.ir/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b`
|
||||
|
||||
Take the actual RUNNING run ID from `runs` (do not guess). Confirm version=6 and original process has ended. Invoke:
|
||||
|
||||
```
|
||||
POST https://stageapi.canina.ir/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/editorial-failure
|
||||
Authorization: Bearer <existing independent admin session JWT>
|
||||
Content-Type: application/json
|
||||
|
||||
{"runId":"<actual original RUNNING run UUID>","expectedVersion":6,"idempotencyKey":"editorial-recovery:565ace1f:v6","reason":"Original supervised runner process ended before artifact ingestion; cache access failure; actual spend unknown"}
|
||||
```
|
||||
|
||||
Requires exact editorial provenance, matching current run, expired lease, expected task version and unreconciled owned 20 reservation; rejects cross-run/cross-task/active lease. This does not require an expired execution approval to become valid again merely to stop work. Existing kill policy still applies: FREEZE_NEW_WORK permits stopping; STOP_AGENTS/DISABLE_MUTATIONS/EMERGENCY_HALT block as for other core operations. Owner controls switches through existing policy, not this endpoint. Identical replay is safe; different payload/key collision is rejected. Locks serialize heartbeat/result/claim/failure. Success is task FAILED v7, run FAILED, outbox DONE, token cleared, no artifact/QA/reconciliation, original unknown20 retained.
|
||||
|
||||
Held lease variant: canonical PMO worker may `POST /api/internal/prepare-worker/editorial-failure` with the same fields plus `taskId` and valid unexpired `leaseToken`; no worker can perform stale recovery. Never include actualCents or QA.
|
||||
|
||||
## Explicit retry and budget boundary
|
||||
|
||||
There is intentionally **no retry of this exhausted 20-cent task**: preserving unknown20 and reserving another20 under a20 task cap is mathematically impossible. Reusing the original reservation as fresh spend would falsely manufacture free capacity. A repeat claim on FAILED is denied before any ledger write; duplicate failure never creates another reservation.
|
||||
|
||||
After predecessor is confirmed FAILED/fenced, parent can explicitly submit a **new** editorial proposal through existing authenticated `POST /api/internal/prepare-worker/editorial-proposals`, with a fresh requestId, the reviewed deployment commit SHA, same bounded topic/criteria and budgetLimitCents=20 (see editorial-execution.md contract). Obtain a new independent Gate1 via existing `POST /api/admin/orchestration/tasks/<newTaskId>/gates/1/decide` with APPROVED, its current expectedVersion and a new idempotencyKey. This atomically queues READY under current policy. Do not renew or mutate the FAILED predecessor. Only then execute the reviewed hermes-identity runner on the *new task ID*. Original unknown20 remains reserved; the new explicit approval authorizes up to20 additional, so cumulative upper bound is40. Parent must make that extra-budget authorization explicit; if the existing authorization is a cumulative20 ceiling, retry remains blocked until actual spend is measured through a separately reviewed reconciliation path. This patch does not bypass that ceiling or invent cost0.
|
||||
|
||||
## Verification
|
||||
|
||||
TDD: missing failure method was observed red (3 tests), then green. Migration tests verify twice, exact ownership/modes, outside sentinel, symlink/public secret/unknown path rejection and injected partial-failure rollback. Real TCP/PostgreSQL worker test races duplicate failure, rejects wrong token/actor/extra cost field, denies heartbeat/result/reclaim after stop and verifies only original RESERVE20, no artifacts or attestations. Unit tests cover stale version, active stale recovery, wrong run/task, independent role and idempotency payload mismatch.
|
||||
|
||||
Disposable test database `editorial_recovery_isolated` only. Full migration chain has pre-existing `blogs` missing relation; isolated tests apply the four scoped orchestration migrations to a dedicated DB instead. Shared generated Prisma client was stale; tests/build use private generated .prisma mount, not shared mutation. Build initially failed from remapped fixture ownership and stale Prisma; private owned fixture fixed both. No Stage/Production migrations or writes, deploy, push, scheduler, runner or live research executed.
|
||||
@@ -1,9 +0,0 @@
|
||||
# Owner recovery control
|
||||
|
||||
Command center task detail offers **ثبت شکست اجرای متوقفشده** only when the authenticated detail response supplies `editorialRecovery: {runId}` and that ID matches the registered RUNNING staging run/commit with no artifacts. The server derives the hint from the actual expired outbox lease, canonical editorial admission and unreconciled 20-cent reservation for an independent reviewer. Lists contain no hint. No lease owner/token/credentials are serialized. The existing failure command remains the atomic authority, including provenance, version and run/lease fencing.
|
||||
|
||||
Opening the control refetches detail. The modal requires a nonblank reason of at most 500 characters and explicit acknowledgement. It explains retained unknown 20-cent spend, not cost zero, no QA, no autoapproval, no release/retry/budget authorization. A first submit freezes exact runId/expectedVersion/idempotencyKey/reason bytes; ambiguous network retries reuse them. 4xx rejections require refresh. Successful commands and close reconcile with a fresh list. Background content is inert while the recovery modal is mounted.
|
||||
|
||||
This adds a backend **read-only detail hint** because the old safe run projection contains neither lease expiry nor a trustworthy recovery capability. A frontend-only age heuristic cannot establish actual expiry. Deploy both admin and backend changes through normal CI. No change to the failure endpoint, authorization, budgets or worker transport.
|
||||
|
||||
Validation: disposable source/dependency copies, no published ports or live state writes. Scoped admin/API tests and application tsc + Vite build; backend hint/failure/read/HTTP tests plus Prisma generation and tsc build. No push/deployment or live task recovery performed here; the owner must authenticate and click after integration.
|
||||
@@ -1,51 +0,0 @@
|
||||
# One-task research runner
|
||||
|
||||
Installed through `scripts/provision-editorial-runtime.py`'s exact runtime-package allowlist, not a live edit. This adds no activation, scheduler, approval or grant.
|
||||
|
||||
After parent deploy/approval verification, run **inside canina-hermes as its configured runtime identity**:
|
||||
|
||||
```
|
||||
timeout --signal=TERM --kill-after=5s 570s python3 -B /opt/data/editorial-v4/runtime-package/runner.py --task-id 565ace1f-8cfc-4447-b978-66c36e7b767b
|
||||
```
|
||||
|
||||
Do not invoke until the original approval is valid and task READY. Runner cannot queue or approve; claim and result independently enforce backend Gate1. No automatic retry (including ambiguous ingestion failure). Inspect authenticated task status before any owner-directed recovery. Expired approvals/reservations are never changed locally.
|
||||
|
||||
Limits: one task, four sequential installed canonical profile invocations (market competitor-worker, coverage content-worker, SEO seo-worker, PMO synthesis), eight turns and 120 seconds per profile, 540 seconds total plus bounded HTTP overhead, five-second heartbeat interval/HTTP timeout, 1MiB stdout and 256KiB stderr per child; report <=16KiB, final canonical brief <=24KiB. SIGTERM/heartbeat loss/error kills child process group. Profile-local writable cache is cwd/TMPDIR; no root workspace or terminal sandbox. Web toolset is only web_search/web_extract. Model tools cannot access service credential. No filesystem, terminal, browser, image, article, publication, QA, release or production tools.
|
||||
|
||||
Hermes CLI installed help/source inspected: `--query-file - --oneshot --format stream-json --toolsets web --max-turns 8 --run-budget 120`. Parse exactly one successful terminal `result` JSONL envelope; reject unknown tool events, duplicate/error result and invalid JSON. Extract one URL per call with char_limit=1000 to keep CLI's 5000-character tool-output cap parseable. Require worker retrieval events, successful nonempty extraction content, and final source URLs in those worker retrievals. This is transport provenance, not factuality/QA certification. Source/date/scoring truth remains independent QA's job.
|
||||
|
||||
Result submits only task/run/lease/brief, expects VERIFYING/PENDING_INDEPENDENT_QA and retained unknown reservation20. It never claims zero spend or a passed QA. No durable local lease token/log is emitted. CLI failures suppress private provider/backend details.
|
||||
|
||||
Tests use disposable localhost HTTP and real subprocesses inside disposable network-isolated Python containers. Explicit test-only synthetic CLI events/content prove protocol, cancellation and fencing, **not live research or application QA**. Live model/research acceptance intentionally not run; parent owns promotion and original-approval check.
|
||||
|
||||
|
||||
## Identity failure diagnosed on 2026-10-24
|
||||
|
||||
The existing installed package/credential/runner lock were UID0; competitor cache
|
||||
was UID0 mode0700 while canonical profile belonged to hermes UID10000. The actual
|
||||
`/opt/hermes/bin/hermes` wrapper drops UID0 to hermes. A read-only UID10000 access
|
||||
probe returned false for that cache. This is a concrete pre-model process boundary
|
||||
failure, not evidence of a claim-response mismatch. Deployed compiled claim returns
|
||||
`{lease:{taskId,runId,attempt,leaseToken,leaseUntil,commitSha,environment,maxCostCents,pilotKind}}`;
|
||||
heartbeat accepts exactly taskId/runId/leaseToken and returns `{leaseUntil}`. These
|
||||
match the runner. No failure/report endpoint exists in worker transport; `complete`
|
||||
is NOT a failure protocol (it attests QA and reconciles cost), and must not be used.
|
||||
|
||||
Installer now explicitly uses `docker exec --user hermes` for installation and skill
|
||||
discovery; existing root-owned state fails closed. Do not run a root runner or set
|
||||
HERMES_DOCKER_EXEC_AS_ROOT to bypass the privilege boundary. Preflight ownership
|
||||
checks occur before credential access and claim. Failure JSON contains only local
|
||||
stage/error-code constants and explicitly requires reading backend status, never
|
||||
claims task completion or zero spend.
|
||||
|
||||
Current task 565ace1f-8cfc-4447-b978-66c36e7b767b remains RUNNING v6, artifact null
|
||||
(read-only authenticated status). It was not reclaimed, retried, renewed or altered.
|
||||
Lease expiry alone does not transition state; its unknown 20-cent reservation stays.
|
||||
Recovery requires owner review: retain reservation and audit failed run; authorize
|
||||
an explicit backend fenced failure/cancel protocol before changing task state (none
|
||||
exists currently), and a separately reviewed CI-only ownership migration for the
|
||||
exact installed package/credential/runner-created cache paths. Do NOT recursively
|
||||
chown profiles, invent actualCents=0, clear DB rows, or invoke runner to recover.
|
||||
After that migration, install via reviewed CI under hermes; a new execution still
|
||||
requires explicit parent/owner authorization and a backend-ready task. This patch
|
||||
is not installed, deployed, activated or live-model accepted.
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user